CitectSCADA Cicode Reference
CitectSCADA Cicode Reference
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
27
27 28 28 29
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
37
37 38 39 39 39 39
41
41 42 43 43 44 44 45 46 46 47 48 50 50 51 52 53 54 56 57 58 60
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
69
69 70 70 70 71 72 72 72 73 74 74
75
75 76 77 78 79
81
81 82 83 83 83 85
87
87 89 90 91 92
93
93
Contents
Using FOR ... DO Loops Using WHILE ... DO Conditional Loops Nested Loops Using the SELECT CASE statement
94 95 95 96
99
99 100 101 101 102 102
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
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
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
1300 1323
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
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
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.
15
16
var while
If you use any of these words inappropriately in your Cicode, it will not be allowed by the compiler.
17
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
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
<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 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
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.
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.
23
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
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
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.
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
25
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
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
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
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
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
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
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
30
where: FunctionName is the name of the function Arg1, Arg2, ... are the arguments you pass to the function
31
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.
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
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
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";
34
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.
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
When the command executes, the page name is passed to the function as Arg1. The operator can then display any page, for example:
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
Alarm Functions Page Functions Keyboard Functions Report Functions Time/date Functions Miscellaneous Functions
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
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
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
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
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
41
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
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).
43
your project.
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
/* ** ** ** ** ** ** ** ** ** ** */
This file contains functions to allow the operator to load the recipe data from the SQL server to the PLC.
45
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.
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.
46
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
TagReadEx(Tag1)
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
TagReadEx (Tag1.V)
Standards for constants, variable tags, and labels Standards variables: declaration, scope, and naming
47
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).
48
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.
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
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.
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
51
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
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
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.
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
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.
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
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.
56
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
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
Replace the <InitialDefaultValue> placeholder in the following function example with an appropriate value for your Argument variable.
58
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
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
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 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
62
63
REAL STRING
Floating point (64 bits) Text string (128 bytes maximum, including null termination character) ActiveX control Represents the CitectSCADA quality
OBJECT QUALITY
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.
The assignment operation also allows for the QUALITY data type.
Example: QUALITY q1; QUALITY q2; q1 = q2; q1 = Tag1.Field.Q;
64
//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;
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
INT OBJECT
x, y; hObject;
The first 32 characters of a variable name needs to be unique. See Also Variable Naming Standards
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
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
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
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
69
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
70
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
71
72
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
See Also Working with Conditional Executors Using Arrays Using Cicode Files
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
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
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,
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
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,
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
variation of IFDEF to check for the existence of alarm tags. See IFDEFDigAlm for digital alarms, or IFDEFAdvAlm for advanced alarms.
Syntax
IFDEFAnaAlm(TagName,
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
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
79
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.
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
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
81
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
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
See Also Converting and Formatting Cicode Variables Using Cicode Files
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
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
83
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
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
85
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
Example
87
ment Command Comment Command Comment Command Comment Command Comment Command Comment Counter = Counter - 1;
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
Command Comment
Message = "For info see " + "Supervisor"; Message now equals "For info see Supervisor"
For example: See Also Working with Operators Using Cicode Files
For example
Command Command Command Command Tag3 = Tag1 BITAND Tag2; Tag3 = Tag1 BITAND 0xFF; Tag3 = Tag1 BITOR Tag2; Tag3 = Tag1 BITXOR Tag2;
89
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;
90
Examples:
Command Comment Expression Comment Expression Comment Command Comment Command Comment Result = (PV12 = 10 AND PV13 = 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
Expression Comment
NOT Tag_1;
This expression is TRUE if Tag_1 = 0. This is commonly used for testing digital variables
92
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
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
94
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
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
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
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
97
98
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
100
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
101
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
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
104
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
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.
106
Double click a Cicode file (*.ci). Choose Tools | Cicode Editor in a CitectSCADA application. Click the Cicode Editor button.
107
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
source files in your project directory will be included when you compile your project.
109
110
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.
View Windows and ToolBars tab Options Properties tab Language Formatter Properties tab
111
112
Note: You can also choose View | Options, and then select the appropriate Window from the dialog.
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
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
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.
114
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:
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
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.
Thread window
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
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.
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.
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
Files window
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
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
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
120
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
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
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
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
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.
123
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.
Enabling/disabling breakpoints
You can enable or disable breakpoints you have inserted into your Cicode.
124
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.
Step Over
125
126
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
127
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";
128
INT
bSuccess = FALSE;
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:
129
Local variable names should not be prefixed (when you declare a variable without specifying the scope, it is considered a Local variable by default):
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
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
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
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
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
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
IF-THEN-ELSE block
IF <expression> THEN ... ELSE ... 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
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
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
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
'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 < {
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 < {
137
Note: The "Tag" name value is outputted as a literal as no closing bracer '}' is detected. Functions Reference
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();
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
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
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>
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
//** 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
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
Sin(x)
More than 1
Moderate
SinAndTan(x)
141
Number of tasks
Example
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
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
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
Handles
144
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 handles
145
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
146
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
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
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
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
* matches all following characters, for example, "Motor*" matches all accumulators starting with the word "Motor"
151
? 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
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
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
FieldName:
153
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
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
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
155
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
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:
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
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
158
ObjectIsValid ObjectToStr
_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
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
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
160
_ObjectGetProperty
Gets a specific property of an ActiveX object.
Syntax
sProperty:
The name of the property you want to get.
Return Value
_ObjectSetProperty
Sets a specific property of an ActiveX object.
Syntax
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
161
Related 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
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
"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
163
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
164
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
165
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
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
166
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
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
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
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
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
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
Return Value
ObjectHasInterface
169
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
sInterface:
The name of the interface (case sensitive).
Return Value
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
170
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
171
172
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
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
AlarmGetThreshold AlarmGetThresholdRec
AlarmHelp
AlarmNextCatRec
174
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
175
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
AlmBrowseEnable
AlmBrowseFirst AlmBrowseGetField
AlmBrowseNext AlmBrowseNumRecords
AlmSummaryClear
176
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
Deprecated in this version Deprecated in this version Deprecated in this version Deprecated in this version
177
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.
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
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
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
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
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
Return Value
Related Functions
GrpOpen
Example
180
Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment
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
AlarmAckRec
181
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
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
182
AlarmAckTag
Acknowledge a specified alarm.
Syntax
ClusterName:
The cluster where the tag resides
Return Value
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
183
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
AlarmCatGetFormat
Returns the display format string of the specified alarm category.
Syntax
Type:
184
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.
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
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
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
Return Value
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
Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment System Keyboard Key Sequence Command Comment
AlarmClear ### Enter AlarmClear(2, Arg1, "clusterXYZ") Clear alarms of a specified category in cluster XYZ
ClearPri ########### Enter AlarmClear(3,Arg1, "clusterXYZ") Clear alarms of a specific priority in cluster XYZ
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
AlarmFirstCatRec() or AlarmNextCatRec() - used to search for a record by alarm category, area, and type (acknowledged, disabled, etc.).
187
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
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
AN:
An animation identifier. It is required that this animation is an alarm event.
Return Value
188
AlarmDsp
Example
AlarmComment(Arg1) Add an alarm comment to the alarm where the cursor is positioned
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
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
// 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
// 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
nCount = AlarmCount(nActiveAlarmType, "MyFilter"); IF nCount greater 0 THEN nError = IsError(); ELSE nError = 0; END
Related Functions
AlarmCountList
Counts the available alarms for the selected filter criteria.
Syntax
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
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
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
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
Return Value
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
System Keyboard Key Sequence Command Comment DisPri ############# Enter AlarmDisable(3,Arg1,"clusterXYZ") Disable alarms of a specific priority in cluster XYZ
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
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
195
Related 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
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
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
11 12 13 14
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
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
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
sClusterName:
The name of the cluster to be used for this alarm list. The argument is enclosed in quotation marks ("").
Return Value
198
AlarmDspClusterInUse
Determines if a cluster is included in a client's alarm list.
Syntax
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
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
sClusterName:
The name of the cluster to remove from this alarm list. The argument is enclosed in quotation marks ("").
Return Value
199
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
Alarm Summary
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
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
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
-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
AlarmDsp, AlarmDspPrev
Example
System Keyboard Key Sequence Command Comment NextAlarm AlarmDspNext(20) Display the next page of alarms (from the alarm list) at AN20
AlarmDspPrev
202
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
-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
AlarmDsp, AlarmDspNext
Example
AlarmDspPrev(20) Display the previous page of alarms (from the alarm list) at AN20
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
Syntax
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
Return Value
204
Related Functions
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
AlarmEnableRec
205
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
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
AlarmEventQue
206
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
207
AlarmFilterClose
This function removes the named filter from memory.
Syntax
Return Value
Related Functions
AlarmFilterEditAppend
208
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
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
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
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
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
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
nError = AlarmFilterEditCommit(hEdit);
Related 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
Return Value
Related Functions
AlarmFilterEditLast
211
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
Return Value
Related 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
212
Return Value
Related 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
Return Value
213
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
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
Return Value
214
// Area=1;
Related 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
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
215
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
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
Related Functions
216
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
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
GrpOpen, AlarmNextCatRec, AlarmFirstPriRec, AlarmNextPriRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec
Example
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
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
219
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
220
AlarmGetDelay
Gets the delay setting for the alarm the cursor is currently positioned over.
Syntax
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
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
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
AlarmGetDsp
222
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
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
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
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
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.
RecordId
Return Value
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
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
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
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.
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
AlarmFirstTagRec, AlarmNextTagRec,
Example 228
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
AlarmGetFilterName
Retrieves the name of the linked named filter for the supplied An. If empty text, there is currently no linked named filter.
Syntax
Return Value
229
Related 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
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
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
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
The AN where the alarm list (with the required information) is displayed.
Return Value
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
AlarmGetThresholdRec
Gets the threshold of analog alarms by the alarm record number.
232
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
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
AlarmHelp
233
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
PageAlarm
Example
System Keyboard Key Sequence Command Comment AlmHelp AlarmHelp() Display the alarm help page
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
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
235
GrpOpen, AlarmFirstCatRec, AlarmFirstPriRec, AlarmNextPriRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetThresholdRec, AlarmSetThresholdRec
Example
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
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
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
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
238
Related Functions
AlarmFirstTagRec, AlarmGetFieldRec, AlarmAckRec, AlarmDisableRec, AlarmEnableRec, AlarmGetDelayRec, AlarmGetThresholdRec, AlarmSetThresholdRec, AlmBrowseOpen, AlmBrowseNext
Example
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
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
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
240
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.
Return Value
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
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.
Return Value
AlarmSetDelay
242
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
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
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
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
AlarmSetInfo
Controls different aspects of the alarm list displayed at a specified AN. Currently applies only to non-hardware alarm lists.
Syntax
244
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
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
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
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
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);
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
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
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
Return Value
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
AlarmSetThresholdRec
250
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:
251
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
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
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
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
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
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
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
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
Return Value
0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions
254
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
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
255
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
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
256
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
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
257
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
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
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
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
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
Return Value
0 (zero) if the alarm browse session exists, otherwise an error code is returned.
Related Functions
260
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
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 ...
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
Example
INT errorCode = 0; ... errorCode = AlmSummaryDeleteAll(iSession); IF errorCode = 0 THEN // Successful case ELSE // Function returned an error END ...
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
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
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
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
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
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
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
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
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
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
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 ...
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
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
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
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
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
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 ...
AlmTagsNext
This command is deprecated in this version of CitectSCADA. Use AlmBrowseNext function instead.
274
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
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 ...
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
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
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 ...
277
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
278
l l l l l l
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
....
Sleep(0);
279
END
280
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
ClipWriteLn
Example
ClipCopy("put this in clipboard");
281
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();
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
WHILE StrLength(sText) > 0 DO ! Do something with text ... ! Read next line of clipboard sText = ClipReadLn(); END
ClipSetMode
Sets the format of data sent to the Windows clipboard.
Syntax
ClipSetMode(nMode) nMode:
The mode of the data:
Return Value
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);
ClipWriteLn
283
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
ClipCopy
Example
ClipWriteLn("first line of text"); ClipWriteLn("second line of text"); ClipWriteLn(""); ! End of write operation
284
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
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
Return Value
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
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
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
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
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
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
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
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
sStandby:
289
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
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
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
Return Value
-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
clusterNameB:
The name of the cluster to activate or deactivate enclosed in quotation marks "".
Return Value
291
ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, TaskCluster See Also Cluster Functions "About cluster context" in the CitectSCADA User Guide
292
PackedRGBToCitectColour
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
GetBlueValue
Returns the Blue component of a packed RGB color.
Syntax
GetBlueValue(nPackedRGB) nPackedRGB:
The packed RGB color.
Return Value
GetGreenValue
Returns the green component of a packed RGB color.
Syntax
GetGreenValue(nPackedRGB) nPackedRGB:
The packed RGB color.
Return Value
GetRedValue
Returns the red component of a packed RGB color.
294
Syntax
GetRedValue(nPackedRGB) nPackedRGB:
The packed RGB color.
Return Value
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
295
PackedRGB
Returns a packed RGB color based on specified red, green, and blue values.
Syntax
nGreen:
The green component of the desired packed RGB color.
nBlue:
The blue component of the desired packed RGB color.
Return Value
PackedRGBToCitectColour
Converts a packed RGB color into a calculated CitectSCADA color value.
Syntax
PackedRGBToCitectColour(nPackedRGB) nPackedRGB:
The packed RGB color.
Return Value
CitectColourToPackedRGB
296
297
298
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
299
Example
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
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
Related Functions
301
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
sBuffer:
302
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
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
303
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
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
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
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.
ComOpen
Example
SerialKey("Port1"); ! enable the serial keyboard
306
DDEPost
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.
DDEExec
307
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
sCommand:
The command that the application will execute.
Return Value
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
Syntax
sCommand:
The command that the application will execute.
Return Value
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
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
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
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
311
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
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
DDEhReadLn
312
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
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
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
313
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
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
sMode:
The mode of the DDE conversation:
314
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
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
315
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
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
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
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
317
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
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:
The value (from the external application) as a string, or an empty string if the function cannot read the desired values.
Related Functions
318
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
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
319
320
321
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.
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
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
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
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
323
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
DevOpen
Example
DevClose(hDev);
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
nType:
The type of command:
0 - Re-index the device based on the key defined in the device record (dBASE devices only).
324
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
DevOpen, DevZap
Example
! pack a dBASE file device DevControl(hDev, 1, "");
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
DevOpen, DevPrint
325
Example
! Get the report device number. hDev=DevCurr();
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
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
State:
The disable state:
DevOpen
Example
! Disable the AlarmLog device. DevDisable("AlarmLog",1); : DevDisable("AlarmLog",0);
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
327
Example
hDev = DevOpen("Log", 0); WHILE NOT DevEOF(hDev) DO Prompt(DevGetField(hDev,"Tag")); DevNext(hDev); END DevClose(hDev);
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
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
DevOpen, DevSeek
Example
328
! 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
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);
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
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
DevOpen, DevClose
Example
! Flush device to disk. DevFlush(hDev);
DevGetField
Gets field data from the current record in a device.
Syntax
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
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
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
331
DevOpen, DevControl
Example
! Create history file DevHistory(hDev);
DevInfo
Gets information on a device.
Syntax
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
Return Value
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
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
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
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.
334
Related 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
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
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
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
DevOpenGrp
Opens a group of devices.
Syntax
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
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
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
sData:
The data to print to the group of devices.
339
NewLine:
The newline flag:
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);
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
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
Related 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
DevRecNo
341
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);
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
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
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
DevSetField
Sets new field data in the current record in a device.
Syntax
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
343
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);
344
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
sData:
The data to write, as a string.
Return Value
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.)
DevWriteLn
345
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
sData:
The data to write, as a string.
Return Value
DevOpen, DevWrite
Example
/* Write PV123 to the device followed by a newline character */ DevWriteLn(hDev,"PV123="+PV123:###.#);
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
346
Related Functions
DevDelete
Example
! Delete all records in the alarm log database. hDev = DevOpen("AlarmLog", 0); DevZap(hDev);
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
PrintFont
347
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
Print
Example
348
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
349
350
DspAnFree DspAnGetArea
DspAnGetPrivilege
DspAnSetMetadataAt DspBar
351
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
352
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.
DspGetNearestAn DspGetParentAn
353
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
354
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.
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
355
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
CreateObject, CreateControlObject
Example
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
DspAnFree(nAN) nAN:
The animation-point number.
Return Value
DspAnNew
Example
/* Remove AN20 from the current page. */ DspAnFree(20);
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
DspAnGetMetadata
Retrieves the field value of the specified metadata entry.
Syntax
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
Retrieves metadata information at the specified index.
Syntax
DspAnGetMetadataAt(nAN,nIndex,sField) nAn:
358
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
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
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);
DspAnInfo
Note: This function is only used for V3.xx and V4.xx animations, and has been
360
superseded by future releases. Gets information on an AN - the type or state of the animation that is currently displayed.
Syntax
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
IF DspAnInfo(25,0) = "1" THEN /* If color on AN 25, then get the color */ col = DspAnInfo(25,1); END
DspAnInRgn
Checks if an AN is within a region bounded by two ANs.
Syntax
One, Two:
One - the AN at a corner of the region; two - the AN at the opposite corner of the region.
Return Value
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
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
DspAnMoveRel
Example
DspAnMove(25,100,200); ! Moves AN25 to pixel location 100,200.
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
Return Value
DspAnMove
Example
DspAnMoveRel(25,10,20); /* Moves AN25 by 10 pixels to the right and 20 pixels downward, relative to its current position. */
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
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 */
DspAnSetMetadata
Non-blocking function, that sets the value of the specified metadata entry.
365
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
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
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
366
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
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
Bar:
367
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
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. */
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
sFile:
368
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
DspDel
Example
// Display the bitmap "MyImage.bmp" at AN 60 DspBMP(60, "MyImage.bmp", 0)
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
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
370
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");
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
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
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
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
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
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
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);
DspCol
DspCol is deprecated in this version of CitectSCADA.
Syntax
DspCol(nAN, Color)
373
nAN:
The animation-point number.
Color:
The color to display at the AN.
Return Value
DspDel
Example
DspCol(25,RED); /* Displays the color red at AN25. */
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
DspDirty
Example
DspDel(25);
374
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
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();
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
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. */
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
DspDel
Example
DspDirty(20); ! Forces an update of AN20.
377
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
CodeSetMode, Prompt
Example
DspError("Error found"); ! Displays "Error found" at the prompt AN.
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
378
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
DspFileGetInfo
Gets the attributes of a file-to-screen display (used for displaying text files).
Syntax
nType:
The type of data required:
379
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
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
380
DspFileScroll
Scrolls a file (displayed in the display "window") by a number of characters.
Syntax
Direction:
The direction in which to scroll:
Return Value
Page Keyboard Key Sequence Command Comment PgUp DspFileScroll(20,3,10) Scroll up 10 lines
381
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
sName:
The name of the file to display.
Return Value
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
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.
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
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
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
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
Fonts
384
Font Name Font Type Pixel Size Foreground Color Background Color Comment
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. */
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
Mode:
Fullscreen mode:
0 - Disable fullscreen mode. 1 - Enable fullscreen mode without title bar 2 Enable fullscreen mode with title bar.
Return Value
WinMode
Example
/*Minimize the Window, Enable fullscreen mode and then maximize the window.*/ WinMode(6); DspFullScreen(1); WinMode(3);
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
386
nBottom = DspGetAnBottom(30);
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
/* 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
DspGetAnExtent
Gets the extent of the object (the enclosing boundary) at the specified AN.
Syntax
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
DspGetAnFirst
388
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
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
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
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
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
nHeight = DspGetAnHeight(30);
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
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
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
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
DspGetAnTop
Gets the top extent of the object at the specified AN.
Syntax
DspGetAnTop(nAN) nAN:
The animation-point number.
Return Value
392
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
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
DspGetEnv
Gets a page environment variable.
Syntax
DspGetEnv(sName)
393
sName:
The name of the variable (set using the page environment dialog)
Return Value
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
! If the mouse cursor is at x,y pixel coordinate 43,20; DspGetMouse(X,Y); ! Sets X to 43 and Y to 20.
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
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
395
Related 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);
DspGetSlider
396
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);
DspGetTip
Gets the tool tip text associated with an AN.
Syntax
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.)
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));
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
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
398
Related 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
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
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
400
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
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
401
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
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
Return Value
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
The object information block handle. If no object data is available, then -1 is returned.
Related 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
404
Example
IF DspInfoValid(hInfo) THEN EngValue=DspInfoField(hInfo,sTag,"Eng_Value"); END
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
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
405
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).
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
KerCmd, TraceMsg
Example
DspKernel(1); !Display the Citect Kernel window
DspMarkerMove
Moves a trend or chart marker to a specified position.
Syntax
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
DspMarkerNew, OnEvent
Example
DspMarkerNew
407
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
Mode:
The mode of the marker:
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
END
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
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*/
DspPlaySound
409
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
nMode:
Not used. Needs to be 0 (zero).
Return Value
Beep
Example
410
DspPlaySound("C:\WINNT\MEDIA\Notify.wav",0); DspPlaySound("SystemStart",0);
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
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
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(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
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
! If 'Item B2' is selected, iSelection will equal 102 ! If 'Item B3' is selected, iSelection will equal 103 END
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
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
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);
DspRichTextEdit
Enables editing of the contents of the rich text object at nAN if nEdit = TRUE, and disables editing if nEdit = FALSE.
Syntax
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
415
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
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
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);
DspRichTextGetInfo
Retrieves size information about the rich text object at animation point nAN.
Syntax
iType:
416
The following size information (in pixels) can be returned about the specified rich text object:
0 - Height 1 - Width
Return Value
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);
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
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
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
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");
DspRichTextPgScroll
Scrolls the contents of the rich text object displayed at nAN, by one page length in the direction given in direction.
Syntax
iDirection:
418
The direction in which you want to scroll each time this function is run. You can choose from the following:
DspRichTextPrint
Prints the contents of the rich text object at animation point nAN, to the port PortName.
Syntax
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
419
Related Functions
DspRichText, FileRichTextPrint
Example
! This lines prints DspRichTextPrint(25,"LPT1:");
DspRichTextSave
Saves the contents of the rich text object at animation point nAN, to the file Filename.
Syntax
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
DspRichTextScroll
420
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
iDirection:
The direction in which you want to scroll each time this function is run. You can choose from the following:
Return Value
DspRubEnd
421
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
cx,cy:
The x and y coordinates of the end position.
Return Value
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
422
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
Return Value
DspRubStart
423
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
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
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
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
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
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
DspGetSlider
425
Example
// Set the position of the slider at AN 30 to 1/2 scale DspSetSlider(30, 16000);
DspSetTip
Sets tool tip text associated with an AN. Any existing text associated with the AN will be replaced with the new text.
Syntax
sText:
The tool tip text to set for the AN.
Return Value
DspGetTip, DspTipMode
Example
!Set a tool tip for AN19 DspSetTip(19, "Start Slurry Pump");
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
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
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");
DspStatus
Determines whether the object at the specified AN will be grayed (hatch pattern) in the event communication attempts are unsuccessful.
Syntax
427
nMode:
0 - Normal display when communication attempts are unsuccessful 1 - Gray the object (with a hatch pattern) when communication attempts are unsuccessful
Return Value
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
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:
428
0 - Length as pixels truncated (default) 1 - Length as pixels truncated with ellipsis 2 - Length interpreted as characters.
Return Value
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. */
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
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
Not used. The mode is always set to 1, which means do not erase the existing symbol, just draw the new symbol.
Return Value
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");
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
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
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
DspSym
Example
DspSymAnm(25,"Pumps.Centrifuge","Pumps.Floatation"); ! Alternately displays the centrifuge symbol and the flotation symbol (from the pumps library) at AN25.
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
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
DspSym
Example
DspSymAnmEx(25,-1,"Pumps.Centrifuge","Pumps.Floatation"); ! Alternately displays the centrifuge symbol and the flotation symbol (from the pumps library) at AN25.
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
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
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
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
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
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
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 - Length as pixels truncated (default) 1 - Length as pixels truncated with ellipsis 2 - Length interpreted as characters.
Return Value
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:
435
DspSetTip, DspGetTip
Example
DspTipMode(1); //Switch on tool tips
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
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
Value2...8:
The values to display on Pen 2...Pen 8 of the trend (optional).
Return Value
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
DspTrendInfo
Get information on a trend definition.
Syntax
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
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);
439
440
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
sArgs:
441
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
DLLOpen, DLLClose
Example
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
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
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
DLLOpen, DLLCall
Example
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
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
/* 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
446
EquipBrowseGetField
EquipBrowseNext
EquipBrowseNumRecords
EquipBrowseOpen EquipBrowsePrev
EquipCheckUpdate
EquipGetProperty
EquipSetProperty EquipStateBrowseClose
EquipStateBrowseFirst EquipStateBrowseGetField
EquipStateBrowseNext EquipStateBrowseNumRecords
EquipStateBrowseOpen
EquipStateBrowsePrev
447
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
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
Return Value
0 (zero) if the equipment database browse session exists, otherwise an error code is returned.
Related Functions
448
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
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
449
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
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
Return Value
450
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
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
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
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
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
452
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
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
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
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
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
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
Return Value
Returns 0 if the equipment state database browse session has been closed successfully, otherwise an error is returned.
Related Functions
456
ErrSet(1); INT error; fieldValue = EquipStateBrowseClose(iSession); error = IsError(); IF(error <> 0) THEN //return error ELSE //successful
ErrSet(0) end
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
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
This function is a non-blocking function. It does not block the calling Cicode task.
Syntax
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
ErrSet(0) end
458
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
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
Return Value
Returns the number of records which matches the current filter criteria. 0 means no records were found.
459
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
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
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
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
462
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
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}
ErrDrv
Gets a protocol-specific error message and native error code.
Syntax
sField:
The field in the PROTERR.DBF database:
l l l l l l l
nError:
464
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);
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
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
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
ErrHelp
Displays information about a hardware error.
Syntax
ErrHelp(Error) Error:
The Cicode hardware error string (as returned by ErrMsg()).
Return Value
ErrInfo
Gets extended error information on the last error that was detected.
Syntax
ErrInfo(nType) nType:
467
The type of error information. If type is 0 (zero), function returns the animation number where the error occurred.
Return Value
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
468
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
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
ErrSet(Mode) Mode:
Error-checking mode:
0 - default - CitectSCADA will check for errors. 1 - The user needs to check for errors.
Return Value
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
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
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
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
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
bHalt:
Determines whether the Cicode execution will be halted.
473
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()
474
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
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
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
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
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
478
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
OnEvent, GetEvent
Example
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
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
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
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
482
.. ! Restore old event handler. SetEvent(0,hFn); INT FUNCTION MouseFn() .. ! Chain call old event handler. RETURN ChainEvent(hFn); END
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
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
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
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
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
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
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
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
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
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
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
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
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
GetEvent
Example
491
492
493
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.
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
FileOpen
Example
File=FileOpen("C:\Data\Report.Txt","r"); .. ! Do file operations. .. ! Close the file. FileClose(File);
FileCopy
494
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
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 complete.
Related Functions
FileDelete
Example
! Copy Report.Txt to Report.Bak. FileCopy ("C:\Data\Report.Txt", "C:\Data\Report.Bak",0); /* Copy AlarmLog.Txt to AlarmLog.Bak only if the file time is different. Copy in the background. */ FileCopy ("AlarmLog.Txt", "AlarmLog.Bak",1+2);
495
FileDelete
Deletes a file.
Syntax
FileDelete(sName) Name:
The name of the file to delete.
Return Value
FileCopy
Example
! Delete old report file. FileDelete("C:\Data\Report.Txt");
FileEOF
Determines if the end of the file has been reached.
Syntax
FileEOF(File) File:
The file number.
Return Value
FileSeek
Example
WHILE NOT FileEOF(File) DO
496
Str=FileReadLn(File); END
FileExist
Checks if a file exists. If the return value is 1, the file exists.
Syntax
FileExist(sName) Name:
The name of the file to check.
Return Value
FileOpen
Example
! Check if the file exists IF FileExist("C:\Data\Report.Txt") THEN ! The file exists END
FileFind
Finds a file that matches a specified search criteria. To find a list of files, you need to first call this function with the required path and mode (to find the first file), then call the function again with an empty path and a mode of 0 (to find the remaining files). After the last file is found, an empty string is returned. If the search is for multiple files, FileFindClose needs to be called if the search does not run to completion (for example, you do not run until an empty string is returned).
Syntax
FileFind(sPath, nMode)
497
sPath:
The name of the file to check. To search for multiple files, the wildcards * and ? can be used to match multiple entries.
nMode:
The type of file to check:
0 - Normal files (includes files with read-only and archived attributes) 1 - Read-only files only 2 - Hidden files only 4 - System files only 16 - Subdirectories only 32 - Archived files only 128 - Files with no attributes only
These numbers can be added together to search for multiple types of files during one search.
Return Value
The full path and filename. If no files are found, an empty string is returned.
Related Functions
FileFindClose
Closes a find (started with FileFind) that did not run to completion.
Syntax
FileFindClose()
Return Value
498
FileFind
Example
//Find the first dbf file starting with fred sPath = FileFind("[run]:\fred*.dbf", 0); IF (StrLength(sPath) > 0) THEN //Do work here FileFindClose(); END
FileGetTime
Gets the time on a file.
Syntax
FileGetTime(File) File:
The file number.
Return Value
The file time of the file (in the CitectSCADA time/date variable format).
Related Functions
FileMakePath
Creates a file path string from individual components.
499
Syntax
sDir:
The directory string.
sFile:
The file name (without the extension).
sExt:
The file extension.
Return Value
FileOpen
Opens a file and returns a file number that can be used by other file functions. The maximum file size supported is 1 Megabyte for displaying text files. You can also use this function to check if a file exists, by opening the file in read-only mode. A return value of -1 indicates that the file cannot be opened. ErrSet(1) needs to be in the previous line of your code, else the execution stops and a hardware error is generated. If ErrSet(1) is used then it doesn't halt, and -1 is returned.
Syntax
nMode:
500
"a" - Append mode. Allows you to append to the file without removing the end of file marker. The file cannot be read. If the file does not exist, it will be created. "a+" - Append and read modes. Allows you to append to the file and read from it. The end of file marker will be removed before writing and restored when writing is complete. If the file does not exist, it will be created. "r" - Read-only mode. Allows you to (only) read from the file. If the file does not exist or cannot be found, the function call will return the value -1. "r+" - Read/write mode. Allows you to read from, and write to, the file. If the file already exists (before the function is called), its contents will be deleted. If the file does not exist or cannot be found, the function call will return the value -1. "w" - Write mode. Opens an empty file for writing. If the file already exists (before the function is called), its contents will be deleted. If the file does not exist or cannot be found, the file will be created. "w+" - Read/write mode. Opens an empty file for both reading and writing. If the file already exists (before the function is called), its contents will be deleted. If the file does not exist or cannot be found, the file will be created.
Return Value
The file number. If the file cannot be opened, -1 is returned and the code is halted.
Related Functions
FilePrint
Prints a file on a device.
Syntax
FilePrint(Devicename, Filename)
501
Devicename:
The name of the target device.
Filename:
The name of the file to print on the device.
Return Value
FileRead
Reads a number of characters from a file. The string can contain less characters than requested if the end of file is reached. A maximum of 255 characters can be read in each call.
Syntax
Length:
The number of characters to read.
Return Value
502
FileReadBlock
Reads a number of characters from a file. The buffer can contain less characters than requested if the end of file is reached. A maximum of 255 characters can be read in each call. The data should be treated as a binary data and should not be passed to string functions. You may use StrGetChar() function to extract each character from the buffer, or pass the buffer to another function which will accept binary data.
Syntax
Buffer:
The buffer to return the binary data. This may be a string or a string packed with binary data. The string terminator is ignored and the length argument specifies the number of characters to write.
Length:
The number of characters to read.
Return Value
The number of characters read from the file. When the end of the file is found 0 will be returned. If an error occurs -1 will be returned and IsError() will return the error code.
Related Functions
503
FileReadLn
Reads a line from a file. Up to 255 characters can be returned. The carriage return and newline characters are not returned. If the line is longer than 255 characters, the error overflow (code 275) is returned - you should call this function again to read the rest of the line.
Syntax
FileReadLn(File) File:
The file number.
Return Value
FileRename
Renames a file.
Syntax
Newname:
504
Return Value
FileCopy, FileDelete
Example
! Rename REPORT.TXT as REPORT.OLD. FileRename("C:\Data\Report.Txt","C:\Data\Report.Old");
FileRichTextPrint
Prints the rich text file sFilename to the printer given by sPortname.
Syntax
PortName:
The name of the printer port to which the rich text file 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 Values
PageRichTextFile, DspRichTextPrint
505
Example
// This would print the file [Data]\richtext.rtf to LPT1. Remember that the [Data] path is specified in the Citect.ini file. The file richtext.rtf is the name of the output file for the report, as specified in the Devices form. // iResult = FileRichTextPrint("[Data]\richtext.rtf","LPT1:"); // This would print the file f:\citect\data\richtext.rtf to LPT1. The file richtext.rtf is the name of the output file for the report, as specified in the Devices form. // iResult = FileRichTextPrint("f:\citect\data\richtext.rtf","LPT1:");
FileSeek
Moves the file pointer to a specified position in a file.
Syntax
Offset:
The offset in bytes, from 0 to (maximum file size -1). This value needs to be >= 0.
Return Value
FileSize
Example
! Seek to the start of the file. FileSeek(File,0);
FileSetTime
Sets the time on a file.
506
Note: In order for this function to work, the file needs to first be opened in write or read/write mode.
Syntax
iTime:
The new file time, in the CitectSCADA time/date variable format.
Return Value
FileSize
Gets the size of a file.
Syntax
FileSize(File) File:
The file number.
Return Value
FileSeek
507
Example
! Get the size of the file. Size=FileSize(File);
FileSplitPath
Splits a file path into individual string components. You enter the full path string as sPath. The individual components of the path name are returned in the arguments sDrive, sDir, sFile, and sExt. Arguments must be declared as Cicode variables. If declared as local variables or tags, an "Incompatible Types" error will be returned.
Syntax
sDrive:
The disk drive.
sDir:
The directory string.
sFile:
The file name (without the extension).
sExt:
The file extension.
Return Value
See FileFind
508
FileWrite
Writes a string to a file. The string is written at the current file position.
Syntax
String:
The string to write.
Return Value
FileWriteBlock
Writes a string or buffer to a file. The data is written at the current file position. You may create the binary data by using the StrSetChar function or by reading the data from some other function. This function is similar to the FileWrite() function however you specify the length of data to write to the file. The FileWrite() function will send the data to the file until the sting terminator is found. FileWriteBlock() will ignore any string terminator and copy the length of bytes to the file. This allows this function to be used for binary data transfer.
Syntax
509
Buffer:
The data to write to the file. This may be a string or a string packed with binary data. The string terminator is ignored and the length argument specifies the number of characters to write.
Length:
The number of characters to write. The maximum number of characters you may write in one call is 255. (If you use a string without a terminator in a function that expects a string, or in a Cicode expression, you could get invalid results.) To use the string to build up a buffer, you do not need the terminating 0 (zero).
Return Value
The number of characters written to the file. If an error is detected -1 will be returned and IsError() will return the error code.
Related Functions
FileWriteLn
Writes a string to a file, followed by a newline character. The string is written at the current file position.
Syntax
String:
The string to write.
Return Value
510
The number of characters written (including the carriage return and newline characters).
Related Functions
511
512
513
FormListDeleteText FormListSelectText FormNew FormNumPad FormOpenFile FormPassword FormSecurePassword FormPosition FormPrompt FormRadioButton FormRead FormSaveAsFile FormSelectPrinter FormSetData FormSetInst FormSetText FormWndHnd
Deletes existing text from combo box or list box. Selects (highlights) a text entry in a combo box or a list box. Creates a new form. Provides a keypad form for the operator to add numeric values. Displays a File Open dialog box. Adds a password (no echo) input field. Adds a secure password (no echo) input field.
Sets the position of a form on the screen, before it is displayed. Adds a prompt to a form. Adds a radio button to the current form. Displays a form and reads user input. Displays a File Save As dialog box. Displays the Select Printer dialog box. Sets data in a form. Associates data to a field on a form. Sets field text on an active form. Gets the window handle for the given form.
FormActive
Checks if a form is currently active (displayed on the screen). This function is useful when forms are being displayed in asynchronous mode and another Cicode task is trying to access the form.
Syntax
514
FormActive(hForm) hForm:
The form handle, returned from the FormNew() function. The form handle identifies the table where all data on the associated form is stored.
Return Value
FormDestroy, FormNew
Example
FormAddList
Adds a text string to a list box or combo box. You should call this function only after the FormNew() function, and immediately after either the FormComboBox() or the FormListBox(), and before the FormRead() function otherwise an error is returned. The text is added at the end of the list box or combo box. To add text to a form that is already displayed, use the FormListAddText() function, and use the FormListSelectText() function to highlight text on the list.
Syntax
FormAddList(sText) sText:
The text string to add to the list box or combo box.
Return Value
515
FormButton
Adds a button to the current form. You can add buttons that run callback functions (specified in Fn) to perform any actions you need, as well as the standard buttons - an [OK] button to save the operator's entries and close the form, and a [Cancel] button to close the form but discard the changes. You should call this function only after the FormNew() function and before the FormRead() function. The button is added to the form at the specified column and row position. The width of the button is automatically sized to suit the text.
Syntax
Row:
The number of the row in which the button will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the button in row 6, enter 5.
sText:
The text to display on the button.
Fn:
The callback function to call when the button is selected. Set to 0 to call no function. Please be aware that the Fn parameter needs to be of type INT and the callback function cannot contain a blocking function.
Mode:
Button mode:
0 - Normal button. When this button is selected the callback function is called. 1 - OK button. When this button is selected, the form is closed, and all operator-entered data is copied to buffers (specified by the other form functions). FormRead() returns 0 (zero) to indicate a successful read. The callback function specified in Fn is called. Be aware that this mode destroys the form.
516
2 - Cancel button. When this button is selected, the form is closed and operator-entered data is discarded. FormRead() returns with an error 299. The callback function specified in Fn is called. Be aware that this mode destroys the form.
Return Value
FormNew, FormRead
Example
! Create a form, add buttons and then display the form on the current page FUNCTION FnMenu() FormNew("MENU",20,6,1); FormButton(0 ,4 ," FIND ", FindMenu, 0); FormButton(10,4 ," TAG ", ShowTag, 0); FormButton(0 ,5 ," CANCEL ", KillForm, 0); FormButton(10,5 ," GOTO ", GotoPg, 0); FormRead(0); END
FormCheckBox
Adds a check box to the current form. The check box is a form control that allows the operator to make individual selections. Each check box can be either checked (true) or cleared (false). You should call this function only after the FormNew() function and before the FormRead() function. The check box is added to the form at the specified column and row position. The width of the button is automatically sized to suit the text.
Syntax
Row:
517
The number of the row in which the check box will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the check box in row 6, enter 5.
sText:
The text associated with the check box.
sBuf:
The string buffer in which to put the state of the check box. You should initialize this buffer to the state of the check box. When the form returns, this buffer will contain either '1' or '0' if the box is checked.
Return Value
The field handle if the check box is successfully added, otherwise -1 is returned.
Related Functions
FormNew, FormRead
Example
! Create a form, add check boxes, and display the form. ! The operator may select none or all of the check boxes. FUNCTION FnMenu() STRING sNuts, sCherrys, sChocolate; sNuts = "1"; sCherrys = "0"; sChocolate = "1"; FormNew("IceCream",20,6,1); ] FormCheckBox(2 ,2,"Nuts", sNuts); FormCheckBox(2, 3,"Cherrys", sCherrys); FormCheckBox(2 ,4,"Chocolate", sChocolate); FormRead(0); If sNuts = "1" THEN ! add the nuts END IF sCherrys = "1" THEN ! add the cherrys END IF sChocolate = "1" THEN ! add the chocolate END END
FormComboBox
Adds a combo box to the current form. A combo box is a form control that allows the operator to type a selection or make a single selection from a text list.
518
You should call this function only after the FormNew() function and before the FormRead() function. The combo box is added to the form at the specified column and row position with the specified width and height. If more items are placed in the list than the list can display, a scroll bar displays (to scroll to the hidden items). Use the FormAddList() function to add items for display in the list box. If the form is already displayed, you can use the FormListAddText() and FormListSelectText() functions to add (and highlight) text in the list box.
Syntax
Row:
The number of the row in which the combo box will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the combo box in row 6, enter 5.
Width:
The width of the list box, which should be wide enough to display your widest item. Items wider than the list box are clipped.
Height:
The height of the list box (the number of items that can be seen in the list box without scrolling).
sBuf:
The string buffer in which to store the selected item. The sBuf parameter can also hold the starting selection for the Combo box. For example if you set the sBuf string to "HELLO" before calling FormComboBox, HELLO will be displayed in the box upon opening the form.
Mode:
The mode in which to create the combo box:
0 - Sort the combo box elements alphabetically. 1 - Place elements in combo box in the order they were added.
Default mode is 0.
Return Value
The field handle if the combo box is successfully added, otherwise -1 is returned.
Related Functions
519
Example
! Create a form, add combo box and then display the form ! the operator may type in or select one of the items from the list FUNCTION FnMenu() STRING sBuf; FormNew("Select Item",20,6,1); FormComboBox(2 ,2, 15, 5, sBuf, 1); FormAddList("Item One"); FormAddList("Item two"); FormAddList("Item three"); FormRead(0); ! sBuf should contain the selected item or entered text END
FormCurr
Gets the form and field handles for the current form and field. You should call this function only from within a callback function. You can then use the same callback function for all forms and fields, regardless of how the boxes, buttons, etc. on the forms are used. You should use this function with the FormGetInst() function.
Syntax
hField:
The field handle of the field currently selected.
Return Value
FormGetInst
Example
520
FormDestroy
Destroys a form, that is removes it from the screen. Use this function (from an event) to close a form.
Syntax
FormDestroy(hForm) hForm:
The form handle, returned from the FormNew() function. The form handle identifies the table where all data on the associated form is stored.
Return Value
FormNew
Example
/* Display message to the operator. If after 10 seconds the operator has not selected OK, then destroy the form. */ hForm=FormNew("Hello",4,20,0); FormPrompt(1,1,"Something bad has happened"); FormButton(5,2,"OK",0,1); FormRead(1); ! Wait 10 seconds. Sleep(10); IF FormActive(hForm) THEN ! Destroy form. FormDestroy(hForm); END
FormEdit
Adds an edit field to the current form. You should call this function only after the FormNew() function and before the FormRead() function. A user input/edit box is added to the form at the specified column and row position. The operator can enter or edit the text in the edit box. This text is then passed to this function as Text.
Syntax
521
The number of the column in which the edit field will be placed. Enter a number from 0 (column 1) to the form width - 1. For example, to place the edit field in column 8, enter 7.
Row:
The number of the row in which the edit field will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the edit field in row 6, enter 5.
Text:
The text in the edit field. Text initially contains the default text (if any) for the operator to edit. When the function closes, this argument is passed back with the operator's input.
Width:
The width of the edit field.
maxTextLength:
This optional parameter specifies the maximum length of input text. The default value is 0 meaning the string can have the maximum length allowed in the system (Cicode allows strings of 255 characters).
Return Value
FormNew
Example
STRING Recipe; FormNew("Recipe",5,30,0); ! Add edit field, default Recipe to "Jam". Recipe="Jam"; FormEdit(1,2,Recipe,20); ! Read the form. FormRead(0); ! Recipe will now contain the operator-entered data.
FormField
Adds a field control device (such as a button , check box, or edit field) to the current form. You should call this function only after the FormNew() function and before the FormRead() function. This function allows you to specify a control device with more detail than the other field functions.
Syntax 522
Row:
The number of the row in which the control will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the control in row 6, enter 5.
Width:
The width of the control device.
Height:
The height of the control device.
nType:
The type of control device:
0 - None 1 - Edit 2 - Edit Password 3 - Text 4 - Button 5 - OK button 6 - Cancel button 7 - Group box 8 - Radio button 9 - Check box Buffer:
The output buffer for the field string. The default value of the control device is initialized to the value of the buffer. If you specify a Radio button or Check box, you should initialize the buffer to "0" or "1". The result of the field will also be set to "0" or "1".
Label:
The display label for a button, or the default label for an edit field
Fn:
The callback function to call when the button is selected. Set to 0 to call no function. Please be aware that the Fn parameter needs to be of type INT, and the callback function cannot contain a blocking function. For types other than 4,5, and 6, set this argument to 0.
maxTextLength:
523
This optional parameter specifies the maximum length of input text for edit fields (this parameter is ignored for other controls). The default value is 0 meaning the string can have the maximum length allowed in the system (Cicode allows strings of 255 characters).
Return Value
The field handle if the field is successfully added, otherwise it will return -1.
Related Functions
FormNew
Example
! Display a form with check boxes to start !! specific motors. FUNCTION SelectMotor() INT hform; STRING check1 = "0"; STRING check2 = "0"; STRING check3 = "0"; hform = FormNew("Selection Menu", 26, 22, 6); FormField(16, 1, 12, 1, 9, check1, "Primary ", 0); FormField(16, 2, 12, 1, 9, check2, "Secondary", 0); FormField(16, 3, 12, 1, 9, check3, "backup ", 0); FormButton( 9, 20, " &Cancel ", 0, 2); IF FormRead(0) = 0 THEN IF check1 = "1" THEN StartMotor(MOTOR_1); END IF check2 = "1" THEN StartMotor(MOTOR_2); END IF check3 = "1" THEN StartMotor(MOTOR_3); END END END
FormGetCurrInst
Extracts data associated with a field (set by the FormSetInst() function). You should call this function only from within a field callback function. This function is the same as calling the FormCurr() function and then the FormGetInst() function.
Syntax
524
Integer data.
sData:
String data.
Return Value
FormGetData
Gets all data associated with a form and puts it into the output string buffers. Normally the field data is copied to the output string buffers only when the user selects the [OK] button. If you want to use the data while the form is displayed, call this function to get the data. You should call this function only while the form is displayed otherwise an error is returned, for example, from a field callback function.
Syntax
FormGetData(hForm) hForm:
The form handle, returned from the FormNew() function. The form handle identifies the table where all data on the associated form is stored.
Return Value
FormCurr
525
Example
! Field callback to save data. FUNCTION Save() INT hForm,hField; FormCurr(hForm,hField); FormGetData(hForm); ! Access all data. .. END
FormGetInst
Extracts the data associated with a field (set by the FormSetInst() function). You would normally use this function in a field callback function. It allows single callback functions to know that the form and field are associated.
Syntax
hField:
The field handle of the field currently selected.
iData:
Integer data.
sData:
String data.
Return Value
526
INT FUNCTION GetNextRec() INT hDev,hForm,hField; STRING Str; ! Get field data, for example, the hDev value. .. FormCurr(hForm,hField); FormGetInst(hForm,hField,hDev,Str); DevNext(hDev); ! Display new record in form. .. RETURN 0; END
FormGetText
Gets the current text from a form field. You should call this function only while the form is displayed; for example,, from a field callback function.
Syntax
hField:
The field handle of the field currently selected.
Return Value
FormSetText
Example
FUNCTION Search() INT hForm,hField; STRING Recipe; FormCurr(hForm,hField); Recipe=FormGetText(hForm,hField); ! Go and find recipe. ..
527
END
FormGoto
Goes to a specified form. The form is displayed on top of all windows and the keyboard focus is set to this form.
Syntax
FormGoto(hForm) hForm:
The form handle, returned from the FormNew() function. The form handle identifies the table where all data on the associated form is stored.
Return Value
FormNew
Example
FormGoto(hForm);
FormGroupBox
Adds a group box to the current form. A group box is a form control box drawn to the specified size. If the box contains radio buttons, they are grouped together. You should call this function only after the FormNew() function and before the FormRead() function. The group box is added to the form at the specified column and row position with the specified width and height. Use the FormRadioButton() function to add the radio buttons to the box, and call this function between each group of radio buttons.
Syntax
528
The number of the column in which the group box will be placed. Enter a number from 0 (column 1) to the form width - 1. For example, to place the group box in column 8, enter 7.
Row:
The number of the row in which the group box will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the group box in row 6, enter 5.
Width:
The width of the group box, which should be wide enough to display your widest item.
Height:
The height of the group box.
Text:
The text to display as the group box label.
Return Value
The field handle if the group box is successfully added, otherwise -1 is returned.
Related Functions
FormInput
529
Adds a prompt and edit field to the current form. You should call this function only after the FormNew() function and before the FormRead() function. When FormRead() is called, the form will display with the prompt and edit box. The operator's input is passed back as a string (Text).
Syntax
Row:
The number of the row in which the prompt will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the prompt in row 6, enter 5.
Prompt:
The prompt string.
Text:
The output text string containing the operator's input.
Note: Only cicode variables can be used in output parameters, variable or local tags cannot be used and will result in a compiler error if attempted. Width:
The width of the edit field.
maxTextLength:
This optional parameter specifies the maximum length of input text. The default value is 0 meaning the string can have the maximum length allowed in the system (Cicode allows strings of 255 characters).
Return Value
FormNew, FormRead
Example
FormInput(1,2,"Recipe",Recipe,20);
530
FormListAddText
Adds a new text entry to a combo box or a list box while the form is displayed. It only adds the text to the list - it does not select it. Use the FormListSelectText() function to select (highlight) an entry. Call this function only when the form is displayed, for example, from a field callback function.
Syntax
hField:
The field handle of the field currently selected.
Text:
The output text string containing the operator's input.
Return Value
531
FormListBox
Adds a list box to the current form. The list box is a form control that allows the operator to select from a list of items. You should call this function only after the FormNew() function and before the FormRead() function. The list box is added to the form at the specified column and row position with the specified width and height. If more items are placed in the list than the list can display, a scroll bar displays for scrolling to the hidden items. Use the FormAddList() function to add items for display in the list box. If the form is already displayed, you can use the FormListAddText() and FormListSelectText() functions to add (and highlight) text in the list box.
Syntax
Row:
The number of the row in which the list box will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the list box in row 6, enter 5.
Width:
The width of the list box, in characters. Width should be wide enough to display your widest item. Items wider than the list box are clipped.
Height:
The height of the list box, as the number of items that can be seen in the list box without scrolling.
sBuf:
The string buffer in which to store the selected item.
Mode:
The mode in which to create the list box:
0 - Sort the list box elements alphabetically. 1 - Place elements in list box in the order they were added. Mode 0 is the default.
Return Value 532
The field handle if the list box is successfully added, otherwise -1 is returned.
Related Functions
FormListDeleteText
Deletes an existing text entry from a combo box or a list box while the form is displayed. It only deletes the text from the list - it does not change the selection. Call this function only when the form is displayed, for example, from a field callback function.
Syntax
hField:
The field handle of the field currently selected.
Text:
The text to delete.
Return Value
533
Related Functions
FormListSelectText, FormListAddText
Example
/* create a form with a list */ hForm = FormNew("Ingredients", 40, 10, 1); hField = FormListBox(2,2,20,5,sBuf); FormAddList("Flour"); FormAddList("Water"); FormAddList("Salt"); FormAddList("Sugar"); /* Display the form */ FormRead(1); .. /*Remove Sugar from the list */ FormListDeleteText(hForm, hField, "Sugar"); ..
FormListSelectText
Selects (highlights) a text entry in a Combo box or a List box while the form is displayed. The text to be selected needs to exist in the list. (Use the FormListAddText() function to add a text entry to a list.) Call this function only when the form is displayed, for example, from a field callback function.
Syntax
hField:
The field handle of the field currently selected.
Text:
The text to be selected. If this text is not present in the list, then no item will be selected (and this text will not be added).
Return Value
534
FormListAddText, FormSetText
Example
/* Create a form with a list */ hForm = FormNew("Ingredients", 40, 10, 1); hField = FormListBox(2,2,20,5,sBuf); FormAddList("Flour"); FormAddList("Water"); FormAddList("Salt"); FormAddList("Sugar"); /* Display the form */ FormRead(1); .. /*Select Flour */ FormListSelectText(hForm, hField, "Flour");
FormNew
Creates a new data entry form and defines its size and mode. After the form is created, you can add fields, and then display the form. Before you can display a form on the screen, you need to call this function to set the size and mode of the form, and then call the various form field functions, FormInput(), FormButton(), FormEdit() etc to add user input fields to the form. To display the form on the screen (to allow the user to enter data) call the FormRead() function.
Syntax
Width:
The character width of the form (1 to 131).
Height:
The character height of the form (1 to 131).
Mode:
The mode of the form:
535
2 - Fixed pitch font 4 - Static text compression where the vertical spacing is reduced. This can cause formatting errors if buttons are too close, because the vertical spacing will be less than the height of a button. 8 - Keep the form on top of the CitectSCADA window. 16 - The current window cannot be changed or closed until the form is finished or cancelled. 32 - Makes a form with no caption. 128 - The form will not close if the ESC or ENTER key is pressed, unless you specifically define at least one button on the form which acts as an OK or Cancel button. For a form with no buttons, the ENTER key normally closes the form; this mode disables that behavior. 256 Makes a from with no system-menu (mostly appears as a single close button X) .
Multiple modes can be selected by adding them (for example, to use Modes 4 and 2, specify Mode 6).
Return Value
The form handle if the form is created successfully, otherwise -1 is returned. The form handle identifies the table where all data on the associated form is stored.
Related Functions
FormNumPad
Provides a keypad form for the operator to add numeric values. You can customize the standard form as a mathematical keypad, with the +, -, and / operators and the decimal point. For a time keypad, use the AM, PM, and : (hour/minute divider) buttons. You can also include a password edit field.
Syntax
536
Title:
The title to display on the number pad form.
Input:
The existing or default value. This value is returned if the form is cancelled or accepted without changes.
Mode:
The buttons to include on the keypad form. The Mode can be a combination of the following:
0 - Standard keypad 1 - Password edit field 2 - not used 4 - With +/- button 8 - With / button 16 - With . button 32 - With : button 64 - With AM, PM buttons 128 - with Now button 512 - with 1hr, 2hr and 8hr buttons Note: Modes 128 and 512 can not be used together on one FormNumPad.
Multiple modes can be selected by adding them. For example, to include +/- buttons and a . button, specify Mode 20 (16+4).
Return Value
The string value entered by the operator. The IsError() function returns 0 (zero). If the form was cancelled, the value of Input is returned, and the IsError() function returns error number 299.
Example
/* Set defaults first, then four keypad forms to adjust recipe. */ Qty_Flour=FormNumPad("Add Flour", Qty_Flour, 17); Qty_Water=FormNumPad("Add Water", Qty_Water, 17); Qty_Salt=FormNumPad("Add Salt", Qty_Salt, 17); Qty_Sugar=FormNumPad("Add Sugar", Qty_Sugar, 17);
FormOpenFile
537
sTitle:
A title to display at the top of the form.
sFilter:
A file filter list to display in the "List Files of Type" field. The file filter list has the following format: <File Type>|<Filter>| where: File Type is the text that displays in the drop-down box, for example All Files (*.*). Filter is the file type, for example *.CI
Return Value
The name and full path of the selected file (as a string) or an empty string ("") if the Cancel button is selected.
Related Functions
FormSaveAsFile, FormSelectPrinter
Example
// Display the Open File dialog with the following filter list: // All Files (*.*) // Exe Files (*.EXE) // Cicode Files (*.CI) sFilename = FormOpenFile("Open", "*.CI", "All Files (*.*)|*.*|Exe Files (*.EXE)|*.EXE|Cicode Files (*.CI)|*.CI|");
FormPassword
Adds both a password prompt and edit field to the current form. You should call this function only after the FormNew() function and before the FormRead() function. When FormRead() is called, the form will also display the password prompt and edit field.
538
The operator's input is not echoed in the field; a single asterisk (*) is displayed for each character.
Syntax
Row:
The number of the row in which the prompt will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the prompt in row 6, enter 5.
Prompt:
The prompt string.
Password:
The password entered by the operator.
Width:
The width of the edit field.
Return Value
FormEdit
Example
! Add Password input. FormPassword(1,2,"Enter Password",Password,10);
FormPosition
Sets the position of a form on the screen, before it is displayed. You should call this function only after the FormNew() function and before the FormRead() function.
Syntax
FormPosition(X, Y, Mode)
539
X, Y:
The x and y pixel coordinates of the form.
Mode:
Not used, set it to 0.
Return Value
FormNew, FormRead
Example
hForm = FormNew("title", 20, 5, 0); ! display form at x=100, y=50 FormPosition(100, 50, 0);
FormPrompt
Adds a prompt field to the current form. You should call this function only after the FormNew() function and before the FormRead() function.
Syntax
Row:
The number of the row in which the prompt will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the prompt in row 6, enter 5.
Prompt:
The prompt string.
Return Value
540
FormNew, FormRead
Example
FormPrompt(1,2,"Enter Recipe");
FormRadioButton
Adds a radio button to the current form, allowing the operator to make a selection from a multiple choice list. You should call this function only after the FormNew() function and before the FormRead() function. The radio button is added to the form at the specified column and row position. The width of the button will be sized to suit the text. By default, all radio buttons are placed into the one group. If you require separate groups, use this function in conjunction with the FormGroupBox() function.
Syntax
Row:
The number of the row in which the button will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the button in row 6, enter 5.
sText:
The text associated with the radio button.
sBuf:
The string buffer in which to put the state of the radio button. You should initialize this buffer to the state of the button. When the form returns, this buffer will contain either '1' or '0' if the radio button is checked.
Return Value
The field handle if the radio button is successfully added, otherwise -1 is returned.
Related Functions
541
Example
! Create a form, add radio buttons and then display the form. ! The operator may only select one radio button , either Fast, Medium or Slow FUNCTION FnMenu() STRING sFast, sSlow, sMedium; sFast = "1"; sMedium = "0"; sSlow = "0"; FormNew("Speed",20,6,1); FormRadioButton(2 ,2,"Fast", sFast); FormRadioButton(2, 3,"Medium", sMedium); FormRadioButton(2 ,4,"Slow", sSlow); FormRead(0); If sFast = "1" THEN ! do fast stuff ELSE IF sMedium = "1" THEN ! do Medium stuff ELSE IF sSlow = "1" THEN ! do slow stuff END END
FormRead
Displays the current form (created with the FormNew() function), with all the fields that were added (with the form field functions). You can display the form and wait for the user to finish entering data by setting the Mode to 0. This mode is the most commonly used, with [OK] and [Cancel] buttons to either save or discard operator entries and to close the form. To display the form and return before the user has finished, use Mode 1. This mode is used to animate the data on the form or to perform more complex operations. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
FormRead(Mode) Mode:
Mode of the form:
542
FormNew
Example
! Display the form and wait for the user. FormRead(0); ! Display the form and do not wait for the user. FormRead(1); ! While the form is displayed, update the time every second. WHILE FormActive(hForm) DO FormSetText(hForm,hField,Time()); Sleep(1); END
FormSaveAsFile
Displays a File Save As dialog box.
Syntax
sFileName:
The name of the default file to display in the "File Name" field.
sFilter:
A file filter list to display in the "List Files of Type" field. The file filter list has the following format: <File Type>|<Filter>| where: File Type is the text that displays in the drop-down box, for example All Files (*.*). Filter is the file type, for example *.CI
sDefExt:
543
The file extension that will be used as a default when you use the FormSaveAsFile() function. If you do not specify a default extension, files will be saved without an extension.
Return Value
The name and full path of the selected file (as a string) or an empty string ("") if the Cancel button is selected.
Related Functions
FormOpenFile, FormSelectPrinter
Example
// Display the SaveAs dialog with the following filter list: // All Files (*.*) // Exe Files (*.EXE) // Cicode Files (*.CI) sFilename = FormSaveAsFile("Save As", "Alarms", "All Files (*.*)|*.*|Exe Files (*.EXE)|*.EXE|Cicode Files (*.CI)|*.CI|", "ci");
FormSecurePassword
Adds both a password prompt and edit field to the current form. You should call this function only after the FormNew() function and before the FormRead() function. When FormRead() is called, the form will also display the password prompt and edit field. The operator's input is not echoed in the field; a single asterisk (*) is displayed for each character. The function does not return the password as a plain text, it returns an encrypted password string. The user can send this string to the UserLogin or UserVerify functions.
Syntax
Row:
The number of the row in which the prompt will be placed. Enter a number from 0 (row 1) to the form height - 1. For example, to place the prompt in row 6, enter 5.
Prompt:
544
Password:
The encrypted password entered by the operator.
Width:
The width of the edit field.
Return Value
FormSelectPrinter
Displays the Select Printer dialog box.
Syntax
FormSelectPrinter()
Return Value
The name of the selected printer (as a string) or an empty string ("") if the Cancel button is selected.
Related Functions
FormOpenFile, FormSaveAsFile
Example
// Display the Select Printer dialog sPrinter = FormSelectPrinter();
545
FormSetData
Sets all the edit data from the string buffers into the form. You should call this function only while the form is active.
Syntax
FormSetData(hForm) hForm:
The form handle, returned from the FormNew() function. The form handle identifies the table where all data on the associated form is stored.
Return Value
FormGetData
Example
INT FUNCTION MyNextRec() INT hForm,hField; FormCurr(hForm,hField); FormSetData(hForm); RETURN 0; END
FormSetInst
Associates an integer and string value with each field on a form. This data could then be used by a callback function. You can use a single callback function for all fields, and use the data to perform different operations for each field.
Syntax
hField:
The field handle of the field currently selected.
546
iData:
Integer data.
sData:
String data.
Return Value
FormGetInst
Example
! Open recipe database. hDev=DevOpen("Recipe", 0); hForm=FormNew("Recipe",20,5,0); hField=FormButton(5,2,"Next",GetNextRec,0); FormSetInst(hForm,hField,hDev,""); /* The device handle hDev is put into the next button , so when the button is selected it can get hDev and get the next record. */
FormSetText
Sets new field text on a field. This function allows you to change field text while the form is displayed. Call this function only when the form is displayed, for example, from a field callback function. If you are using this function on a Combo box or a List box, it will select the text from the Combo box or List box list. If no text exists in the Combo box or List box list, the function will add it.
Syntax
hField:
547
The field handle of the field currently selected. If the hField is a handle to the secure edit field created with FormSecurePassword, the text in the secure edit field will not be changed. However, when an empty string is passed to FormSetText(), the contents of the secure edit field will be cleared.
Text:
New field text.
Return Value
FormWndHnd
Gets the window handle for the given form. The window handle may be used by 'C' programs and CitectSCADAWnd... functions. You should call this function only after the FormRead() function. The window handle is not the same as the CitectSCADA window number and cannot be used with functions that expect the CitectSCADA window number (the Win... functions).
Syntax
FormWndHnd(hForm) hForm:
The form handle, returned from the FormNew() function. The form handle identifies the table where data on the associated form is stored.
Return Value
548
549
550
FmtClose
Closes a format template. After it is closed, the template cannot be used. Closing the template releases system memory.
Syntax
FmtClose(hFmt) hFmt:
The format template handle, returned from the FmtOpen() function. The handle identifies the table where all data on the associated format template is stored.
Return Value
551
FmtOpen
Example
FmtClose(hFmt);
FmtFieldHnd
Gets the handle of a field in a format template. You can then use the field handle in the FmtGetFieldHnd() and FmtSetFieldHnd() functions. By using a handle, you only need to resolve the field name once and then call other functions as required (resulting in improved performance.)
Syntax
sName:
The field name.
Return Value
The handle of the format template field, or -1 if the field cannot be found.
Related Functions
FmtGetFieldHnd, FmtSetFieldHnd
Example
!Resolve names at startup. hName=FmtFieldHnd(hFmt,"Name"); hDesc=FmtFieldHnd(hFmt,"Desc"); !Set field data. FmtSetFieldHnd(hFmt,hName,"CV101");
552
FmtGetField
Gets field data from a format template. Use this function to extract data after a call to StrToFmt().
Syntax
sName:
The field name.
Return Value
The data (as a string). If the field does not contain any data, an empty string will be returned.
Related Functions
FmtGetFieldCount
Retrieves the number of fields in a format object.
Syntax
FmtGetFieldCount(hFmt) hFmt:
The format template handle, returned from the FmtOpen() function. The handle identifies the table where data on the associated format template is stored.
553
Return Value
FmtGetFieldHnd
Gets field data from a format template. Use this function to extract data after a call to StrToFmt(). This function has the same effect as FmtGetField(), except that you use a field handle instead of the field name.
Syntax
hField:
The field handle.
Return Value
The data (as a string). If the field does not contain any data, an empty string will be returned.
Related Functions
StrToFmt, FmtFieldHnd
Example
StrToFmt(hFmt,"CV101 Raw Coal Conveyor"); hField=FmtFieldHnd(hFmt,"Name"); Str=FmtGetField(hFmt,hField); ! Str will contain "CV101".
FmtGetFieldName
Retrieves the name of a particular field in a format object.
554
Syntax
hField:
The field handle.
Return Value
FmtGetFieldWidth
Retrieves the width of a particular field in a format object.
Syntax
hField:
The field handle.
Return Value
FmtOpen
555
Creates a format template. After you create a template, you can use it for formatting data into strings or extracting data from a string. To format a template, use the same syntax as a device format, that is {<name>[,width[,justification]]}. The maximum number of formats that can be created in a project is 512. If you attempt to create formats in excess of this number, an error code (code 258: CT_ERROR_BUFFER_OVERRUN) will be generated. Note: This function should be concluded with the FmtClose function, otherwise the same error code (code 258: CT_ERROR_BUFFER_OVERRUN) will be generated.
Syntax
Format:
The format of the template, as {<name>[,width[,justification]]}. Not used for alarm format.See Format Templates for more information.
Mode:
The mode of the open:
0 - Open the existing format. 1 - Open a new format. 2 - Open Summary Format from Alarm Category specified by Name. 3 - Open Display Format from Alarm Category specified by Name. 4 Open SOE format from Alarm Category specified by Name
Return Value
FmtClose
Examples
hFmt=FmtOpen("MyFormat","{Name}{Desc,20}",0); FmtSetField(hFmt,"Name", "CV101"); FmtSetField(hFmt,"Desc","Raw Coal Conveyor"); Str =FmtToStr(hFmt); ! Str will contain "CV101 Raw Coal Conveyor". FmtOpen("0", "", 2);
556
! Display Format from Alarm Category 0 FmtOpen("0", "", 3); ! Summary Format from Alarm Category 0.
FmtSetField
Sets data in a field of a format template. After you have set all the fields, you can build the formatted string with the FmtToStr() function.
Syntax
sName:
The name of the format template.
Data:
Field data.
Return Value
FmtGetField, FmtToStr
Example
hFmt=FmtOpen("MyFormat","{Name}{Desc, 20}",0); FmtSetField(hFmt,"Name", "CV101"); FmtSetField(hFmt,"Desc","Raw Coal Conveyor"); Str =FmtToStr(hFmt); ! Str will contain "CV101 Raw Coal Conveyor".
FmtSetFieldHnd
557
The fields, you can build the formatted string with the FmtToStr() function. This function has the same effect as FmtSetField() except that you use a field handle instead of the field name.
Syntax
hField:
The field handle.
Data:
Field data.
Return Value
FmtToStr
Builds a formatted string from the current field data (in a format template).
Syntax
FmtToStr(hFmt) hFmt:
The format template handle, returned from the FmtOpen() function. The handle identifies the table where all data on the associated format template is stored.
Return Value
558
Related Functions
StrToFmt
Example
! Get the formatted string. Str=FmtToStr(hFmt);
559
560
FTPClose
Closes an FTP session. This function can only be used on the Internet Display Client.
Syntax
FTPClose(hndFTP) hndFTP:
The handle of a valid FTP session, as returned by FTPOpen().
Return Value
FTPOpen
Example
INT hFtp; hFtp = FtpOpen("", "", ""); .. FtpClose(hFtp);
561
FTPFileCopy
Copies a file from the FTP server to the Internet Display Client. Before calling this function, you need to call FtpOpen(). This function can only be used on the Internet Display Client.
Syntax
sSrcPath:
The file name and path of the file to be copied from the FTP Server to the Internet Display Client. This can be any FTP server.
sDestPath:
The destination of the copied file (including the name of the file).
Return Values
0 (zero) if successful, otherwise an error is returned. Note: The [Internet]ZipFiles parameter does not apply to files copied to the Internet Display Client using this function.
Related Functions
FTPFileFind
Finds a file on the FTP server that matches a specified search criteria. Before you can call this function, you need to call FTPOpen(). This function can only be used on the Internet Display Client. To find a list of files, you need to first call this function twice: once to find the first file, then again with an empty path to find the remaining files. After the last file is found, an empty string is returned.
562
If the search is for multiple files, FTPFileFindClose needs to be called if the search does not run to completion (for example, you do not run until an empty string is returned).
Syntax
sPath:
The path you want to search for the desired file. Do not use path substitution here. To search for multiple files, the wildcards * and ? may be used to match multiple entries.
nMode:
The type of file to check:
0 - Normal files (includes files with read-only and archived attributes) 1 - Read-only files only 2 - Hidden files only 4 - System files only 16 - Subdirectories only 32 - Archived files only 128 - Files with no attributes only
These numbers can be added together to search for multiple types of files during one search.
Return Value
The full path and filename. If no files are found, an empty string is returned.
Related Functions
FTPFileCopy, FTPOpen
Example
INT hFtp; STRING sFindPath; STRING sPath; sFindPath = "\User\Example\*.RDB"; hFtp = FtpOpen("", "", ""); sPath = FtpFileFind(hFtp, sFindPath); WHILE StrLength(sPath) > +0 DO sPath = FtpFileFind(hFtp, ""); END FtpClose(hFtp);
563
FTPFileFindClose
Closes a find (started with FTPFileFind) that did not run to completion. This function can only be used on the Internet Display Client.
Syntax
FTPFileFindClose(hndFTP) hndFTP
The handle of a valid FTP session, as returned by FTPOpen().
Return Value
FTPFileFind
Example
//Find the first DBF file starting with fred sPath = FileFind("\User\Example\FRED*.DBF", 0); IF (StrLength(sPath) > 0) THEN //Do work here FileFindClose(); END
FTPOpen
Connects to an FTP server. This function can only be used on the Internet Display Client.
Syntax
sUsername:
564
The FTP login username. If you omit both the username and IP address, the CitectSCADA FTP password will be used. If you omit just the username, an anonymous logon will occur.
sPassword:
The FTP server password. If you wish to log on anonymously or you wish to log on to the CitectSCADA FTP server, do not specify a password, here.
Return Value
A handle to the FTP server otherwise -1 if an error occurs (for example, the server cannot be found).
Related Functions
565
566
FuzzyClose
Frees all memory and information for the specified instance. After the fuzzy instance is closed, the handle given in the hFuzzy parameter is no longer valid.
Syntax
FuzzyClose(hFuzzy) hFuzzy:
The fuzzy instance handle (and integer greater than 0).
Return Value
FuzzyOpen
Example
See FuzzyOpen.
567
FuzzyGetCodeValue
Gets a value for the specified input of the specified instance.
Syntax
iIOIndex:
Specifies the variable to receive the value. The I/O-Indices start with 0 and increment by 1 for each variable. To find the correct index for a specific variable, the variables need to be sorted in alphanumerical order, first the inputs and then the outputs.
NoHitFlag:
Variable to receive the new value of the No-hit-flag. The No- hit-flag is TRUE if no rule was active for the variable specified by iIOIndex, otherwise it is FALSE. This needs to be a Cicode variable of INT type - it cannot be a constant or PLC variable tag.
Return Value
The code value if the function was successful, otherwise -1. Use IsError() to find the error number if the function does not succeed.
Related Functions
FuzzyOpen, FuzzySetCodeValue
Example
FuzzyGetShellValue
Gets a value for the specified input of the specified instance. The variables in the instance needs to have the data type REAL (floating point values).
Syntax
568
iIOIndex:
Specifies the variable to receive the value. The I/O-Indices start with 0 and increment by 1 for each variable. To find the correct index for a specific variable, the variables need to be sorted in alphanumerical order, first the inputs and then the outputs.
NoHitFlag:
Variable to receive the new value of the No-hit-flag. The No- hit-flag is TRUE if no rule was active for the variable specified by iIOIndex, otherwise it is FALSE. This needs to be a Cicode variable of INT type - it cannot be a constant or PLC variable tag.
Return Value
The shell value if the function was successful. Use IsError() to find the error number if the function does not succeed.
Related Functions
FuzzyOpen, FuzzySetShellValue
Example
FuzzyOpen
This function loads a *.FTR file, allocates memory and creates a handle for this fuzzy instance. To use the FuzzyTech functions you need to be a registered user of one or more of the following fuzzyTech products: fuzzyTECH Online Edition, fuzzyTECH Precompiler Edition, or fuzzyTECH for Business PlusC. And you need to only use fuzzyTECH to generate the *.FTR file for FTRUN. The application needs to call the FuzzyClose function to delete each fuzzy instance handle returned by the FuzzyOpen function.
Syntax
FuzzyOpen(sFile) sFile:
Specifies the filename of the .FTR file to load.
Return Value
569
The handle to the fuzzy instance, or -1 if the function cannot complete the operation. Use IsError() to find the error number.
Related Functions
FuzzySetCodeValue
Sets a value for the specified input of the specified instance.
Syntax
iIOIndex:
570
Specifies the variable to receive the value. The I/O-Indices start with 0 and increment by 1 for each variable. To find the correct index for a specific variable, the variables need to be sorted in alphanumerical order, first the inputs and then the outputs.
iCodeValue:
The value to be copied to the variable specified by iIOIndex.
Return Value
FuzzyOpen, FuzzyGetCodeValue
Example
FuzzySetShellValue
Sets a value for the specified input of the specified instance.
Syntax
iIOIndex:
Specifies the variable to receive the value. The I/O-Indices start with 0 and increment by 1 for each variable. To find the correct index for a specific variable, the variables need to be sorted in alphanumerical order, first the inputs and then the outputs.
rShellValue:
The value to be copied to the variable specified by iIOIndex.
Return Value
FuzzyOpen, FuzzyGetShellValue
Example
571
FuzzyTrace
Controls the trace process (starting and stopping) of the specified instance.
Syntax
TraceOn:
Specifies whether to start or to stop a trace process for the Fuzzy instanse specified by hFuzzy. If this parameter is TRUE (1), the trace process is started. If this parameter is FALSE (0), the trace process is stopped.
Return Value
FuzzyOpen
Example
572
GrpClose
Closes a group. The group is destroyed and the group handle becomes invalid. You should close a group when it is not in use, to release the associated memory. CitectSCADA closes all groups on shutdown.
Syntax
GrpClose(hGrp) hGrp:
The group handle, returned from the GrpOpen() function. The group handle identifies the table where all data on the associated group is stored.
Return Value
573
GrpOpen
Example
hGrp=GrpOpen("MyGrp",1); .. GrpClose(hGrp);
GrpDelete
Deletes a single element or all elements from a group. You can also delete another group from within the group.
Syntax
Value:
The element to delete from the group, from 0 to 16375.
l l
Set Value to -1 to delete all elements from the group. Set Value to a group handle to delete another group from this group.
Return Value
GrpInsert, GrpOpen
Example
! Delete 10 and 14 from a group. GrpDelete(hGrp,10); GrpDelete(hGrp,14);
574
GrpFirst
Gets the value of the first element in a group. The first element in the group is the element with the lowest value. You can follow this function with a GrpNext() call, to get the value of all the elements in a group.
Syntax
GrpFirst(hGrp) hGrp:
The group handle, returned from the GrpOpen() function. The group handle identifies the table where all data on the associated group is stored.
Return Value
GrpOpen, GrpNext
Example
Value=GrpFirst(hGrp); IF Value<>-1 THEN Prompt("First value is "+Value:###); END
GrpIn
Determines if an element is in a group.
Syntax
Value:
The element to locate, from 0 to 16375.
575
Set Value to a group handle to check if another group exists in the group.
Return Value
GrpInsert
Adds an element (or another group) to a group.
Syntax
Value:
The element to add to the group, from 0 to 16375.
l l
Set Value to -1 to add all elements (0 to 16375) to the group. Set Value to a group handle to insert another group into the group.
Return Value
576
GrpMath
Performs mathematical operations on two groups, and stores the result in another group. You can add the two groups, subtract one from the other, or perform Boolean AND, NOT, and XOR operations on the two groups.
Syntax
hOne:
Number of first group used in the mathematical operation.
hTwo:
Number of the second group used in the mathematical operation.
nType:
Type of mathematical operation:
0 - Add groups one and two. 1 - Subtract group two from group one. 2 - AND groups one and two. 3 - NOT groups one and two. 4 - XOR groups one and two.
Return Value
GrpOpen
Example
hOne=GrpOpen("Plantwide",0); hTwo=GrpOpen("Section1",0); hResult=GrpOpen("Result",0);
577
GrpName
Gets the name of a group from a group handle.
Syntax
GrpName(hGrp) hGrp:
The group handle, returned from the GrpOpen() function. The group handle identifies the table where all data on the associated group is stored.
Return Value
GrpOpen
Example
! Get the current group name. sName=GrpName(hGrp);
GrpNext
Gets the value of the next element in a group. You can get the value of all the elements in a group. Call the GrpFirst() function to get the value of the first element, and then call this function in a loop.
Syntax
Value:
578
Return Value
The value of the next element in a group, or -1 if the end of the group has been found.
Related Functions
GrpFirst
Example
! Count all values in a group. Count=0; Value=GrpFirst(hGrp); WHILE Value<>-1 DO Count=Count+1; Value=GrpNext(hGrp,Value); END Prompt("Number of values in group is "+Count:###);
GrpOpen
Creates a group and returns a group handle, or gets the group handle of an existing group. After you open a group, you can use the group number in functions that use groups, for example, SetArea() and AlarmSetInfo(). You can open a group that is specified in the Groups database. You can also create groups at runtime. When you open a group that is defined in the database, a copy of the group is made the original group is not used. You can therefore change the values in the group without affecting other facilities that use this group.
Syntax
Mode
The mode of the open:
0 - Open an existing group 1 - Create a new group 2 - Attempts to open an existing group. If the group does not exist, it will create it.
579
Return Value
The group handle , or -1 if the group cannot be created or opened. The group handle identifies the table where data on the associated group is stored.
Related Functions
GrpClose
Example
! Open Plantwide group defined in the database. hGrp=GrpOpen("Plantwide",0); ! Set current user area to Plantwide. SetArea(hGrp); GrpClose(hGrp); ! Set area to 1...10, 20 and 25 by creating a new group. hGrp=GrpOpen("MyGrp",1); StrToGrp(hGrp,"1..10,20,25"); SetArea(hGrp); GrpClose(hGrp);
GrpToStr
Converts a group into a string of values separated by " , " and " .. ". You can then display the group on the screen or in a report.
Syntax
GrpToStr(hGrp) hGrp:
The group handle, returned from the GrpOpen() function. The group handle identifies the table where all data on the associated group is stored.
Return Value
GrpOpen, StrToGrp
Example
! Display current areas. hGrp=GetArea();
580
Str=GrpToStr(hGrp); DspStr(21,"WhiteFont",Str);
581
582
Gets information on an I/O Device. Gets statistical information for I/O Devices.
DriverInfo
Provides information about the driver for a specified I/O device. Select the device using the IODevice argument, and the information to be returned using the Type argument. This function can only be used if the I/O Server is on the current machine. When the I/O Server is not in the calling process, this function will become blocking and cannot be called from a foreground task. In this case, the return value will be undefined and a Cicode hardware alarm will be raised.
Syntax
nType:
The type of information returned about the driver. Specify one of the following:
0 - Driver Name 1 - Driver Title 2 - Block constant 3 - Max Retrys 4 - Transmit Delay 5 - Receive Timeout
583
6 - Polltime 7 - Watchtime (milliseconds Note: The DISKDRV driver name is returned as "Disk" instead of "DISKDRV". If the Polltime is set as "Interrupt", the function returns "0". sClusterName:
Specifies the name of the cluster in which the I/O Server resides. This is optional if you have one cluster or are resolving the I/O server via the current cluster context. The argument is enclosed in quotation marks "".
ServerName:
Specifies the name of the the I/O Server. This parameter is only required if you are running more than one I/O server process from the same cluster on the same computer and need to instruct the system which process to redirect to. The argument is enclosed in quotation marks "".
Return Value
The driver information as a string. In the case of an error the return value is an empty string.
Example
// Using the IODevice Number sName = DriverInfo(20, 0); ! Get the name of the driver used with I/O device 20 sName = DriverInfo(2, 1); ! Get the title of the driver used with I/O device 2 // Using the IODevice Name sName = DriverInfo("IODev",3); ! Get the Max Retrys value of the driver used with IODev sName = DriverInfo("IODev1",5); ! Get the Receive Timeout value of the driver used with IODev1
IODeviceControl
Provides control of individual I/O devices. You might need to call this function several times. If you use incompatible values for the various options of this function, you might get unpredictable results. This function can only be used if the I/O Server is on the current machine. When the I/O Server is not in the calling process, this function will become blocking and cannot be called from a foreground task. In this case, the return value will be undefined and a Cicode hardware alarm will be raised.
Syntax
584
nType:
The type of control action:
0 - No longer supported. 1 - Enable/Disable the I/O device on the I/O server. If disabled, attempts to read and write from the I/O device are ignored. (If another I/O device is configured as a standby I/O server, CitectSCADA switches communications to that I/O device.) The I/O server does not attempt to communicate with the I/O device until it is re-enabled. When the I/O device is re-enabled, the I/O server attempts to re-establish communication immediately. Mode 1 can only be called by the I/O Server which is associated with this device. 2 - No longer supported. An invalid argument error is returned if this option is specified. 3 - No longer supported. An invalid argument error is returned if this option is specified. 4 - The data in the associated I/O device cache is flushed. This allows flushing of the data from the I/O device without waiting for the aging time. This is useful when you have long cache time and you want to force a read from the I/O device. The Data value is ignored with this mode. 5 - (For scheduled and remote I/O devices). The I/O device is added to the bottom of the list of I/O devices to be contacted. I/O devices already in the list (already waiting to be contacted) are given priority over this I/O device. 6 - (For scheduled and remote I/O devices). The I/O device is added to the top of the list of I/O devices to be contacted; it is given high priority. If there are already I/O devices at the top of the list with high priority, then this I/O device will be added to the list after them (that is it will be contacted after them). For dial-up remote I/O devices, if the modem is already in use - connected to another I/O device - this I/O device will not be dialled until that connection has been terminated.
585
7 - (For scheduled and remote I/O devices). The I/O device is added to the top of the list of I/O devices to be contacted, and it is given top priority. For dial-up remote I/O devices, if the modem is currently connected to another I/O device, the connection will be cancelled, and the top priority I/O device will be dialled. It will also stay connected until manually disconnected with another call to IODeviceControl(). Note: This mode will not attempt to disconnect any other persistent connections. Persistent connections can only be disconnected using mode 8. 8 - (For scheduled and remote I/O devices). Disconnect an I/O device. Current requests will be completed before the I/O device is disconnected. 9 - (For scheduled I/O devices). The communication schedule for the I/O device is disabled. This is to minimize the likelihood that the I/O device will be contacted when its scheduled dial-time occurs. 10 - (For scheduled I/O devices). Puts the I/O device into Write On Request mode. That is, as soon as a write request is made, the I/O device will be added to the list of I/O devices to be contacted. It is given priority over existing read requests, but not over existing write requests. In this situation, there will be a delay while the I/O device is contacted. Do not mistake this pause for inactivity (for example, do not continually execute a command during this delay). 11 - Change the I/O device cache timeout. If the I/O Server is restarted, the cache timeout will return to its original value. (For scheduled I/O devices, this value can be checked using the Kernel Page Unit command. For all other I/O devices, this value is configured in the Cache Time field at the I/O Devices Properties form.) 12 - The time of day at which to add the I/O device to the list of I/O devices to be contacted. Set the time in Data in seconds from midnight (for example, specify 6 p.m. as 18 * 60 * 60). Use Type 12 to specify a one-timecommunication. 13 - The communication period (the time between successive communication attempts). The value you specify represents different periods, depending on what type of schedule you are using (that is daily, weekly, monthly, or yearly. This is set using Type 15.). You can choose to specify the communication period either in seconds from midnight, day of week (0 to 6, Sunday = 0), month (1 to 12), or year. Enter the value in Data. For example, if your schedule is weekly, and you set Data = 3, you are specifying each Wednesday. If your schedule is monthly, Data = 3 indicates March. For daily communication, set the period in Data in seconds from midnight; for example, set Data to 6 * 60 * 60 to contact the I/O device every 6 hours.
586
14 - The time at which the I/O Server will first attempt to communicate with the I/O device. Set the time in Data in seconds from midnight, for example, to synchronize at 10a.m., set Data to 10 * 60 * 60. 15 - Type of schedule. Set Data to one of the following: l 1 - Daily l 2 - Weekly l 3 - Monthly l 4 - Yearly 16 - (For remote I/O devices) Read all tags from the I/O device. Data is unused set it to 0 (zero). 18 - Set Control Inhibit (Control Mode) for all tags of the I/O device. Data:
Data for the control operation*:
1:
l l
Disable the I/O device (Disable Write On Request mode for Type 10) Set Control Inhibit to ON (mode for type 18) Enable the I/O device (Enable Write On Request mode for Type 10) or the I/O device name (for Type 2 or 3). Set Control Inhibit to OFF (mode for type 18)
0:
l
sClusterName:
Specifies the name of the cluster in which the I/O Server resides. This is optional if you have one cluster or are resolving the I/O server via the current cluster context. The argument is enclosed in quotation marks "".
ServerName:
Specifies the name of the the I/O Server. This parameter is only required if you are running more than one I/O server process from the same cluster on the same computer and need to instruct the system which process to redirect to. The argument is enclosed in quotation marks "".
Return Value
587
IODeviceInfo
Gets information about a specified I/O device. Apart from when Type is set to 3 or 17, this function can only be used if the I/O Server is on the current machine, otherwise the function will not succeed and will return empty string. When the I/O Server is not in the calling process, this function will become blocking and cannot be called from a foreground task. In this case, the return value will be undefined and a Cicode hardware alarm will be raised. If both the primary and standby I/O devices are on the same server and they have the same I/O device name, you can get information about them individually by specifying the following:
IODeviceInfo("PLC1,P",1); // for the Primary IODeviceInfo("PLC1,S",1); // for the Standby
where P represents the primary I/O device and S the standby I/O device. If you have more than one standby device on the same server, there is currently no way of using this function for other than the first standby device. Note: When the I/O server is not in the calling process, this function could become a blocking function if the information required by this function is on an I/O server (except types 3 and 17, which are normally non-blocking). If this is the case, this function cannot be called from a foreground task (such as a graphics page) or an expression. Otherwise the return value will be undefined and a Cicode hardware alarm raised.
Syntax
nType:
The type of information:
0 - Name of I/O device 1 - Protocol of I/O device 2 - Protocol address 3 - Client I/O device state
588
l l
l l l
1 = Running - Client is either talking to an online I/O device or talking to a scheduled device that is not currently connected but has a valid cache 2 = Standby - Client is talking to an online standby I/O device 4 = Starting - Client is talking to an I/O device that is attempting to come online 8 = Stopping - Client is talking to an I/O device that is in the process of stopping 16 = Offline - Client is pointing to an I/O device that is currently offline 32 = Disabled - Client is pointing to a device that is disabled 66 = Standby write - client is talking to an I/O device configured as a standby write device
4 - Current generic error number (decimal) 5 - Current driver error number (decimal) 6 - Disabled flag 7 - Statistics, minimum read time 8 - Statistics, maximum read time 9 - Statistics, average read time 10 - I/O server I/O device state l 1 = Running - I/O device for this I/O server is online or a scheduled device that is not currently connected but has a valid cache l 2 = Standby - I/O device for this I/O server is online and a standby unit l 4 = Starting - I/O device for this I/O server is attempting to come online. Starting may be combined with either Offline or Remote such as: 20 = Starting(4) + Offline(16) or 132 = Starting(4) + Remote(128). l 8 = Stopping - I/O device for this I/O server is currently in the process of stopping l 16 = Offline (only valid on an I/O server) - I/O device for this I/O server is currently offline l 32 = Disabled - I/O device for this I/O server is disabled l 66 = Standby write - I/O device for this I/O server is configured as a standby write device l 128 = Remote (returned in combination with another value specified above - see Starting - I/O device for this I/O server is a scheduled device but not currently connected 11 - Unit number 12 - Configured I/O server name 13 - Configured Port name 14 - Configured startup mode 15 - Configured comment 16 - The primary I/O server name the client uses to communicate to this device
589
17 - The I/O Server the client is using to communicate to this device. Will be Standby if the Primary is down. 18 - State of the remote unit: l 0 = Remote unit is disconnected and OK l 1 = Remote unit is connected and online l 2 = Remote unit is in the dial queue l 16 = Remote unit is disconnected and offline l 32 = Remote unit is disconnected and disabled This mode causes redirection to the I/O server if running in separate processes. 19 - Number of successful attempts to communicate with the scheduled I/O device. 20 - Number of unsuccessful attempts to communicate with the scheduled I/O device. 21 - Write mode: Write On Request, and normal (as per schedule defined in the Express Communications Wizard). 22 - Number of queued read requests for the scheduled I/O device. (This mode causes redirection to the I/O server if running in separate processes.) 23 - Number of queued write requests for the scheduled I/O device. (This mode causes redirection to the I/O server if running in separate processes.) 24 - The cache timeout (in milliseconds). 26 - The name of the line device (for example, modem) you are using to connect to the I/O device. (This mode causes redirection to the I/O server if running in separate processes.) 27 - The call_status of a currently connected remote I/O device.
DIALCALLSTATE_UNAVAIL DIALCALLSTATE_IDLE DIALCALLSTATE_OFFERING DIALCALLSTATE_ACCEPTED DIALCALLSTATE_DIALTONE DIALCALLSTATE_DIALING DIALCALLSTATE_RINGBACK DIALCALLSTATE_BUSY 0 1 2 3 4 5 6 7
590
DIALCALLSTATE_SPECIALINFO DIALCALLSTATE_CONNECTED DIALCALLSTATE_PROCEEDING DIALCALLSTATE_ONHOLD DIALCALLSTATE_CONFERENCED DIALCALLSTATE_ONHOLDPENDCONF DIALCALLSTATE_ONHOLDPENDTRANSFER DIALCALLSTATE_DISCONNECTED_NORMAL DIALCALLSTATE_DISCONNECTED_LINELOST DIALCALLSTATE_DISCONNECTED_UNKNOWN DIALCALLSTATE_DISCONNECTED_REJECT DIALCALLSTATE_DISCONNECTED_PICKUP DIALCALLSTATE_DISCONNECTED_FORWARDED DIALCALLSTATE_DISCONNECTED_BUSY DIALCALLSTATE_DISCONNECTED_NOANSWER DIALCALLSTATE_DISCONNECTED_BADADDRESS DIALCALLSTATE_DISCONNECTED_UNREACHABLE DIALCALLSTATE_DISCONNECTED_CONGESTION DIALCALLSTATE_DISCONNECTED_INCOMPATIBLE DIALCALLSTATE_DISCONNECTED_UNAVAIL DIALCALLSTATE_DISCONNECTED_NODIALTONE DIALCALLSTATE_DISCONNECTED_NUMBERCHANGED
8 9 10 11 12 13 14 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
591
31 32 33 34 35 36 48
(This mode causes redirection to the I/O server if running in separate processes.) 28 - The call rate (in bits per second) which may be the DTE or DCE connection speed depending on the server modem settings. (This mode causes redirection to the I/O server if running in separate processes.) 30 - The last time an I/O device from the remote I/O device redundant group was connected (primary or any standbys). 31 -The state of the remote I/O device redundant group: l 0 = not connected (none of the redundant I/O devices connected) l 1 =connected (one of the redundant I/O devices is connected) 32 - The next time the specified I/O device is scheduled to connect (unless a higher priority I/O device comes online). sClusterName:
Specifies the name of the cluster in which the I/O Server resides. This is optional if you have one cluster or are resolving the I/O server via the current cluster context. The argument is enclosed in quotation marks "".
ServerName:
Specifies the name of the I/O Server. This parameter is only required if you are running more than one I/O server process from the same cluster on the same computer and need to instruct the system which process to redirect to. The argument is enclosed in quotation marks "".
Return Value
592
Example
//Using sName = sName = //Using sName = sName = the IODevice Number IODeviceInfo(20, 0); ! Get the name of I/O device 20 IODeviceInfo(2, 1); ! Get the protocol of I/O device 2 the IODevice Name IODeviceInfo("IODev",10); ! Get the I/O Server State IODeviceInfo("IODev1",3); ! Get the State of IODev1
IODeviceStats
Gets statistical information for all I/O devices, and displays the information in a dialog box. Note: In a multi-process environment this function needs to be called from the IOServer process or redirected there using MsgRPC. If this isn't done, some of the information on the IODeviceStats form will not be displayed correctly.
Syntax
IODeviceStats()
Return Value
IODeviceInfo
Example
IODeviceStats(); ! display all I/O device information
593
594
Moves the command cursor left. Moves the command cursor in the requested direction. Gets a key from the key command line without removing the key. Puts a raw key code into the key command line. Puts a string into the key command line. Replays the last key sequence. Replays and executes the last key sequence. Moves the command cursor right. Moves the command cursor to a specified AN.
Adds a keyboard sequence at runtime. Moves the command cursor up. Sends a keystroke (or string of keystrokes) to a window.
595
KeyAllowCursor
Allows (or disallows) the command cursor to move to the specified AN or to all ANs. The command cursor normally moves only to ANs that have commands defined.
Syntax
State:
Allow state:
0 - Do not allow the cursor to move to this AN. 1 - Allow the cursor to move to this AN.
Return Value
KeyGetCursor
Example
KeyAllowCursor(20,1); ! Allows the command cursor to move to AN20. KeyAllowCursor(0,1); ! Allows the command cursor to move to any AN.
KeyBs
Removes the last key from the key command line. If the key command line is empty, this function will not perform any action. You should call this function using a "Hot Key" command (as shown in the example below), otherwise the backspace character is placed into the key command line and the command does not execute. A "Hot Key" command is a command that executes as soon as it is placed into the key command line.
Syntax 596
KeyBs()
Return Value
KeyGet
Example
System Keyboard Key Sequence Command Comment *Bs KeyBs() Define a backspace Hot Key
KeyDown
Moves the command cursor down the page to the closest AN. If an AN-Down cursor override is specified (in the Page Keyboard database) for the graphics page, the command cursor moves to that AN instead.
Syntax
KeyDown()
Return Value
597
KeyGet
Gets the last key code from the key command line. The key is removed from the command line. Use this function to process the operator key commands directly. You should call this function from the keyboard event function.
Syntax
KeyGet()
Return Value
The last key code from the key command line. If the key command line is empty, 0 (zero) is returned.
Related Functions
KeyPeek, KeyPut
Example
/* If "START A B C" is in the key command line and "START" is the Key Name for the "F1" key: */ Variable=KeyGet(); ! Sets Variable to 67 (ASCII "C"). Variable=KeyGet(); ! Sets Variable to 66 (ASCII "B"). Variable=KeyGet(); ! Sets Variable to 65 (ASCII "A"). Variable=KeyGet(); ! Sets Variable to 170 (the ASCII value of the F1 key (Key_F1)). Variable=KeyGet(); ! Sets Variable to 0.
KeyGetCursor
598
Gets the AN at the position of the command cursor. If this function is called from within a larger piece of code, the cursor may have moved away from where it was originally positioned when the larger piece of code was started. If you are using groups, and there are currently two command cursors, the AN for the innermost will be returned. For example, if there is a cursor for a group as well as a cursor for one of its objects, the AN for the object will be returned.
Syntax
KeyGetCursor()
Return Value
KeySetCursor
Example
! If the command cursor is on AN25: AN=KeyGetCursor(); ! Sets AN to 25.
KeyLeft
Moves the command cursor left (across the page) to the closest AN. If an AN-Left cursor override is specified (in the Page Keyboard database) for the graphics page, the command cursor moves to that AN instead.
Syntax
KeyLeft()
Return Value
See KeyRight
599
KeyMove
Moves the command cursor in a specified direction to the closest AN. If an AN cursor override is specified, the command cursor moves to that AN directly. This function is equivalent to the KeyUp(), KeyDown(), KeyLeft(), and KeyRight() functions.
Syntax
KeyMove(Direction) Direction:
Direction to move the cursor:
KeyPeek
Gets the ascii key code from the key command line (at a specified offset), without removing the key from the key command line. An offset of 0 returns the key code from the last position in the key command line.
Syntax
KeyPeek(Offset) Offset:
600
Return Value
KeyGet
Example
! If "A B C" is in the key command line: Variable=KeyPeek(0); ! Sets Variable to 67 (ASCII "C") Variable=KeyPeek(2); ! Sets Variable to 65 (ASCII "A")
KeyPut
Puts an ASCII key code or Keyboard key code into the last position of the key command line. If this key completes any command, that command will execute.
Syntax
KeyPut(KeyCode) KeyCode:
The key code to put into the key command line.
Return Value
KeyGet
Example
KeyPut(Key_F1); /* Puts "Key_F1" (the Key Code for the "F1" key) into the last position of the key command line. If "START" is the Key Name for the "F1" key, this would be equivalent to KeyPutStr("START"). In either case, "START" will display on the key command line. */ KeyPut(StrToChar("A"));
601
/* Puts the Key Code for the "A" key into the last position of the key command line. */
KeyPutStr
Puts a string at the end of the key command line. The string can contain either key names or data characters. If this string completes any command, that command will execute.
Syntax
KeyPutStr(String) String:
The string to put into the key command line.
Return Value
KeyPut
Example
KeyPutStr("START ABC"); ! Places "START ABC" at the end of the key command line. KeyPutStr("TURN PUMP 1 ON"); ! Places "TURN PUMP 1 ON" at the end of the key command line.
KeyReplay
Replays the last key sequence (except for the last key, which would execute the command). This function is useful when a command is to be repeated. To call this function from the keyboard, use a Hot Key "*" (asterisk) command, otherwise the KeyReplay() function itself is replayed.
Syntax
KeyReplay(sub) sub:
602
Return Value
KeyReplayAll
Example
KeyReplayAll
Replays the last key sequence and executes the command. To call this function from the keyboard, use a Hot Key " * " (asterisk) command, otherwise the KeyReplayAll() function itself is replayed.
Syntax
KeyReplayAll()
Return Value
KeyReplay
Example
KeyRight
603
Moves the command cursor right (across the page) to the closest AN. If an AN-Right cursor override is specified (in the Page Keyboard database) for the graphics page, the command cursor moves to that AN instead.
Syntax
KeyRight()
Return Value
KeySetCursor
Displays the command cursor at a specified AN. A keyboard command needs to exist, or you need to first call the KeyAllowCursor() function (at the AN) to allow the cursor to move to the AN. If the AN does not exist, or if a command does not exist at that AN, or if KeyAllowCursor() has not been called, the command cursor does not move.
Syntax
KeySetCursor(nAN) nAN:
The AN where the command cursor will be displayed.
Return Value
If the AN does not exist, or if a command does not exist at that AN, or if KeyAllowCursor() has not been called, the return value is 1. Otherwise, the function will return 0.
Related Functions
KeyGetCursor, KeyAllowCursor
Example
604
KeySetSeq
Adds a keyboard sequence to the current page at runtime. The key sequence is only added to the current window. When the page is closed, the keyboard sequence is deleted.
Syntax
nAN:
The AN where the keyboard sequence will apply. If you set AN to 0 (zero), the keyboard sequence will apply to all ANs on the page.
Fn:
The function to call when the keyboard sequence matches. This function needs to be a callback function.
Return Value
DspButton, DspButtonFn
Example
/* Set the key sequence and call the "Callback" function when the sequence is found. */ KeySetSeq("F2 ### Enter", 0, Callback); ! This function is called when the key sequence is found. INT FUNCTION CallBack() INT Value; ! Get user data. Value=Arg1; .. RETURN 0; END
605
KeyUp
Moves the command cursor up the page to the closest AN. If an AN-Up cursor override is specified (in the Page Keyboard database) for the graphics page, the command cursor moves to that AN.
Syntax
KeyUp()
Return Value
SendKeys
Sends a keystroke (or string of keystrokes) to a window as if they were typed on the keyboard. The window receives input focus and is brought to the foreground.
Syntax
sKeys:
The key (or keys) to send to sTitle.
l
To send a single keyboard character, use the character itself. For example, to send the letter a, set sKeys to a. To send more than one character, append each additional character to the string. For example, to send the letters a, b, and c, set sKeys to abc. The plus (+), caret (^), and percent sign (%) have special meanings. To send one of these special characters, enclose the character with braces. For example, to send the plus sign, use {+}. To send a { character or a } character, use {{} and {}}, respectively.
606
To specify characters that are not displayed when you press a key (such as Enter or Tab) and other keys that represent actions rather than characters, use the codes shown below:
Code {backspace} or {bs} or{bksp} {break} {capslock} {clear} {delete} or {del} {end} {enter} or ~ {escape} or {esc} {help} {home} {insert} {numlock} {pgdn} {pgup} {prtsc} {scrolllock} {tab} {up} {down} {right}
Key Backspace Break Caps Lock Clear Del End Enter Esc Help Home Insert Num Lock Page Down Page Up Print Screen Scroll Lock Tab Up Arrow Down Arrow Right Arrow
607
{left} {f1} {f2} {f3} {f4} {f5} {f6} {f7} {f8} {f9} {f10} {f11} {f12}
To specify keys combined with any combination of Shift, Ctrl, and Alt, precede the regular key code with one or more of these codes:
Key Shift Ctrl Alt Code + ^ %
To specify that Shift , Ctrl , and/or Alt are held down while several keys are pressed, enclose the keys in parentheses. For example, to hold down the Shift key while sending E then C, use +(EC). To hold down Shift while sending E, followed by C without the Shift key, use +EC. To specify repeating keys, use the form {key number}. For example, {left 42} means send the left arrow key 42 times. Be aware that you need to leave a space between the key and number.
Return Value
608
WndFind
Example
SendKeys("Untitled - Notepad", "abc"); // Send the key sequence "abc" to the Notepad application
609
610
MailError
Gets the last mail error code. The error code is extracted from the MAPI mail system, and explains what caused the MAPI error.
Syntax
MailError()
Return Value
611
MailLogoff
Logs off from the mail system. You should log off the mail system when all mail operations are complete. CitectSCADA automatically logs off the mail system on shutdown.
Syntax
MailLogoff()
Return Value
MailLogon
Logs on to the mail system. You need to call this function before any other mail function. The mail system uses the MAPI standard interface, so you can use any mail system that supports this standard. You should log on to the mail system when CitectSCADA starts, and log off only at shutdown. (The logon procedure can take a few seconds to complete.) You can only log on as one user at a time for each computer, so you can only read mail for this user name.
Syntax
sPassword:
The password of the mail user.
612
iMode:
The mode of the logon:
0 - Normal logon. 2 - Get unique logon, do not share existing mail client logon.
Return Value
MailRead
Reads a standard mail message. The mail message can contain text, an attached file, or both. Before you can use this function, you need to use the MailLogon() function to log on to the mail system. You can only read mail sent to the user name specified in the MailLogon() function.
Syntax
sSubject:
The subject text of the mail message.
sNote:
613
The note section of the message. If the message is longer than 255 characters, CitectSCADA will save the message in a file and return the file name in sNote. Use the file functions to read the message. The name of the file will be in the form CTxxxxx where x is a unique number. You need to delete the file after you have finished with the mail message.
sFileName:
The name of any attached file. If there is no attached file in the message, specify sFileName as an empty string "".
iMode:
The mode of the read:
0 - Read a message. If no message is available, wait for a message. 1 - Read a message. If no message is available, return with an error code.
Return Value
MailSend
Sends a standard mail message. The mail message can contain text, an attached file, or both. Before you can use this function, you need to use the MailLogon() function to log on to the mail system. You can only send mail from the user name specified in the MailLogon () function. You can send mail to any mail user or to another Citect client.
Syntax
614
sSubject:
The subject text of the mail message (a short description of what the message is about).
sNote:
The note section of the message (the main section of the message text). You can enter up to 255 characters, or a file name for longer messages. If you enter a file name, set iMode to 1.
sFileName:
The name of any attached file. If there is no attached file in the message, set sFileName to an empty string "".
iMode:
The mode of the send:
0 - Normal mail message. 1 - The sNote argument is the name of a text file to send as the note.
Return Value
615
616
617
Converts an angle from radians to degrees. Gets a random number. Rounds a number. Gets the sign of a number. Gets the sine of an angle. Gets the square root of a number. Gets the tangent of an angle.
Abs
Calculates the absolute (positive) value of a number. The absolute value of a number is the number without its sign.
Syntax
Abs(Number) Number:
Any number.
Return Value
Sign
Example
Variable=Abs(-67); ! Sets Variable to 67. Variable=Abs(67); ! Sets Variable to 67.
618
ArcCos
Calculates the arccosine of an angle.
Syntax
ArcCos(Number) Number
The cosine of the angle.
Return Value
Cos
Example
Variable=ArcCos(0.4); ! Sets Variable to 1.1592...
ArcSin
Calculates the arcsine of an angle.
Syntax
ArcSin(Number) Number:
The sine of the angle.
Return Value
Sin
Example
Variable=ArcSin(1);
619
ArcTan
Calculates the arctangent of an angle.
Syntax
ArcTan(Number) Number:
The tangent of the angle.
Return Value
Tan
Example
Variable=ArcTan(0.4); ! Sets Variable to 0.3805...
Cos
Calculates the trigonometric cosine of an angle.
Syntax
Cos(Angle) Angle:
Any angle (in radians).
Return Value
620
ArcCos
Example
Variable=Cos(0.7854); ! Sets Variable to 0.7071...
DegToRad
Converts an angle from degrees to radians.
Syntax
DegToRad(Angle) Angle:
Any angle (in degrees).
Return Value
RadToDeg
Example
Variable=DegToRad(180); ! Sets Variable to 3.1415... (pi).
Exp
Calculates the exponential of a number (natural logarithm base e).
Syntax
Exp(Number) Number:
Any number.
Return Value
621
Log
Example
Variable=Exp(1); ! Sets Variable to 2.7182...
Fact
Calculates the factorial of a number.
Syntax
Fact(Number) Number:
Any number.
Return Value
HighByte
Gets the high-order byte of a two-byte integer.
Syntax
HighByte(TwoByteInteger) TwoByteInteger:
A two-byte integer.
Return Value
622
HighWord
Gets the high-order word of a four-byte integer.
Syntax
HighWord(FourByteInteger) FourByteInteger:
A four-byte integer.
Return Value
Ln
Calculates the natural (base e) logarithm of a number.
Syntax
Ln(Number) Number:
623
Any number.
Return Value
Log
Example
Variable=Ln(2); ! Sets Variable to 0.6931...
Log
Calculates the base 10 logarithm of a number.
Syntax
Log(Number) Number:
Any number.
Return Value
Ln
Example
Variable=Log(100); ! Sets Variable to 2 (that is 100=10 to the power of 2).
LowByte
Gets the low-order byte of a two-byte integer.
Syntax
624
LowByte(TwoByteInteger) TwoByteInteger:
A two-byte integer.
Return Value
LowWord
Gets the low-order word of a four-byte integer.
Syntax
LowWord(FourByteInteger) FourByteInteger:
A four-byte integer.
Return Value
Max
625
Number2:
The second number.
Return Value
Min
Example
Variable=Max(24,12); ! Sets Variable to 24.
Min
Returns the lower of two numbers.
Syntax
Number2:
The second number.
Return Value
Max
626
Example
Variable=Min(24,12); ! Sets Variable to 12.
Pi
Gets the value of pi (the ratio of the circumference of a circle to its diameter).
Syntax
Pi()
Return Value
Pow
Calculates x to the power of y.
Syntax
Pow(X, Y) X:
The base number.
Y:
The exponent.
Return Value
X to the power of Y.
Related Functions
Exp
627
Example
Variable=Pow(5,3); ! Sets Variable to 125.
RadToDeg
Converts an angle from radians to degrees.
Syntax
RadToDeg(Angle) Angle:
Any angle (in degrees).
Return Value
DegToRad
Example
Variable=RadToDeg(Pi()); ! Sets Variable to 180.
Rand
Generates a random number between 0 and a specified maximum number less one. The Rand function is zero-based, so the resultant number generated will range from zero to one less than the number provided in the Maximum argument.
Syntax
Rand(Maximum) Maximum:
The maximum number. This number needs to be between 2 and 32767 (inclusive).
628
Return Value
Round
Rounds a number to a specified number of decimal places.
Syntax
Places:
The number of decimal places.
Return Value
Sign
Gets the sign of a number.
Syntax
629
Sign(Number) Number:
Any number.
Return Value
Abs
Example
Variable=Sign(100); ! Sets Variable to 1. Variable=Sign(-300); ! Sets Variable to -1. Variable=Sign(0); ! Sets Variable to 0.
Sin
Calculates the trigonometric sine of an angle.
Syntax
Sin(Angle) Angle:
Any angle (in radians).
Return Value
ArcSin
Example
Variable=Sin(0.7854); ! Sets Variable to 0.7071...
630
Sqrt
Gets the square root of a number.
Syntax
Sqrt(Number) Number:
Any positive number.
Return Value
Pow
Example
Variable=Sqrt(4); ! Sets Variable to 2.
Tan
Calculates the trigonometric tangent of an angle.
Syntax
Tan(Angle) Angle:
Any angle (in degrees).
Return Value
ArcTan
Example
631
632
MenuGetFirstChild MenuGetGenericNode
MenuGetNextChild MenuGetPageNode
MenuNodeIsDisabled
MenuNodeIsHidden
MenuNodeRemove MenuNodeRunCommand
633
Set the item value of the specified menu node. Reload base Menu Configuration from the compiled database.
MenuGetChild
Returns the handle to the child node with the specified name.
Syntax
sName:
The name of the child Menu node requested.
Return Value
The handle of the child node with the requested name, or -1 if unsuccessful.
Related Functions
MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuGetFirstChild
Returns the handle to the first child of a menu node.
634
Syntax
MenuGetFirstChild(hNode) hNode:
The handle to the parent node in the menu tree.
Return Value
MenuGetChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuGetGenericNode
Returns the handle to the base node of the menu tree for the generic pages. Its child nodes represent the menu items that do not have a page specified in the menu configuration database.
Syntax
MenuGetGenericNode([bCreate]) bCreate:
Determines if the node should be created if it does not exist. Defaults to 0, do not create.
Return Value
The handle to the base node of the menu tree, or -1 if it cannot find the node.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload
635
MenuGetNextChild
Returns the next node that shares the same parent.
Syntax
MenuGetNextChild(hChild) hChild:
Handle to the current node in the menu tree
Return Value
The handle to next node that shares the same parent, or -1 if unsuccessful.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuGetPageNode
Returns the handle to the base node of the menu tree of a specified page. Its child nodes represent the menu items that have the particular page specified in the menu configuration database.
Syntax
bCreate:
Determines if the node should be created if it does not exist. Defaults to 0, do not create.
Return Value
636
The handle to the base node of the menu tree, or -1 if no handle returned to the base node of menu.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuGetParent
Returns the parent node of the menu item.
Syntax
MenuGetParent(hNode) hNode:
Handle to the current node in the menu tree.
Return Value
The handle to parent menu node of the given menu item, or -1 if unsuccessful.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuGetPrevChild
Returns the previous node that shares the same parent.
Syntax
MenuGetPrevChild(hChild)
637
hChild:
Handle to the current node in the menu tree.
Return Value
The handle to previous node that shares the same parent, or -1 if unsuccessful.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuGetWindowNode
Returns the handle to the root node for a given window. This menu node is dynamically created for each page instance. Its child nodes represent the menu items for the generic pages merged with the ones specific to this page.
Syntax
MenuGetWindowNode(hWin) hWin:
The window number of the desired window. You can call WinNumber() to get the window number of the page that calls this Cicode function.
Return Value
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
638
MenuNodeAddChild
Dynamically add a new item to the menu at runtime. Be reminded that the changes are for the current session only and will not be persisted to the _Pagemen.RDB file. Be reminded that changes made to the menu tree will not be persisted back to the menu configuration database.
Syntax
sName:
The string label of the new menu item.
sCommandName:
Specifies the name of the Cicode function to run.
sCommandArgs:
Specifies the parameters of the Cicode function to run.
sSymbol:
The symbol to be associated with the menu item.
iOrder:
The relative position in the menu for new item.
Return Value
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions Introduction
639
Menu Functions
MenuNodeGetProperty
Return the item value of the specified menu node.
Syntax
iField:
Field for which you want the value:
0 - Name of Menu Item. 1 - Icon symbol to be associated with the menu item 2 - Privilege level required to run the command, otherwise the menu item is disabled. 3 - Area level required to run the command, otherwise the menu item is disabled. 4 - Disabled Style. Allows different display style for a disabled menu item. 5 - Checked setting. Whether the menu item will display a checkbox next to the label. 6 - Width. Specifies the menu item width in pixels. 7 - Comment
Return Value
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuNodeHasCommand
Checks whether the menu node has a valid cicode command associated with it.
Syntax 640
MenuNodeHasCommand(hNode) hNode:
Handle of node to check.
Return Value
1 if the menu node has a valid cicode command, 0 if the menu node has no cicode command.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuNodeIsDisabled
Checks whether the menu node is disabled by evaluating its DisabledWhen cicode expression.
Syntax
MenuNodeIsDisabled(hNode) hNode:
Handle of node to check.
Return Value
1 if menu node DisabledWhen expression evaluates to true, 0 if menu node DisabledWhen expression evaluates to false.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload
Example
641
INT hNode = MenuNodeFirstChild(hParent); IF (MenuNodeIsDisabled(hNode)) THEN ! set the menu item graphic state to disabled END
MenuNodeIsHidden
Checks whether the menu node is hidden by evaluating its HiddenWhen cicode expression.
Syntax
MenuNodeIsHidden(hNode) hNode:
Handle of node to check.
Return Value
1 if menu node HiddenWhen expression evaluates to true, 0 if menu node HiddenWhen expression evaluates to false.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload
Example
INT hNode = MenuNodeFirstChild(hParent); IF (MenuNodeIsHidden(hNode)) THEN ! set the menu item graphic state to hidden END
MenuNodeRemove
Remove the menu node from the menu tree.
642
Be reminded that changes made to the menu tree will not be persisted back to the menu configuration database.
Syntax
MenuNodeRemove(hNode) hNode:
Handle of node to remove.
Return Value
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions Introduction Menu Functions
MenuNodeRunCommand
Run the associated command for a menu node.
Syntax
MenuNodeRunCommand(hNode) hNode:
Handle of node to run command.
Return Value
No error(0) on success. Bad handle specified (269) if hNode does not refer to a valid node.
Related Functions
643
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload See Also Menu Functions
MenuNodeSetDisabledWhen
Set the DisabledWhen expression for a newly added node. Be aware this function only works for menu nodes added with MenuNodeAddChild(). The DisabledWhen expression may only be set once for a node. Be reminded that changes made to the menu tree will not be persisted back to the menu configuration database.
Syntax
sDisabledWhenName:
Cicode function for DisabledWhen expression. The function needs to return an INT.
sDisabledWhenArgs:
Cicode parameters for DisabledWhen expression. Only supports static arguments.
iDisabledStyle:
Disabled Style. Allows different display styles for a disabled menu item.
Return Value
No Error(0) on success, Bad handle specified (269) if hNode does not refer to a valid node, Invalid argument passed (274) if DisabledWhen Cicode has already been set or is not a valid expression.
Related Functions
644
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetHiddenWhen, MenuNodeSetProperty, MenuReload
Example
INT hNode = MenuNodeAddChild((hParent, "LogIn", "LogIn"); INT Error = MenuNodeSetDisabledWhen(hNode, "UserInfo", "0", 1);
MenuNodeSetHiddenWhen
Set the HiddenWhen expression for a newly added node. Be aware this function only works for menu nodes added with MenuNodeAddChild(). The HiddenWhen expression may only be set once for a node. Be reminded that changes made to the menu tree will not be persisted back to the menu configuration database.
Syntax
sHiddenWhenName:
Cicode function for HiddenWhen expression. The function needs to return an INT.
sHiddenWhenArgs:
Cicode parameters for HiddenWhen expression. Only supports static arguments.
Return Value
No Error (0) on success, Bad handle specified (269) if hNode does not refer to a valid node, or Invalid argument passed (274) if HiddenWhen Cicode has already been set or is not a valid expression.
Related Functions
645
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetProperty, MenuReload
Example
INT hNode = MenuNodeAddChild(hParent, "LogIn", "LogIn"); INT Error = MenuNodeSetHiddenWhen(hNode, "UserInfo", "0");
MenuNodeSetProperty
Set the item value of the specified menu node. Be reminded that changes made to the menu tree will not be persisted back to the menu configuration database.
Syntax
iField:
Field for which you want to set the value:
0 - Name of Menu Item. 1 - Icon symbol to be associated with the menu item 2 - Privilege level required to run the command, otherwise the menu item is disabled. 3 - Area level required to run the command, otherwise the menu item is disabled. 4 - Disabled Style. Allows different display style for a disabled menu item. 5 - Checked setting. Whether the menu item will display a checkbox next to the label. 6 - Width. Specifies the menu item width in pixels. 7 - Comment sValue:
646
Return Value
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuReload See Also Menu Functions Introduction Menu Functions
MenuReload
Reload base Menu Configuration from the compiled database. Be reminded that the menu configuration loaded on the currently displayed page will not change until the page is refreshed. By default, menu configuration is automatically reloaded whenever a page is displayed.
Syntax
MenuReload()
Return Value
None.
Related Functions
MenuGetChild, MenuGetFirstChild, MenuGetGenericNode, MenuGetNextChild, MenuGetPageNode, MenuGetParent, MenuGetPrevChild, MenuGetWindowNode, MenuNodeAddChild, MenuNodeGetProperty, MenuNodeHasCommand, MenuNodeIsDisabled, MenuNodeIsHidden, MenuNodeRemove, MenuNodeRunCommand, MenuNodeSetDisabledWhen, MenuNodeSetHiddenWhen, MenuNodeSetProperty See Also Menu Functions
647
648
Assert Beep CitectInfo CodeTrace DebugBreak DebugMsg DebugMsgSet DelayShutdown DisplayRuntimeManager DumpKernel EngToGeneric Exec GetArea GetEnv GetLogging InfoForm
Dumps Kernel data to the Kernel.dat file. Converts a variable into generic scale format. Executes an application or PIF file. Gets the current viewable areas. Gets an environment variable. Gets the current value for one or more logging parameters. Displays graphics object help information for the AN closest to the cursor. Displays graphics object help information for an AN.
InfoFormAn
649
Gets text input from the operator. Converts an integer variable into a real (floating point) number. Executes a command in a kernel window. Obtains the number of rows in a queue. Provides a consistent method of accessing items within a Kernel Table. Obtains the number of rows in a Kernel Table.
Displays a message box on the screen. Gets the value of a system parameter. Updates a system parameter. Determines if the currently executing process contains a Client component. Determines if the currently executing process contains a particular server component. Restarts the current process in which Cicode is running. Returns information about the CitectSCADA product. Returns information about a particular project, which is identified by a project enumerated number. Gets the path to the project to be run the next time CitectSCADA is restarted. Sets the path to the project to be run the next time CitectSCADA is restarted. Sets the name or path of the current project. Displays a message in the prompt line.
ProcessIsServer
ProjectRestartGet
ProjectRestartSet
ProjectSet Prompt
650
Pulse ServerDumpKernel
Pulses (jogs) a variable tag every two seconds. Dumps Kernel data to the KERNEL.DAT file either on a local server or on a remote server. Gets information about services running in the component calling this function. Sets the current viewable areas. This function is now obsolete. Adjusts logging parameters while online. Ends CitectSCADA's operation. Displays a form that allows an operator to shut down the CitectSCADA system. Gets the mode of the shutdown/restart. Switches focus to the CitectSCADA configuration application. Generates a random wave. Generates a saw wave. Generates a sine wave. Generates a square wave. Generates a triangular wave. Toggles a digital tag on or off. Displays a message in the Kernel and Debugger debug windows. Gets the version number of the CitectSCADA software.
ServiceGetList
Version
AreaCheck
Determines whether the current user has access to a specified area.
Syntax 651
AreaCheck(Area) Area:
The area number (0 - 255)
Return Value
TRUE (1) if the user has access to the Area or FALSE (0) if not.
Related Functions
GetArea, GetPriv
Example
IsArea = AreaCheck(5);
Assert
Verifies that the specified expression is TRUE. If then expression is FALSE, the current task will be halted. This is useful to help prevent the execution of code you do not want to run in the event an error has been detected. This function can be used in a debug mode, where the FALSE assertion will be logged to the Kernel and SysLog.DAT, with the time, date, Cicode file name, and line number. Additionally the operator will be prompted with a dialog. The debug mode can be set by using the [Code]DebugMessage parameter or DebugMsgSet() function. Note: If you have the "Citect will start debugger on hardware errors" option set in the Cicode Editor, the Debugger will start with the position before the Halt() instruction. You need to 'step over' this command if you want to continue debugging the function that called the Assert().
Syntax
Assert(bCondition) bCondition:
The boolean expression. This expression needs to evaluate to TRUE (1) or FALSE (0).
Return Value
Beep
Beeps the internal speaker or sound card (installed in the computer). If you use the internal speaker on your computer, the function does not return until the sound has completed. If you use a sound card, the function returns immediately and the sound plays in the background. Use the Windows Control Panel to set up waveforms.
Syntax
Beep(nSound) nSound:
The type of sound:
-1 - Standard beep 0 - Default beep waveform 1 - Critical stop waveform 2 - Question waveform 3 - Exclamation waveform 4 - Asterisk waveform
Return Value
DspPlaySound
Example
653
CitectInfo
Gets information about a CitectSCADA variable. This function returns internal statistics and other information about the CitectSCADAruntime system. Note: This function is a non-blocking function and can only access data contained within the calling process; consequently it cannot return data contained in a different server process. This function is not redirected automatically by CitectSCADA runtime. If you want to make a call from one process to return data in another, use MsgRPC() to make a remote procedure call on the other process. Alternatively, include the server process that has the information that CitectInfo requires in the calling process.
Syntax
sName:
The name of the variable. This name depends on sGroup:
l l
"General" - the name is ignored. "Port" - the name of the I/O port configured in the database (with the Ports database). The port information is only valid for an I/O server. If the port name is "total", the total statistics for the I/O server are returned. "IODevice" - the name of the I/O device configured in the I/O devices database. "Network" - the name is ignored. "Stats" - The name of the statistics buffer or Statistical Information Record (SIR):
l l
"Alarm Proc" - Alarm Processing (includes Digital, Analog, Advanced and High Resolution alarms). "Citect n" - The CitectSCADA window where n is the window number (returned from the WinNumber() function)
654
"Code n" - The user Cicode task (thread) where n is the task handle (returned from the TaskHnd() function) "Reset" - Reset the CitectSCADA statistics. "ElapsedTimeMS" - The elapsed time since statistics have been reset. Returns -1 if more than 20 days has elapsed.
l
0 - CPU usage 1 - CitectSCADA Kernel cycles per second 2 - CitectSCADA Kernel tasks per second 3 - CitectSCADA Kernel boot time 4 - CitectSCADA Kernel running time (in seconds) 5 - CitectSCADA startup time 6 - CitectSCADA running time in seconds 7 - Not supported in v7.10 or later 8 - Total read requests 9 - Total read requests per second 10 - Total write requests 11 - Total write requests per second 12 - Total Physical read requests 13 - Total Physical read requests per second 14 - Total Physical write requests 15 - Total Physical write requests per second 16 - Total Blocked read requests 17 - Total Blocked write requests
655
18 - Total Digital read requests 19 - Total Register read requests 20 - Total Digital read requests per second 21 - Total Register read requests per second 22 - Total Cache reads count 23 - Total Cache reads % 24 - Overall Average response time (ms) 25 - Overall Minimum response time (ms) 26 - Overall Maximum response time (ms) 27 - Request sample for response times 28 - Static point count is no longer supported. Calling the function with parameter 28 returns a value of 0 and a hardware alarm is raised. 29 - Dynamic point count currently in use 30 - Number of pending read requests from the device 31 - Number of pending write requests to the device 32 - Determines if CitectSCADA Kernel window is open 33 - Percentage of the CPU used by the current CitectSCADA process 34 - Total CPU time spent by the current CitectSCADA process in milliseconds 35 - Total number of handles opened by the current CitectSCADA process 36 - Total number of threads owned by the current CitectSCADA process "Port" - Port information for the I/O Server: 0 - Read requests 1 - Write requests 2 - Physical read requests 3 - Physical write requests 4 - Cached read requests 5 - Cached write requests 6 - Blocked read requests 7 - Blocked write requests 8 - Read requests per second 9 - Write requests per second 10 - Error count 11 - Read bytes counter 12 - Channel usage % 13 - Read bytes per second 14 - Statistics, minimum read time 15 - Statistics, maximum read time
656
16 - Statistics, average read time 17 - Statistics, time of samples 18 - Statistics, number of sample 100 - 119 - Driver specific counter values. CitectSCADA drivers can maintain up to 20 unique counters that can be accessed via this function. They are zero based, indexed from 100 to 119. If a value is not defined or maintained by the driver, 0 is returned for the value of the counter. "IODevice" - I/O device information for the I/O device: 0 - Client side status: l 1 = Running - Client is either talking to an online IO device or talking to a scheduled device that is not currently connected but has a valid cache l 2 = Standby - Client is talking to an online standby IO device l 4 = Starting - Client is talking to an IO device that is attempting to come online l 8 = Stopping - Client is talking to an IO device that is in the process of stopping l 16 = Offline - Client is pointing to an IO device that is currently offline l 32 = Disabled - Client is pointing to a device that is disabled l 66 = Standby write - Client is talking to an I/O device configured as a standby write device 1 - I/O Server status: l 1 = Running - I/O Server is either talking to an online IO device or talking to a scheduled device that is not currently connected but has a valid cache l 2 = Standby - I/O Server is talking to an online standby IO device l 4 = Starting - I/O Server is talking to an IO device that is attempting to come online l 8 = Stopping - I/O Server is talking to an IO device that is in the process of stopping l 16 = Offline - I/O Server is pointing to an IO device that is currently offline l 32 = Disabled - I/O Server is pointing to a device that is disabled l 66 = Standby write - I/O Server is talking to an I/O device configured as a standby write device 2 - If this I/O device is a standby device 3 - Last generic error 4 - Last driver error 5 - Error count 6 - Initialization count 7 - Statistics, minimum read time 8 - Statistics, maximum read time
657
9 - Statistics, average read time 10 - Statistics, number of samples "Network" - Network statistical information: 0 - Read Network Control Blocks (NCBs) 1 - Maximum pending read NCBs 2 - Minimum pending read NCBs 3 - Current pending read NCBs 4 - Number of short read NCBs 5 - Write NCBs 6 - Maximum pending write NCBs 7 - Minimum pending write NCBs 8 - Current pending write NCBs 9 - Number of short write NCBs 10 - Total NCBs 11 - Maximum pending total NCBs 12 - Minimum pending total NCBs 13 - Current pending total NCBs 14 - Number of short total NCBs 15 - Minimum send response time in milliseconds 16 - Maximum send response time in milliseconds 17 - Average send response time in milliseconds 18 - Send packet count "Stats" - Statistical information: 0 - Minimum time between code executions (cycles) 1 - Maximum time between code executions (cycles) 2 - Average time between code executions (cycles) 3 - Total cycle time in milliseconds 4 - Minimum time to execute the code in milliseconds 5 - Maximum time to execute the code in milliseconds 6 - Average time to execute the code in milliseconds 7 - Total execute time in milliseconds "Memory" - Memory information: 0 - Free virtual memory 1 - Free windows system resources as % 2 - Free Physical Memory 3 - Memory Paging File Size
658
4 - Total Physical Memory 5 - Total % of Physical Memory Used (Win 2000 or later) and % of the last 1000 pages in memory that are in use (Win NT or earlier). 6 - Total working set size counter for current CitectSCADA process 7 - Private bytes counter of current CitectSCADA process "Disk" - Disk information: 0 - Free disk space in bytes 1 - Total disk space in bytes 2 - Free disk space in kilobytes 3 - Total disk space in kilobytes
Return Value
CodeTrace
Traces Cicode into the Kernel and the SYSLOG.DAT file. Use this function for finding bugs in your Cicode. It will trace the functions called, the arguments to those functions, and their return values. It will also trace any errors, writes to the I/O devices, and task state changes. Note: Use this function only during system development; it can cause excessive loading on the CPU.
659
UNINTENDED EQUIPMENT OPERATION Only use the CodeTrace() function during system development and testing. This function is not intended for use in an operational system. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Syntax
0 - Foreground Cicode. -2 - The next created task. -3 - New created tasks. -4 - All tasks. nMode:
The mode of the trace:
0 - Tracing off 1 - Trace user Cicode functions calls 2 - Trace built-in function calls 4 - Trace errors 8 - Trace writes to the I/O devices 16 - Trace task state changes -1 - All modes (except 0)
Return Value
660
.... // Stop tracing CodeTrace(TaskHnd(), 0); // trace functions in new task CodeTrace(-2, 1 + 2); TaskNew("MyFunc", "data", 0);
DebugBreak
Causes a breakpoint exception error to occur (error number 342). This allows programmers to trap invalid states in their Cicode. If the Cicode Editor is not running, and the Citect will start debugger on hardware errors option is set (Debug menu - Options), the Debugger will be started. When the debugger starts, the correct Cicode file, function, and line will be displayed.
Syntax
DebugBreak()
Return Value
None.
Related Functions
DebugMsg
Provides in-line debug messages of user Cicode, to the Kernel, Debugger Debug window, and the SysLog.DAT file. This function can be enabled or disabled with the [Code]DebugMessage parameter or DebugMsgSet() function at runtime.
661
Syntax
DebugMsg(sMessage) sMessage:
The debugging message to log. Be sure to enclose this message in double quotes (" ").
Return Value
None.
Related Functions
DebugMsgSet
Enables/disables the DebugMsg() logging functionality. It also controls whether logging is enabled for the Assert() function. This function also sets the [Code]DebugMessage parameter appropriately.
Syntax
DebugMsgSet(nMode) nMode:
The logging mode:
662
Related Functions
Assert, DebugMsg
Example
Buttons Text Command Comment Debug Enable DebugMsgSet(1) Enable debug logging
DelayShutdown
Terminates CitectSCADA's operation after the specified delay period (in milliseconds). This function is suitable to be called by the CTAPI. The delay period enables the user to close the connection between the CTAPI and third-party applications before CitectSCADA shuts down.
Syntax
DelayShutdown(Delay) Delay:
The period (in milliseconds) after whichCitectSCADA will shut down.
Return Value
No return value.
Related Functions
663
DisplayRuntimeManager
This function will start the CitectSCADA Runtime Manager if it is not already running , otherwise it will just bring the CitectSCADA Runtime Manager to the foreground.
Syntax
DisplayRuntimeManager()
Return Value
DumpKernel
Dumps Kernel data to the KERNEL.DAT file. Instead of creating a new file subsequent calls to this function will append Kernel data to the KERNEL.DAT file.
Syntax
0x0010
664
Dump the queue. 0x0040 0x0100 Dump list of current SCADA parameter settings Dump in verbose mode. 0x4000 Dump kernel data in non-verbose mode. To dump data in verbose mode, set iMode to 0xc000 (0x8000 + 0x4000).
0x8000
You can select any one of the above modes or may add them together to get more than one type of information. For example, to dump driver and I/O device data in verbose mode, set iMode to 0x400c (0x0004 + 0x0008 + 0x4000). Using 0x4000 on its own will dump no data, it needs to be combined with another mode. sName:
The queue or table name (if "", returns data for all queues or tables). Only valid if iMode is 0x0020 and 0x0040.
Return Value
EngToGeneric
Gets a variable in the CitectSCADA generic scale format. CitectSCADA uses this scale to display trends. It calls this function automatically for trends defined in the project. If you want to display a trend using Cicode you need to call this function.
Syntax
EngLow:
The engineering units zero scale.
EngHigh:
The engineering units full scale.
Return Value
DspBar, DspTrend
Example
/* Using trend definition 5 at AN20, display the value of Tag1 on Pen1 of the trend. Tag1 has an engineering scale of 0 to 100. */ DspBar(20,5,EngToGeneric(Tag1,0,100));
Exec
Executes an application or PIF file. The application or command starts up and continues to run in parallel with CitectSCADA. This function can return while the application is still starting up, so you should use the Sleep() function to allow the application enough time to start.
Syntax
Mode:
The mode of the window:
666
Return Value
Sleep
Example
Exec("c:\winnt\system32\mspaint.exe"); ! Starts up the Paint application with a normal window. Exec("cmd /c mkdir c:\test"); ! Uses the DOS shell to create a new directory
you need to quote paths and applications passed to the exec function (using ^" to embed quotes) so that the function can be executed correctly when long file names are used. For example:
Exec(PathToStr("^"" + "[BIN]:\Ctcicode")+ "^" ^"" + PathToStr("[RUN]:\cicode.ci") + "^"")
GetArea
Gets the current logged-in areas.
Syntax
GetArea()
Return Value
The login area groups as an integer that represents a group handle. If this group is modified, the actual login areas do not change.
Related Functions
SetArea
Example
667
! If the current areas are 1, 5 and 20: hGrp=GetArea(); Str=GrpToStr(hGrp); ! sets Str to "1,5,20".
GetEnv
Gets a DOS environment variable.
Syntax
GetEnv(sName) sName:
The name of the environment variable.
Return Value
GetLogging
Gets the current value for logging parameters. The parameters you can query include the following:
l l l l l l l l l l
[Debug]DriverTrace [Debug]SysLogSize [Debug]Priority [Debug]CategoryFilterMode [Debug]CategoryFilter [Debug]SeverityFilterMode [Debug]SeverityFilter [Debug]LogShutdown [Debug]DebugAllTrans [Debug]EnableLogging
668
l l l l
Syntax
sName:
The system parameter name.
Return Value
If the function succeeds, the value is returned as a string. An empty string is returned if an error occurs. To get extended error information, call IsError().
Related Functions
InfoForm
Displays graphics object information for the object under the mouse pointer. If there is no object directly under the mouse pointer, it displays information for the nearest object. Each tag associated with the object is displayed, along with its raw and engineering values and a button that displays the details from the Variable Tags form. The function also displays the Cicode expression, with any result that the expression has generated. This function only supports the display of simple Cicode expressions.
Syntax
InfoForm(Mode) Mode:
For security purposes, the Write button on the information form displayed by this function can be disabled.
0 - The Write button on the displayed information form will be available and will function normally. 1 - The Write button will not be shown.
If you omit the mode, the default mode is 0.
669
Return Value
InfoFormAn
Example
System Keyboard Key Sequence Command Comment AnHelp InfoForm(); Display graphics object help for the AN closest to the cursor
InfoFormAn
Displays graphics object information for a specified AN. This function displays each tag associated with the object, along with its raw and engineering values and a button that displays the details from the Variable Tags form. The function also displays the Cicode expression, with any result that the expression has generated.
Syntax
Mode:
For security purposes, the Write button on the information form displayed by this function can be disabled.
0 - The Write button on the displayed information form will be available and will function normally. 1 - The Write button will not be shown.
If you omit the mode, the default mode is 0.
Return Value
Related Functions
InfoForm
Example
System Keyboard Key Sequence Command Comment ### AnHelp InfoFormAn(Arg1); Display graphics object help for a specified AN
Input
Displays a dialog box in which an operator can input a single value. The dialog box has a title, a prompt, and a single edit field. For multiple inputs, use the Form functions. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
Prompt:
The prompt text.
Default:
The default text that the operator can edit or replace.
Return Value
The edit field entry (as a string). If the user presses the Cancel button , an empty string is returned and the IsError() function returns the error code 299.
Related Functions
Message, FormNew
Example 671
/* Shut down CitectSCADA if the user inputs "Yes". */ STRING sStr; sStr=Input("Shutdown","Do you wish to shutdown?","Yes"); IF sStr="Yes" THEN Shutdown(); END
IntToReal
Converts an integer into a real (floating point) number.
Syntax
IntToReal(Number) Number:
The integer to convert.
Return Value
RealToStr, StrToInt
Example
! Sets Variable to 45.0 Variable=IntToReal(45); ! Sets Variable to -45.0 Variable=IntToReal(-45);
KerCmd
Executes a command in a Kernel window.
Syntax
672
sCommand:
The command to execute in the Kernel window.
Return Value
KernelQueueLength
Obtains the number of records in a queue.
Syntax
KernelQueueLength(sName) sName:
The name of the queue, which can be enumerated by the page queue kernel command.
Return Value
This function returns the Length value of the page queue command.
Related Functions
KernelTableInfo
Provides a consistent method of accessing items within Kernel Table.
Syntax
673
sTable Bufferpool
sField Mode, Size, Total, Free, InUse, Max, Peak, Short, Gets, TotErr, Grow, Shrink Name, HND, State, CPU_Time, Poll_ Time, Slice
CiCode
The value of the 'Name' field or the 'HND' field. If the user specifies a number as the sRecord we will assume it is a handle, otherwise we will look it up as a string name
The CiCode function TaskNew exposes the handle. That is why record access by handle is acceptable for this table. The name field may or may not be unique (if you run the same CiCode task twice with different parameters). Accessing by Name will not succeed if there are duplicates None
Task
Mode, Hnd, State, Prty, Cpu, Min, Max, Avg, Count Name, Node, Type, Mode, Hnd, Cnt, Send, Rec, Wait, Stack, Service, State, Login, ReconnectCount, UpTime, TotalTxRxBytes
Tran
The counters ReconnectCount, UpTime and TotalTxRxBytes can be viewed in verbose mode on Table Tran page of the Kernel
Trendqueues
sRecord:
The key to a column in the table depending on the sTable parameter.
sField:
The key to a column in the table depending on the sTable parameter.
Return Value
Returns the content of a field of the given table in the format of a Cicode STRING.
Related Functions
KernelTableItemCount
674
KernelTableItemCount(sName) sName:
The name of the table that can be enumerated by the page table kernel command.
Return Value
Returns the number of active records in the table (not the length value displayed by the page table kernel command). The following tables row counts are not returned by this command (it returns 0)
l l l l
LanguageFileTranslate
Translates an ASCII file into a local language. Use this function to translate RTF reports for viewing on client screens. The local language used by this function is specified by the [Language]LocalLanguage parameter. You need to set this parameter accordingly.
Syntax
sDestFile:
The name of the destination file which will be created/ replaced with the local/translated version of the source file. You should specify the full path or use path substitution. The path and name should be contained within quotation marks.
Return Value
675
1 if successful, otherwise 0.
Related Functions
StrToLocalText
Example
/* Translates the text in Shift.RTF and saves it in LShift.RTF. */ LanguageFileTranslate("c:\MyApplication\data\Shift.RTF","c:\MyApplication\data\ LShift.RTF"); /* Translates the text in [Data]:Shift.RTF and saves it in [LocalData]:LShift.RTF. */ LanguageFileTranslate("[Data]:Shift.RTF","[LocalData]:LShift.RTF" );
Message
Displays a message box on the screen and waits for the user to select the OK or Cancel button. This function is a blocking function. It will block the calling Cicode task until the operation is complete. This function will be blocked if called from a non-client process, as well as from kernel window of a client process if [Client]DisableDisplay is set to TRUE.
Syntax
Prompt:
The prompt displayed in the message box.
Mode:
The mode of the message box:
0 - OK button 1 - OK and Cancel button 16 - Stop Icon 32 - Question Icon 48 - Exclamation Icon
676
64 - Information Icon
Select more than one mode by adding the modes. For example, set Mode to 33 to display the OK and Cancel buttons and the Question icon. You can only display one icon for the message box.
Return Value
0 (zero) if successful, otherwise an error is returned. If the user presses the Cancel button the function returns an error code of 299.
Related Functions
Input
Example
/* Display an error message in a message box. */ IF Total<>100 THEN Message("Error","Total not 100%",48); END
ParameterGet
Gets the value of a system parameter. The system parameter can exist in the CITECT.INI file and/or in the Parameters database. If the system parameter does not exist in the CITECT.INI file or the database, the default value is returned. If the system parameter exists in both CITECT.INI and the database, the value of the system parameter is taken from CITECT.INI.
Syntax
sName:
The system parameter name.
Default:
The default value of the parameter. Note: If in your Cicode you perform a ParameterGet("alarm", "alarmsave", 1000) for say the [Alarm]SavePeriod parameter, and NO entry exists in Citect.ini or the parameters records, the returned value will be 1000 however CitectSCADA will internally be using the default value of 600.
677
Return Value
ParameterPut
Updates a system parameter in the CITECT.INI file. If the system parameter does not exist, it is added to the CITECT.INI file.
Syntax
sName:
The system parameter name.
Value:
The value to put in the system parameter.
Return Value
678
ProcessIsClient
Determines if the currently executing process contains a Client component.
Syntax
ProcessIsClient()
Return Value
TRUE (1) if the process contains a Client component, otherwise FALSE (0).
Related Functions
ProcessIsServer
Determines if the currently executing process contains a particular server component.
Syntax
sClusterName:
Optional case insensitive string specifying the cluster name to combine with the server type specified in the first argument and the server name (if specified).
sServerName:
Optional case insensitive string specifying a server name to combine with the server type specified in the first argument and the cluster name (if specified).
Return Value
TRUE (1) if the process contains the specified component, otherwise FALSE (0).
679
Related Functions
To execute disk PLC tag simulation code only on the I/O server in Cluster1 with the name IOServer3:
IF (ProcessIsServer("IOServer", "Cluster1", "IOServer3")) THEN SimulateDiskTags(); END
ProcessRestart
Restarts the current process in which Cicode is running.
Syntax
0 (zero) if successful, otherwise the following error is returned: 256 - General software error See Also Cicode and General errors
Related Functions
ServerRestart
Example
ProcessRestart()
ProductInfo
Returns information about the CitectSCADA product.
Syntax
680
ProductInfo(iType) iType:
Type of information required:
0 - product name, default 1 - product company 2 - product major version 3 - product minor version 4 - product version string
Return Value
The product information. An empty string will be returned if the type is invalid.
Related Functions
ProjectInfo
Returns information about a particular project, which is identified by a project enumerated number.
Syntax
iType:
Type of information to return:
0 - Project name 1 - Project description 2 - Project major version 3 - Project minor version 4 - Project date 5 - Project time
Return Value
681
The specified project information. An empty string will be returned if the project number or type is invalid
Related Functions
ProjectRestartGet
Gets the path to the project to be run the next time CitectSCADA is restarted. (you need to have a project already set using either ProjectSet or ProjectRestartSet. Use this function with the Shutdown() function to shut down and then restart the project that is currently running.
Syntax
ProjectRestartGet()
Return Value
The path to the project to be run the next time CitectSCADA is restarted.
Related Functions
ProjectRestartSet
Sets the path to the project to be run the next time CitectSCADA is restarted.
Syntax
ProjectRestartSet(sPath) sPath:
The path to the project. You need to use the full path, for example to specify the path to the project "Demo", use: "C:\CITECT\USER\DEMO".
Return Value
682
Related Functions
ProjectSet
Sets either the name or the path of the project to be run next time CitectSCADA is restarted. The project path is written to the [CtEdit]Run parameter.
Syntax
ProjectSet(sProject) sProject:
The name of the project (for example "DEMO"), or the path to the project. If you specify the path to the project, you need to use the full path. If you do not specify a project, the current project will be used.
Return Value
Prompt
Displays a message in the prompt line (AN=2) on the operator's computer.
Syntax
Prompt(String) String:
The message to be displayed.
683
Return Value
Message, DspError
Example
/* Display "This is a prompt!" at the prompt AN. */ Prompt("This is a prompt!");
Pulse
Pulses (jogs) a variable tag on, then off. The variable tag is switched ON (1) and two seconds later it is switched OFF (0). The exact period of the pulse is determined by the communication channel to the I/O device. If the communication channel is busy, the pulse time may be longer than two seconds. The code in the I/O device should not be dependant on a pulse time of exactly 2 seconds. Use the pulse as a trigger only.
Syntax
Pulse(sTag) sTag:
The digital tag to pulse.
Return Value
Toggle
Example
684
Comment
ServerDumpKernel
Dumps Kernel data to the KERNEL.DAT file (written to the Logs folder) either on a local server or on a remote server. The server is specified with the server and cluster parameters. Instead of creating a new file subsequent calls to this function will append Kernel data to the KERNEL.DAT file. This is a blocking function.
Syntax
0x0010
685
0x0100
0x4000 Dump kernel data in non-verbose mode. To dump data in verbose mode, set iMode to 0xc000 (0x8000 + 0x4000).
0x8000
You can select any one of the above modes or may add them together to get more than one type of information. For example, to dump netstat and I/O device data in verbose mode, set iMode to 0x4014 (0x0004 + 0x0010 + 0x4000). Using 0x4000 on its own will dump no data, it needs to be combined with another mode. sName:
The queue or table name (empty for all queues or tables). Only valid if iMode is 0x0020 and 0x0040.
sServer:
Specifies the name of the server, as defined in the project, on which kernel data will be dumped.
sCluster:
Specifies the cluster of the server on which kernel data will be dumped. This parameter is optional in a single cluster environment.
Return Value
ServiceGetList
Determines the service type(s), cluster name(s), and service name(s) of all services currently running in the component that called this function. It also determines if the client component is running.
686
If you call this function from a component that is running purely as a Control Client or View-only Client, the function will return "Client". If you call this function from a single-process component that includes:
l l l l l
I/O server called IOServ1 on ClustA Trend server called Trend1 on ClustB Alarm server called Alarm1 on ClustA Report server called Report1 on ClustB Client
The function will return a string similar to: "IOServer.ClustA.IOServ1,Trend.ClustB.Trend1,Alarm.ClustA.Alarm1,Report.ClustB.Report1,Client" The order of components in the string is not fixed so the exact string may vary from the above. You should parse the returned string or alternatively use ProcessIsClient or ProcessIsServer to find the information you need.
Syntax
ServiceGetList()
Return Value
SetArea
Sets the current viewable areas. You can pass a single area number, or a group of areas to set multiple areas. You can only set areas that are flagged for the current user.
Syntax
SetArea(Area) Area:
The area to set (1 to 255).
Return Value
687
GrpOpen
Example
/* Set current viewable area to Area 1. */ SetArea(1);
SetLogging
Adjusts logging parameters while online. The parameters you can modify include the following:
l l l l l l l l l l l l l l
[Debug]DriverTrace [Debug]SysLogSize [Debug]Priority [Debug]CategoryFilterMode [Debug]CategoryFilter [Debug]SeverityFilterMode [Debug]SeverityFilter [Debug]LogShutdown [Debug]DebugAllTrans [Debug]EnableLogging [IOServer]RedundancyDebug [General]Verbose [General]VerboseToSysLog [CtAPI]Debug
Syntax
sName:
The system parameter name.
Value:
The value you would like to set the parameter to.
688
Persist:
Makes the value persistent across restarts by writing the value to the INI file.
Return Value
Shutdown
Terminates CitectSCADA's operation. Use this function to shut down the CitectSCADA system, otherwise buffered data could be lost. Note: With one exception, the Shutdown command will succeed only if there is an Alarm Server in your system. The exception to this is if you specify an empty string for the sDest parameter (shutdown this computer only). In this case the shutdown will succeed even if there is no Alarm Server. The shutdown can affect only the computer that calls it, or all or part of a CitectSCADA network. If you are shutting down a network, specify the computers (Control Clients and servers) to be shut down in sDest, and the extent of the shutdown in Mode. Note: If [Shutdown]NetworkIgnore parameter is set to 0 (zero) and a client receives a shutdown request message from a server. Phase 2 clients only receive a shutdown request when the first phase 1 client has reconnected to the server. You can allow selected computers to override the shutdown with the [Shutdown]NetworkIgnore parameter. (You might set this parameter for key servers, for example, I/O servers.) Use the ShutdownForm() function to prompt the user for verification before shutting CitectSCADA down. Note: If the [Shutdown]NetworkStart parameter is set to 0 (zero), the Shutdown() function will ignore the sDest argument. This will result in the shutting down and restarting of the machine the function is run on regardless of the machine specified.
Syntax
689
"" (blank string) - This computer only - Default value ["Computer_Name"] - The specified CitectSCADA client (defined in the computer's CITECT.INI file) ["Server_Name"] - The specified CitectSCADA server "All Clients" - All CitectSCADA clients on the network "All Servers" - All CitectSCADA servers on the network "Everybody" - All CitectSCADA computers on the network sProject:
The full path of the project to run on restart as a string. The path is written to the configuration files and is used when the system restarts. The default value is "", which means that no changes are made to the configuration and the current project is restarted.
Mode:
The type of shutdown:
1 - Shutdown CitectSCADA only - Default value 2 - Shutdown and restart CitectSCADA (without logging off Windows) 3 - Shutdown and restart CitectSCADA and log off Windows (needs to set up an auto login to the Operating System and CitectSCADA needs to be configured to run on start up or log in) 4 - Shutdown CitectSCADA and re-boot the computer 5 - Shutdown CitectSCADA only 6 - Shutdown and restart CitectSCADA clients, but not this computer 7 - Shutdown CitectSCADA and shutdown the computer. If the computer supports power off feature the power will be turned off sClusterName:
The name of the cluster that the machine(s) named in Dest belongs to. This is not required if:
l l
the function is called with Dest empty (the default); OR the client is connected to only one cluster containing an Alarm Server.
CallEvent:
Flag for initiating a user-specified shutdown event prior to shutting down. Refer to OnEvent() type code for the value of shutdown event.
690
l l
0 - no event 1 - raise event. The user defined shutdown event handler will be called before the shutdown occurs - Default value Note: If the event handler is non-interactive with an instant return value, it can be called directly.
Note: If the event handler is interactive or with a long delay in processing the event, it needs to be called indirectly using the NewTask("EventHandler") function, and the actual handler, EventHandler(), needs to call Shutdown() with the CallEvent flag set to 0 from the handler if it decides the shutdown is permitted.
Return Value
ShutdownForm
Displays a dialog box to verify that the user really wants to shut down the CitectSCADA system. If the user selects [Yes], CitectSCADA is shut down. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax
ShutdownForm()
Return Value
691
Shutdown
Example
System Keyboard Key Sequence Command Comment Buttons Text Command Comment Shutdown ShutdownForm(); Display the shutdown form Shutdown ShutdownForm(); Display the shutdown form
ShutdownMode
Gets the mode of the last Shutdown function call. The mode is useful to identify the type of Shutdown that was performed.
Syntax
ShutdownMode()
Return Value
Shutdown
Example
nMode = ShutdownMode() If nMode = 4 Then Prompt ("Citect closed down and computer was rebooted") END
692
SwitchConfig
Switches focus to a specific CitectSCADA configuration application. If the specified application is not running, it will be started.
Syntax
SwitchConfig(nApp) nApp:
The configuration application:
1 - Citect Graphics Builder (CTDRAW32.EXE) 2 - Citect Project Editor (CTEDIT32.EXE) 3 - Citect Explorer (CTEXPLOR.EXE) 4 - Citect Cicode Editor (CTCICODE.EXE)
Return Value
TestRandomWave
Generates a random wave. The height of the wave is restricted by minimum and maximum values. You can offset the starting point of the wave, for example, to display multiple waves at the same AN. You can use this function to generate test input.
Syntax
Low:
The lowest value of the wave. If no low value is entered, this value has a default of 0.
693
High:
The highest value of the wave. If no high value is entered, this value has a default of 100.
Offset:
The offset in seconds, to generate the wave. If no offset is entered, the offset has a default of 0.
Return Value
TestSawWave
Generates a saw wave. The height of the wave is restricted by minimum and maximum values. You can offset the starting point of the wave, for example, to display multiple waves at the same AN. You can use this function to generate test input.
Syntax
Low:
The lowest value of the wave. If no low value is entered, this value has a default of 0.
High:
The highest value of the wave. If no high value is entered, this value has a default of 100.
Offset:
The offset in seconds, to generate the wave. If no offset is entered, the offset has a default of 0.
TestSinWave
Generates a sine wave. The height of the wave is restricted by minimum and maximum values. You can offset the starting point of the wave, for example, to display multiple waves at the same AN. You can use this function to generate test input.
Syntax
Low:
The lowest value of the wave. If no low value is entered, this value has a default of 0.
High:
The highest value of the wave. If no high value is entered, this value has a default of 100.
Offset:
The offset in seconds, to generate the wave. If no offset is entered, the offset has a default of 0.
Return Value
695
/* Specifies a sine wave of 30 seconds duration, with a minimum value of 0 units and a maximum value of 100 units, with no offset. */ TestSinWave(30);
TestSquareWave
Generates a square wave. The height of the wave is restricted by minimum and maximum values. You can offset the starting point of the wave, for example, to display multiple waves at the same AN. You can use this function to generate test input.
Syntax
Low:
The lowest value of the wave. If no low value is entered, this value has a default of 0.
High:
The highest value of the wave. If no high value is entered, this value has a default of 100.
Offset:
The offset in seconds, to generate the wave. If no offset is entered, the offset has a default of 0.
Return Value
696
TestTriangWave
Generates a triangular wave. The height of the wave is restricted by minimum and maximum values. You can offset the starting point of the wave, for example, to display multiple waves at the same AN. You can use this function to generate test input.
Syntax
Low:
The lowest value of the wave. If no low value is entered, this value has a default of 0.
High:
The highest value of the wave. If no high value is entered, this value has a default of 100.
Offset:
The offset in seconds, to generate the wave. If no offset is entered, the offset has a default of 0.
Return Value
Toggle
Toggles a digital tag on or off. If the variable tag is ON (1), this function will turn it OFF. If the variable tag is OFF (0), this function will turn it ON.
697
Syntax
Toggle(sTag) sTag:
The digital tag to toggle.
Return Value
Pulse
Example
Buttons Text Command Comment Motor 145 Toggle(M145) Toggle the variable tag M145 (Motor 145) on or off
TraceMsg
Displays a message in the Kernel and Debugger debug windows.
Syntax
TraceMsg(String) String:
The message to display.
Return Value
698
Version
Gets the version number of the CitectSCADA software in use.
Syntax
Version(nType) nType:
The type of version:
0 - Major version number 1 - Minor version number 2 - Revision number 3 - Version text
Return Value
699
700
PageBack PageDisabled
PageHardware
PageHistoryDspMenu
PageHistoryEmpty
PageHome PageInfo
701
Displays the last ten graphics pages. Gets number of pages in the page list of the current window. Gets index of the current page in the page list of the current window. Gets information of a page at the specific index in the page list of current window. Recalls (displays) a page at the specific index in the page list of the current window, and moves the current index to the page. When a page is recalled, the original parameters (such as cluster context, super genie associations, PageTask arguments if applicable) used to display the page will be restored. Removes a page at the specific index from the page list of the current window. Displays a menu page with page selection buttons. Displays the next graphics page. Return the index in the page navigation history for the current page.. Gets information about a Page at an offset in the page navigation history. Gets the last page in the page navigation history. Displays the pop up window at the mouse position. Displays the previous graphics page. Displays a Process Analyst page (in the same window) preloaded with the pre-defined Process Analyst View (PAV) file. Display a page and add the specified pens to the first pane of the specified PA object on the page. Puts a page on the end of the page navigation history. Displays the page at a specified depth in the page navigation history. Used as a page entry function - creates a rich text object, and loads a rich text file into that object.
PageListInfo
PageListDisplay
PageListDelete
PagePeekLast
PageRichTextFile
702
PageSelect
Displays a dialog box with a list of graphics pages defined in the project. Stores a local page-based integer. Stores a local page-based string. Displays a category of sequence of events (SOE) entries on the SOE page. Displays a category of alarm summary entries on the predefined alarm page. Used for running preliminary Cicode before displaying a page in a window. Converts Page coordinates to absolute screen coordinates. Displays a standard trend page in a single cluster system. Displays a standard trend page in a multi-cluster system.
PageSummary
PageTask
PageAlarm
Displays a category of active alarms on the alarm page. To use this function, you need to have a page in your project that was created using the Alarm template. By default, the name of the page is expected to be "Alarm". However, you can use an alarm page with a different name by adjusting the setting for the INI parameter [Page]AlarmPage. Notes
l
The operation of this function has changed. In Version 2.xx this function displayed the built-in alarm page from the Include project. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
703
Return Value
PageDisabled, PageHardware
Example
System Keyboard Key Sequence Command Comment AlarmPage PageAlarm(0) Display active alarms on the alarm page
System Keyboard Key Sequence Command Comment Alarm ### Enter PageAlarm(Arg1) Display a specified category of active alarms on the alarm page
PageBack
Displays the previously displayed page in the Window.
Syntax
PageBack([iCount]) iCount:
Optional parameter to specify the number of pages to move back. Default value is 1.
Return Value
No Error (0) on success. Bad handle specified (269) if current window handle does not correspond to a valid window. Invalid argument passed (274) if count is outside of allowable bounds.
Related Functions
704
PageDisabled
Displays a category of disabled alarms on the disabled alarms page. To use this function, you need to have a page in your project that was created using the Disabled template. By default, the name of the page is expected to be "Disabled". However, you can use a page with a different name by adjusting the setting for the INI parameter [Page]DisabledPage. Notes
l
The operation of this function has changed. In Version 2.xx this function displayed the built-in disabled alarm page from the Include project. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
Return Value
PageAlarm
Example
705
PageDisplay
Displays a graphics page in the active window. The page needs to be in one of the operator's current areas. The page to be displayed is identified by its Page Name or the Page Number. When this function is executed, it tests whether or not the identified page is based on a CSV_Include project template. If it is, the function uses TaskNew to run a CSV version of the PageDisplay function, "CSV_MM_PageDisplay". This confirms if multi-monitor support is required. As TaskNew is used to execute this function, no return value becomes available to PageDisplay. Under these circumstances, PageDisplay will return zero (0). If this function is called to change the page in a pop-up window of a CSV_Include project, the page displayed by the base window will change. To change this default behaviour, set the [Page]NewPageInBase parameter to 0. Then a pop-up window can be changed with this function in single monitor mode. You can specify if the page operates within the context of a particular cluster in a multiple cluster project. When the page launches during runtime, the ClusterName argument is used to resolve any tags that have a cluster omitted. CitectSCADA stores the current page (onto a stack) before it displays the required page. You can call PageLast() to re-display the pages on the stack. You cannot call this function from the Exit command field (see Page Properties) or a Cicode Object. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageDisplay(Page,[ClusterName])
706
Page:
The name or page number of the page to display (in quotation marks ""). Can be prefixed by the name of a host cluster, that is "ClusterName.Page". This will take precedence over the use of the ClusterName parameter if the two differ.
ClusterName:
The name of the cluster that will accommodate the page at runtime (in quotation marks ""). The specified cluster is used to resolve any tags that have a cluster omitted. If the Page parameter is prefixed with the name of a cluster, this parameter will not be used. This parameter is optional, however if you omit a cluster context in the Page properties, then any tags which omit an explicit Cluster. TagName will be ambiguous and become unresolved if you have multiple clusters defined in the project. Note that this ambiguity and resulting unresolved state will only occur if the parameter [General]TagDB is set to "0" which disables variable tag database loading.
Return Value
0 (zero) if the page is successfully displayed, otherwise an error is returned. If the page is based on a CSV_Include project template, the function will return 0 (zero) as a CSV version of the function is executed via TaskNew.
Related Functions
PageGoto, PageLast
Example
Buttons Text Command Comment System Keyboard Key Sequence Command Comment Page ############## Enter PageDisplay(Arg1) Display a specified page Mimic Page PageDisplay("Mimic") Display the "Mimic" page
PageDisplay("MIMIC1");
707
! Displays page "MIMIC1". PageDisplay("MIMIC2"); /* Displays page "MIMIC2" and places page "MIMIC1" onto the page navigation history. */ PageDisplay("10"); /* Displays page "10" and places page "MIMIC2" onto the page navigation history. */ PageLast(); /* Displays the last page on the page navigation history, that is page "MIMIC2" and removes it from the stack. */
Note: Before CitectSCADA version 5.0, page records could be edited in the Project Editor. One of the fields available for configuration was "Page Number". The value entered for a page could then be used in runtime with the Page Cicode functions such as PageDisplay(), PageGoto(), and PageInfo(1). For example, PageDisplay("1") can be used to display the page that has "1" (without the quotes) set in the Page Number field. PageInfo(1) returns the Page Number of the current page. From version 5.0 on, this feature is only backwards-supported. The "Alias" field in the project Pages.DBF file still contains the Page Numbers from upgraded projects; however, the Pages database records are no longer available for direct editing in CitectSCADA. See Also Page Functions Cluster Context Improved Client Side Online Changes
PageFile
Displays a file on the page. After the file is displayed, you can scroll up and down through the file. To use this function, you need to use the Graphics Builder to create a page called "File" (using the file template). Notes
l
The operation of this function has changed. In Version 2.xx this function displayed the built-in file page from the Include project. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageFile(sName) sName:
708
Return Value
DspFile
Example
System Keyboard Key Sequence Command Comment File ######## Enter PageFile(Arg1) Display the specified file on the page
PageFileInfo
Returns the width or height of an unopened page.
Syntax
nMode:
Retrieves either the width or the height of the specified page in pixels.
The height or width of the specified page in pixels, depending on the value set for nMode. See Also Page Functions
709
PageForward
If PageBack() is called, PageForward() will restore the previously displayed page in the window. PageForward requires PageBack to have been called and no other page display functions to have been called in between. Calling the display functions PageDisplay or PageGoto will remove the forward pages from the display stack.
Syntax
PageForward([iCount]) iCount:
Optional parameter to specify the number of pages to move forward. Default value is 1.
Return Value
No Error (0) on success. Bad handle specified (269) if current window handle does not correspond to a valid window. Invalid argument passed (274) if count is outside of allowable bounds.
Related Functions
PageGetInt
Returns the integer value associated with a variable name on a particular page. If two or more windows are displayed, each window has a unique copy of the variable. You can use these variables in Cicode to keep track of variables unique to each window. Notes
l
You can find out the current setting for [Page]ScanTime parameter, by calling this function as follows: PageGetInt(-2). This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
iWinNum:
710
Return Value
PageGetStr
Gets the string associated with a variable name on a particular page. Page-based variables are local to each display page. If two or more windows are displayed, each window has a unique copy of the variable. You can use these variables in Cicode to keep track of variables unique to each window. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
iWinNum:
Window number of the page. Default is current window.
Return Value
PageGoto
711
Displays a graphics page in the active window. The page needs to be in one of the operator's current areas. You can specify either the Page Name or the Page Number of the graphics page. You can also specify if the page operates within the context of a particular cluster in a multiple cluster project. When the page launches during runtime, the ClusterName argument is used to resolve any tags that have the cluster name omitted. This function is similar to PageDisplay(), however PageGoto() does not put the current page into the page navigation history. You cannot call this function from the Exit command field (see Page Properties) or a Cicode Object. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageGoto(Page,ClusterName) Page:
The name or page number of the page to display (in quotation marks ""). Can be prefixed by the name of a host cluster, that is "ClusterName.Page". This will take precedence over the use of the ClusterName parameter if the two differ.
sClusterName:
The name of the cluster that will accommodate the page at runtime (in quotation marks ""). The specified cluster is used to resolve any tags that have the cluster name omitted. If the Page parameter is prefixed with the name of a cluster, this parameter will not be used.
Return Value
PageDisplay
Example
PageDisplay("MIMIC1"); ! Displays page "MIMIC1". PageDisplay("MIMIC2"); /* Displays page "MIMIC2" and places page "MIMIC1" onto the page navigation history. */ PageGoto("10");
712
/* Displays page "10". Page "MIMIC2" is not placed onto the page navigation history. */
Note: Before CitectSCADA version 5.0, page records could be edited in the Project Editor. One of the fields available for configuration was "Page Number". The value entered for a page could then be used in runtime with the Page Cicode functions such as PageDisplay(), PageGoto(), and PageInfo(1). For example, PageDisplay("1") can be used to display the page that has "1" (without the quotes) set in the Page Number field. PageInfo(1) returns the Page Number of the current page. From version 5.0 on, this feature is only backwards-supported. The "Alias" field in the project Pages.DBF file still contains the Page Numbers from upgraded projects; however, the Pages database records are no longer available for direct editing in CitectSCADA. See Also Page Functions Improved Client Side Online Changes
PageHardware
Displays the active hardware alarms on the hardware alarms page. To use this function, you need to have a page in your project that was created using the Hardware template. By default, the name of the page is expected to be "Hardware". However, you can use a page with a different name by adjusting the setting for the INI parameter [Page]HardwarePage. Notes
l
The operation of this function has changed. In Version 2.xx this function displayed the built-in hardware alarm page from the Include project. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised. 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
PageHardware()
713
Return Value
PageAlarm
Example
System Keyboard Key Sequence Command Comment Hardware PageHardware() Display active hardware alarms on the hardware alarms page
PageHistoryDspMenu
Displays a pop-up menu which lists the page history of current window. The user can select any page in the history to recall the page. When full page history is specified, the currently displayed page will also be listed and marked in the menu.
Syntax
PageHistoryDspMenu([iType]) iType:
The type of page history to be listed:
PageHistoryEmpty
714
Used to determine if the page history of the current window is empty. The currently displayed page is not counted as history.
Syntax
PageHistoryEmpty([iType]) iType:
The type of page history to be checked:
PageHome
Displays the predefined home page in the window.
Syntax
PageHome([sCluster]) sCluster:
Optional parameter to the Cluster to associate the page being opened with. Default value "".
Return Value
No eerror(0) on success. Bad handle specified (269) if current window handle does not correspond to a valid window. Bad handle specified (274) if INI parameter [Page]HomePage is not set. See Also Page Functions
PageInfo
Gets information about the current page.
715
Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageInfo(nType) nType:
The type of page information required:
0 - Page Name 1 - Page Number 2 - Page Title 3 - Display filename 4 - Symbol filename 5 - Next Page Name 6 - Previous Page Name 7 - Previous display count, incremented at each page scan. The page scan rate defaults to the value of the Citect.ini parameter [Page]ScanTime, and can be overridden per page by changing the scan time setting in the General tab of the page properties in Graphics Builder. 8 - Parent window number. Returns -1 if there is no parent 9 - First child window number. Returns -1 if there are no children 10 - Next child in child link. Returns -1 for the end of the list 11 - Window mode (set by the WinNewAt() function) 12 - Width of window 13 - Height of window 14 - X position of window 15 - Y position of window 16 - Dynamic window horizontal scale 17 - Dynamic window vertical scale Types 16 and 17 return a real number between 0 and 1 (as a STRING) and will be identical, as the dynamic scaling does not allow a change in the aspect ratio. 18 - Flashing color state. Type 18 returns one of the following: "0" - the palette does not flash "1" - the palette is primary now
716
"2" - the palette is secondary now 19 - In animation cycle. Returns a 1 (true) or 0 (false) 20 - In communications cycle. Returns a 1 (true) or 0 (false) 21 - Width of background page 22 - Height of background page 23 - The number of animation points on a page 24 - The value of the highest animation point on the page 25 - Indicates when the page's "On Page Shown" event has been triggered. Returns 1 if triggered, 0 if it has not. 26 - The cluster that has been specified to host the page. Returns the cluster name, or an empty string if no cluster has been specified. 27 - Indicates whether the Cicode library used by the page is different from the currently loaded library. Returns 1 if different, 0 if the versions are the same. 28 Return X Coordinate of Client rectangle origin. 29 Return Y Coordinate of Client rectangle origin.
Return Value
PageDisplay, PageTransformCoords
Example
! If currently on page "MIMIC1"; Variable=PageInfo(0); ! Sets Variable to "MIMIC1".
Note: Before CitectSCADA version 5.0, page records could be edited in the Project Editor. One of the fields available for configuration was "Page Number". The value entered for a page could then be used in runtime with the Page Cicode functions such as PageDisplay(), PageGoto(), and PageInfo(1). For example, PageDisplay("1") can be used to display the page that has "1" (without the quotes) set in the PageNumber field. PageInfo(1) returns the Page Number of the current page. From version 5.0 on, this feature is only backwards-supported. The "Alias" field in the project Pages.DBF file still contains the Page Numbers from upgraded projects;
717
however, the Pages database records are no longer available for direct editing in CitectSCADA.
PageLast
Displays the graphics page that was last displayed. With this function, you can successively recall the last ten pages that were displayed. Graphics pages displayed using this command cannot be subsequently recalled. You cannot call this function from the Exit command field (see Page Properties) or a Cicode Object. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageLast()
Return Value
Buttons Text Command Comment Last Page PageLast() Display the graphics page that was last displayed
718
/* Displays page "MIMIC2" and places page "MIMIC1" onto the page navigation history. */ PageDisplay("10"); ! Displays page "10" and places page "MIMIC2" onto the PageLast stack. PageLast(); /* Displays the last page on the stack, that is page "MIMIC2" and removes it from the stack. */ PageLast(); /* Displays the last page on the stack, that is page "MIMIC1" and removes it from the stack. */ PageLast(); /* Returns an "Out of range" error code as there are no more pages on the stack.*/
PageListCount
Gets number of pages in the page list of the current window.
Syntax
PageListCount()
Return Value
INT count; INT index; INT error; STRING PageName; // While 4 entries will be added to page history, only 3 unique pages will be added to page list PageDisplay(Page1); PageDisplay(Page2); PageDisplay(Page1); PageDisplay(Page3); // iterate the pages in the list
719
count=PageListCount() PageName=PageListInfo(0,0); PageName=PageListInfo(1,0); PageName=PageListInfo(2,0); index=PageListCurrent(); pageName=PageListInfo(index,0); error-PageListDisplay(1); index=PageListCurrent(); PageName=PageInfo(0); error=PageListDelete(index); PageName=PageInfo(0); index=PageListCurrent(); reduced count=PageListCount();
//count=3 //PageName=Page1 //PageName=Page2 //PageName=Page3 //index=2,as Page3 is currently displayed //PageName=Page3 //recall Page2, error=0 //index=1, as current index is moved as part of the recall //PageName=Page2 as it becomes the current page //remove current page, i.e. Page2, error=0 //PageName=Page3, next page in the list is displayed //index=1, current index is not changed while the list is //count=2, only 2 pages left in the list
PageListCurrent
Gets Index of the current page in the page list of current window
Syntax
PageListCurrent()
Return Value
INT count; INT index; INT error; STRING PageName; // While 4 entries will be added to page history, only 3 unique pages will be added to page list PageDisplay(Page1); PageDisplay(Page2); PageDisplay(Page1); PageDisplay(Page3); // iterate the pages in the list
720
count=PageListCount() PageName=PageListInfo(0,0); PageName=PageListInfo(1,0); PageName=PageListInfo(2,0); index=PageListCurrent(); pageName=PageListInfo(index,0); error-PageListDisplay(1); index=PageListCurrent(); PageName=PageInfo(0); error=PageListDelete(index); PageName=PageInfo(0); index=PageListCurrent(); reduced count=PageListCount();
//count=3 //PageName=Page1 //PageName=Page2 //PageName=Page3 //index=2,as Page3 is currently displayed //PageName=Page3 //recall Page2, error=0 //index=1, as current index is moved as part of the recall //PageName=Page2 as it becomes the current page //remove current page, i.e. Page2, error=0 //PageName=Page3, next page in the list is displayed //index=1, current index is not changed while the list is //count=2, only 2 pages left in the list
PageListInfo
Gets information of a page at the specific index in the page list of the current window.
Syntax
Type
Information to return: 0- Page name (default) 1- Configured Page Title 2- Active Page Title
Return Value
String value of the requested information, or empty string if no valid information can be found
Related Functions
721
INT count; INT index; INT error; STRING PageName; // While 4 entries will be added to page history, only 3 unique pages will be added to page list PageDisplay(Page1); PageDisplay(Page2); PageDisplay(Page1); PageDisplay(Page3); // iterate the pages in the list count=PageListCount() PageName=PageListInfo(0,0); PageName=PageListInfo(1,0); PageName=PageListInfo(2,0); index=PageListCurrent(); pageName=PageListInfo(index,0); error-PageListDisplay(1); index=PageListCurrent(); PageName=PageInfo(0); error=PageListDelete(index); PageName=PageInfo(0); index=PageListCurrent(); reduced count=PageListCount();
//count=3 //PageName=Page1 //PageName=Page2 //PageName=Page3 //index=2,as Page3 is currently displayed //PageName=Page3 //recall Page2, error=0 //index=1, as current index is moved as part of the recall //PageName=Page2 as it becomes the current page //remove current page, i.e. Page2, error=0 //PageName=Page3, next page in the list is displayed //index=1, current index is not changed while the list is //count=2, only 2 pages left in the list
PageListDisplay
Recalls (displays) a page at the specific index in the page list of current window, and moves the current index to the page. When a page is recalled, the original parameters (such as cluster context, supergenie associations, PageTask arguments if applicable) used to display the page will be restored.
Syntax
Return Value
722
INT count; INT index; INT error; STRING PageName; // While 4 entries will be added to page history, only 3 unique pages will be added to page list PageDisplay(Page1); PageDisplay(Page2); PageDisplay(Page1); PageDisplay(Page3); // iterate the pages in the list count=PageListCount() PageName=PageListInfo(0,0); PageName=PageListInfo(1,0); PageName=PageListInfo(2,0); index=PageListCurrent(); pageName=PageListInfo(index,0); error-PageListDisplay(1); index=PageListCurrent(); PageName=PageInfo(0); error=PageListDelete(index); PageName=PageInfo(0); index=PageListCurrent(); reduced count=PageListCount();
//count=3 //PageName=Page1 //PageName=Page2 //PageName=Page3 //index=2,as Page3 is currently displayed //PageName=Page3 //recall Page2, error=0 //index=1, as current index is moved as part of the recall //PageName=Page2 as it becomes the current page //remove current page, i.e. Page2, error=0 //PageName=Page3, next page in the list is displayed //index=1, current index is not changed while the list is //count=2, only 2 pages left in the list
PageListDelete
Removes a page at the specific index from the page list of the current window. This function will return an error if only one page is in the list. If the page is currently displayed, the next page will be displayed. If there is no next page, the previous page will be displayed.
Syntax
Return Value
723
INT count; INT index; INT error; STRING PageName; // While 4 entries will be added to page history, only 3 unique pages will be added to page list PageDisplay(Page1); PageDisplay(Page2); PageDisplay(Page1); PageDisplay(Page3); // iterate the pages in the list count=PageListCount() PageName=PageListInfo(0,0); PageName=PageListInfo(1,0); PageName=PageListInfo(2,0); index=PageListCurrent(); pageName=PageListInfo(index,0); error-PageListDisplay(1); index=PageListCurrent(); PageName=PageInfo(0); error=PageListDelete(index); PageName=PageInfo(0); index=PageListCurrent(); reduced count=PageListCount();
//count=3 //PageName=Page1 //PageName=Page2 //PageName=Page3 //index=2,as Page3 is currently displayed //PageName=Page3 //recall Page2, error=0 //index=1, as current index is moved as part of the recall //PageName=Page2 as it becomes the current page //remove current page, i.e. Page2, error=0 //PageName=Page3, next page in the list is displayed //index=1, current index is not changed while the list is //count=2, only 2 pages left in the list
PageMenu
Displays a menu page with page selection buttons. A page goto button is displayed for each of the first 40 pages defined in the project.
Syntax
PageMenu()
Return Value
724
Related Functions
Buttons Text Command Comment System Keyboard Key Sequence Command Comment Menu PageMenu() Display the menu page Menu PageMenu() Display the menu page
PageNext
Displays the next page as specified in the project. You cannot call this function from the Exit command field (see Page Properties) or a Cicode Object. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageNext()
Return Value
PagePrev
725
Example
Buttons Text Command Comment System Keyboard Key Sequence Command Comment PageNext PageNext() Display the next page in the browse sequence Page Next PageNext() Display the next page in the browse sequence
/* If graphics page 1 is currently displayed, and the graphics page 1 has Next Page Name=10. */ PageNext(); ! Displays graphics page 10.
PagePeekCurrent
Return the index in the page stack for the current page.
Syntax
PagePeekCurrent()
Return Value
Index in the page stack for the current page. -1 indicates that current window handle does not correspond to a valid window.
Related Functions
PagePeekLast
726
Gets information about a Page at an offset in the page navigation history. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
If you then navigate "Back" twice the iOffset value indicates the following pages: iOffset value: corresponding page: 2 1 0 -1 -2 A B C D E
If you further navigate to pages F then G the iOffset value indicates the following pages: iOffset value: corresponding page: 4 3 2 1 0 A B C F G
iType:
An enumeration representing the type of information required. The default value is 0.
String value of the requested information, or empty string if no valid result for given arguments.
727
Related Functions
PagePopLast
Gets the Page Name of the last item in the page navigation history and removes the page from the history. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PagePopLast()
Return Value
PagePopUp
728
Display pop up window at the mouse position. If the mouse position is not known then the pop up will display in the centre of the screen. The window is displayed with no resize and will be closed if the page is changed.
Syntax
Note: Before CitectSCADA version 5.0, page records could be edited in the Project Editor. One of the fields available for configuration was "Page Number". The value entered for a page could then be used in runtime with the Page Cicode functions such as PageDisplay(), PageGoto(), and PageInfo(1). For example, PageDisplay("1") can be used to display the page that has "1" (without the quotes) set in the Page Number field. PageInfo(1) returns the Page Number of the current page. From version 5.0 on, this feature is only backwards-supported. The "Alias" field in the project Pages.DBF file still contains the Page Numbers from upgraded projects; however, the Pages database records are no longer available for direct editing in CitectSCADA. sClusterName:
The name of the cluster that will accommodate the page at runtime (in quotation marks ""). The specified cluster is used to resolve any tags that have a cluster omitted. If the Page parameter is prefixed with the name of a cluster, this parameter will not be used. This parameter is optional, however if you omit a cluster context in the Page properties, then any tags which omit an explicit Cluster. TagName will be ambiguous and become unresolved if you have multiple clusters defined in the project. Note that this ambiguity and resulting unresolved state will only occur if the parameter [General]TagDB is set to "0" which disables variable tag database loading.
Related Functions
PagePrev
Displays the previous page as specified in the project.
729
You cannot call this function from the Exit command field (see Page Properties) or a Cicode Object. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PagePrev()
Return Value
PageNext
Example
Buttons Text Command Comment System Keyboard Key Sequence Command Comment PagePrev PagePrev() Display the previous page in the browse sequence Page Previous PagePrev() Display the previous page in the browse sequence
/* If graphics page 10 is currently displayed, and graphics page 10 has Prev Page Name=1. */ PagePrev(); ! Displays graphics page 1.
PageProcessAnalyst
730
Displays a Process Analyst page (in the same window) preloaded with the pre-defined Process Analyst View (PAV) file.
Syntax
PageProcessAnalyst(sPage, sPAVFile1 [, iFileLocation1 [, iButtonMask1 [, sObjName1 [, sPAVFile2 [, iFileLocation2 [, iButtonMask2 [, sObjName2 ]]]]]]]) sPage:
The name of the page that contains Process Analyst object(s). For example, pages based on the Process Analyst templates found in the Tab_Style_Include project.
sPAVFile1:
Name of the 1st PAV file
iFileLocation1:
PAV file location code for the 1st PAV file, see PA doc LoadFromFile() for details.
iButtonMask1:
Bit mask for removing command buttons from the 1st PA, bit flags as shown below:
l l l l l l l l l
1 - Load View 2 - Save View 4 - Print 8 - Copy to Clipboard 16 - Copy to File 32 - Add Pens 64 - Remove Pens 128 - Show Properties 256 - Help
sObjName1:
Name of the PA object on the given Page where the 1st PAV file will be loaded. If this parameter is not specified or empty string, it is defaulted to the object name used in the tab style templates, that is "_templatePA1".
sPAVFile2:
Name of the 2nd PAV file
iFileLocation2:
PAV file location code for the 2nd PAV file
iButtonMask2:
731
Bit mask for removing command buttons from the 2nd PA, refer iButtonMask1 for details
sObjName2:
Name of the PA object on the given Page where the 2nd PAV file will be loaded. If this parameter is not specified or empty string, it is defaulted to the object name used in the tab style templates, that is "_templatePA2".
Return Value
PageProcessAnalystPens, ProcessAnalystLoadFile, ProcessAnalystPopUp, ProcessAnalystSelect, ProcessAnalystSetPen, ProcessAnalystWin, TrnSetPen, WinNewAt See Also Page Functions
PageProcessAnalystPens
Display a page and add the specified pens to the first pane of the specified PA object on the page. If a PAV file is also specified, it will be loaded first, and the pens in the first pane will be removed before the specified pens are created on the PA.
Syntax
PageProcessAnalystPens(sPage, sTag1 [, sTag2..sTag8 [, iButtonMask [, sObjName [, iPane [, sPAVFile [, iFileLocation ]]]]]]) sPage:
The name of the page that displays the PA.
sTag1..sTag8:
Up to 8 Trend tags can be added to the PA.
iButtonMask:
Mask to remove button(s) from the main tool bar of PA. The following values can be combined to remove multiple buttons:
l l l l l l
1 - Load View 2 - Save View 4 - Print 8 - Copy to Clipboard 16 - Copy to File 32 - Add Pens
732
l l l
sObjName
The name of the PA object. If not specified it is defaulted to "_templatePA1" which is the name used by the built-in templates.
iPane
The pane in PA where the trend or variable tags are added. If this is not specified or less than 1, it is defaulted to 1 (the 1st pane). If the specified pane does not exist in the PA object, a new pane will be created.
sPAVFile:
Optional Process Analyst View file to be loaded, default ="".
iFileLocation:
Optional location of the PAV file. The allowed values are:
l l l
0 - Analyst Views subfolder in project folder (default) 1 - Folders specified in properties primary/standby server path 2 - My documents folder
Return Value
PageProcessAnalyst, ProcessAnalystLoadFile, ProcessAnalystPopUp,ProcessAnalystSelect, ProcessAnalystSetPen, ProcessAnalystWin, TrnSetPen, WinNewAt See Also Page Functions
PagePushLast
Places a page at the end of the page navigation history. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PagePushLast(Page)
733
Page:
The Page Name or Page Number (of the page) to place at the end of the page navigation history.
Return Value
PageRecall
Displays the page at a specified depth in the page navigation history.
Syntax
PageRecall(iIndex) iIndex:
The index into the page navigation history of the Page to be displayed. To get the index for the currently displayed page, call PagePeekCurrent(). Then increment it to access pages in the forward history, or decrement it to access pages in the backward history. Be reminded that you cannot recall the page that is currently displayed.
Return Value
734
No error(0) on success. Bad handle specified (269) if current window handle does not correspond to a valid window. Bad handle specified (274) if index is outside of allowable bounds.
Related Function
PageRichTextFile
This function creates a rich edit object, and loads a copy of the rich text file Filename into that object. The rich text object will be rectangular in shape, with dimensions determined by nHeight, and nWidth. If you do not specify nHeight and nWidth, nAN will define the position of one corner, and (AN + 1) the position of the diagonally opposite corner. This function would often be used as a page entry function.
Syntax
Filename:
The name of the file to be copied and loaded into the rich text object. The filename needs to be entered in quotation marks "". If you are loading a copy of an RTF report, the report needs to have already 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 rtf extension, you need to change it to reflect the number of the desired history file, for example, 001.
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.
735
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.
nHeight:
The height of the rich text object in pixels. The height is established by measuring down from the animation point. If you do not enter a height and width, the size of the object will be determined by the position of nAN and AN+1.
nWidth:
The width of the rich text object in pixels. The width is established by measuring across to the right of the animation point. If you do not enter a height and width, the size of the object will be determined by the position of nAN and AN+1.
Return Value
None
Related Functions
DspRichText, DspRichTextLoad, DspRichTextEdit, DspRichTextEnable, DspRichTextGetInfo, DspRichTextPgScroll, DspRichTextPrint, DspRichTextSave, DspRichTextScroll, FileRichTextPrint
Example
PageRichTextFile(108,"f:\citect\data\richtext.rtf",0); // This function would produce a rich text object at animation point 108. Into this object a copy of f:\citect\data\richtext.rtf would then be loaded. Remember, richtext.rtf is the name of the output file for the report, as specified in the Devices form. Because 0 was specified as the nMode for this example, the contents of this object will be display only. // PageRichTextFile(53,"[Data]\richtext.rtf",1); //This function would produce a rich text object at animation point 53. Into this object a copy of [Data]\richtext.rtf would then be loaded. It will be possible to select and copy the
736
PageSelect
Displays a dialog box with a list of graphics pages defined in the project. AN operator can select a page name for display.
Syntax
PageSelect()
Return Value
Buttons Text Command Comment Page Select PageSelect() Display the page selection dialog box
PageSetInt
Associates an integer variable with a particular page. Page-based variables are stored in an array, local to each display page. This function allows you to save integer variables in temporary storage. Notes
737
You can dynamically change the setting for [Page]ScanTime parameter, by calling this function as follows: PageSetInt(-2, <scantime>). This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
sVar:
The integer to store.
iWinNum:
Window number of the page. Default is current window.
Return Value
No error(0) on success. Bad handle specified (269) if WinNum handle does not correspond to a valid window. Bad handle specified (274) if Label or Var is not a valid variable.
Related Functions
PageSetStr
Stores a local page-based string and associates the string with the page. Page-based variables are stored in an array, local to each display page. This function allows you to save string variables in temporary storage. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
738
sVar:
The string to store. The string length is 128 characters.
iWinNum:
Window number of the page. Default is current window.
Return Value
No error (0) on success. Bad handle specified (269) if WinNum handle does not correspond to a valid window. Bad handle specified (274) if Label or Var is not a valid variable.
Related Functions
PageSOE
Displays a category of sequence of events (SOE) entries on the SOE page. To use this function, you need to have a page in your project that was created using the SOE template. By default, the name of the page is expected to be "SOE". However, you can use an alarm page with different name by adjusting the setting for the INI parameter [Page]SOEPage.
Syntax
PageSOE(INT Category, INT Fallback) Category: The category number for the alarms you want to display their events Fallback: Whether to display the Summary page instead if the SOE page does not exist. If not specified it defaults to FALSE (0).
Return Value
PageAlarm
Example
739
PageSummary
Displays a category of alarm summary entries on the alarms summary page. To use this function, you need to have a page in your project that was created using the Summary template. By default, the name of the page is expected to be "Summary". However, you can use an alarm page with a different name by adjusting the setting for the INI parameter [Page]SummaryPage. Notes
l
The operation of this function has changed. In Version 2.xx this function displayed the built-in summary alarm page from the Include project. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
PageSummary(Category) Category:
The category number for the alarms you want to summarise.
Return Value
PageAlarm
Example
System Keyboard Key Sequence Command Comment SummaryPage
System Keyboard
740
PageSummary(Arg1) Display a specified category of alarm summary entries on the alarm page
PageTask
PageTask() is used for running preliminary Cicode before displaying a page in a window. It makes it possible for the same Cicode to be run if the page is re-entered by navigating forward or back. PageTask() is similar to TaskNew(). PageTask() returns a handle to a code task the first time it is run. The custom Cicode of the sFunctionName parameter needs to call PageDisplay() in order to display the page. When the page changes, the function and its parameters will be pushed onto the Page History stack. The Cicode fnTask will be called again when the page is navigated to using the PageForward or PageBackward functions.
Syntax
sFunctionName:
String representing the Cicode function to run each time the page is navigated to using the forward and backward navigation functions.
sFunctionArg:
String representing the parameters to use with function fnTask.
Return Value
A handle to a code task the first time it is run. BAD_HANDLE (-1) if the function did not complete.
Related Functions
PageBack, PageForward
Example
741
PageTransformCoords
Converts Page coordinates to absolute screen coordinates.
Syntax
PageX:
X coordinate of page coordinate.
iPageY:
Y coordinate of page coordinate.
iDisplayX :
Output parameter Transformed X coordinate.
iDisplayY:
Output parameter Transformed Y coordinate.
iType:
The value of output coordinate:
0 - Absolute screen coordinates 1 - Coordinates relative to Window origin 2 - Coordinates relative to Client rectangle origin
Return Value
0 Success 269 ERROR_BAD_HANDLE hPage is not a valid Page handle 274 ERROR_INVALID_ARG either DisplayX, DisplayY or Type is invalid.
Related Functions
742
PageTrend
Displays a trend page with the specified trend pens. Use this function to display trends in a single cluster system with a single trend page. You need to create the trend page with the Graphics Builder and set the pen names to blank. Then display that page by calling this function and passing the required trend tags. Call this function from a menu of trend pages. Note: Because you cannot mix templates in a project, PageTrend will not work if you have included the CSV_Include project in your project. For example, if your project includes the CSV_Include project, PageTrend("pagename", "trendtag") only works on trend pages based on XP-style templates (that is, "Trend"). When using PageTrend to go to a page based on a standard template (for example, "SingleTrend"), the page displays, but no trend tag is added. This also applies for the CSV_Trend_Page function. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised. For a multi-cluster system use PageTrendEx.
Syntax
sTag1:
The first trend tag to display on the page.
sTag2..sTag8:
Optionally trend tags 2 to 8 to display on the page.
Return Value
0 (zero) if successful, otherwise an error is returned. Note: Before CitectSCADA version 5.0, page records could be edited in the Project Editor. One of the fields available for configuration was "Page Number". The value entered for a page could then be used in runtime with the Page Cicode functions such as PageDisplay(), PageGoto(), and PageInfo(1). For example, PageDisplay("1") can be used to display the page that has "1" (without
743
the quotes) set in the Page Number field. PageInfo(1) returns the Page Number of the current page. From version 5.0 on, this feature is only backwards-supported. The "Alias" field in the project Pages.DBF file still contains the Page Numbers from upgraded projects; however, the Pages database records are no longer available for direct editing in CitectSCADA.
Related Functions
Buttons Text Command Comment Process Trend PageTrend("MyTrend", "PV1", "PV2", "PV3") Display the trend page with three trend pens
PageTrend("MyTrend", "PV1", "PV2", "PV3") /* Display three trend tags on a single trend page. */
PageTrendEx
Displays a trend page of a specified cluster in a multi-cluster system with the specified trend pens. Use this function to display trends in a mult-cluster system with a single trend page. You need to create the trend page with the Graphics Builder and set the pen names to blank. Then display that page by calling this function and passing the required trend tags. Call this function from a menu of trend pages. This function can also be used in a single cluster system, the sCluster argument is optional in such a case. Note: Because you cannot mix templates in a project, PageTrendEx will not work if you have included the CSV_Include project in your project. For example, if your project includes the CSV_Include project, PageTrend("pagename", "trendtag") only works on trend pages based on XP-style templates (that is, "Trend"). When using PageTrend to go to a page based on a standard template (for example,
744
"SingleTrend"), the page displays, but no trend tag is added. This also applies for the CSV_Trend_Page function. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
sCluster:
Name of the cluster in which the trend page is located.
sTag1:
The first trend tag to display on the page.
sTag2..sTag8:
Optionally trend tags 2 to 8 to display on the page.
Return Value
0 (zero) if successful, otherwise an error is returned. Note: Before CitectSCADA version 5.0, page records could be edited in the Project Editor. One of the fields available for configuration was "Page Number". The value entered for a page could then be used in runtime with the Page Cicode functions such as PageDisplay(), PageGoto(), and PageInfo(1). For example, PageDisplay("1") can be used to display the page that has "1" (without the quotes) set in the Page Number field. PageInfo(1) returns the Page Number of the current page. From version 5.0 on, this feature is only backwards-supported. The "Alias" field in the project Pages.DBF file still contains the Page Numbers from upgraded projects; however, the Pages database records are no longer available for direct editing in CitectSCADA.
Related Functions
745
Buttons Text Command Comment Process Trend PageTrendEx("MyTrend", "MyCluster", "PV1", "PV2", "PV3")
Display the trend page on the specified cluster with three trend pens
PageTrendEx("MyTrend", "MyCluster", "PV1", "PV2", "PV3") /* Display three trend tags on a single trend page on the specified cluster. */
746
Draws gridlines to be used for plotted lines. Gets information about a plot. Plots a line through a set of data points. Draws markers on a plotted line or at a specified point. Opens a new plot, sets its output device, and returns a plot handle for use by the other plot functions. Draws scale lines (with markers) beside the grid on your plot (if there is one). Sets (registers) a symbol as a marker.
PlotClose
Displays the plot on screen or sends it to the printer (depending on the output device you specified in the PlotOpen() function), then closes the plot. Once the plot is closed, it cannot be used.
747
Syntax
PlotClose(hPlot) hPlot:
The plot handle, returned from the PlotOpen() function. The plot handle identifies the table where all data on the plot is stored.
Return Value
PlotDraw, PlotGetMarker, PlotGrid, PlotInfo, PlotLine, PlotMarker, PlotOpen, PlotScaleMarker, PlotSetMarker, PlotText, PlotXYLine, TrnPlot
Example
PlotDraw
Constructs drawings on your plot. Use the coordinates (X1,Y1) and (X2,Y2) to define a point, line, rectangle, square, circle, or ellipse. You can specify the style, color, and width of the pen, and a fill color for a box or circular shape. you need to call the PlotOpen() function first, to get the handle for the plot (hPlot) and to specify the output device.
Syntax
PlotDraw(hPlot, Type, PenStyle, PenCol, PenWidth, nFill, X1, Y1, X2, Y2) hPlot:
The plot handle, returned from the PlotOpen() function. The plot handle identifies the table where data on the plot is stored.
nType:
The type of drawing:
748
0 - Solid 1 - Dash ( - - - - - ) 2 - Dot (...............................) 3 - Dash and dot ( - . - . - . - . - ) 4 - Dash, dot, dot ( - . . - . . - . . - ) 5 - Hollow PenCol:
The color of the pen (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
PenWidth:
Pen width in pixels. If the width is thicker than one pixel, you need to use a solid pen (PenStyle = 0). Maximum width is 32.
nFill:
The fill color of the rectangle, square, circle, or ellipse (flashing color is not supported). Select a color from the list of predefined color names and codes or create an RGB-based color using the function MakeCitectColour. For a point or line, nFill is ignored.
X1, Y1:
X and y coordinates (in pixels) of the upper-left corner of the drawing (the origin).
X2, Y2:
X and y coordinates (in pixels) of the lower-right corner of the drawing. For a point, (X1,Y1) and (X2,Y2) are assumed to be the same, so (X2,Y2) is ignored. To draw a circle or ellipse, enter the coordinates for a square or rectangle; the circle or ellipse is automatically drawn within the box. If the plot is for display on the screen, coordinates are relative to the AN specified in the PlotOpen() function. If the output device is a printer, coordinates are relative to the point (0,0).
Return Value
PlotClose, PlotGrid, PlotInfo, PlotLine, PlotMarker, PlotOpen, PlotScaleMarker, PlotText, PlotXYLine, TrnPlot
Example
See PlotOpen.
749
PlotGetMarker
Gets the marker number of a symbol. The symbol needs to be a symbol and registered with the PlotSetMarker() function.
Syntax
PlotGetMarker(sSymbolName) sSymbolName:
The library name and symbol name ("Library.Symbol") of the symbol that is registered as a marker.
Return Value
PlotGrid
Defines a frame and draws horizontal and vertical grid lines within this frame. These grid lines can then be used by the PlotLine(), PlotXYLine(), and PlotScaleMarker() functions. You need to define the frame for a plot before you can plot points with the PlotLine() and PlotXYLine() functions. nSamples specifies the maximum number of samples that can be plotted for a single line. If you set FrameWidth to 0 (zero), the frame will be defined but not displayed (however, the plot will still be displayed).
750
You can specify the number of grid lines and their color, as well as the background color which will fill the frame. If nHorGrid and nVerGrid are set to 0 (zero), then the grid lines will not be drawn. you need to call the PlotOpen() function, first, to get the handle for the plot (hPlot), and to specify the output device. Then call this function to set up the frame and grid. You can then call the PlotScaleMarker() function to draw scale lines beside the frame, and call the PlotLine() or PlotXYLine() to plot a set of data points.
Syntax
PlotGrid(hPlot, nSamples, X1, Y1, X2, Y2, nHorGrid, HorGridCol, nVerGrid, VerGridCol, FrameWidth, FrameCol, nFill, nMode) hPlot:
Plot handle, returned from the PlotOpen() function. The plot handle identifies the table where data on the plot is stored.
nSamples:
The maximum number of samples that can be plotted for a single line in this grid (valid values between 2 and 16000 inclusive). For example, if you set nSamples to 10, then plot 2 lines in this grid (using the PlotLine() function), each line will be plotted with a maximum of 10 samples. For this example, a line can possess less than 10 samples, but if it has more, it will be shortened to 10 samples.
X1, Y1:
The x and y coordinates of the upper-left corner of the frame containing the grid lines.
X2, Y2:
The x and y coordinates of the lower-right corner of the frame containing the grid lines. If the plot is for display on the screen, you should set ( X1,Y1) to (0,0). The origin of the frame is then positioned at the AN specified in the PlotOpen() function. If the output device is a printer, both ( X1,Y1) and ( X2,Y2) are relative to the point (0,0).
nHorGrid:
The number of rows (formed by the horizontal grid lines) to draw within the frame. If there is no need of grid lines, set nHorGrid to 0 (zero) and HorGridCol to 0. nHorGrid cannot exceed the pixel width of the plot.
HorGridCol:
The color of the horizontal grid lines (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
nVerGrid:
751
The number of columns (formed by the vertical grid lines) to draw within the frame. If there is no need of grid lines, set nVerGrid to 0 (zero) and VerGridCol to 0. nVerGrid cannot exceed the pixel height of the plot.
VerGridCol:
The color of the vertical grid lines (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
FrameWidth:
The width (also called pen width) of the frame enclosing the grid, in pixels. To define the frame without drawing its boundaries, set FrameWidth to 0 (zero) and FrameCol to 0. The maximum is 32.
FrameCol:
The color of the frame enclosing the grid (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
nFill:
The background color for the frame (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
nMode:
The mode of the plot. For future use only - set it to 0 (zero).
Return Value
PlotClose, PlotDraw, PlotInfo, PlotLine, PlotMarker, PlotOpen, PlotScaleMarker, PlotText, PlotXYLine, TrnPlot
Example
PlotInfo
752
Gets information about the plot. You can call this function to determine the number of pixels per page or inch, the resolution of a plot, and the size and spacing of characters for a specified text font. You can also check whether a printer can print rotated text. (See PlotText().) you need to first call the PlotOpen() function to get the handle for the plot (hPlot) and specify the output device.
Syntax
nType:
The type of plot information to get:
0 - Horizontal pixels on a printout page 1 - Vertical pixels on a printout page 2 - Horizontal pixels per inch 3 - Vertical pixels per inch 4 - Horizontal resolution 5 - Vertical resolution 6 - Height of the font used 7 - External leading of the font used 8 - Character width of the font used 9 - Rotatable text is allowed or not 10 - Indicates whether or not a font is supported 11 - Horizontal size of a page in millimeters 12 - Vertical size of a page in millimeters sInput:
The font handle (hFont), returned from the DspFont() function. Useful only for Type 6, 7, 8, or 10.
Return Value
PlotClose, PlotDraw, PlotGrid, PlotLine, PlotMarker, PlotOpen, PlotScaleMarker, PlotText, PlotXYLine, TrnPlot
Example 753
hPlot = PlotOpen(36,"Display",1); : /* Print text in upward direction but first check if printer supports text rotation. Set default text orientation to left to right (just in case). */ Orient = 0; IF PlotInfo(hPlot,9) THEN Orient = 1; END PlotText(hPlot,hFont,Orient,100,100,"scale"); .. /* Print text "Citect Graph" centred horizontally at top of page.*/ PageWidth = PlotInfo(hPlot,0); ! Get width of page hFont = DspFont("Courier",14,black,-1); TextWidth = PlotInfo(hPlot,8,hFont); ! Get width of each character TextPosn = (PageWidth - TextWidth * 12) / 2 ! Get start of 1st character PlotText(hPlot,hFont,0,TextPosn,0,"Citect Graph"); .. PlotClose(hPlot);
PlotLine
Draws a line (in the CitectSCADA plot system) for a set of data points. You specify the data points in the table pTable, and plot these points between the LoScale and HiScale values. The line is drawn inside the frame defined by the PlotGrid() function. For each line on a plot, you can specify a different pen style, color, and width, and a different marker style and color. You can draw lines either from left to right or from right to left. you need to first call the PlotOpen() function to get the handle for the plot (hPlot) and specify the output device. You should then use the PlotGrid() function to set up the frame and grid, before you call this function to plot the line.
Syntax
PlotLine(hPlot, PenStyle, PenCol, PenWidth, MarkerStyle, MarkerCol, nMarker, Length, pTable, LoScale, HiScale, Mode) hPlot:
The plot handle, returned from the PlotOpen() function. The plot handle identifies the table where all data on the plot is stored.
PenStyle:
The style of the pen used to draw:
0 - Solid
754
1 - Dash ( - - - - - ) 2 - Dot (...............................) 3 - Dash and dot ( - . - . - . - . - ) 4 - Dash, dot, dot ( - . . - . . - . . - ) 5 - Hollow PenCol:
The color of the pen (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
PenWidth:
The width of the pen, in pixels. If the width is thicker than one pixel, you need to use a solid pen (PenStyle = 0). The maximum width is 32.
MarkerStyle:
The style of the markers:
0 - No markers 1 - Triangle 2 - Square 3 - Circle 4 - Diamond 5 - Filled triangle 6 - Filled square 7 - Filled circle 8 - Filled diamond 20 - 32000 - User-defined markers. You can register any symbol as a marker with the PlotSetMarker() function. Call the PlotGetMarker() function if the number of markers you have previously registered are unknown. MarkerCol:
The color of the markers (flashing color is not supported). Select a color from the list of predefined color names and codes or create an RGB-based color using the function MakeCitectColour.
nMarker:
The number of samples between markers.
Length:
The length of the array, that is, the number of points in the table pTable for PlotLine(), or in tables xTable and yTable for PlotXYLine().
l
For every line you draw with the PlotLine() and PlotXYLine() functions within a plot, you need to add the Length arguments for each call, and pass
755
the total to the PlotGrid() function (in the nSamples argument). pTable:
The points to be plotted (as an array of floating-point values).
LoScale:
The lowest value that will be displayed on the plot (that is the value assigned to the origin of your grid). The LoScale and HiScale values determine the scale of your grid. This scale is used to plot values. for example, If LoScale = 0 (zero) and HiScale = 100, a value of 50 will be plotted half way up the Y-axis of your grid. LoScale needs to be in the same units as the values in pTable.
HiScale:
The highest value that will be displayed on the plot. The LoScale and HiScale values determine the scale of your grid. This scale is used to plot values. for example, If LoScale = 0 (zero) and HiScale = 100, a value of 50 will be plotted half way up the Y- axis of your grid. HiScale needs to be in the same units as the values in pTable.
Mode:
The origin of your grid, and the direction of the plotted line:
1 - Origin is bottom-left, x is left to right, y is upwards 2 - Origin is bottom-right, x is right to left, y is upwards 4 - Origin is top-left, x is left to right, y is downwards 8 - Origin is top-right, x is right to left, y is downwards
Return Value
PlotClose, PlotDraw, PlotGetMarker, PlotGrid, PlotInfo, PlotMarker, PlotOpen, PlotScaleMarker, PlotSetMarker, PlotText, PlotXYLine, TrnPlot
Example
PlotMarker
Draws markers on a plotted line or at a specified point. You can plot any one of the standard markers, or use a symbol of your choice. (you need to first register your symbol as a marker, by using the PlotSetMarker() function.)
756
To draw a single marker at a specified point, set X and Y to the coordinates of the point, and set Length to 1. You can draw markers on a plotted line when you draw the line, that is within the PlotLine() or PlotXYLine() function. You would use the PlotMarker() function only if you need to draw a second set of markers on the same line. Call PlotMarker() immediately after the line is drawn. Set X and Y to -1 and Length to the number of data points (specified in the Length argument of the PlotLine() or PlotXYLine() function). you need to first call the PlotOpen() function to get the handle for the plot (hPlot) and specify the output device.
Syntax
MarkerStyle:
The style of the markers:
0 - No markers 1 - Triangle 2 - Square 3 - Circle 4 - Diamond 5 - Filled triangle 6 - Filled square 7 - Filled circle 8 - Filled diamond 20 - 32000: User-defined markers. You can register any symbol as a marker with the PlotSetMarker() function. Call the PlotGetMarker() function if the number of markers you have previously registered are unknown. MarkerCol:
The color of the marker (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
nMarker:
The number of samples between markers.
Length:
757
The length of the array (the number of line points in the table pTable) plotted in the PlotLine() or PlotXYLine() function. To draw only one marker at a specified point, set Length to 1.
X, Y:
The x and y coordinates, in pixels, of the point where the marker is to be drawn. If the plot is for display on the screen, the coordinates are relative to the AN specified in the PlotOpen() function. If the output device is a printer, the coordinates are relative to the point (0,0). To draw the markers on a plotted line, set both X and Y to -1, and set Length to the same value as the Length passed in the PlotLine() or PlotXYLine() function.
Return Value
PlotClose, PlotDraw, PlotGetMarker, PlotGrid, PlotInfo, PlotLine, PlotOpen, PlotScaleMarker, PlotSetMarker, PlotText, PlotXYLine, TrnPlot
Example
hPlot=PlotOpen(36,"Display",1); .. /* Draw a filled red square marker at the point (X=100,Y=200). */ PlotMarker(hPlot,6,red,1,1,100,200); .. /* Draw 10 black triangles and 5 green cylinders along a plot line. */ PlotLine(hPlot,0,black,3,5,black,10,100,Buf2[0],0,100,2); PlotSetMarker(20,"Global.Cylinder"); PlotMarker(hPlot,20,green,5,100,-1,-1) .. PlotClose(hPlot);
PlotOpen
Opens a new plot, sets its output device, and returns its plot handle. You can send the plot to any one of your system printers, or display it on screen at the specified AN. you need to call this function before you can call the other plot functions.
Syntax
758
The animation point (AN) where the plot will display. Set the AN to 0 (zero) when sOutput is a printer. Do not use an animation point number at which a graphic object exists as this will prevent the PlotOpen() function from succeeding.
sOutput:
The output device where the plot is sent, for example:
l
"Display" - Display on screen. The plot is recorded in a metafile and displayed (at the specified AN) when the plot system is closed. "LPT1:" - Send to printer LPT1. "LPT2:" - Send to printer LPT2. "\\ABC\Printers\Color1" - Send to UNC port (and so on for any output device)
l l l
Mode:
When a plot is removed or updated, the portion of the background screen beneath it is blanked out. The mode determines how the background screen is restored. The mode of the plot system:
1 - Normal mode 2 - Use for compatibility with the old graph functions 17 - Soft (valid for normal mode). The background screen (a rectangular region beneath the plot) is restored with the original image. Any objects that are within the rectangular region are destroyed when the background is restored. 33 - Hard (valid for normal mode). The background screen (a rectangular region beneath the plot) is painted with the color at the AN. 65 - Persistent (valid for normal mode). The plot is not erased. As the plot is updated, it is re-displayed on top. This mode provides fast updates. Transparent color is supported in this mode. 129 - Opaque animation (valid for normal mode). The plot is not erased. As the plot is updated, it is re-displayed on top. This mode provides the fastest updates. Transparent color is not supported in this mode. 257 - Overlapped animation (valid for normal mode). The background screen (the rectangular region beneath the plot) is completely repainted.
Return Value
The plot handle if the plot is opened successfully, otherwise -1 is returned. The plot handle identifies the table where all data on the associated plot is stored.
Related Functions
759
PlotClose, PlotDraw, PlotGrid, PlotInfo, PlotLine, PlotMarker, PlotScaleMarker, PlotText, PlotXYLine, TrnPlot
Example
hPlot=PlotOpen(0,"LPT2:",1); IF hPlot <> -1 THEN /* Set up a black frame with red & blue grid lines. */ PlotGrid(hPlot,18,450,800,1850,1600,5,red,10,blue,4,black,white,0); /* Draw a scale line to the left of the frame. */ PlotScaleMarker(hPlot,400,1600,6,1,black,0); /* Plot a simple line in green for a table of 10 values. */ PlotLine(hPlot,0,green,3,6,green,2,10,Buf1,0,100,1); /* Plot a line in yellow (with black markers) for tables of 8 X and Y values. */ PlotXYLine(hPlot,0,yellow,4,3,black,2,8,Buf2,0,150,Buf3,0,100,1); /* Draw a title box above the plot frame, with the heading "Citect Graph". */ PlotDraw(hPlot,1,0,black,1,grey,900,250,1400,400); hFont = DspFont("Times",-60,black,grey); PlotText(hPlot,hFont,0,950,350,"Citect Graph"); PlotClose(hPlot); END
PlotOpen(0,"LPT1:",1)
760
PlotOpen(20,"DISPLAY",17) // normal plot with soft animation PlotOpen(20,"DISPLAY",257) // normal plot with overlap animation PlotOpen(20,"DISPLAY",1) // normal plot with overlap animation (for default animation mode is overlap animation) PlotOpen(20,"DISPLAY",16) // INVALID (does not specify whether it is normal or Version 2.xx mode). PlotOpen(20,"DISPLAY",2) // INVALID for Version 2.xx graph system (does not support display as output).
PlotScaleMarker
Draws scale lines beside the grid on your plot (if there is one) and places markers on them. The height of the scale line is automatically set to the height of the frame set in the PlotGrid() function. you need to first call the PlotOpen() function to get the handle for the plot (hPlot) and specify the output device. You should then use the PlotGrid() function to set up the frame and grid, before you call this function to draw the scale lines.
Syntax
X, Y:
The x and y coordinates of the point where the scale line starts. The end coordinates of the scale line are automatically defined by the size of the frame (set in the PlotGrid() function). If the plot is for display on the screen, coordinates are relative to the AN specified in the PlotOpen() function. If the output device is a printer, coordinates are relative to the point (0,0).
nMarker:
The number of markers on the scale line.
PenWidth:
The width of the scale line, in pixels.
PenCol:
The color of the pen (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
Mode:
761
0 - Both sides of the scale line 1 - Left of the scale line 2 - Right of the scale line
Return Value
PlotClose, PlotDraw, PlotGrid, PlotInfo, PlotLine, PlotMarker, PlotOpen, PlotText, PlotXYLine, TrnPlot
Example
PlotSetMarker
Registers a symbol as a marker. You can then draw the new marker at points and on plotted lines, by specifying the MarkerNo of the symbol as the MarkerStyle in the PlotMarker() function. Call the PlotGetMarker() function if you do not know the number of a marker.
Syntax
sSymbolName:
The name and path of the symbol to be defined as a marker.
Return Value
762
hPlot=PlotOpen(30,"Display",1); .. /* Display red hourglass as marker at point (100,200). */ PlotSetMarker(20,"Global.Hourglass"); PlotMarker(hPlot,20,red,1,1,100,200); .. PlotClose(hPlot);
PlotText
Prints text on a plot. You can specify the font, position, and orientation of the text. If you specify an orientation other than 'left-to-right', you need to check that the font (and the printer) supports the orientation. you need to first call the PlotOpen() function to get the handle for the plot (hPlot) and specify the output device. You also needs to call the DspFont() function to get a handle for the font (hFont).
Syntax
hFont:
The font handle, returned from the DspFont() function. The font handle identifies the table where details of that font are stored.
Orientation:
The orientation of the text:
X, Y:
763
The x and y coordinates (in pixels) of the start of the text. If the plot is for display on the screen, the coordinates are relative to the AN specified in the PlotOpen() function. If the output device is a printer, the coordinates are relative to the point (0,0).
sText:
The text string to be plotted.
Return Value
DspFont, PlotClose, PlotDraw, PlotGrid, PlotInfo, PlotLine, PlotMarker, PlotScaleMarker, PlotXYLine, TrnPlot
Example
PlotXYLine
Plots values from two different tables. Values from one table are considered X coordinates, and values from the other are considered Y coordinates. Points are plotted between the low and high scale values specified for x and y. The line is plotted inside the frame defined by the PlotGrid() function. For each line, you can specify a different pen style, color, and width, and a different marker style and color. You can draw lines either from left to right or from right to left. You need to first call the PlotOpen() function to get the handle for the plot (hPlot) and specify the output device. You should then use the PlotGrid() function to set up the frame and grid, before you call this function to plot the line.
Syntax
PlotXYLine(hPlot, PenStyle, PenCol, PenWidth, MarkerStyle, MarkerCol, nMarker, Length, xTable, LoXScale, HiXScale, YTable, LoYScale, HiYScale, Mode) hPlot:
The plot handle, returned from the PlotOpen() function. The plot handle identifies the table where all data on the plot is stored.
PenStyle:
The style of the pen used to draw:
0 - Solid
764
1 - Dash ( - - - - - ) 2 - Dot (...............................) 3 - Dash and dot ( - . - . - . - . - ) 4 - Dash, dot, dot ( - . . - . . - . . - ) 5 - Hollow PenCol:
The color of the pen (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
PenWidth:
The width of the pen, in pixels. If the width is thicker than one pixel, you need to use a solid pen (PenStyle = 0). The maximum width is 32.
MarkerStyle:
The style of the markers:
0 - No markers 1 - Triangle 2 - Square 3 - Circle 4 - Diamond 5 - Filled triangle 6 - Filled square 7 - Filled circle 8 - Filled diamond 20 - 32000 - User-defined markers. You can register any symbol as a marker with the PlotSetMarker() function. Call the PlotGetMarker() function to recall the number of a marker you have previously registered. MarkerCol:
The color of the markers (flashing color is not supported). Select a color from the list of Predefined Color Names and Codes or create an RGB-based color using the function MakeCitectColour.
nMarker:
The number of samples between markers.
Length:
The length of the array, that is the number of points in the table pTable for PlotLine(), or in tables xTable and yTable for PlotXYLine().
765
For every line you draw with the PlotLine() and PlotXYLine() functions within a plot, you need to add the Length arguments for each call, and pass the total to the PlotGrid() function (in the nSamples argument).
xTable:
The x coordinates for the points in the line, as an array of floating point values.
LoXScale:
The lowest X-axis value that will be displayed on the plot (that is the X-coordinate of the origin of your grid). The LoXScale and HiXScale values determine the scale of your grid. This scale is used to plot values. for example, If LoXScale = 0 (zero) and HiXScale = 100, a value of 50 will be plotted half way along the X-axis of your grid. LoXScale needs to be in the same units as the values in xTable.
HiXScale:
The highest X-axis value that will be displayed on the plot. The LoXScale and HiXScale values determine the scale of your grid. This scale is used to plot values. for example, If LoXScale = 0 (zero) and HiXScale = 100, a value of 50 will be plotted half way along the X-axis of your grid. HiXScale needs to be in the same units as the values in xTable.
yTable:
The y coordinates for the points in the line, as an array of floating point values.
LoYScale:
The lowest Y-axis value that will be displayed on the plot (that is the Y-coordinate of the origin of your grid). The LoYScale and HiYScale values determine the scale of your grid. This scale is used to plot values. for example, If LoYScale = 0 (zero) and HiYScale = 100, a value of 50 will be plotted half way up the Y-axis of your grid. LoYScale needs to be in the same units as the values in xTable.
HiYScale:
The highest Y-axis value that will be displayed on the plot. The LoYScale and HiYScale values determine the scale of your grid. This scale is used to plot values. for example, If LoYScale = 0 (zero) and HiYScale = 100, a value of 50 will be plotted half way up the Y-axis of your grid. HiYScale needs to be in the same units as the values in xTable.
Mode:
The origin of your grid, and the direction of the plotted line:
1 - Origin is bottom-left, x is left to right, y is upwards 2 - Origin is bottom-right, x is right to left, y is upwards 4 - Origin is top-left, x is left to right, y is downwards 8 - Origin is top-right, x is right to left, y is downwards
766
Return Value
767
768
ProcessAnalystLoadFile
Loads the specified PAV file to a Process Analyst object, which is identified by parameter ObjName.
Syntax
iFileLocation:
PAV file location code for the PAV file. Indicates which known location to load the file from. Member Name FileLocation_Local FileLocation_Server Description Refers to the project folder Refers to the both the primary/standby server paths Value 0 1
FileLocation_User
iButtonMask:
769
Bit mask for removing command buttons from the PA, bit flags as shown below:
l l l l l l l l l
1 - Load View 2 - Save View 4 - Print 8 - Copy to Clipboard 16 - Copy to File 32 - Add Pens 64 - Remove Pens 128 - Show Properties 256 - Help
sObjName:
Name of the PA object on the given Page where the PAV file will be loaded.
Return Value
Zero (0) if the function is successfully run. otherwise an error code is returned.
Related Functions
PageProcessAnalyst, PageProcessAnalystPens, ProcessAnalystPopUp, ProcessAnalystSelect, ProcessAnalystSetPen, ProcessAnalystWin, TrnSetPen, WinNewAt See Also Process Analyst Functions
ProcessAnalystPopup
Displays a Process Analyst page (in a new page child window) at the current mouse position preloaded with the pre-defined Process Analyst View (PAV) file.
Syntax
sPAVFile:
Name of the PAV file
iFileLocation:
PAV file location code for the PAV file, see PA doc LoadFromFile() for details.
770
iButtonMask:
Bit mask for removing command buttons from the PA, bit flags as shown below:
l l l l l l l l l
1 - Load View 2 - Save View 4 - Print 8 - Copy to Clipboard 16 - Copy to File 32 - Add Pens 64 - Remove Pens 128 - Show Properties 256 - Help
sObjName:
Name of the PA object on the given Page where the PAV file will be loaded. If this parameter is not specified or empty string, it is defaulted to the object name used in the tab style templates, that is "_ templatePA1".
iMode:
The mode of the window (see WinNewAt() for details).
Return Value
PageProcessAnalyst, PageProcessAnalystPens, ProcessAnalystLoadFile, ProcessAnalystSelect, ProcessAnalystSetPen, ProcessAnalystWin, TrnSetPen, WinNewAt See Also Process Analyst Functions
ProcessAnalystSelect
Works like the existing Cicode Function TrnSelect(). It allows a set of pens to be selected before displaying the PA page. When PageProcessAnalystPens() is called after ProcessAnalystSelect(), the pens specified by both functions will be available in the final PA display. You can also repeat the call sequence of ProcessAnalystSelect() and ProcessAnalystSetPen() multiple times to set up multiple PA objects for the same page before displaying the page.
Syntax
771
sPage:
The name of the page that displays the PA.
sObjName:
The name of the PA object. If this is not specified, it is defaulted to "_TemplatePA1" which is the name used by the built-in templates.
sClusterName:
The name of the cluster that is associated with any trend tag for this PA. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
iButtonMask:
Bit mask for removing command buttons from the PA, bit flags as shown below:
l l l l l l l l l
1 - Load View 2 - Save View 4 - Print 8 - Copy to Clipboard 16 - Copy to File 32 - Add Pens 64 - Remove Pens 128 - Show Properties 256 - Help
sPAVFile:
Name of the PAV file
iFileLocation:
PAV file location code for the PAV file, see PA doc LoadFromFile() for details.
Return Value
772
Related Functions
PageProcessAnalyst, PageProcessAnalystPens, ProcessAnalystLoadFile, ProcessAnalystPopup, ProcessAnalystSetPen, ProcessAnalystWin, TrnSetPen, WinNewAt See Also Process Analyst Functions
ProcessAnalystSetPen
Works like the existing function TrnSetPen(). Allows a new pen to be added to a PA display. The pane defaults to the first pane of the PA if it is not specified.
Syntax
sTag:
The trend tag name to be assigned to the pen.
sObjName:
The name of the PA object. If this is set to "-2", the pen is set to the next displayed PA page set up by ProcessAnalystSelect(). If the specified ObjName is valid, the changes will be applied to the currently displayed PA. Otherwise, the function will try to set the pen to the specified object on the currently displayed page. If this parameter is not specified or is an empty string, it will default to the object name used in the tab style templates, that is "_templatePA1".
iPane:
Optional number of the pane where the trend or variable tags are added. Please see the same parameter for function PageProcessAnalystPens() for details. Defaulted to 0, that is, the first pane.
773
iPenType:
Pen type for creation. The allowed values are: 0 - Analog Trend (Default) 1 - Digital Trend 2 - Alarm
Note: This optional parameter is ignored for existing pens. To change pen type, delete a pen and create a new one.
Return Value
PageProcessAnalyst, PageProcessAnalystPens, ProcessAnalystLoadFile, ProcessAnalystPopup, ProcessAnalystSelect, ProcessAnalystWin, TrnSetPen, WinNewAt See Also Process Analyst Functions
ProcessAnalystWin
Displays a Process Analyst page (in a new window) preloaded with the pre-defined Process Analyst View (PAV) file.
Syntax
ProcessAnalystWin(sPage, iX, iY, iMode [, sPAVFile [, iFileLocation [, iButtonMask [, sObjName ]]]]) sPage:
The name of the page that contains Process Analyst object(s). For example, pages based on the Process Analyst templates found in the Tab_Style_Include project.
iX:
The X pixel coordinate
iY:
The Y pixel coordinate
iMode:
The mode of the window (see WinNewAt() for details).
sPAVFile:
774
iFileLocation:
PAV file location code for the PAV file, see PA doc LoadFromFile() for details.
iButtonMask:
Bit mask for removing command buttons from the PA, bit flags as shown below:
l l l l l l l l l
1 - Load View 2 - Save View 4 - Print 8 - Copy to Clipboard 16 - Copy to File 32 - Add Pens 64 - Remove Pens 128 - Show Properties 256 - Help
sObjName:
Name of the PA object on the given Page where the PAV file will be loaded. If this parameter is not specified or empty string, it is defaulted to the object name used in the tab style templates, that is "_ templatePA1".
Return Value
PageProcessAnalyst, PageProcessAnalystPens, ProcessAnalystLoadFile, ProcessAnalystPopup,ProcessAnalystSelect, ProcessAnalystSetPen, TrnSetPen, WinNewAt See Also Process Analyst Functions
775
776
QualityCreate
Creates a quality value based on the quality fields provided. When the value of a particular quality field is out of range, the value of its corresponding part in the returned quality remains at 0, and hardware error is generated.
Syntax
QualityCreate(INT generalQuality [, INT qualitySubstatus [, INT qualityLimit [, INT extendedSubstatus [, INT bOverride [, bControlInhibit [, INT datasourceErrorCode ]]]]]] ) generalQuality:
Specifies the general quality.
qualitySubstatus:
Specifies the quality substatus.
qualityLimit:
TheQuality Limit.
777
extendedSubstatus:
Specifies the extended quality substatus.
bOverride:
Specifies the Tag Status Override Flag.
bControlInhibit:
Specifies the Tag Status Control Inhibit Flag.
datasourceErrorCode:
Specifies the data source error code.
For further information on the quality arguments listed above, refer to the Tag Extensions documentation in the main help.
Return Value
QualityGetPart
Extracts a requested part of the Quality value from the QUALITY variable.
Syntax
part:
The part to extract:
778
0 The General Quality value 1 Quality Substatus value 2 - The Quality Limit value 3 - The Extended Quality Substatus value 4 The Tag Status Override flag 5 The Tag Status Control Inhibit flag 6 - The DataSource error code 7 The OPC Quality (General + Substatus + Limit)
Return Value
QualityIsControlInhibit
Returns a value indicating whether the tag is in Control Inhibit Mode.
Syntax
Return Value
0: the tag is not in Control inhibit Mode. 1: the tag is in Control inhibit Mode.
779
Related Functions
QualityIsBad
This function will return a value indicating whether the general part of quality is bad.
Syntax
Return Value
QualityIsGood
This function will return a value indicating whether the general part of quality is good.
780
Syntax
Return Value
QualityIsOverrride
Returns a value indicating whether the tag is in Override Mode.
Syntax
Return Value
781
QualityIsUncertain
This function will return a value indicating whether the general part of quality is uncertain.
Syntax
Return Value
QualitySetPart
Sets a Quality parts value to the QUALITY variable.
Syntax
782
part:
The part to extract: 0 The General Quality value 1 Quality Substatus value 2 - The Quality Limit value 3 - The Extended Quality Substatus value 4 The Tag Status Override flag 5 The Tag Status Control Inhibit flag 6 - The DataSource error code 7 The OPC Quality (General + Substatus + Limit)
value:
The new value for the given part.
Return Value
The modified Quality value, or the original value if the given part is not applicable.
Related Functions
QualityToStr
Returns a textual representation of the quality.
Syntax
783
part:
Specifies the part of quality to obtain the textual representation. -2: Short representation in the format <General Quality> [ <Quality Substatus>] -1: Full representation in the format <General Quality> [Override] [Control Inhibit] <Quality Substatus> 0: <General Quality> 1: <Quality Substatus> 2: <Quality Limit> 3: <Extended Quality Substatus> 4: <Quality Override> 5: <Control Inhibit>
localized:
The flag indicating if the returned text should be in native language or in Runtime localized language.
Return Value
A textual representation of the quality, or an empty string if the part given is not applicable.
Related Functions
STRING str;
q = QualityCreate(QUAL_GOOD, 0, QUAL_LIMITED_NOT_LIMITED,
784
QUAL_EXT_NON_SPECIFIC, 1, 1, 0);
q = QualityCreate(QUAL_GOOD, QUAL_GOOD_LOCAL_OVERRIDE,
QUAL_LIMITED_NOT_LIMITED, QUAL_EXT_NON_SPECIFIC);
q = QualityCreate(QUAL_GOOD, 0, QUAL_LIMITED_QL_LOW_LIMITED,
QUAL_EXT_NON_SPECIFIC);
SetLanguage(FRENCH);
q = QualityCreate(QUAL_GOOD, 0, QUAL_LIMITED_NOT_LIMITED,
QUAL_EXT_NON_SPECIFIC, 1, 1, 0);
785
SetLanguage(ENGLISH);
q = QualityCreate(QUAL_BAD, QUAL_BAD_CONFIGURATION_ERROR,
QUAL_LIMITED_NOT_LIMITED, QUAL_EXT_NON_SPECIFIC);
SetLanguage(FRENCH);
q = QualityCreate(QUAL_BAD, QUAL_BAD_CONFIGURATION_ERROR,
QUAL_LIMITED_NOT_LIMITED, QUAL_EXT_NON_SPECIFIC);
786
SetLanguage(ENGLISH);
q = QualityCreate(QUAL_UNCR, QUAL_UNCR_NON_SPECIFIC,
QUAL_LIMITED_NOT_LIMITED, QUAL_EXT_TAG_OUT_OF_RANGE);
q = QualityCreate(QUAL_UNCR, QUAL_UNCR_NON_SPECIFIC,
QUAL_LIMITED_NOT_LIMITED, QUAL_EXT_TAG_OUT_OF_RANGE);
q = QualityCreate(QUAL_UNCR, QUAL_UNCR_SUBNORMAL,
QUAL_LIMITED_NOT_LIMITED, QUAL_EXT_NON_SPECIFIC);
787
VariableQuality
Extracts the quality from a given variable.
Note: This function is designed to be used within Cicode; using it on graphical pages may result in displaying an error message instead of an expected quality message when either its argument has not good quality or an execution error is set.
Syntax
VariableQuality(Variable) Variable:
The variable from which the quality will be extracted.
Return Value
The QUALITY of the given variable. If Variable is NULL, it returns quality uncertain (0x40). Timestamps of uninitialized stack variables, uninitialized code variables and constants are equal to 0 - invalid timestamp, while their qualities are GOOD
Related Functions
INT
FUNCTION
MyFunction(REAL arg1)
QUALITY q;
q = VariableQuality(codeVariable);
//code variable
788
q = VariableQuality(arg1);
//function argument
q = VariableQuality(str);
//stack variable
q = VariableQuality(Tag1);
RETURN 1;
END
789
790
RepGetCluster
This function retrieves the name of the cluster a report is running on. This function should only be called from a report file.
Syntax
RepGetCluster()
Return Value
The name of the cluster the report in running on. See Also Report Functions
RepGetControl
Gets report control information on a report. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
791
nType:
The type of report control information to get (send back in the return value):
0 - State of the report - returns one of: l 0 -Idle l 1 - Waiting for PLC data for trigger l 2 - Waiting for PLC data l 3 - Running 1 - Time of day that the report is due to run next. 2 - The report period, in seconds, or week day, month or year, for example, if the report is weekly, this is the day of the week, 0 (Sunday) to 6 (Saturday). 3 - Synchronisation time of day of the report, for example, 10:00:00 (In seconds from midnight). 4 - Type of report schedule - returns one of: l 0 - Event triggered l 1 - Daily l 2 - Weekly l 3 - Monthly l 4 - Yearly 5 - Report state - returns one of: l 0 - Enabled l 1 - Disabled sClusterName:
Name of the cluster in which the report resides. This is optional if you have one cluster or are resolving the report server via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
RepSetControl, Report
Example
Next=RepGetControl("SHIFT",1,"ClusterXYZ"); ! Sets Next to the time that the report is due to run. ! Display a message at the prompt AN (AN2) if ! the report is running. IF RepGetControl("SHIFT",0,"ClusterXYZ")=3 THEN Prompt("Shift report is running"); END
792
Report
Runs a report on the Report Server. This function only schedules the report for execution. The running of the report is controlled entirely by the Report Server. This function will start the specified report on the Reports Server to which the CitectSCADA computer is communicating. If you are using the Reports Servers in Primary/Standby mode, the report can run on the Standby Server. If you call this function on the Standby Server then the report will definitely run on the Standby Server, even if the Primary Server is active. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
sClusterName:
Name of the cluster in which the report resides. This is optional if you have one cluster or are resolving the report server via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
RepSetControl, RepGetControl
Example
793
Report("SHIFT","ClusterXYZ"); ! Runs the report named "SHIFT". Report("DAY","ClusterXYZ"); ! Runs the report named "DAY". /* The "SHIFT" and "DAY" reports are started. The order in which the reports are run cannot be determined. If you want the "DAY" report to run after the "SHIFT" report, call Report("DAY") at the end of the "SHIFT" report. */
RepSetControl
Sets report control information to temporarily override the normal settings for a specified report. You can change the report schedule for a periodic report, and run one-time or event-triggered reports. These new settings are set on both the primary and standby report servers, but are not saved to the database. When you restart your system, CitectSCADA uses the existing settings, defined in the Reports database. You might need to call this function several times. For example, to change an event-triggered report to run at 6 hourly intervals, you need to change the schedule (Type 4), synchronization time (Type 3), and period (Type 2). If you use incompatible values for these options, you can get unpredictable results. To change more than one option, disable the report, set the options, and then re-enable the report. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
794
nType:
The type of report control information to set:
1 - The time of day at which to run the next report in Cicode (date/time) variable type. Subsequent reports are run at the times calculated from the period (Type 2) and synchronisation time (Type 3). Use Type 1 to specify a one-time report. Set the time in Data in seconds from midnight (for example, specify 6 p.m. as TimeMidNight() + (18 * 60 * 60) ). 2 - The report period. Set the new period in Data according to the report schedule (Type 4), in seconds from midnight, day of week (0 to 6, Sunday = 0), month (1 to 12), or year. For a daily report schedule, set the report frequency in Data in seconds from midnight; for example, set Data to 6 * 60 * 60 for a 6 hourly shift report. If the report is weekly, set Data to the day of the week, for example, when Data = 2, the day is Tuesday. 3 - Synchronisation time of day of the report. Set the time in Data in seconds from midnight, for example, to synchronize at 10a.m., set Data to 10 * 60 * 60. 4 - Type of report schedule. Set Data to one of the following: l 0 - Event triggered l 1 - Daily l 2 - Weekly l 3 - Monthly l 4 - Yearly 5 - Report state. Set Data to either: l 0 - Enabled l 1 - Disabled Data
The new data value, dependent on the Type.
sClusterName:
Name of the cluster in which the report resides. This is optional if you have one cluster or are resolving the report server via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
RepGetControl, Report
Examples
795
Scheduler Functions
The following functions relate to Scheduler.
SchdClose Terminates a browsing session and cleans up the resources used by the session. 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 schedules configured. Places the data browse cursor at the previous record. Places the data browse cursor at the first record. Returns the value of the particular field in a record to which the
SchdConfigClose
SchdConfigFirst SchdConfigGetField
SchdConfigNext SchdConfigNumRecords
796
data browse cursor is currently referencing. SchdNext SchdNumRecords 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 runtime schedules. Places the data browse cursor at the previous record. Adds a new schedule to the scheduler engine. Deletes an existing schedule. Modifies an existing schedule. Adds recurrence information for an existing schedule to the scheduler engine.
SchdSpecialItemAdd SchdSpecialItemClose
797
SchdSpecialNext SchdSpecialNumRecords
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 special day groups. Places the data browse cursor at the previous record.
SchdSpecialOpen SchdSpecialPrev
SchdClose
The SchdClose function terminates a browsing session and cleans up the resources used by the session.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdFirst,SchdNext, SchdPrev, SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdConfigClose
The SchdConfigClose function terminates a browsing session and cleans up the resources used by the session.
Syntax
INT SchdConfigClose(LONG Session ) Session: The handle to a browse session previously returned by the SchdConfigOpen call.
Return Value
798
Related Functions
SchdConfigOpen, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdConfigFirst
The SchdConfigFirst function places the data browse cursor at the first record.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst, SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdConfigGetField
The SchdConfigGetField function returns the value of the particular field in a record to which the data browse cursor is currently referencing.
Syntax
field
A field to retrieve. Refer to ScheduleConfigOpen for detailed list of fields.
799
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
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete
Example
TIMESTAMP tsStart = StrToTimestamp(SchdConfigGetFiel(hSession, "Start"),15,0);
SchdConfigNext
The SchdConfigNext 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.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
800
SchdConfigNumRecords
The SchdConfigNumRecords function returns the number of records that match the current filter criteria. This function uses iSession as an argument which is previously returned by the SchdConfigOpen function.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdConfigOpen
The SchdConfigOpen function initiates a new session for browsing the schedules configured. It returns a handle for the browsing session which can be used for further browsing operations.
Syntax
LONG SchdConfigOpen([TIMESTAMP Start] [, LONG Duration] [, STRING Filter] [, STRING Fields] [, STRING Clusters] ) start: The start date of the schedules in UTC time to return during the browse.If not specified, today at midnight will be taken as start time. The types of this field is TIMESTAMP. Use StrToTimestamp or TimestampCreate cicode functions to create a TIMESTAMP type. Duration: The duration of the browse in seconds. The default is 86400 seconds(24 hour) Filter:
801
A filter expression specifying the records to return during the browse. An empty string indicates that every record will be returned.
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 every available column. Supported fields are: ID: The unique ID of the schedule within the schedule engine. ID value is the same for all recurring schedules. EQUIPMENT: The equipment name STATE: The state of the schedule START: The start time of the schedule. OCCURRENCESTART: The start of this occurrence. For non-recurring entries will be the same as START. END: The end time of the schedule. OCCURRENCEEND: The end of this occurrence. For non-recurring entries will be the same as END. DESC: The description of the schedule. MODIFIEDTIME: The time when the entry was modified last time.
802
Note: Time values (START, OCCURRENCESTART, END, OCCURRENCEEND, MODIFIEDTIME) are TIMESTAMP type. Use TimestampToStr() cicode function to convert it to string. The following fields are used when a schedule is recurrent. The value of FREQ filed -1 means the schedule is not recurrent: FREQ: The type of the recurrence: 4 - daily, 5 - weekly, 6- monthly, 7 yearly, 8 - special days. -1 means this schedule is non-recurring. INTERVAL: The interval of the recurrence. 1 - every 1 day/week/month etc., 2 every second day/week/month etc. and so on. WEEKDAY: The first day of the week WEEKDAYMASK: The day of week mask. Defines day of week where recurrence happens. None = 0, Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, Everyday = 127, Weekdays = 62, Weekenddays = 65 Combination of days can be achieved by addition. For example, Tuesdays and Wednesdays would be 12 (4 + 8). MAXREC:
803
The maximum number recurrences (-1 means MAXREC is not specified. If MAXREC is -1 then the recurrence stops on the date specified by RECUNTIL field. If RECUNTIL is not specified the recurrence occurs forever). RECUNTIL: The time until recurrence occurs. -1 means never stops (or finishes after MAXREC occurrences if is specified). DAYORD: Day ordinal. Applicable for monthly and yearly recurrence patterns. Using the values 1 to 4 you can set the schedule to run on the first, second, third, or fourth occurrence of the DAY in each month (monthly recurrences), or the specified MONTH (yearly recurrences). Use the value -1 for the last week of the month DAY: The day of month MONTH: The month of the year SPECIALINC: Defined whether the special day is included in the pattern. 0 none, 1 - all, 2 - selected. GROUPIDS A list of groups ID included in the recurring pattern (used only when SPECIALINC is defined as 2 (selected)). 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
SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete
Example
804
"", "Cluster1");
IF iConfigtimeSession = -1 THEN
END
SchdConfigPrev
The SchdConfigPrev 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.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
805
SchdFirst
The SchdFirst function places the data browse cursor at the first record.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdNext, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdGetField
The SchdGetField function returns the value of the particular field in a record to which the data browse cursor is currently referencing.
Syntax
Field:
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. See SchdOpen for supported 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
806
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete Example
TIMESTAMP tsStart = StrToTimestamp(SchdGetField(hSession, "Start"),15,0);
SchdNext
The SchdNext 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.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst, SchdPrev,SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdNumRecords
The SchdNumRecords function returns the number of records that matchthe current filter criteria.
Syntax
807
Session:
The handle to a browse session previously returned by the SchdOpen 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
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdPrev,SchdGetField, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdOpen
The SchdOpen function initiates a new session for browsing the runtime schedules. It returns a handle for the browsing session which can be used for further browsing operations.
Syntax
LONG SchdOpen(STRING Equipment[, TIMESTAMP Start] [,LONG Duration] [,STRING Filter] [,STRING Fields] [, STRING Clusters] ) Equipment:
The name of the equipment to browse.
Start:
The start date of the schedules. If not specified, today at midnight will be taken as the start time. The types of this field is TIMESTAMP. Use StrToTimestamp or TimestampCreate Cicode functions to create a TIMESTAMP type.
Duration:
The duration of the browse in seconds. The default is 86400 seconds(24 hour)
Filter:
A filter expression specifying the records to return during the browse. An empty string indicates that every record will be returned.
Fields:
808
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. Supported fields are: EQUIPMENT: The equipment name STATE: The state to be set by the schedule START: The start time of the schedule. The time is returned as a Timestamp value. Use StrToTimestamp() to get a TIMESTAMP data value. END: The end time of the schedule. The time is returned as a Timestamp value. Use StrToTimestamp() to get a TIMESTAMP data value. INHERITED: Indicates if the schedule entry is inherited from a schedule defined in a parent equipment higher in the hierarchy. DESC: The description of the schedule.
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 a handle to the browse session otherwise an error code is returned. For errors refer to the topic Cicode Errors in the Cicode Reference help
Related Functions
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords, SchdClose, SchdFirst,SchdNext, SchdPrev, SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete
Example
IF iRuntimeSession = -1 THEN
809
END
SchdPrev
The SchdPrev 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.
Syntax
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
SchdSpecialAdd
The SchdSpecialAdd adds a new Special Day Group to the scheduler engine.
Syntax
Name:
Name of the special day group
810
Return Value
Returns the Id of the Special Day Group which can be used for modifying and deleting this Special Day Group. Returns the ID for an existing Special Day group. This function returns -1 if, unsuccessful. Trap the error to get the error returned by this function.
Related Functions
SchdSpecialClose
The SchdSpecialClose 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 SchdSpecialOpen function.
Syntax
INT SchdSpecialClose(LONG Session) Session: Current special day group browsing session obtained by SchdSpecialOpen
Return Value
SchdSpecialOpen, SchdSpecialFirst, SchdSpecialNext, SchdSpecialPrev, SchdSpecialGetField, SchdSpecialNumRecords See Also Scheduler Functions
SchdSpecialDelete
The SchdSpecialDelete function deletes an existing special day group.
Syntax
ID
811
Return Value
SchdSpecialFirst
The SchdSpecialFirst function places the data browse cursor at the first record. This function uses iSession as the argument which is previously returned by the SchdSpecialOpen function.
Syntax
Return Value
SchdSpecialOpen, SchdSpecialClose, SchdSpecialNext, SchdSpecialPrev, SchdSpecialGetField, SchdSpecialNumRecords See Also Scheduler Functions
SchdSpecialGetField
The SchdSpecialGetField function returns the value of a particular field from the record currently referenced by the data browse cursor. This function uses iSession as an argument which is previously returned by the SchdSpecialOpen function and the field name of the value to be returned.
Syntax
812
Field
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. Supported fields are:
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
SchdSpecialOpen, SchdSpecialFirst, SchdSpecialNext, SchdSpecialPrev, SchdSpecialClose, SchdSpecialNumRecords See Also Scheduler Functions
SchdSpecialItemAdd
The SchdSpecialItemAdd function adds a new Special Day to the scheduler engine. It returns the ID of the Special Day which can be used for modifying and deleting the Special Day.
Syntax
LONG SchdSpecialItemAdd(STRING Cluster, LONG GroupID, STRING Name, TIMESTAMP Day) Cluster:
Name of the Cluster
GroupID:
Special day group ID
Name:
Name of special day
Day:
The special day as a TIMESTAMP. Use TimestampCreate or StrToTimestamp() cicode functions to get a TIMESTAMP data value.
Return Value
813
Returns the ID for an existing special day or -1 if unsuccessful. Trap the error to get the error returned by this function.
Related Functions
SchdSpecialItemModify, SchdSpecialItemDelete
Example
END
END
SchdSpecialItemClose
This 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 SchdSpecialItemOpen function.
Syntax
814
Return Value
SchdSpecialItemOpen, SchdSpecialItemFirst, SchdSpecialItemNext, SchdSpecialItemPrev, SchdSpecialItemGetField, SchdSpecialItemNumRecords See Also Scheduler Functions
SchdSpecialItemDelete
This function deletes an existing Special Day.
Syntax
ID:
Special day ID
Return Value
SchdSpecialItemFirst
The SchdSpecialItemFirst places the data browse cursor at the first record. This function uses iSession as the argument which is previously returned by the SchdSpecialItemOpen function.
Syntax
815
Return Value
SchdSpecialItemOpen, SchdSpecialItemClose, SchdSpecialItemNext, SchdSpecialItemPrev, SchdSpecialItemGetField, SchdSpecialItemNumRecords See Also Scheduler Functions
SchdSpecialItemGetField
This function returns the value of the particular field in a record to which the data browse cursor is currently referencing. This function uses iSession as an argument which is previously returned by the SchdSpecialItemOpen function and the field name of the value to be returned.
Syntax
Field 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. Supported fields are: GROUPNAME: The group name of the special day NAME: The name of the special day DAY: The special day. The time is returned as a Timestamp value. Use StrToTimestamp() to get a TIMESTAMP data value ID: The unique ID of the special day. Every special day is assigned a unique ID.
Return Value
816
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
SchdSpecialItemModify
This function modifies an existing Special Day.
Syntax
LONG SchdSpecialItemModify(STRING Cluster, LONG ID, STRING Name) Cluster: The name of the cluster ID ID of the special day to be modified. Name The name of the special day.
Return Value
SchdSpecialItemNext
817
This function places the data browse cursor at the next available record. This function uses iSession as the argument which is previously returned by the SchdSpecialItemOpen function. This function will return an EOF error code if called when the data cursor is at end of the records.
Syntax
Return Value
SchdSpecialItemOpen, SchdSpecialItemClose, SchdSpecialItemFirst, SchdSpecialItemPrev, SchdSpecialItemGetField, SchdSpecialItemNumRecords See Also Scheduler Functions
SchdSpecialItemNumRecords
The SchdSpecialItemNumRecords function returns the number of records that match the current filter criteria. This function uses iSession as an argument which is previously returned by the SchdSpecialItemOpen function.
Syntax
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
818
SchdSpecialItemOpen
This function initiates a new session for browsing the special days. It returns a handle for the browsing session which can be used for further browsing operations.
Syntax
LONG SchdSpecialItemOpen(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. 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. See SchdSpecialItemGetField for the fields supported. 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
SchdSpecialItemFirst, SchdSpecialItemClose, SchdSpecialItemNext, SchdSpecialItemPrev, SchdSpecialItemGetField, SchdSpecialItemNumRecords See Also Scheduler Functions
SchdSpecialItemPrev
This function places the data browse cursor at the previous record. This function uses iSession as the argument which is previously returned by the SchdSpecialItemOpen function. This function will return an error(EOF) if called when the data cursor is at beginning of the records.
Syntax
819
Return Value
SchdSpecialItemOpen, SchdSpecialItemClose, SchdSpecialItemNext, SchdSpecialItemFirst, SchdSpecialItemGetField, SchdSpecialItemNumRecords See Also Scheduler Functions
SchdSpecialModify
This function modifies an existing special day group.
Syntax
ID:
Existing ID for the current special day group.
NewName:
New name of the current special day group.
Return Value
This function returns 0 if successful otherwise it returns an error. For error code information codes refer to the topic Cicode Errors in the Cicode Reference help
Related Functions
SchdSpecialNext
820
This function places the data browse cursor at the next available record. This function uses iSession as the argument which is previously returned by the SchdSpecialOpen function. This function will return an EOF error code if called when the data cursor is at end of the records.
Syntax
Return Value
SchdSpecialOpen, SchdSpecialFirst, SchdSpecialClose, SchdSpecialPrev, SchdSpecialGetField, SchdSpecialNumRecords See Also Scheduler Functions
SchdSpecialNumRecords
The SchdSpecialNumRecords function returns the number of records that match the current filter criteria. This function uses iSession as an argument which is previously returned by the SchdSpecialOpen function.
Syntax
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
821
SchdSpecialOpen
The SchdSpecialOpen function initiates a new session for browsing the special day groups. It returns a handle for the browsing session which can be used for further browsing operations.
Syntax
LONG SchdSpecialOpen(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. Multiple filters can be specified and separated with ';'. 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". 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. Supported fields are: NAME: The name of the special day group. ID: The unique ID of the special day group. Every special day group is assigned a unique ID. 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
SchdSpecialClose, SchdSpecialFirst, SchdSpecialNext, SchdSpecialPrev, SchdSpecialGetField, SchdSpecialNumRecords See Also Scheduler Functions
SchdSpecialPrev
822
The SchdSpecialPrev places the data browse cursor at the previous record. This function uses iSession as the argument which is previously returned by the SchdSpecialOpen function. This function will return an error(EOF) if called when the data cursor is at beginning of the records.
Syntax
Return Value
SchdSpecialOpen, SchdSpecialFirst, SchdSpecialNext, SchdSpecialClose, SchdSpecialGetField, SchdSpecialNumRecords See Also Scheduler Functions
ScheduleItemAdd
The ScheduleItemAdd function adds a new schedule to the scheduler engine. It returns the Id of the schedule which can be used for modifying, setting recurrence and deleting this schedule.
Syntax
LONG ScheduleItemAdd(STRING Cluster, STRING Equipment, STRING State, TIMESTAMP Start, TIMESTAMP End, STRING Desc) Cluster:
The name of the cluster
Equipment:
The name of the equipment to browse.
State:
The state of the schedule
Start:
The start time of the schedule. The type of this parameter is TIMESTAMP. Use TimestampCreate or StrToTimestamp to get a TIMESTAMP value.
823
End:
The end time of the schedule. The type of this parameter is TIMESTAMP. Use TimestampCreate or StrToTimestamp to get a TIMESTAMP value.
Desc
The description of the schedule.
Return Value
The id of the schedule which can be used for modifying, setting recurrence and deleting this schedule. This function returns -1 if unsuccessful. Trap the error to get the error returned by this function.
Related Functions
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdGetField, SchdNumRecords, ScheduleItemSetRepeat, ScheduleItemModify, ScheduleItemDelete
Example
//The following example creates a schedule item using state MyState1 for
MyEquipment1, that starts from 3am and ends at 4am on 20th of Nov 2011.
TIMESTAMP tsStartTime;
TIMESTAMP tsEndTime;
INT iScheduleID;
iScheduleID = ScheduleItemAdd("Cluster1",
824
"MyEquipment1","MyState1",tsStartTime,tsEndTime,"MyScheduleItem1");
ScheduleItemDelete
The ScheduleItemDelete function deletes an existing schedule. LONG ScheduleItemDelete(STRING Cluster, LONG ID) Cluster:
Name of cluster.
ID:
The unique ID of the schedule within the schedule engine.
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemModify See Also Scheduler Functions
ScheduleItemModify
The ScheduleItemModify function modifies an existing schedule.
Syntax
LONG ScheduleItemModify(STRING Cluster, LONG ID, STRING State, TIMESTAMP Start, TIMESTAMP End, STRING Desc) Cluster:
Name of cluster.
ID:
The unique ID of the schedule within the schedule engine
State:
The state of the schedule
825
Start:
The start time of the schedule. The type of this parameter is TIMESTAMP. Use TimestampCreate or StrToTimestamp to get a TIMESTAMP value.
End:
The end time of the schedule. The type of this parameter is TIMESTAMP. Use TimestampCreate or StrToTimestamp to get a TIMESTAMP value.
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemSetRepeat, ScheduleItemDelete See Also Scheduler Functions
ScheduleItemSetRepeat
The ScheduleItemSetRepeat function adds recurrence information to an existing schedule to the scheduler engine. The same function is used if the schedule already has recurrence information that need to be changed.
Syntax
LONG ScheduleItemSetRepeat(STRING Cluster, LONG ID, LONG Freq, LONG Interval, LONG Weekday, LONG WeekDayMask, LONG MaxRec, LONG RecUntil,LONG DayOrd, LONG Day, LONG Month,LONG SpecialInc, STRING GroupIds) Cluster
Name of cluster
ID The existing schedule id to apply recurrence. Freq: The type of the recurrence: 4 daily, 5 weekly, 6- monthly, 7 yearly, 8 special days. Interval:
826
The interval of the recurrence. 1 every 1 day/week/month etc., 2 every second and so on. WeekDay: The first day of week Sunday (0) or Monday (1) WeekDayMask: The day of week mask. Defines day of week where recurrence happens. None = 0, Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, Everyday = 127, Weekdays = 62, Weekenddays = 65 Combination of days can be achieved by addition. For example, Tuesdays and Wednesdays would be 12 (4 + 8). MaxRec: The maximum number recurrences (-1 means does not stop) RecUntil: The time specifies the time until recurrence is occurring. The type of this parameter is TIMESTAMP. Use TimestampCreate or StrToTimestamp to get a TIMESTAMP value. To create a recurring schedule that does not end use TimestampCreate(1601, 1, 1, 0, 0, 0, 0, 1) DayOrd: Day ordinal. Applicable for monthly and yearly recurrence patterns. Can be 1-4 or -1 (every 1, second, third, fourth or last week of a month). Day: The day of month Month:
827
The month of the year SpecialInc: Defined whether the special day is included in the pattern. 0 none, 1 every, 2 selected. GroupIds : A list of groups ID included in the recurring pattern (used only when SpecialIncl is defined as 2 (selected)).
Return Value
SchdConfigOpen,SchdConfigClose, SchdConfigFirst,SchdConfigNext,SchdConfigPrev, SchdConfigGetField, SchdConfigNumRecords,SchdOpen, SchdClose, SchdFirst,SchdNext, SchdGetField, SchdNumRecords, ScheduleItemAdd, ScheduleItemModify, ScheduleItemDelete See Also Scheduler Functions
828
LoginForm
MultiSignatureTagWrite
Name UserCreate
UserCreateForm
UserDelete
UserEditForm
UserInfo
829
UserLogin
Logs an operator into the CitectSCADA system using a secure password string. Changes a user's password during run time. Not available when logged in as Windows user. Returns the number of days left before the user's password is due to expire. Not available when logged in as Windows user. Displays a form for the operator to change their own password during run time. Not available when logged in as Windows user. Sets the value of the given field for the given user record in the project configuration (users.dbf ) on the local machine. Triggers a recompile of the local project configuration, then notifies the running system that user configuration has been modified and needs to be reloaded. Uses the authentication functionality in the user login system. Displays a form that allows a single user to enter their credentials. Displays a form that allows any single user to enter their credentials in order to approve a write of a specific value to a specific tag. Displays the name of the operator who is currently logged-in to the system.
UserPassword
UserPasswordExpiryDays
UserPasswordForm
UserSetStr
UserUpdateRecord
UserVerify VerifyPrivilegeForm
VerifyPrivilegeTagWrite
WhoAmI
FullName
Gets the full name of the user who is currently logged on to the system. The user can be a Citect or a Windows user. For a Citect user the full name is the one defined in the users form. For a Windows user the full name is in the format of <DomainName>\<UserName>. When there is no one logged in or the logged in user is a "system user" this function returns an empty string.
Syntax
FullName()
830
If the user is logged on as a Domain user the name should be the Windows domain name and user account name in the format of <DomainName\UserName>. If the user is logged on as a local user the name should be the local machine name and user account name in the format of <MachineName\UserName>.
Return Value
Name, UserInfo
Example
/* Display the full name of the current user at AN20. */ DspText(20, 0, FullName());
GetPriv
Checks if the current user has a privilege for a specified area. With this function, you can write your own Cicode functions to control user access to the system.
Syntax
Area
The area of privilege (0..255).
Return Value
Returns 1 if the user has the specified privilege in the area, or 0 (zero) if the user does not have the privilege.
Related Functions
SetArea
Example
831
/* User needs to have privilege 2, or cannot do operation. */ IF GetPriv(2, 0) THEN ! Do operation here ELSE Prompt("No privilege for command"); END
Login
Not available when logged in as Windows user. Logs a user into the CitectSCADA system, using CitectSCADA security and gives users access to the areas and privileges assigned to them in the Users database, and uses the locale language defined for that user. Only one user can be logged into a computer at any one time. If a user is already logged in when a second user logs in, the first user is automatically logged out. When using Windows security use UserLogin to limit Windows credentials being exposed as plain text. At startup, or when the user logs out, a default user is active, with access to area 0 (zero) and privilege 0 (zero) only. Use the LoginForm() function to display a form for logging in to the system.
Syntax
sPassword:
The user's password, as defined in the Users database.
bSync:
Optionally specifies whether the function operates in blocking or non-blocking mode. If set to 1 blocks caller until login is complete. If set to 0 (default) does not block caller.
sLanguage:
The specified language needs to be one of the languages defined in System/Languages (LANG.DBF). If the specified language is undefined, the default language is used by the login user, and a message Undefined language is shown in the prompt line. An empty string (i.e. ) can be specified to indicate that the default language is used by the login user. The default language defined by [Language]LocalLanguage INI parameter.
832
Return Value
0 (zero) if successful.
Related Functions
/* ** Log in a user whose user name is "FRED" and whose password ** is "ABC". ** ** The language of the logged in user session will be set to ** English. */ Login("FRED", "ABC", 0, "English");
LoginForm
Displays a form in which a user can log in to the CitectSCADA system by entering their name and password and local language. If the login is correct, the user is logged into the CitectSCADA system with the area(s) and privilege(s) assigned to them in the Users database. From version 7.10 this form can be pre-filled by the caller. Both Citect and Windows users are supported. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
833
sUserName:
Optionally, the user's name, as defined in the Users database.
sPassword:
Optionally, the user's password, as defined in the Users database.
sLanguage:
The specified language must be one of the languages defined in System/Languages (LANG.DBF). If the specified language is undefined, the default language is used by the login user, and a message Undefined language is shown in the prompt line. An empty string (i.e. ) can be specified to indicate that the default language is used by the login user. The default language defined by [Language]LocalLanguage INI parameter. The default value of this parameter is .
Return Value
Login, UserLogin
Example
System Keyboard Key Sequence LoginForm Comment Buttons Text LoginForm Comment Operator Login Display the Login form Allow user login Login Display the Login form Allow user login
Logout
834
Logs the current user out of the CitectSCADA system. CitectSCADA continues to run, but with access to area 0 (zero) and privilege 0 (zero) only. If the current page requires access for a specified area (as defined by the page's area property), the system returns to the home page as specified by the parameter[Page]HomePage, and if unsuccessful that returns to the startup page. When multiple pages are currently displayed, this occurs for each open window. Calling this function to logout the logged on user will cause an automatically logged in user to be logged back on. If there is no user logged in, calling this function will return an error. When the logged on user is an automatically logged in user, calling this function will return an error.
Syntax
Logout()
Return Value
LogoutIdle
Sets an idle time for logging out the current user. If the current user does not execute a command within the specified idle time, a prompt is displayed. If the prompt is ignored, then the user is logged out. For every user to have the same idle time, you would call this function at startup. Otherwise, you can call the function from the Users database to specify an idle time for each user. This function will not log out an automatically logged on user. Until reset LogoutIdle remains active. To reset call LogoutIdle (-1) from the Exit command of the Users database record.
Syntax
LogoutIdle(Idle) Idle:
835
The number of minutes the user needs to be idle before logout will occur. Set Idle to -1 to disable the current logout timeout.
Return Value
No return value.
Related Functions
Users User Name LoginForm Comment Operator1 LogoutIdle(5) Logs the user out after five minutes
MultiSignatureForm
Displays a form that allows up for 4 users to have their credentials verified in order to approve an operation. The usernames can be Citect or Windows users.
Syntax
sLogDevice:
The name of a log device if logging is required, otherwise pass an empty string.
sUser1..4:
Each sUser argument needs to be either a Citect user name, a Windows user name (including domain\ prefix) or a blank string. Even though the sUser arguments are numbered 1 through 4, this only controls the order in which users are displayed on the multi-signature form. You can pass empty strings for any of these arguments, but at least one user needs to be specified.
Return Value
836
TRUE (1) if the operation approved (that is all users' credentials were verified and the operator clicked the "Approve" button, otherwise FALSE (0).
Related Functions
MultiSignatureTagWrite
Displays a form that allows up for 4 users to have their credentials verified in order to approve a write of a specific value to a specific tag. If all users are verified successfully, the write to the tag is performed by this function before it returns. The usernames can be Citect or Windows users.
Syntax
sValuetoWrite:
The value to write to the tag if approval succeeds.
sLogDevice:
The name of a log device if logging is required, otherwise pass an empty string.
sUser:
837
Each sUser argument needs to be either a Citect user name, a Windows user name (including domain\ prefix) or an empty string. Even though the sUser arguments are numbered 1 through 4, this only controls the order in which users are displayed on the multi-signature form. You can pass empty strings for any of these arguments, but at least one user needs to be specified.
Return Value
TRUE (1) if the operation was approved (that is all users' credentials were verified and the operator clicked the "Approve" button, otherwise FALSE (0).
Related Functions
Name
Gets the name of the operator who is currently logged on to the display system. The user can be a Citect or a windows user.If this function is called on a server, it returns the name of the local operator. If there is no one logged on, or the logged on user is a "system user" this function returns an empty string.
Syntax
Name()
Return Value
838
The name of the user as a string. If the user is logged on as a Windows user the name will be the Windows user account name.
Related Functions
UserCreate
Not available for a Windows user. Creates a record for a new user. A new user of the specified type is created. The name of the user needs to be unique. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path. Note: This function is not supported on the Internet Display Client. If this function is called on the Internet Display Client then it will return an error.
Syntax
sFullName:
The full name of the user.
sPassword:
The password of the user.
839
The sPassword argument is optional. If not passed, this argument defaults to an empty string which is subsequently ignored. It is included for the purposes of handling duplicate user names and separate password identification compatibility.
sType:
The generic type of user. The type needs to be defined in the Users database (with the Users form).
sAccess:
User's viewable areas.
sPrivGlobal:
User's global privilege.
sPriv1-8:
User's privilege for areas 1 - 8.
Return Value
UserCreateForm
Not available for a Windows user. Displays a form to create a record for a new user. A new user of the specified type is created. The name of the user needs to be unique. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
Syntax
840
UserCreateForm()
Return Value
UserDelete
Not available for a Windows user. Deletes the record for a user. Changes are written to both the Users database and the runtime database in memory. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
Syntax
UserDelete(sName) sName:
The name of the user.
Return Value
UserCreate, UserEditForm
Example
841
UserEditForm
Not available for a Windows user. Displays a form to allow the user to create or delete any user record in the database. This function should have restricted access. Changes are written to both the Users database and the runtime database in memory. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
Syntax
UserEditForm()
Return Value
UserCreate, UserDelete
Example
/* Display a form for the user to create or delete user records. */ UserEditForm();
UserInfo
Gets information about the operator who is currently logged-in to the system.
Syntax
UserInfo(nType)
842
nType:
The type of user information:
0 - Flag to indicate whether any user other than a view-only user is logged in 1 - The login name of the user 2 - The full name of the user 3 - The time the user logged in 4 - The time the user entered the last command 5 - The number of commands entered by the user 6 - The type of login: l "0" indicates that the current user is a view-only user. l "1"indicates there is CitectSCADA or Windows non-default user explicitly logged in. l "2" indicates the logged on user is a CitectSCADA default user (control client auto login CitectSCADA user). l "3" indicates the logged on user is a Windows default user (control client auto login windows user).
Return Value
Login
Example
/* Check if a user has logged on. If so, get the user's full name and the number of commands they have performed. */ String sName; String sCount; IF UserInfo(0) = "1" THEN sName = UserInfo(2); sCount = UserInfo(5); END
UserLogin
843
Logs a user into the CitectSCADA system, using either Windows integrated security or CitectSCADA security and gives users access to the areas and privileges assigned to them in the Users database, and uses the locale language defined for that user. Only one user can be logged into a computer at any one time. If a user is already logged in when a second user logs in, the first user is replaced by the newly logged on user. When a newly logged in user does not have access to view the current page (as defined by the page's area), the system returns to the home page as specified by the parameter[Page]HomePage, and if unsuccessful that returns to the startup page. When multiple pages are currently displayed, this occurs for each open window. To call this function at user login, the password argument passed needs to be in secure string format. At startup, or when the user logs out, a default user is active, with access to area 0 (zero) and privilege 0 (zero) only. Use the LoginForm() function to display a form for logging in to the system.
Syntax
sPassword:
The user's password, as defined in the Users database or Windows account formatted as a secure string. To improve the user credentials protection provides a system built-in user login function that takes the user name and secure password as the arguments. This reduces the chance that the user's password can be exposed in plaint text from the runtime system
sLanguage:
The specified language needs to tagbe one of the languages defined in System/Languages (LANG.DBF). If the specified language is undefined, the default language is used by the login user, and a message Undefined language is shown in the prompt line. An empty string (i.e. ) can be specified to indicate that the default language is used by the login user. The default language defined by [Language]LocalLanguage INI parameter. The default value of this parameter is .
Return Value
0 (zero) if successful.
Related Functions
844
Example
/* ** ** ** ** ** ** ** */
FUNCTION NAME:LoginForm This function displays the login form, get the user name, password and the language of the user session and then trys to log the user in. If the login does not succeed it will retry until login is ok or user presses the cancel button.
INT FUNCTION LoginForm(STRING sName="", STRING sPassword="", STRING sLanguage="English") INT bDone; INT nStatus; INT hForm; bDone = FALSE; WHILE bDone = FALSE DO FormNew("@(Login Form)", 35, 5, 5); FormPrompt(1, 0, "@(Name)"); FormInput(16, 0, "", sName, 16); FormPrompt(1, 2, "@(Password)"); FormSecurePassword(18, 2, "", sPassword, 16); FormPrompt(1, 4, "@(Language)"); FormInput(16, 4, sLanguage, 16); FormButton(6, 6, " " + "@(OK)" + " ", 0, 1); FormButton(20, 6, "@(Cancel)", 0, 2); IF FormRead(0) = 0 THEN hForm = FormNew("@(User Login)", 36, 1, 8 + 16 + 128 + 256); FormPrompt(1, 0, "@(Authentication in progress ...)"); FormRead(1); SleepMs(200); IF UserLogin(sName, sPassword, sLanguage) = 0 THEN bDone = TRUE nStatus = 0; ELSE sPassword = ""; END IF FormActive(hForm) THEN FormDestroy(hForm); END ELSE bDone = TRUE;
845
UserPassword
Not available for a Windows user. Changes the password for the user. Changes are written to both the Users database and the runtime database in memory. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
Syntax
sPassword:
The password of the user. The sPassword argument is optional. If not passed, this argument defaults to an empty string which is subsequently ignored. It is included for the purposes of handling duplicate user names and separate password identification compatibility.
sOldPassword:
The password assigned to the user before the UserPassword() function is run. The sOldPassword argument is optional. If passed, CitectSCADA will only permit the password change (and consequent re-setting of the expiry period) when the old password is correctly entered. If the sOldPassword parameter is not passed, the password change will proceed without restriction.
Return Value
846
UserPasswordExpiryDays
Not available for a Windows user. Returns the number of days left before the user's password is due to expire. To use this function, you can build a form page by using cicode that takes the user name and password as inputs and output the number of days that return by UserPasswordExpiryDays().
Syntax
sPassword:
The password of the user. The sPassword argument is optional. If not passed, this argument defaults to an empty string which is subsequently ignored. It is included for the purposes of handling duplicate user names and separate password identification compatibility.
Return Value
The return value contains either the number of days before password expiry, or one of two exception conditions:
l l l
Related Functions
847
UserPasswordForm
Not available for a Windows user. Display a form to allow users to change their own passwords. Changes are written to both the Users database and the runtime database in memory. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
Syntax
UserPasswordForm()
Return Value
UserSetStr
Sets the value of the given field for the given user record in the project configuration (users.dbf ) on the local machine. After this function has been called, use the function UserUpdateRecord to update the user record on the running system. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
848
Syntax
sField:
The name of the field in users.dbf to modify.
sData:
The new value of the field.
Return Value
UserUpdateRecord
Triggers a recompile of the local project configuration, then notifies the running system that user configuration has been modified and needs to be reloaded. Use this function in conjunction with UserSetStr to modify user configuration online. An alarm server needs to be configured and running in the project, so that all clients are notified that an online change to the users configuration has been completed. In order to perform user configuration changes online in a system with multiple computers running SCADA nodes using these functions, you will need to use the RUN and COPY parameters to check the updates are distributed throughout the system, and that the functions are called from the computer which uses the COPY path as it's RUN path.
Syntax
UserUpdateRecord()
Return Value
849
UserVerify
Verifies a given user by authenticating the user's credential, verifies the user privileges and areas against those specified in the functions parameters. Successful verification however does not log the user into the CitectSCADA runtime system.
Syntax
sPassword:
The password of the user. The sPassword argument needs to be passed as a secure string.
sAccess:
Specifies the required user's viewable areas.
sPrivGlobal:
Specifies the required user's global privilege.
sPriv1-8:
Specifies the required areas for privileges 1 - 8. That is, sPriv1 contains the areas (1,2,3,4,...,255) where the user has Privilege 1.
Return Value
0 (zero) if successful, otherwise an error code is returned. The successful verification has to meet the following conditions:
l l
The selected user credentials can be authenticated The required user privileges are included in the authenticated user's total privileges.
850
Related Functions
VerifyPrivilegeForm
Displays a form that allows a single user to enter their credentials. These credentials are checked against a specified set to ensure the user has the required privileges before allowing the operation to proceed. The user can be a Citect or Windows user.
Syntax
VerifyPrivilegeForm(sOperationDescription,sLogDevice, sAccess, sGlobalPriv, sPriv1, sPriv2, sPriv3, sPriv4, sPriv5, sPriv6, sPriv7, sPriv8) sOperationDescription:
851
sLogDevice:
The name of a log device if logging is required, otherwise pass an empty string.
sAccess:
The required user viewable areas, or pass an empty string for none.
sGlobalPriv:
The required global privilege, otherwise pass an empty string.
sPriv1..8:
Specifies the required areas for privileges 1 - 8. That is, sPriv1 contains the areas (1,2,3,4,...,255) where the user has Privilege 1. Each argument needs to be either specified or an empty string for none.
Return Value
The name of the user that met the required privileges, otherwise ""
Related Functions
VerifyPrivilegeTagWrite
852
Displays a form that allows any single user to enter their credentials in order to approve a write of a specific value to a specific tag. These credentials are checked against a specified set to ensure the user has the required privileges before allowing the operation to proceed. The usernames can be Citect or Windows users.
Syntax
VerifyPrivilegeTagWrite(sTagName, sValueToWrite, sLogDevice, sAccess, sGlobalPriv, sPriv1, sPriv2, sPriv3, sPriv4, sPriv5, sPriv6, sPriv7, sPriv8) sTagName:
The name of the tag to which a write needs to be approved.
sValuetoWrite:
The value to write to the tag if approval succeeds.
sLogDevice:
The name of a log device if logging is required, otherwise pass an empty string.
sAccess:
The required user viewable areas, or pass an empty string for none.
sGlobalPriv:
The required global privilege, otherwise pass an empty string.
sPriv1..8:
Specifies the required areas for privileges 1 - 8. That is, sPriv1 contains the areas (1,2,3,4,...,255) where the user has Privilege 1. Each argument needs to be either specified or an empty string for none.
Return Value
Name of user that met the required privileges (and therefore the value was written to the specified tag), otherwise ""
Related Functions
853
// This example generates a form to request a user to approve the tag write operation. // This user needs privilege levels of 6 and 3. // When approved, the PLC_VAR1 tag is written with the value 123 and a page string // is set to indicate the approval status. IF (VerifyPrivilegeTagWrite("PLC_VAR1", "123", "ApprovalLog", "PlantWide", "", "6", "3", "", "", "", "", "", "")<>"") THEN PageSetStr(1, "TagWrite Successful"); ELSE PageSetStr(1, "TagWrite Not Successful"); END
WhoAmI
Displays the user name and full name of the user currently logged-in to the system. When the current logged on user is Windows user this function returns the users full name in the format of <DomainName>\<UserName>. The names are displayed at the prompt AN.
Syntax
WhoAmI()
Return Value
854
SOEArchive
Use this function to archive event journals.
Syntax
INT SOEArchive()
Return Value
0 (zero) if successful, otherwise an error code is returned. See Also SOE Functions
SOEDismount
Use this function to dismount archive volume.
Syntax
INT SOEDisMount()
Return Value
0 (zero) if successful, otherwise an error code is returned. See Also SOE Functions
SOEEventAdd
Use this function to insert an event into the Event Journal:
Syntax
855
Message:
The message for the event.
Tag:
Alarm tag associated with the event. This can be Cluster.Tag or Tag if running on a single cluster system. If not specified the event is classed as a User event.
Cluster:
Specify if running on a multi-cluster system and Tag has been specified. If Tag has not been specified and the Cluster is blank, the User event will be broadcast to all clusters the client is currently connected to.
Return Value
0 (zero) if successful, otherwise an error code is returned. See Also SOE Functions
SOEMount
Use this function to mount an archive volume. Archived data from the volume is displayed on the Sequence of events page.
Syntax
0 (zero) if successful, otherwise an error code is returned. See Also SOE Functions
856
ServerBrowseFirst
ServerBrowseGetField
ServerBrowseNext
ServerBrowseNumRecords ServerBrowseOpen
ServerBrowsePrev
ServerGetProperty
ServerInfo ServerInfoEx
ServerIsOnline
ServerReload ServerRestart
857
any Cicode node in system, without affecting other server processes running on the same machine. ServerRPC Calls a remote procedure on the Citect server specified by the ServerName argument.
ServerBrowseClose
The ServerBrowseClose function terminates an active data browse session and cleans up resources associated with the session.
Syntax
ServerBrowseClose(iSession) iSession:
Handle to a browse session previously opened by a ServerBrowseOpen call.
Return Value
0 (zero) if the server browse session exists, otherwise an error code is returned.
Related Functions
ServerBrowseFirst, ServerBrowseGetField, ServerBrowseNext, ServerBrowseNumRecords, ServerBrowseOpen, ServerBrowsePrev See Also Server Functions
ServerBrowseOpen
The ServerBrowseOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls.
Syntax
ServerBrowseOpen(STRING Filter , STRING Fields , STRING Clusters) Filter: A semicolon delimited list of field name=field value pairs, specifying the records to return during the browse. An empty string indicates that all records will be returned.
858
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 available columns. Supported fields are:
Clusters:
An optional parameter that specifies via a comma delimited string the subset of clusters to browse. An empty string indicates that connected clusters will be browsed.
Return Value
An integer handle to the browse session. Returns -1 on error. The returned entries will be ordered alphabetically by name.
Related Functions
ServerBrowseFirst
The ServerBrowseFirst function places the data browse cursor at the first record.
Syntax
ServerBrowseFirst(iSession) iSession:
Handle to a browse session previously opened by a ServerBrowseOpen call.
Return Value
859
0 (zero) if the server browse session exists, otherwise an error code is returned.
Related Functions
ServerBrowseClose, ServerBrowseGetField, ServerBrowseNext, ServerBrowseNumRecords, ServerBrowseOpen, ServerBrowsePrev See Also Server Functions
ServerBrowseNext
The ServerBrowseNext 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).
Syntax
ServerBrowseNext(iSession) iSession:
Handle to a browse session previously opened by a ServerBrowseOpen call.
Return Value
0 (zero) if the server browse session exists, otherwise an error code is returned.
Related Functions
ServerBrowseClose, ServerBrowseFirst, ServerBrowseGetField, ServerBrowseNumRecords, ServerBrowseOpen, ServerBrowsePrev See Also Server Functions
ServerBrowsePrev
The ServerBrowsePrev 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).
Syntax
ServerBrowsePrev(iSession) iSession:
Handle to a browse session previously opened by a ServerBrowseOpen call.
0 (zero) if the server browse session exists, otherwise an error code is returned.
Related Functions
ServerBrowseClose, ServerBrowseFirst, ServerBrowseGetField, ServerBrowseNext, ServerBrowseNumRecords, ServerBrowseOpen See Also Server Functions
ServerBrowseGetField
The ServerBrowseGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing.
Syntax
sFieldName:
The name of the field that references the value to be returned. Supported fields are:
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
ServerBrowseClose, ServerBrowseFirst, ServerBrowseNext, ServerBrowseNumRecords, ServerBrowseOpen, ServerBrowsePrev See Also Server Functions
ServerBrowseNumRecords
The ServerBrowseNumRecords function returns the number of records that match the filter criteria.
861
Syntax
ServerBrowseNumRecords(iSession) iSession:
Handle to a browse session previously opened by a ServerBrowseOpen call.
Return Value
The number of records that matched the filter criteria. A value of 0 denotes that no records matched. A value of -1 denotes that the browse session is unable to provide a fixed number. This could be the case if the data being browsed changed during the browse session.
Related Functions
ServerBrowseClose, ServerBrowseFirst, ServerBrowseGetField, ServerBrowseNext, ServerBrowseOpen, ServerBrowsePrev See Also Server Functions
ServerGetProperty
This function returns information about a specified server and can be called from any client. Note: This function can only be called for Alarm, Report and Trend Servers
Syntax
sProperty:
The name of the requested property. Can be one of the following:
"RDBMemTime" - Returns the date and time of currently loaded RDB (in-memory) "RDBDiskTime" - Returns the date and time of RDB on disk (compiled) "LibRDBMemTime" - Date and time of currently loaded cicode library (_library.RDB) "LibRDBDiskTime" - Date and time of cicode library on disk (_library.RDB)
862
"LastReloadError" - Error Code from the latest reload "ReloadStatus" - Returns 1 if the server is reloading, 0 if not "ReloadProgress" - Reload Progress (in percent) Range: 0 100 "SyncStatus" - Returns the startup synchronization status: l 0 the server has been synchronized with its redundant peer. l 1 the server is not connected to peer server. l 2 the server is synchronizing with its redundant peer. "SyncProgress" - The percentage of the server synchronization progress: Range: 0-100 Note: The "SyncStatus" and "SyncProgress" properties are only supported for Trend and Alarm servers. sCluster:
The cluster of the server to be queried in quotation marks "". This parameter is optional. However, if the Server Name is not local or not specified in ClusterName.ServerName format an error code is returned.
Return Value
ServerInfo
Gets status information on clients and servers. Note: This function is a non-blocking function and can only access data contained within the calling process; consequently it cannot return data contained in a different
863
server process. This function is not redirected automatically by CitectSCADA runtime. If you want to make a call from one process to return data in another, use MsgRPC() to make a remote procedure call on the other process. Alternatively, use the ServerInfoEx function that allows you to specify the name of the component from which you want to retrieve data.
Syntax
You can also pass a number instead of the name (but it still needs to be enclosed in quotes). The number represents the target client. For example, if there are 12 clients, passing "3" will get information on the 3rd client. If this server is an Alarm, Trend, Report, and I/O server then each client will be attached 4 times. So 12 clients would mean there are 3 CitectSCADA computers using this server - one of which is itself.
Type:
The type of information required (depends on the Name you specify): "Alarm", "Trend", or "Report" name:
0 - Active flag (returns 1 if this is the active server, 0 if an inactive server). 1 - Number of clients attached to this server. 2 - If this client is attached to the primary or standby server for the specified server name. If Name is "Alarm" and if this client is attached to the primary alarm server, the return value is 0. If this client is attached to the standby, the return value is 1. 3 - The status of the client connection to the specified server name. If Name is "Report" and the client is talking to a report server (either primary or standby), the return value is 1. If not, the return value is 0.
"Client" name:
0 - The computer name, as specified by [LAN]Node. 1 - Not supported. 2 - Not supported. 3 - Not supported.
For modes 1,2 and 3, use ServerInfoEx instead. "Server" name:
864
0 - Not supported. 1 - The number of clients attached to this server. This is the total number of Alarm, Trend Report, and I/O server clients.
"<number>":
0 - The name of the server this client is talking to. For example, "Alarm", "Trend", "Report", or "IOServer". 1 - The login name of the client. This may be an empty string if the client has not logged in. 2 - The CitectSCADA computer name of the client computer. 3 - The time the client logged in. 4 - The number of messages received from this client. 5 - The number of messages sent to this client. 6 - If this client has a licence (1) from this server or not (0). 7 - The type of the licence; full licence (0), View-only Client (1), or Control Client (2). 8 - If the client is remote (1) or local (0). ClusterName:
The name of the cluster that the server belongs to. This is only relevant if:
l l
The Name is "alarm", "report", or "trend"; AND The type of information required, nType, is 2 or 3.
Return Value
865
ServerInfoEx
Gets status information on clients and servers from a specified component in a multiprocess runtime environment. When this function is called, the system redirects the call to the process that contains the specified component. If the specified component is in the calling process, the call is not redirected. If the specified component is not one of the servers listed in the sComponent argument description (see below), of if the system cannot find the component from the connected local processes, a hardware alarm is raised.
Syntax
STRING ServerInfoEx(STRING Name, INT Type, STRING Component [, STRING ClusterName] [, STRING ServerName] ) Name:
The name of the client or server, either "Client", "Server", "Alarm", "Trend", or "Report".
l
You can also pass a number instead of the name (but it still needs to be enclosed in quotes). The number represents the target client. For example, if there are 12 clients, passing "3" will get information on the 4th client. If this server is an Alarm, Trend, Report, and I/O server then each client will be attached 4 times. So 12 clients would mean there are 3 CitectSCADA computers using this server - one of which is itself.
Type:
The type of information required (depends on the Name you specify): "Alarm", "Trend", or "Report" name:
0 - Active flag (returns 1 if this is the active server, 0 if an inactive server). 1 - Number of clients attached to this server. 2 - If this client is attached to the primary or standby server for the specified server name. If Name is "Alarm" and if this client is attached to the primary alarm server, the return value is 0. If this client is attached to the standby, the return value is 1. 3 - The status of the client connection to the specified server name. If Name is "Report" and the client is talking to a report server (either primary or standby), the return value is 1. If not, the return value is 0.
866
Note: If the sComponent is "IOServer" and the sName is "Client", Types 1 and 2 return an empty string, as the concept of primary and standby servers does not apply to IOServers. "Client" name: 0 - The computer name, as specified by [LAN]Node. 1 - The primary server name, as specified in the server configuration forms in Project Editor. 2 - The secondary server name, as specified , as specified in the server configuration forms in Project Editor. 3 - The name of the INI file being used, for example, Citect.INI. "Server" name: 0 - The server name, as specified in the server configuration forms in Project Editor. 1 - The number of clients attached to this server. This is the total number of Alarm, Trend Report, and I/O server clients. "<number>": 0 - The name of the server this client is talking to. For example, "Alarm", "Trend", "Report", or "IOServer". 1 - The login name of the client. This may be an empty string if the client has not logged in. 2 - The CitectSCADA computer name of the client computer. 3 - The time the client logged in. 4 - The number of messages received from this client. 5 - The number of messages sent to this client. 6 - If this client has a licence (1) from this server or not (0). 7 - The type of the licence; full licence (0), View-only Client (1), or Control Client (2). 8 - If the client is remote (1) or local (0). sComponent:
Specifies the component name from which to retrieve the status information:
" "- An empty string causes the function to run on the calling process. "Alarm" - Redirects the function to the alarm server process. "Trend" - Redirects the function to the trend server process. "Report" - Redirects the function to the report server process. "IOServer" - Redirects the function to the I/O server process.
867
Note: If sName is "Client", the function will NOT be redirected to the component specified by sComponent. Instead, the function gets information of type nType from the current client connection to the component specified by sComponent. ClusterName:
The name of the cluster that the server belongs to. This is only relevant if:
l l
The Name is "alarm", "report", or "trend"; AND The type of information required, nType, is 2 or 3.
ServerName:
Specifies the name of the the I/O Server. This parameter is only required if you are running more than one I/O server process from the same cluster on the same computer and need to instruct the system which process to redirect to. The argument is enclosed in quotation marks "".
Return Value
This example gets the server information from the report process.
sSrvInfo=ServerInfoEx("Report",0, "Report"); IF sSrvInfo THEN ! This is a primary report server. ELSE ! This is a stand-by report server. END /* Get and store the names of clients attached to the report server */ iCount = 1; iClients = ServerInfoEx("Server", 1, "Report"); WHILE iCount <= iClients DO sName[iCount] = ServerInfoEx(IntToStr(iCount), 2, "Report"); iCount = iCount + 1; END
ServerIsOnline
The ServerIsOnline function checks if the given server can be contacted by the client for giving the online/offline status of the server.
Syntax 868
Cluster:
The cluster of the server to be queried in quotation marks "". An empty string indicates that the default cluster will be used.
Return Value
ServerReload
This function can only be called for Alarm, Report and Trend Servers and reloads the server specified by cluster and server name. If the server is not found an error code is returned. ServerReload can be used in blocking or non-blocking modes using the bSync parameter. When used in non-blocking mode, the server status can be returned using the ServerGetProperty function. To call this function successfully a valid user needs to be logged in as the client and you need to set the [LAN]AllowRemoteReload parameter in the Citect.ini file to "1" on the computer where the receiving server is running. It is recommended that the ServerGetProperty cicode function be used with the LibRDBMemTime and LibRDBDiskTime properties to check if there is a change to the Cicode library before attempting a reload. Following a reload please check the corresponding server's syslog.dat file for any reload messages. The cicode changes will not be reloaded, therefore a restart may be more appropriate.
869
UNINTENDED EQUIPMENT OPERATION Restart the server process if a "Cicode library timestamp differs" error is detected. A library mismatch is indicated on the server in either the hardware alarm or the server's syslog.dat file. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Note: A message in the Syslog.dat file and hardware alarm of "Cicode library timestamp differs" (error code 454) will be raised if the Cicode library used by one or more server runtime databases is different from the one in memory. The timestamps will be different if the project has been fully recompiled (with or without Cicode modification), or if the project has been incrementally recompiled after any Cicode has been modified.
Syntax
sCluster:
The cluster of the server to be reloaded in quotation marks "". This parameter is optional. However, if the server name is not local or not specified in ClusterName.ServerName format, an error code is returned.
bSync:
Specifies whether the function operates in blocking or non-blocking mode. If bSync is set to 1, the function will not return until the server reload is complete. The reload is complete when all the records of all rdb files have been processed and updated. Blocking mode cannot be used from a foreground task (for example on graphic pages). When bSync is set to 0, the function operates in nonblocking mode. You can get the latest status of the reload using the ServerGetProperty function. Default value is 0.
Return Value
0 (zero) if the function was successful. Returns an error if unsuccessful.Outline of errors: 418 - Server is not found or if the client is not allowed to visit the cluster described in sCluster.
870
281 - Server is sitting on a remote machine to the client and the connection towards the server is not available. 519 - Server connection was available but interrupted. 451 - Server is busy with previous load request.
Related Functions
ServerRestart
Restart any specific alarm, report, trend or I/O server from any Cicode node in system, without affecting other server processes running on the same machine. To call this function a valid user needs to be logged in as the client. For this function to be successful you need to set the [Shutdown]NetworkStart parameter in the Citect.ini file to "1" on the computer where the issuing client is running.
Syntax
sCluster:
The cluster the server belongs to. This parameter is optional. If sCluster is not specified the current system cluster is used.
Return Value
0 (zero) if successful, otherwise one of the following error codes is returned: 256 - General software error 292 - Invalid function 403 - Cluster not found 418 - No server of type on cluster 512 - Time out error
871
513 - Access denied error See Also Cicode and General errors.
Related Functions
872
Connection functions
SQLClose Closes a SQL connection between the DB connection object and a database. Makes a connection to a database system for execution of SQL statements. Creates an internal DB connection object. Closes a database connection.
SQLConnect
Disposes the DB connection object. Gets information about a database connection. Opens an SQL connection between the DB connection object and the database.
Transaction functions
SQLBeginTran SQLCommit SQLRollBack Starts a database transaction. Commits a transaction to the database. Rolls back (or cancels) the last database transaction.
Statement functions
SQLAppend Appends a text string to the SQL buffer.
873
Executes an SQL query on a database. Terminates an SQL query. Executes an SQL query on a database. Executes an SQL query on a database. Executes an SQL query on a database. Sets a statement string in the SQL buffer.
Recordset functions
SQLCancel Cancels both the current operation on the given connection and all other pending operations on the given connection. Gets information about the fields or columns selected in an SQL query. Gets field or column data from a database record. Checks presence of null value in field from a recordset.
Gets the next database record from a SQL query. Gets the number of fields or columns that were returned by the last SQL statement. Gets the number of records that were modified in the last insert, update, or delete SQL statement. Gets the number of fields or columns that were returned by the last SQL statement. Gets the previous database record from an SQL query. Gets the number of rows in the recordset.
874
SQLParamsSetAsInt
SQLParamsSetAsReal
SQLParamsSetAsString
ExecuteDTSPkg
Loads and executes a DTS (Data Transformation Services) package which initiates data transfer and transformations between OLE DB data sources. A DTS package is created using the DTS utility provided in Microsoft SQL Server 7.0. It can be saved in a COM structured file, a Microsoft Repository, or in an SQL Server Database. All except the first of this function's parameters are optional, and their use will depend on your needs.
Syntax
ExecuteDTSPkg(sFileOrSQLSvrName [, sPkgName] [, sParam1, ... , sParam5] [, sPkgPwd] [, sPkgVer] [, sLogFile] [, sSQLSvrUsr] [, sSQLSvrPwd]) sFileOrSQLSvrName:
875
The path and name of the file containing the package (for file-based packages), or the SQL Server name (for SQL Server stored packages).
sPkgName:
The package name.
l
For file-based packages where only one package is stored in a file, you can ignore this parameter, as the package name defaults to the name of the file. If the package has been named differently to the file, or a file contains more than one package, you need to specify the package name. You need to also specify the package name for SQL Server stored packages.
sParam1, ,sParam5:
Five optional variables which may be used as global variables within the DTS package. The variables need to be named Param1, Param2, Param3, Param4, and Param5.
sPkgPwd:
The package password. The creator of the DTS package may have implemented a password so that unauthorized users cannot access it. In this case, you need to specify the package password. If no password has been implemented, you can omit this parameter.
sPkgVer:
The package version. If you don't specify a version, the most recent version is used.
sLogFile:
AN optional path and name for a log file. The log file can track activity such as:
l l l l l
File DTS package detected SQL DTS package detected Package initialized successfully Package executed sucessfully Package execution was not successful
sSQLSvrUsr:
The user name providing access to the SQL Server where the DTS package is stored. A user's account on the SQL Server consists of this user name and, in most cases, a password. This parameter also determines which method is used to load the package. If sSQLSvrUsr is specified, the package is assumed to be an SQL Server stored package. In this case, the package is loaded using the LoadFromSQLServer() method. Otherwise, the package is file-based and LoadFromStorageFile() is called.
sSQLSvrPwd:
876
The password providing access to the SQL Server, if the user's account on the server requires a password.
Return Value
0 (zero) if the package was executed successfully, otherwise a DTS error number is returned.
Example
/* File-based package with one package per file, where the package name is the same as the file name.*/ iResult = ExecuteDTSPkg("c:\dtspackages\package.dts"); /*SQL Server stored package with additional parameters */ iResult = ExecuteDTSPkg("Server1", "TestPackage", "Param1", "Param2", "Param3", "Param4", "Param5", "Fred", "1", "c:\packages\PkgLog.txt", "jsmith", "secret");
SQLAppend
Appends a query string to the SQL buffer. Cicode cannot send an SQL query that is longer than 255 characters. If you have an SQL query that is longer than the 255 character limit, you can split the query into smaller strings, and use this function to append the query in the SQL buffer. This function can be called in the foreground or background. Queries which are built on the basis of user data, for example inputed by users via graphics pages or forms, may be prone to SQL Injection attacks. In such case, try to limit the risk by using CiCode functions from parameterized queries group and refer to a professional advice in this matter.
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
Building queries from pieces (SQLSet, SQLAppend) or adding parameters to either queries or connections (SQLParam functions) requires a few calls to respective CiCode functions. If a few functions try to manipulate the same connection in the same time some conflicts and unintended operations may occur. It is a typical multithreading problem.
877
To avoid this, instead of manipulating connections, consider using locally created and locally disposed queries. For example:
int function SAFE_SQL_CICODE_MULTITHREAD_USE() //locally created query int hStmt = SQLQueryCreate(hConnection); //Set the query SQLSet(hStmt, "select * from TAB where NAME=@Name"); //Add parameters to the query SQLParameterSetAsString(hStmt, "Name", "Aaa"); //Execute the query SQLGetRecordset(hStmt, ""); //the locally created query is disposed SQLQueryDispose(hStmt); End
Syntax
String:
The query string to append to the SQL buffer.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLBeginTran
878
Starts a database transaction. When you make a transaction, your changes are not written to the database until you call the SQLCommit() function. Alternatively, you can use the SQLRollBack() function to discard all changes made during the transaction. After you begin a transaction, you need to call either SQLCommit() to save the changes or SQLRollBack() to discard the changes. You need to use one of these functions to complete the transaction and release all database locks. A single database connection can only handle one transaction at a time. After you call SQLBeginTran(), you need to complete that transaction before you can call SQLBeginTran() again. If you disconnect from a database while a transaction is active (not completed), the transaction is automatically "rolled back" any changes you made to the database in that transaction are discarded. You do not need to begin a transaction to modify a database. Any changes you make to a database before you call the SQLBeginTran() are automatically committed, and no database locks are held. The SQLBeginTran() function is not supported by all databases. If the function is not performing as you expect, check that both your database and/or DB provider support transactions. Refer to the documentation for your database for more information on transactions. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLBeginTran(hSQL) hSQL:
The handle to the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLCommit, SQLConnect, SQLDisconnect, SQLEnd, SQLErrMsg, SQLExec, SQLFieldInfo, SQLGetField, SQLInfo, SQLNext, SQLNoFields, SQLNumChange, SQLRollBack, SQLTraceOff, SQLTraceOn
Example
879
/* Increase each employee's salary and superannuation by a specified amount. If any errors occur, the changes are aborted */ INT FUNCTION PayIncrease(STRING sIncrease) INT hSQL; INT Count1; INT Count2; hSQL = SQLConnect("DRV=QEDBF"); SQLBeginTran(hSQL); SQLExec(hSQL, "UPDATE C:\DATA\EMPLOYEE SET Salary = Salary + " +sIncrease); Count1 = SQLNumChange(hSQL); SQLExec(hSQL, "UPDATE C:\DATA\EMPLOYEE SET Super = Super + " +sIncrease); Count2 = SQLNumChange(hSQL); IF Count1 = Count2 THEN SQLCommit(hSQL); ELSE SQLRollBack(hSQL); END SQLEnd(hSQL); SQLDisconnect(hSQL); END
SQLCall
Executes an SQL query on a database. The function returns the number of rows affected by the executed query. With this function, you can execute any SQL query or command supported by the SQL database. If it returns some data (as for SELECT query), the data is ignored. This function is a blocking function and should not be called from a foreground task. Queries which are built on the basis of user data, for example inputed by users via graphics pages or forms, may be prone to SQL Injection attacks. In such case, try to limit the risk by using CiCode functions from parameterized queries group and refer to a professional advice in this matter.
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
Syntax
880
sSelect:
The SQL query to be sent to the SQL database.
Return Value
The number of affected records or -1 if an error is detected. (For details call the SQLErrMsg() function). The presence of error code can be tested by calling the IsError() CiCode function.
Related Functions
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd See Also SQL Functions
SQLCancel
This function cancels both the current operation on the given connection and all other pending operations on the given connection. The cancellation means that the current operation on the SCADA side is immediately finished. The cancelled operation returns error code 299 and its state on the database side should be considered as undefined, that is, it is not known that it either succeeded, partially succeeded, or was unsuccessful. This function can be called in the foreground or background.
Syntax
SQLCancel(hConnection) hConnection:
The handle to the connection.
Return Value
0 (zero) if successful, otherwise an error code is returned. (For details of the 307 error code, call the SQLErrMsg() function).
Related Functions
881
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo See Also SQL Functions
SQLClose
Closes a SQL connection between the DB connection object specified by the function's parameter and a database. The DB connection object is not deleted from the memory until calling SQLDispose function. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLClose(hSQL) hSQL:
The handle to the DB connection object, returned from the SQLCreate() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 if success, otherwise an error code (For details call the SQLErrMsg() function).
Related Functions
SQLCommit
Commits (to the database) all changes made within a transaction. If you call the SQLBeginTrans() function to begin a transaction, you need to call the SQLCommit() function to save the changes you make to the database during that transaction (with the Insert, Delete, and Update SQL commands). The SQLCommit() and SQLRollBack() functions both complete a transaction and release all database locks. But while the SQLCommit() function saves all changes made during the transaction, the SQLRollBack() function discards these changes. Unless you call the SQLCommit() function before you disconnect the database, the transaction is automatically rolled back any changes you made to the database in that transaction are discarded.
882
The SQLCommit() function could affect different databases in different ways. If the function is not performing as you expect, check that your database is able to service transactions. Refer to the documentation for your database for information on committing transactions. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLCommit(hSQL) hSQL:
The handle to the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg() function).
Related Functions
SQLBeginTran, SQLConnect, SQLDisconnect, SQLEnd, SQLErrMsg, SQLExec, SQLFieldInfo, SQLGetField, SQLInfo, SQLNext, SQLNoFields, SQLNumChange, SQLRollBack, SQLTraceOff, SQLTraceOn
Example
SQLConnect
Creates an internal database connection object and tries to connect it to a database specified by the connection string. Returns a handle to the database connection object for use by the other database functions. You only require one database connection object for each database system to be accessed (for example, Oracle, dBASE, Excel, etc.). It is recommended not to use an SQL database for storage of real-time data (such as alarms), because SQL databases do not provide real-time performance when accessing database data. Only use an SQL database where data transfer is not a priority (for example, recipes or reports). If you try to use SQL to store real time data, CitectSCADA's performance could be greatly decreased.
883
Each database connection object created by SQLConnect should be released by calling SQLDisconnect with handle to the object. The releasing operation should be performed even when the SQL connection to database is no longer active; for example automatically dropped by a remote database or manually closed by SQLClose. Memory leaks can occur if the handles are not properly released. Note: Currently there are certain configurations of providers, connection strings and database systems which can automatically close connections in order to save the database systems resources; for example MS SQL Server dedicated provider with activated pooling closes the connection to MS SQL Server when there is no data exchange between the client and the database server for some predefined time. If such behaviour is observed and is not desired from the system design point of view, it can be either: - switched off by finding and using respective attributes in the connection string (if existing and supported by database) or - by actively checking error codes returned from SQL CiCode functions and reconnecting by using SQLOpen if the connection is dropped. The actual state of connections can be checked by SQLInfo with type 5. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLConnect(sConnect) sConnect:
The connection string, in the format: <attribute>=<value>[;<attribute>=<value>. . .] Acceptable attributes and their values vary accordingly to the provider and/or the database system, so please refer to your database documentation. For example, connecting to a SQL Server via ODBC usually requires giving the computer name and the database name which can be done by defining Server and Database attributes. The same connection via OleDB requires defining the computer as Data Source and the database as Initial Catalog.
Providing username and password as a plain text in the connection string may lead to a security breach on the database side. Please consider using other forms of authentication instead of username/password login, for example Windows Authentication. If this is not possible, try to limit the database account rights and not use the same username and password for other vital parts of the system such as for SCADA.
884
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
Some simple examples are shown below: ODBC provider "Driver={SQL Server};Server=(local);Trusted_Connection=Yes; Database=MyDatabase;" "Driver={Microsoft ODBC for Oracle};Server=ORACLE8i7;Persist Security Info=False;Trusted_Connection=Yes" "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\doc\MyDatabase.mdb" "Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\doc\MySheet.xls" "SCADA Data Provider=Odbc;Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=c:\doc" "DSN=MyDSNname"
OleDB provider "SCADA Data Provider=OleDb;Provider=MSDAORA; Data Source=ORACLE8i7;Persist Security Info=False;Integrated Security=Yes" "SCADA Data Provider=OleDb;Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\bin\LocalAccess40.mdb" "SCADA Data Provider=OleDb;Provider=SQLOLEDB;Data Source=(local);Integrated Security=SSPI"
The provider to be used to communicate to a database. Allowed values are as follows: ODBC ODBC provider, default one if no provider specified, OLEDB OLEDB provider, SQLClient MS SQL Server dedicated provider The timeout in seconds for establishing connections.
SCADA Con-
885
nection Timeout SCADA Query Timeout The timeout in seconds for executing queries. This attribute overwrites [SQL]QueryTimeout INI parameter.
Return Value
The handle to the database connection object if the connection is successful, otherwise -1 is returned. (For details call the SQLErrMsg() function). The handle identifies the database connection object where details of the associated SQL connection to a DB are stored.
Related Functions
886
SQLCreate
Creates an internal DB connection object and returns a handle to the object for use by the other DB functions. The object is in disconnected state and can be connected to a database by executing the SQLOpen function. You only require one DB connection object for each database system to be accessed (for example, Oracle, dBASE, Excel, etc.). Each DB connection object created by SQLCreate should be released by calling SQLDispose with the handle to the object. The releasing operation should be performed even when the SQL connection to DB is no longer active; for example, automatically dropped by a remote DB. Memory leaks can occur if the handles are not properly released. This function can be called in the foreground or background.
Syntax
SQLCreate(sConnect) sConnect:
The connection string, in the format: <attribute>=<value>[;<attribute>=<value>. . .] Acceptable attributes and their values vary accordingly to the provider and/or the database system, so please refer to your database documentation. For example, connecting to a SQL Server via ODBC usually requires giving the computer name and the database name which can be done by defining Server and Database attributes. The same connection via OleDB requires defining the computer as Data Source and the database as Initial Catalog.
Providing username and password as a plain text in the connection string may lead to a security breach on the database side. Please consider use of other forms of authentication instead of username/password login as for example Windows Authentication. If not possible, try to limit the database account rights and not use the same username and password as for other vital part of the system as for example for SCADA.
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
887
ODBC provider "Driver={SQL Server};Server=(local);Trusted_Connection=Yes; Database=MyDatabase;" "Driver={Microsoft ODBC for Oracle};Server=ORACLE8i7;Persist Security Info=False;Trusted_Connection=Yes" "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\doc\MyDatabase.mdb" "Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\doc\MySheet.xls" "SCADA Data Provider=Odbc;Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=c:\doc" "DSN=MyDSNname"
OleDB provider "SCADA Data Provider=OleDb;Provider=MSDAORA; Data Source=ORACLE8i7;Persist Security Info=False;Integrated Security=Yes" "SCADA Data Provider=OleDb;Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\bin\LocalAccess40.mdb" "SCADA Data Provider=OleDb;Provider=SQLOLEDB;Data Source=(local);Integrated Security=SSPI"
The provider to be used to communicate to a DB. Allowed values are as follows: ODBC - ODBC provider, default one if no provider specified, OLEDB - OLEDB provider, SQLClient - MS SQL Server dedicated provider The timeout for establishing connections.
The timeout for executing queries. This attribute overwrites [SQL] QueryTimeout INI parameter.
Return Value
The handle to the DB connection object if the connection is successful, otherwise -1 is returned. (For details call the SQLErrMsg() function). The handle identifies the DB connection object where details of the associated SQL connection to a DB are stored.
Related Functions
888
//* Make a connection to an SQL server and select the name field from each record in the employee database. */ FUNCTION ListNames() INT hSQL; STRING sName; INT Status; INT hRec; INT nColumns; INT nRows; INT i; hSQL = SQLCreate("DSN=MyDatabase;UID=billw;SRVR=CI1"); IF hSQL <> -1 THEN Status = SQLOpen(hSQL); IF Status = 0 THEN hRec = SQLGetRecordset(hSQL, "SELECT NAME FROM EMPLOYEE"); IF hRec <> -1 THEN nRows = SQLRowCount(hRec); FOR i=0 TO nRows - 1 DO sName = SQLGetField(hRec, "NAME", i); .. END SQLEnd(hRec); ELSE Message("Information", SQLErrMsg(), 48); END SQLClose(hSQL); ELSE Message("Information", SQLErrMsg(), 48); END SQLDispose(hSQL); END END
SQLDisconnect
Closes the SQL connection to a database and disposes the DB connection object specified by the function parameter. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLDisconnect(hSQL) hSQL:
The handle to the DB connection object, returned from the SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
889
0 if success, otherwise an error code (For details call the SQLErrMsg() function).
Related Functions
SQLDispose
Disposes the DB connection object specified by its parameter. If there is an active SQL connection to a database, the SQL connection has to be closed before disposal. This function can be called in the foreground or background.
Syntax
SQLDispose(hSQL) hSQL:
The handle to the DB connection object, returned from either the SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 if success, otherwise an error code (For details call the SQLErrMsg() function).
Related Functions
SQLEnd
890
The connection handle, in which case the function releases resources allocated for the default recordset for this connection. Generally, SCADA does the operation automatically each time when a new query is executed through SQLExec on the connection, but the operation can be also triggered manually. However, using the SQLEnd() function aids efficiency and creates good programming standards. SQLEnd() releases the memory that was allocated when the last query was executed via SQLExec. The recordset handle, in which case the function then removes the disconnected recordset associated with the handle from the system. This operation has to be done each time when the recordset is no longer necessary. Not removing recordsets from the system can result in consuming all available memory and halting SCADA and other applications on a computer.
This function is a blocking function and should not be called from a foreground task.
Syntax
SQLEnd(hGeneral) hGeneral:
The handle either to:
l
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored or the recordset
Return Value
0 (zero) if successful, otherwise an error code is returned. (For details of the 307 error code, call the SQLErrMsg() function).
Related Functions
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd
Example
891
SQLErrMsg
Returns an error message from either a particular data object or entire data system. If a 307 error code occurs when one of the SQL functions is called, an SQL error message is generated. Call this function to get that error message. This function can be called in the foreground or background.
Syntax
SQLErrMsg(hGeneral) hGeneral:
The handle to any data object either to the database connection object, recordset or query. The default value is -1 and then the function returns the error message for entire SQL system.
Return Value
SQLExec
Executes an SQL query on a database. With this function, you can execute any SQL query or command supported by the SQL database. Note: All types of fields can be requested in statements, but SCADA has to convert values of the fields to MBCS 8-bit strings which is not always possible. For example either single byte database strings or numbers can be converted to MBCS 8-bit strings, multi-byte strings can be converted to MBCS (their proper presentation depends on correct setup of SCADA and OS), while blobs cannot be encoded at all. Data obtained by this function is stored in the default recordset. The default recordset is always a connected recordset. Connected recordsets fetch only small portion of data when the query is executed, but later they have to fetch further portions when recordset functions are used. This kind of recordset needs open connections to DB, but they need little memory.
892
The SQLNext() function needs to be called after the SQLExec() function before you can access data in the first record. Only one query can be active at a time, so there is no need to end one query before you execute another query; each time you call SQLExec(), the previous query (through a previous SQLExec() call) is automatically ended. It means that each query executed from SQLExec cleans the default recordset. Queries are queued for execution and a result from one query overwrites the result from preceding one. Similarly, CitectSCADA automatically ends the latest query when it disconnects the database, even if you have not called SQLEnd(). However, the SQLEnd() function aids efficiency; SQLEnd() releases the memory that was allocated when the latest query was executed. This function is a blocking function and should not be called from a foreground task. Queries which are built on the basis of user data, for example inputed by users via graphics pages or forms, may be prone to SQL Injection attacks. In such case, try to limit the risk by using CiCode functions from parameterized queries group and refer to a professional advice in this matter. Note: SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions, code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database
Syntax
sSelect:
The SQL query to be sent to the SQL database.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg() function).
Related Functions
893
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd
Example
These examples assume that the following tables are setup in a SQL server (with the name configured in Windows Control Panel) and opened with the SQLConnect() function: PEOPLE
SURNAME MARTIAN CASE LIGHT BOLT FIRSTNAME MARVIN CARRIE LARRY BETTY OCCUPATION ENGINEER SUPPORT PROGRAMMER ENGINEER DEPARTMENT MANAGEMENT SCADA SCADA SYSTEMS
PHONE
SURNAME MARTIAN CASE BOLT LIGHT NUMBER 5551000 5551010 5551020 5551030
Each SQL string (sSQL) should be encased within the SQLExec function, for example:
SQLExec(hSQL, sSQL); To add a record to a table: sSQL = "INSERT INTO PEOPLE (SURNAME, FIRSTNAME, OCCUPATION, DEPARTMENT) VALUES('ALLEN','MATTHEW','PROGRAMMER','SCADA')";
894
Assuming that OK was clicked on the Message Box, the tables change to: PEOPLE
SURNAME CASE LIGHT BOLT FIRSTNAME CARRIE LARRY BETTY OCCUPATION SUPPORT PROGRAMMER ENGINEER DEPARTMENT SCADA SCADA SYSTEMS
PHONE
SURNAME CASE BOLT LIGHT NUMBER 5551010 5551020 5551030
To change a record:
895
This SQL command will return the following table back to CitectSCADA. The table can then be accessed by the SQLNext() function and the SQLGetField() functions. CITECT TABLE for hSQL
SURNAME MARTIAN BOLT
You can also select data using a much more complete SQL string, for example:
sSQL = "SELECT (SURNAME, OCCUPATION, NUMBER) FROM (PEOPLE, PHONE) WHERE DEPARTMENT='SCADA' AND PEOPLE.SURNAME = PHONE.SURNAME";
896
STRING sInfo[3][10] int i = 0; WHILE ((SQLNext(hSQL) = 0) and (i < sInfo[0][i] = SQLGetField(hSQL, sInfo[1][i] = SQLGetField(hSQL, sInfo[2][i] = SQLGetField(hSQL, END
This code example leaves the information in the sInfo two dimensional array as follows: sInfo
0 0 1 2 3 4 ... CASE LIGHT 1 SUPPORT PROGRAMMER 2 5551010 5551030
SQLFieldInfo
Gets information about the fields or columns selected by a SQL query. The function returns the name and width of the specified field. If you call the function within a loop, you can return the names and sizes of all the fields in the database. When the hGeneral is the connection handle, the function returns information about the default recordset. When the hGeneral is the recordset handle, the function returns information about the recordset itself. Keywords such as "DATE", "TIME", and "DESC" cannot be used as field names by some database systems. To use fields with these names, you need to append underscores to the names (for example, "TIME_", "DATE_", "DESC_"). This function can be called in the foreground or background.
897
Some combinations of database drivers and databases can return no name for certain classes of fields/columns, for example for aggregation queries such as "select SUM". In those cases such fields can be either explicitly named in the query itself, or accessed via a unified name in the format of "Field{ColumnNumber}" where {ColumnNumber} is the number of the requested field/column in the recordset.
Syntax
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
hField:
The field (or column) handle, indicating the position of the field in the database.
sName:
Out: A string variable in which the function stores the field name. The argument is returned by the function.
Width:
Out: An integer variable in which the function stores the maximum number of characters in the field. The argument is returned by the function.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
! Lists all fields in the Employee database FUNCTION ListFields() INT hSQL; STRING sField;
898
INT Count; INT Width; INT Index; SQLTraceOn("C:\DATA\TRACE.LOG"); hSQL = SQLConnect("DRV=QEDBF"); SQLExec(hSQL, "SELECT * FROM C:\DATA\EMPLOYEE"); Count = SQLNoFields(hSQL); Index = 0; WHILE Index < Count DO SQLFieldInfo(hSQL,Index,sField,Width); .. END SQLEnd(hSQL); SQLDisconnect(hSQL); SQLTraceOff(); END
SQLGetField
Gets field or column data from a database field. To get to a specific record in the recordset, use either the SQLNext() or SQLPrev() functions or, in case of disconnected recordsets, the nRowIndex argument. When the hGeneral is the connection handle, the function returns information from the default recordset. When the hGeneral is the recordset handle, the function returns information from the recordset itself. Note: All types of fields can be requested in statements, but SCADA has to convert values of the fields to MBCS 8-bit strings which is not always possible. For example either single byte database strings or numbers can be converted to MBCS 8-bit strings, multi-byte strings can be converted to MBCS (their proper presentation depends on correct setup of SCADA and OS), while blobs cannot be encoded at all. Keywords such as "DATE", "TIME", and "DESC" cannot be used as field names by some database systems. To use fields with these names, you need to append underscores to the names (for example, "TIME_", "DATE_", "DESC_"). This function can be called in the foreground or background. Some combinations of database drivers and databases can return no name for certain classes of fields/columns, for example for aggregation queries such as "select SUM". In those cases such fields can be either explicitly named in the query itself, or accessed via a unified name in the format of "Field{ColumnNumber}" where {ColumnNumber} is the number of the requested field/column in the recordset.
Syntax
899
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
sField:
The name of the field or column.
nRowIndex:
If hGeneral is a connection handle and nRowindex is not equal -1, then the function returns an empty string.
Return Value
The field or column data (as a string). The maximum length of the return data is 255 characters. If the returned data is longer than this, the function will return error 306 (can be checked by IsError() cicode function) .
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLGetRecordset
Executes an SQL query on a database and returns a handle to any resulting disconnected recordset. All recordsets created in this way should be closed by the SQLEnd() function. If unsuccessful, the function returns an invalid handle and an error code is returned (can be tested by IsError()). In case of no data returned, the function returns an invalid handle and no error. With this function, you can execute any SQL query or command supported by the SQL database, but it is designed mainly to work with queries returning data like for example SELECT. Queries which don't return database data, like INSERT or UPDATE, should be executed via SQLCall.
900
Recordsets produced by this function are disconnected. The disconnected recordsets fetch the data from the DB when the query is executed and thus they don't need an open connection when recordset functions are used. This kind of recordset improves speed of access to data after executing the query, but may consume significant amounts of memory. Creating disconnected recordsets without releasing them may lead to utilizing all available memory, which can result in degraded performance.
NOTICE
EXCESSIVE MEMORY USAGE Limit the number of disconnected recordsets using the [SQL]MaxConnections parameter. Release unused disconnected recordsets. Test projects using disconnected recordsets prior to deployment in production. Failure to follow these instructions can result in equipment damage.
Note: All types of fields can be requested in statements, but SCADA has to convert values of the fields to MBCS 8-bit strings which is not always possible. For example either single byte database strings or numbers can be converted to MBCS 8-bit strings, multi-byte strings can be converted to MBCS (their proper presentation depends on correct setup of SCADA and OS), while blobs cannot be encoded at all. This function is a blocking function and should not be called from a foreground task. Queries which are built on the basis of user data, for example inputed by users via graphics pages or forms, may be prone to SQL Injection attacks. In such case, try to limit the risk by using CiCode functions from parameterized queries group and refer to a professional advice in this matter.
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
Syntax
901
The handle either to the DB connection object (returned from either SQLCreate() or SQLConnect() function) or to the query handle (returned from SQLQueryCreate()). When it is the connection handle and sSelect is an empty string, the operation is performed on the first query in that DB connection object. When it is the query handle, the operation is performed on that query through the DB object which is associated to it.
sSelect:
The SQL query to be sent to the SQL database.
Return Value
The handle to a recordset holding the result of the query. If unsuccessful an invalid handle and an error code are returned (for details call the SQLErrMsg() function). If no data is returned, an invalid handle and no error message are returned. The presence of an error can be tested by calling the IsError() CiCode function
Related Functions
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd
Example
SQLGetScalar
Executes an SQL query on a database. The value from the first column of the first row is returned. With this function, you can execute any SQL query or command supported by the SQL database. If it doesnt return any data (like INSERT or UPDATE), a respective error code is set which can be tested by calling IsError()). Note: All types of fields can be requested in statements, but SCADA has to convert values of the fields to MBCS 8-bit strings which is not always possible. For example either single byte database strings or numbers can be converted to MBCS 8-bit strings, multi-byte strings can be converted to MBCS (their proper presentation depends on correct setup of SCADA and OS), while blobs cannot be encoded at all. This function is a blocking function and should not be called from a foreground task. Queries which are built on the basis of user data, for example inputed by users via graphics pages or forms, may be prone to SQL Injection attacks. In such case, try to limit the risk by using CiCode functions from parameterized queries group and refer to a professional advice in this matter.
902
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
Syntax
sSelect:
The SQL query to be sent to the SQL database.
isNull:
Out: Indicated whether the returned variable is NULL. The argument is returned by the function.
Return Value
String representing a value from the first column and the first row of the result of executing the SQL query. If the value is NULL, the string is empty and isNull parameter is set to TRUE. If there are no records in the result, the string is empty and the error code is set to 294. For details of the 307 error code, call the SQLErrMsg() function. The presence of error code can be tested by calling the IsError() CiCode function.
Related Functions
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd See Also SQL Functions
SQLInfo
Gets information about a database connection, recordset or query properties. This function can be called in the foreground or background.
903
Syntax
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset the query.
l l
nType:
The type of information to get:
0 - The connection string 1 - The current SQL query for connection handles and query handles or the source SQL query for recordset handles 2 - The current database filename (only works with SQL device) 3 - No longer supported. 4 - No longer supported. Now returns an empty string and sets the SQL error to 'Invalid Type'. 5 - The DB connection object's state: Closed (The connection is closed), Open (The connection is open), Connecting (The connection object is connecting to the data source. For future release), Executing (The connection object is executing a command. For future release), Fetching (The connection object is retrieving data. For future release), Broken (The connection to the data source is broken. This can occur only after the connection has been opened. A connection in this state may be closed and then re-opened. For future release). An empty string means either error occurred or the handle is invalid 6 - The handle to the connection if used on either recordset or query handle. Note: There is no guarantee that the objects behind the connection handles still exist in the system. 7 - Checks whether a new transaction can be opened. The function perform a check how many transaction levels have been already opened and returns TRUE if a new one can be opened, otherwise FALSE. The function doesn't check ability of the external DB to open transactions. The functions returns FALSE for recordset handles.
Return Value
904
Related Functions
SQLIsNullField
Checks presence of null value in field from a recordset. To get to a specific record in the recordset, use either the SQLNext()/SQLPrev() functions or the nRowIndex argument. When the hGeneral is the connection handle, the function returns information from the default recordset. When the hGeneral is the recordset handle, the function returns information from the recordset itself. This function can be called in the foreground or background.
Syntax
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
sField:
The name of the field or column.
nRowIndex:
The number of the row which data is requested. The first row has index 0. -1 means that an internal pointer is used instead. The pointer can be moved forward and backward by executing SQLNext() or SQLPrev() functions.
Return Value
905
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev SQL Functions
SQLNext
Gets the next database record from an SQL query. Use the SQLExec()/SQLGetRecordset() function to select a number of records or rows from the SQL database, and then use the SQLNext() function to step through each record separately. When the hGeneral is the connection handle, the function moves in the default recordset. When the hGeneral is the recordset handle, the function moves in the recordset itself. This function can be called in the foreground or background.
Syntax
SQLNext(hGeneral) hGeneral:
The handle either to:
l
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLNoFields
906
When the hGeneral is the connection handle, the function returns the number of fields or columns that were returned by the last SQL statement. When the hGeneral is the recordset handle, the function returns the number of fields or columns in the recordset itself. Note: This function is deprecated and may be removed in future releases. This function can be called in the foreground or background.
Syntax
SQLNoFields(hGeneral) hGeneral:
The handle either to:
l
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
Return Value
The number of fields. A value of 0 is returned if no fields were returned or if an error has been detected. (For details of an error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLNumChange
Gets the number of records that were modified in the last SQL Insert, Update, or Delete statement. This function can be called in the foreground or background.
Syntax
SQLNumChange(hSQL)
907
hSQL:
The handle to the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
The number of records that were modified. A value of 0 is returned if no fields were returned or if an error has occurred. (For details of an error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLNumFields
When hGeneral is the connection handle, the function returns the number of fields or columns that were returned by the last SQL statement. When hGeneral is the recordset handle, the function returns the number of fields or columns in the recordset itself. This function can be called in the foreground or background.
Syntax
SQLNumFields(hGeneral) hGeneral:
The handle either to:
l
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
Return Value
The number of fields. A value of 0 is returned if no fields were returned or if an error has been detected. (For details of an error code, call the SQLErrMsg function).
Related Functions 908
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLOpen
Opens an SQL connection between the DB connection object specified by the function's parameter and the database defined by the connection string given before as the parameter to either SQLCreate or SQLConnect function. Note: Currently there are certain configurations of providers, connection strings and database systems which can automatically close connections for the sake of saving the database systems' resources; for example MS SQL Server dedicated provider with activated pooling closes the connection to MS SQL Server when there is no data exchange between the client and the DB server for some predefined time. If such behaviour is observed and is not desired from the system design point of view, it can be either: - switched off by finding and using respective attributes in the connection string (if existing and supported by DB) or - by actively checking error codes returned from SQL CiCode functions and reconnecting by using SQLOpen if the connection is dropped. The actual state of connections can be checked by SQLInfo with type 5. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLOpen(hSQL) hSQL:
The handle to the DB connection object, returned from either the SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 if success, otherwise an error code (For details call the SQLErrMsg() function)
Related Functions
909
SQLParamsClearAll
Remove all parameters associated with a particular connection object. Each database provider (Odbc, OleDb, SQL Server) uses parameterized queries in a different way. It is recommended that you look at documentation and examples included with your database. This function is a blocking function and should not be called from a foreground task. Building queries from pieces (SQLSet, SQLAppend) or adding parameters to either queries or connections (SQLParam functions) requires a few calls to respective CiCode functions. If a few functions try to manipulate the same connection in the same time some conflicts and unintended operations may occur. It is a typical multithreading problem. To avoid this, instead of manipulating connections, consider using locally created and locally disposed queries. For example:
int function SAFE_SQL_CICODE_MULTITHREAD_USE() //locally created query int hStmt = SQLQueryCreate(hConnection); //Set the query SQLSet(hStmt, "select * from TAB where NAME=@Name"); //Add parameters to the query SQLParameterSetAsString(hStmt, "Name", "Aaa"); //Execute the query SQLGetRecordset(hStmt, ""); //the locally created query is disposed SQLQueryDispose(hStmt); End
Syntax
SQLParamsClearAll(hSQL) hSQL:
910
The handle to the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLParamsSetAsInt, SQLParamsSetAsReal, SQLParamsSetAsString, SQLParamsClearAll
Example
SQLParamsSetAsInt
Adds or replace a parameterized query parameter and its value in the specified connection. The value of the parameter is given as integer. Each database provider (Odbc, OleDb, SQL Server) uses parameterized queries in a different way. It is recommended that you look at documentation and examples included with your database. Building queries from pieces (SQLSet, SQLAppend) or adding parameters to either queries or connections (SQLParam functions) requires a few calls to respective CiCode functions. If a few functions try to manipulate the same connection in the same time some conflicts and unintended operations may occur. It is a typical multithreading problem. To avoid this, instead of manipulating connections, consider using locally created and locally disposed queries. For example:
int function SAFE_SQL_CICODE_MULTITHREAD_USE() //locally created query int hStmt = SQLQueryCreate(hConnection); //Set the query SQLSet(hStmt, "select * from TAB where NAME=@Name"); //Add parameters to the query SQLParameterSetAsString(hStmt, "Name", "Aaa"); //Execute the query SQLGetRecordset(hStmt, ""); //the locally created query is disposed SQLQueryDispose(hStmt);
911
End
This function is a blocking function and should not be called from a foreground task.
Syntax
ParamName:
The name of the parameter to add or change.
ParamValue:
The value of the parameter as an integer.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLParamsSetAsInt, SQLParamsSetAsReal, SQLParamsSetAsString, SQLParamsClearAll
Examples
The following examples assume that the following table is setup and opened for the three data providers, ODBC, OleDb and SQLClient, respectively:
PEOPLE SURNAME MARTIAN CASE
AGE 27 18
ODBC A parameter is identified by a character "?" in the SQL query. Since the protocol uses a sequential approach for statement parameterization, the parameters order matters. In that case, to confirm that the correct parameters are picked up by the query, it is suggested to clear all the parameters after a query is executed and configure new ones in a correct order for another query unless the parameters are exactly the same in terms of value and position in the sequence between the two queries:
912
INT nError = 0; STRING sValue0 = ""; STRING sValue1 = ""; INT nIsNull = 0; INT hQueryDelete = SQLQueryCreate(hSQL); SQLSet(hQueryDelete, "delete from PEOPLE where SURNAME=? and FIRSTNAME=?"); SQLParamsClearAll(hSQL); //the name of the parameter does not matter SQLParamsSetAsString(hSQL, "sName", "CASE"); SQLParamsSetAsString(hSQL, "fName", "CARRIE"); SQLCall(hQueryDelete, ""); SQLParamsClearAll(hSQL); SQLParamsSetAsString(hSQL, "sName", "JACKSON"); SQLParamsSetAsString(hSQL, "fName", "DAVID"); SQLParamsSetAsInt(hSQL, "nAge", 28); SQLParamsSetAsReal(hSQL, "nHeight", 1.85); SQLCall(hSQL, "insert into PEOPLE (SURNAME, FIRSTNAME, AGE, HEIGHT) values (?,?,?,?) "); SQLParamsClearAll(hSQL); SQLParamsSetAsString(hSQL, "fName", "DAVID"); SQLParamsSetAsString(hSQL, "sName", "JACKSON"); sValue0 = SQLGetScalar(hSQL, "select AGE from PEOPLE where FIRSTNAME=? and SURNAME=?", nIsNull); sValue1 = SQLGetScalar(hSQL, "select HEIGHT from PEOPLE where FIRSTNAME=? And SURNAME=?", nIsNull);
OleDb Same to ODBC, the association and later substitution is based on order of the parameters in a query statement and "?" is used as the mark. Thus the last example for ODBC also works for general cases of OleDb. Additionally, for some databases, i.e. Microsoft Acess, user may have another option: parameter name with "@" prefix. Following examples are specific for communicating with Microsoft Acess through OleDb data protocol.
INT nError = 0; STRING sValue0 = ""; STRING sValue1 = ""; INT nIsNull = 0; INT hQueryDelete = SQLQueryCreate(hSQL); SQLSet(hQueryDelete, "delete from PEOPLE where SURNAME=@sName and FIRSTNAME=@fName");
913
SQLParamsClearAll(hSQL); SQLParamsSetAsString(hSQL, "sName", "CASE"); SQLParamsSetAsString(hSQL, "fName", "CARRIE"); SQLCall(hQueryDelete, ""); SQLParamsClearAll(hSQL); SQLParamsSetAsString(hSQL, "sName", "JACKSON"); SQLParamsSetAsString(hSQL, "fName", "DAVID"); SQLParamsSetAsInt(hSQL, "nAge", 28); SQLParamsSetAsReal(hSQL, "nHeight", 1.85); SQLCall(hSQL, "insert into PEOPLE (SURNAME, FIRSTNAME, AGE, HEIGHT) values (@sName, @fName, @nAge, @nHeight)"); SQLParamsClearAll(hSQL); SQLParamsSetAsString(hSQL, "fName", "DAVID"); SQLParamsSetAsString(hSQL, "sName", "JACKSON"); sValue0 = SQLGetScalar(hSQL, "select AGE from PEOPLE where FIRSTNAME=@fName and SURNAME=@sName", nIsNull); sValue1 = SQLGetScalar(hSQL, "select HEIGHT from PEOPLE where FIRSTNAME=@fName And SURNAME=@sName", nIsNull);
Note: If you want to use a parameter more than once in the same query, there is no need to define it multiple times. However, the parameters have to be prepared in proper order based on their occurrence order in the query statement.
Example
INT nError = 0; STRING sValue0 = ""; STRING sValue1 = ""; INT nIsNull = 0; INT hQueryInsert = SQLQueryCreate(hSQL); SQLSet(hQueryInsert, "insert into TABLE (COLUMN0, COLUMN1, COLUMN2, COLUMN3, COLUMN4) values (@param0, @param0, @param1, @param1, @param0"); SQLParamsClearAll(hSQL); SQLParamsSetAsString(hSQL, "param0", "Value0"); SQLParamsSetAsString(hSQL, "param1", "Value1"); SQLCall(hQueryInsert, "");
914
COLUMN0 Value0
COLUMN1 Value0
COLUMN2 Value1
COLUMN3 Value1
COLUMN4 Value0
SQLClient SQL server uses a named parameter approach for parameterization. Parameters in queries are preceded by the '@' character. The order of the parameters does not matter.
INT nError = 0; STRING sValue0 = ""; STRING sValue1 = ""; INT nIsNull = 0; INT hQueryDelete = SQLQueryCreate(hSQL); SQLSet(hQueryDelete, "delete from PEOPLE where SURNAME=@sName and FIRSTNAME=@fName"); SQLParamsSetAsString(hSQL, "sName", "CASE"); SQLParamsSetAsString(hSQL, "fName", "CARRIE"); SQLCall(hQueryDelete, ""); //Order does not matter SQLParamsSetAsInt(hSQL, "nAge", 28); SQLParamsSetAsReal(hSQL, "nHeight", 1.85); //If a parameter has been defined already, setting the value again //will replace the old value. SQLParamsSetAsString(hSQL, "sName", "JACKSON"); SQLParamsSetAsString(hSQL, "fName", "DAVID"); SQLCall(hSQL, "insert into PEOPLE (SURNAME, FIRSTNAME, AGE, HEIGHT) values (@sName, @fName, @nAge, @nHeight)"); sValue0 = SQLGetScalar(hSQL, "select AGE from PEOPLE where FIRSTNAME=@fName and SURNAME=@sName", nIsNull); sValue1 = SQLGetScalar(hSQL, "select HEIGHT from PEOPLE where FIRSTNAME=@fName And SURNAME=@sName", nIsNull);
AGE 27 28
SQLParamsSetAsReal
915
Adds or replaces a parameterized query's parameter and its value in the specified connection. The value of the parameter is given as a real. Each database provider (Odbc, OleDb, SQL Server) uses parameterized queries in a different way. It is recommended that you look at documentation and examples included with your database. This function is a blocking function and should not be called from a foreground task. Building queries from pieces (SQLSet, SQLAppend) or adding parameters to either queries or connections (SQLParam functions) requires a few calls to respective CiCode functions. If a few functions try to manipulate the same connection in the same time some conflicts and unintended operations may occur. It is a typical multithreading problem. To avoid this, instead of manipulating connections, consider using locally created and locally disposed queries. For example:
int function SAFE_SQL_CICODE_MULTITHREAD_USE() //locally created query int hStmt = SQLQueryCreate(hConnection); //Set the query SQLSet(hStmt, "select * from TAB where NAME=@Name"); //Add parameters to the query SQLParameterSetAsString(hStmt, "Name", "Aaa"); //Execute the query SQLGetRecordset(hStmt, ""); //the locally created query is disposed SQLQueryDispose(hStmt); End
Syntax
ParamName:
The name of the parameter to add or change.
ParamValue:
The value of the parameter as a real.
Return Value
916
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLParamsSetAsInt, SQLParamsSetAsReal, SQLParamsSetAsString, SQLParamsClearAll
Example
SQLParamsSetAsString
Adds or replaces a parameterized query's parameter and its value in the specified connection. The value of the parameter is given as a string. Each database provider (Odbc, OleDb, SQL Server) uses parameterized queries in a different way. It is recommended that you look at documentation and examples included with your database. Building queries from pieces (SQLSet, SQLAppend) or adding parameters to either queries or connections (SQLParam functions) requires a few calls to respective CiCode functions. If a few functions try to manipulate the same connection in the same time some conflicts and unintended operations may occur. It is a typical multithreading problem. To avoid this, instead of manipulating connections, consider using locally created and locally disposed queries. For example:
int function SAFE_SQL_CICODE_MULTITHREAD_USE() //locally created query int hStmt = SQLQueryCreate(hConnection); //Set the query SQLSet(hStmt, "select * from TAB where NAME=@Name"); //Add parameters to the query SQLParameterSetAsString(hStmt, "Name", "Aaa"); //Execute the query SQLGetRecordset(hStmt, ""); //the locally created query is disposed SQLQueryDispose(hStmt); End
This function is a blocking function and should not be called from a foreground task.
Syntax
917
ParamName:
The name of the parameter to add or change.
ParamValue:
The value of the parameter as a string.
nStrType:
The index specifying the type of the string:
0 - Allowing ADO engine to use the default string type of the protocol. For SQLClient, OleDB and ODBC, the default string type is NVarChar (A variable-length stream of Unicode characters ranging between 1 and 4,000 characters); 1 - Forcing the string type to be NVarChar; 2 - Forcing the string type to be NChar (A fixed-length stream of Unicode characters ranging between 1 and 4,000 characters); 3 - Forcing the string type to be VarChar (A variable-length stream of non-Unicode characters ranging between 1 and 8,000 characters. VarChar is used when the database column is varchar(max)); 4 - Forcing the string type to be Char (A fixed-length stream of non-Unicode characters ranging between 1 and 8,000 characters).
The default value of nStrType is 0.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLParamsSetAsInt, SQLParamsSetAsReal, SQLParamsSetAsString, SQLParamsClearAll
Example
SQLPrev
918
Gets the previous database record from an SQL query. The function works only with disconnected recordsets. Use the SQLGetRecordset() function to select a number of records or rows from the SQL database, and then use the SQLNext()/SQLPrev() function to step through each record separately. This function can be called in the foreground (only for disconnected recordsets) or background.
Syntax
SQLPrev(hGeneral) hGeneral:
The handle to the disconnected recordset.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLQueryCreate
The function creates a new query and returns its handle. The query is empty and has to be set by using SQLSet() and/or SQLAppend() functions. The query handle can be used with the statement functions as SQLExec() or SQLGetRecordset(). Queries allocated by SQLQueryCreate should be disposed by SQLQueryDispose when no longer necessary. Each DB connection object has one default query which is created and disposed automatically. The default query need not be disposed by the function SQLQueryDispose. This function can be called in the foreground or background.
Syntax
SQLQueryCreate(hSQL) hSQL:
919
The handle to the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLQueryCreate, SQLQueryDispose, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev See Also SQL Functions
SQLQueryDispose
The function disposes the query which handle is given as the argument. Queries allocated by SQLQueryCreate should be disposed by SQLQueryDispose when no longer necessary. Each DB connection object has one default query which is created and disposed automatically. The default query need not be disposed by the function SQLQueryDispose. This function can be called in the foreground or background.
Syntax
SQLQueryDispose(hQuery) hQuery:
The handle to the query, returned from SQLQueryCreate() function.
Return Value
0 (zero) if successful, otherwise an error code is returned. (For details of the 307 error code, call the SQLErrMsg() function).
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLQueryCreate, SQLQueryDispose, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev See Also SQL Functions
SQLRollBack
920
Rolls back (discards) all changes made to the database within the current transaction. If you call the SQLBeginTrans() function to begin a transaction, you are not committed to changes to the database made by the Insert, Delete, and Update commands until you call the SQLCommit() function. You can discard these changes by calling the SQLRollBack() function. You can only call the SQLRollBack() function if you have called SQLBeginTran() to begin a transaction. You do not need to begin a transaction to modify a database, but any changes you make to a database outside of a transaction are automatically committed. The SQLRollBack() function could affect different databases in different ways. If the function is not performing as you expect, check that your database is able to service transactions. Refer to the documentation for your database for more information on rolling back transactions. This function is a blocking function and should not be called from a foreground task.
Syntax
SQLRollBack(hSQL) hSQL:
The handle to the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLBeginTran, SQLCommit, SQLRollBack
Example
SQLRowCount
Gets the number of rows in the recordset. This function can be called in the foreground or background.
Syntax
921
SQLRowCount(hGeneral) hGeneral:
The handle either to:
l
the DB connection object, returned from either SQLCreate() or SQLConnect() function. The handle identifies the DB connection object where details of the associated SQL connection are stored the recordset
Return Value
The number of rows in the given recordset for disconnected recordsets. For the connected recordset, the function returns always -1.
Related Functions
SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd, SQLNumChange, SQLNoFields, SQLNumFields, SQLFieldInfo, SQLGetField, SQLIsNullField, SQLRowCount, SQLNext, SQLPrev
Example
SQLSet
Sets a query string in the SQL buffer. Cicode cannot send an SQL query that is longer than 255 characters. If you have an SQL query that is longer than the 255 character limit, you can split the query into smaller strings, and use this function and the SQLAppend() function to append the query in the SQL buffer. This function can be called in the foreground or background. Queries which are built on the basis of user data, for example inputed by users via graphics pages or forms, may be prone to SQL Injection attacks. In such case, try to limit the risk by using CiCode functions from parameterized queries group and refer to a professional advice in this matter.
922
NOTICE
SECURITY BREACH VIA SQL INJECTION - Validate all textbox entries using validation controls, regular expressions and code - Use parameterized SQL or stored procedures - Use a limited access account to connect to the database Failure to follow these instructions can result in equipment damage.
Building queries from pieces (SQLSet, SQLAppend) or adding parameters to either queries or connections (SQLParam functions) requires a few calls to respective CiCode functions. If a few functions try to manipulate the same connection in the same time some conflicts and unintended operations may occur. It is a typical multithreading problem. To avoid this, instead of manipulating connections, consider using locally created and locally disposed queries. For example:
int function SAFE_SQL_CICODE_MULTITHREAD_USE() //locally created query int hStmt = SQLQueryCreate(hConnection); //Set the query SQLSet(hStmt, "select * from TAB where NAME=@Name"); //Add parameters to the query SQLParameterSetAsString(hStmt, "Name", "Aaa"); //Execute the query SQLGetRecordset(hStmt, ""); //the locally created query is disposed SQLQueryDispose(hStmt); End
Syntax
sString:
The query string to set in the SQL buffer. The string needs to contain the first part of an SQL query.
Return Value
923
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg() function).
Related Functions
SQLCreate, SQLOpen, SQLClose, SQLDispose, SQLConnect, SQLDisconnect, SQLInfo, SQLSet, SQLAppend, SQLExec, SQLGetRecordset, SQLCall, SQLGetScalar, SQLEnd
Example
hSQL = nError nError nError nError hRec = SQLConnect("DSN=QEDBF"); = SQLBeginTran(hSQL); = SQLSet(hSQL, "SELECT *"); = SQLAppend(hSQL, " FROM EMP"); = SQLAppend(hSQL, " ORDER BY last_name"); SQLGetRecordset(hSQL, "");
SQLTraceOff
Turns off the debug trace. Use this function to stop tracing function calls that are made to the database. The trace can be turned off globally for all connections or for a specific one. This function can be called in the foreground or background.
Syntax
SQLTraceOff(hSQL) hSQL:
The handle to the DB connection object: INVALID HANDLE - The trace is deactivated for all DB connections (default), otherwise - The trace is deactivated for this specific DB connection object.
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
See SQLFieldInfo
924
SQLTraceOn
Turns on a debug trace. Use this function to begin tracing function calls that are made to the database. The information is written to TraceLog.dat file (the strFileName argument is currently ignored). The trace can be turned on globally for all connections or for a specific connection. Note: Currently the SQL tracing functionality uses the standard SCADA logging mechanism. All SQL traces are Information logs and can be written to TraceLog.dat file only if appriopriate logging ini parameters are set respectively, for example [Debug] SeverityFilterMode. This function can be called in the foreground or background.
Syntax
hSQL:
The handle to the DB connection object: INVALID HANDLE - The trace is activated for all DB connections (default), otherwise - The trace is activated for this specific DB connection object.
nTraceLevel:
Defines the level of details written to the trace file. The following values are allowed:
l l
0 - as per 1, but without values (default). 1 - the highest level of details including values of read cells
Return Value
0 (zero) if successful, otherwise an error number is returned. (For details of the 307 error code, call the SQLErrMsg function).
Related Functions
See SQLFieldInfo
925
926
SPCSpecLimitGet
SPCAlarms
Returns the status of the specified SPC alarm. This function is used to configure SPC alarms, by defining alarms with this trigger in Advanced Alarms.
927
This function can only be used if the Alarm Server is on the current machine. When the Alarm Server is not in the calling process, this function will become blocking and cannot be called from a foreground task. In this case, the return value will be undefined and a Cicode hardware alarm will be raised.
Syntax
AlarmType:
The description of the alarm type. The following types are valid: XFreak XOutsideCL XAboveUCL XBelowLCL XOutsideWL XGradualUp XGradualDown XUpTrend XDownTrend XErratic XStratification XMixture ROutsideCL RAboveUCL RBelowLCL
Return Value
AlarmAck
Example
Advanced Alarms Alarm Tag Alarm Desc Expression Comment Feed_SPC_XBLCL Process mean below LCL SPCAlarms("Feed_SPC", XBelowLCL) Trigger an alarm when XBelowLCL condition becomes true.
928
SPCClientInfo
Returns SPC data for the given SPC tag. The information retrieved through this function is from the cache maintained by the client. This function will give a faster response than the related functions which access the SPC (trend) server. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
iType:
The information to be returned:
1 - Subgroup Size 2 - No. of Subgroups 3 - Process Mean (x double bar) 4 - Process Range 5 - Process Standard Deviation 6 - Lower Specification Limit (LSL) 7 - Upper Specification Limit (USL) 8 - Cp - Process Capability Actual 9 - Cpk - Process Capability Potential 10 - Process Skewness 11 - Process kurtosis
Return Value
929
SPCGetHistogramTable
Returns an array containing the frequencies of particular ranges for the given SPC tag. The histogram structure is implied in the order of the table as follows - the first array element is the data less than -3 sigma. The second value is the data between -3 sigma and 3 sigma plus the bar width etc. The last value is the data greater than +3 sigma. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
iNoBars:
The number of bars in the table. The valid range is restricted to values from 7 to 100. This also indicates the size of the array to be returned.
TableVariable:
The Cicode array that will store the histogram data. This variable needs to be defined as a global array of type REAL. The number of elements in the array needs to be equal to (or greater than) iNoBars.
Return Value
930
0 (zero) if successful, otherwise an error number is returned. The histogram table is written to TableVariable.
Related Functions
TableMath
Example
/* This function will get the maximum frequency present in the histogram of a particular SPC tag.*/ REAL iFrequency[7]; ! This variable needs to be global to the file so is declared outside of the function INT FUNCTION GetMaxFreq(STRING sTAG) INT iError; INT iMax = -1; iError = SPCGetHistogramTable(sTag, 7, iFrequency); !The elements of iFrequency now hold the histogram table frequencies. IF iError = 0 THEN ! Get maximum iMax = TableMath(iFrequency,7,1,0); END Return iMax; END
SPCGetSubgroupTable
Returns an array containing the specified subgroup's elements with the mean, range and standard deviation. The data will be in the following order:
Element0, Element1, ... , Element(n-1), Mean, Range, StdDev
where n is the subgroup size. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
iSubgroup:
The number of the subgroup being displayed whose data is to be retrieved. Zero ('0') represents the latest subgroup.
931
TableVariable:
The first element of the Cicode array that will store the sample data. This variable needs to be defined as a global array of type REAL. The number of elements in the array needs to be equal to (or greater than) the subgroup size + 3.
Return Value
0 (zero) if successful, otherwise an error number is returned. The subgroup's data is written to TableVariable.
Related Functions
TableMath
Example
/* This function will get the minimum value present in the sample data of a particular SPC tag.*/ REAL rSubgroup[8]; ! 5 samples + mean + range + stddev. ! This variable needs to be global to the file, so is declared outside of the function REAL FUNCTION GetMinSample(STRING sTAG) INT iError; REAL iMin = 0; iError = SPCGetSubgroupTable(sTag, 7, rSubgroup); !The elements of rSubgroup now hold the group samples, mean, range and stddev. IF iError = 0 THEN ! Get minimum. Be aware that the range of data is 5 iMin = TableMath(rSubgroup,5,0,0); END Return iMin; END
SPCPlot
This function is designed to work only on an SPCXRSChart page. It prints a single page showing three separate trends of the SPC Mean, Range, and Standard Deviation. The Mean needs to be at nAN, the Range at AN + 1, and the Standard Deviation at AN + 2. You can specify a title and a comment for the plot, and whether it is printed in color or in black and white.
Syntax
932
The name of the printer port to which the plot 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.
nAN:
The animation point at which the Mean chart is currently situated. The Range and Standard Deviation charts need to be on the next two consecutive animation numbers. For example, if the Mean chart is at animation point 40, the Range chart needs to be at animation point 41, and the Standard Deviation chart needs to be at animation point 42.
sTitle:
The title of the trend plot.
sComment:
The comment that is to display beneath the title of the trend plot. You do not have to enter a comment.
nMode:
The color mode of the printer.
SPCProcessXRSGet
933
Gets the process mean, range, and standard deviation overrides for the specified SPC tag. The values that are returned are the values that are currently being used by the SPC (trend) server, not necessarily the values specified in the SPC Tag definition. This function is a blocking function. It will block the calling Cicode task until the operation is complete. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
XVariable:
The Cicode variable that stores the process mean (X double bar). This variable needs to be defined as a global of type REAL. A constant is not allowed.
RVariable:
The Cicode variable that stores the range (R). This variable needs to be defined as a global of type REAL. A constant is not allowed.
SVariable:
The Cicode variable that stores the standard deviation (S). This variable needs to be defined as a global of type REAL. A constant is not allowed.
sClusterName:
Specifies the name of the cluster of the SPC tag.
Return Value
0 (zero) if successful, otherwise an error number is returned. The process mean is written to XVariable, the process range to RVariable, and the standard deviation to SVariable.
Related Functions
SPCClientInfo, SPCProcessXRSSet
Example
/* This function will set a new override value for Mean, without overwriting the values already in place for Standard Deviation and Range */ REAL rOldMean; REAL rRange; REAL rStdDev;
934
! These variables need to be global to the file, so are declared outside of the function INT FUNCTION Tank1SPCNewMean(REAL rNewMean) INT iError; iError = SPCProcessXRSGet("TANK_1_TEMP", rOldMean, rRange, rStdDev); ! If no error, rOldMean, rRange and rStdDev now hold the current values of XRS. IF iError = 0 THEN iError = SPCProcessXRSSet("TANK_1_TEMP", rNewMean, rRange, rStdDev); END Return iError; END
SPCProcessXRSSet
Sets the process mean, range and standard deviation overrides for the specified SPC tag. The values entered here will override CitectSCADA's automatic calculations, and the overrides specified in the SPC Tags definition. This function is a blocking function. It will block the calling Cicode task until the operation is complete. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
rMean:
The new value of process mean (x double bar) to set.
rRange:
The new value of process range to set.
rStdDev:
The new value of process standard deviation to set.
sClusterName:
Specifies the name of the cluster of the SPC tag.
Return Value
935
SPCProcessXRSGet
Example
SPCSetLimit
Sets the upper or lower control limits of X-bar, range, or standard deviation charts. Using this function will only set the controller limits on the Client display which will not affect the SPC Alarms. To set the server control limits, use the SPCProcessXRSSet function.
Syntax
nType:
The SPC type:
1 - X-bar upper control limit 2 - X-bar lower control limit 3 - Range upper control limit 4 - Range lower control limit 5 - Standard deviation upper control limit 6 - Standard deviation lower control limit 7 - X-bar centre line 8 - Range centre line 9 - Standard deviation centre line Value:
The value for the control limit.
Setting:
Automatic calculation or manual setting of control limits:
0 - Automatic
936
1 - Manual
Return Value
SPCSpecLimitGet
Gets the process Upper and Lower Specification Limits (USL and LSL) for the specified SPC tag. The values that are returned are the values that are currently being used by the SPC (trend) server, not necessarily the values specified in the SPC Tag definition. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
LSLVariable:
The Cicode variable that stores the Lower Specification Limit (LSL). This variable needs to be defined as a global of type REAL. Do not specify a constant in this field.
USLVariable:
The Cicode variable that stores the Upper Specification Limit (USL). This variable needs to be defined as a global of type REAL. Do not specify a constant in this field.
sClusterName:
Specifies the name of the cluster of the SPC tag.
Return Value
0 (zero) if successful, otherwise an error number is returned. The LSL is written to LSLVariable, while the USL is written to USLVariable.
Related Functions
SPCClientInfo, SPCSpecLimitSet
937
Example
/* This function will increase the current USL and LSL of the specified Tag by 10 percent.*/ REAL rLSL; REAL rUSL; ! These variables need to be global to the file, so are declared outside of the function INT FUNCTION ExpSLbyPercent(STRING sTAG) REAL rIncPercent = 1.1; REAL rDecPercent = 0.9; INT iError; iError = SPCSpecLimitGet(sTag, rLSL, rUSL); ! If no error, rLSL and rUSL now hold the current values of LSL and USL for sTAG rLSL = rLSL * rDecPercent; rUSL = rUSL * rIncPercent; IF iError = 0 THEN iError = SPCSpecLimitSet(sTAG, rLSL, rUSL); END Return iError; END ! The function would be called as follows;
SPCSpecLimitSet
Sets the process Upper and Lower Specification Limits (USL and LSL) for the specified SPC tag. The values entered here will override those specified in the SPC Tags definition. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
938
rLSL:
The new value of Lower Specification Limit (LSL) to set.
rUSL:
The new value of Upper Specification Limit (USL) to set.
sClusterName:
Specifies the name of the cluster of the SPC tag.
Return Value
SPCSpecLimitGet
Example
SPCSubgroupSizeGet
Gets the subgroup size for the specified SPC tag. The value that is returned is the value that is currently being used by the SPC (trend) server, not necessarily the value specified in the SPC Tag definition. This function is a blocking function. It will block the calling Cicode task until the operation is complete. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
SizeVariable:
The Cicode variable that stores the subgroup size. This variable needs to be defined as a global of type INT. A constant is not allowed.
sClusterName:
Specifies the name of the cluster of the SPC tag.
939
Return Value
0 (zero) if successful, otherwise an error number is returned. The subgroup size is written to SizeVariable.
Related Functions
SPCClientInfo, SPCSubgroupSizeSet
Example
SPCSubgroupSizeSet
Sets a new subgroup size for the specified SPC tag. The new subgroup size becomes the new size as long as the SPC (trend) server is running. The subgroup size is updated first in the SPC server, which then informs the clients to update. This will force re-calculation of SPC values (UCL and LCL) across the span of any displayed charts. This function is a blocking function. It will block the calling Cicode task until the operation is complete. This function can only be called while the SPC tag is being displayed on an SPC page.
Syntax
iSize:
The new size of the subgroup to set.
sClusterName:
Specifies the name of the cluster of the SPC tag.
Return Value
SPCSubgroupSizeGet
Example
940
/* This function increments the subgroup size for FEED_RATE_1 by the specified amount. */ INT iSize; ! This variable needs to be global to the file, so is declared outside of the function INT FUNCTION IncSubgroupSize(INT iIncrement) INT iError; iError = SPCSubgroupSizeGet("FEED_RATE_1", iSize); ! If no error, iSize now contains the current subgroup size of FEED_RATE_1 iSize = iSize + iIncrement; IF iError = 0 and (isize > 1) THEN iError = SPCSubgroupSizeSet("FEED_RATE_1", iSize ); END Return iError; END
941
942
943
StrSearch StrSetChar StrToChar StrToDate StrToFmt StrToGrp StrToHex StrToInt StrToLines StrToLocalText StrToPeriod StrToReal StrToTime StrToValue StrTrim StrTruncFont
Searches for a string within a string. Sets a single character into string or buffer. Converts a string to an ASCII code. Converts a string into a date variable. Converts a string into format fields. Converts a string into a group. Converts a hexadecimal string into an integer. Converts a string into an integer variable. Converts a string into lines of limited length. Converts a string from Native language to Local language.
Converts a string into a (time) period. Converts a string into a floating-point variable. Converts a string into a time variable. Converts a string into a floating-point variable. Trims spaces from a string. Returns the truncated string using a particular font (specified by name) or the specified number of characters. Returns the truncated string using a particular font (specified by font number) or the specified number of characters. Converts a string to upper-case. Gets a word from a string.
CharToStr
944
CharToStr(ASCIICode) ASCIICode:
The ASCII code to convert.
Return Value
StrSetChar
Example
str = CharToStr(65); ! Sets str to "A".
HexToStr
Converts a number into a hexadecimal string. The string is the width specified (padded with zeros).
Syntax
Width:
The width of the string.
Return Value
StrToHex, IntToStr
Example
945
Variable=HexToStr(123, 4); ! Sets Variable to "007b". Variable = HexToStr(0x12ABFE, 8); ! Sets Variable to "0012abfe"
IntToStr
Converts a number into a string.
Syntax
IntToStr(Number) Number:
The number to convert.
Return Value
StrFormat
Example
Variable=IntToStr(5); ! Sets Variable to "5".
PathToStr
Converts a CitectSCADA path into a string. The path string can contain one of the standard CitectSCADA path operators, BIN, DATA, RUN, USER or a user-configured path. If the string does not contain a CitectSCADA path, it is unchanged.
Syntax
PathToStr(sPath) sPath:
The CitectSCADA path to convert.
Return Value
946
RealToStr
Converts a floating-point number into a string.
Syntax
Width:
The width of the string.
Places:
The number of decimal places contained in the string.
Separator:
Optionally, the decimal separator contained in the string. Defaults to empty string.
Return Value
StrToReal
Example
947
StrCalcWidth
Retrieves the pixel width of a string using a particular font.
Syntax
iFont:
The font number used to calculate the pixel width of the text. (To use the default font, set to -1).
Return Value
StrTruncFont, StrTruncFontHnd, DspFont, DspFontHnd See Also String Functions, Using the Caret Escape Sequence Character
StrClean
Removes control characters from a string. Any character that is not a displayable ASCII character is removed from the string.
Syntax
StrClean(String) String:
The source string.
Return Value
StrTrim
948
Example
Variable=StrClean("*****Text*****"); /* Sets Variable to "Text" (the "*" character in this example represents an unprintable character). */
See Also String Functions, Using the Caret Escape Sequence Character
StrFill
Fills a string with a number of occurrences of another string.
Syntax
Length:
The length of the string.
Return Value
StrPad
Example
Variable=StrFill("abc",10); ! Sets Variable to "abcabcabca". Variable=StrFill("x",10); ! Sets Variable to "xxxxxxxxxx".
See Also String Functions, Using the Caret Escape Sequence Character
StrFormat
Converts a variable into a formatted string. This function is the equivalent of the Cicode " :#### " operator.
Syntax
949
Variable:
The variable to format into a string.
Width:
The width of the variable after it has been converted to string format.
DecPlaces:
The number of decimal places in the converted string.
EngUnits:
The engineering units of the variable.
Return Value
See Also String Functions, Using the Caret Escape Sequence Character
StrGetChar
Gets a single character from a string or buffer. Use this function to read a string, character by character.
Syntax
iOffset:
The offset in the string, commencing at 0.
Return Value
950
StrSetChar
Example
FOR i = 0 To length DO char = StrGetChar(str, i); ! Get char from string END
See Also String Functions, Using the Caret Escape Sequence Character
StrLeft
Gets the left-most characters from a string.
Syntax
StrLeft(String, N) String:
The source string.
N:
The number of characters to get from the source string.
Return Value
See Also String Functions, Using the Caret Escape Sequence Character
StrLength
Gets the length of a string.
Syntax
StrLength(String)
951
String:
The source string.
Return Value
See Also String Functions , Using the Caret Escape Sequence Character
StrLower
Converts a string to lowercase.
Syntax
StrLower(String) String:
The source string.
Return Value
StrUpper
Example
Variable=StrLower("ABCDEF"); ! Sets Variable to "abcdef". Variable=StrLower("AbCdEf"); ! Sets Variable to "abcdef".
See Also String Functions, Using the Caret Escape Sequence Character
StrMid
952
Offset:
The offset in the string, commencing at 0.
Characters:
The number of characters to get, commencing at the offset.
Return Value
See Also String Functions, Using the Caret Escape Sequence Character
StrPad
Pads a string with a number of occurrences of another string. Padding can be added to the left or to the right of a string. If the string is already longer than the required string length, the string is truncated.
Syntax
PadString:
The padding string.
953
Length:
The length of the string. If a positive length is specified, padding will be added to the right of the string. If a negative length is specified, padding will be added to the left of the string.
Return Value
A padded string.
Related Functions
StrFill
Example
Variable=StrPad("Test"," ",10); ! Sets Variable to "Test ". Variable=StrPad("Test","abc",-14); ! Sets Variable to "abcabcabcaTest".
See Also String Functions, Using the Caret Escape Sequence Character
StrRight
Gets the rightmost characters from a string.
Syntax
StrRight(String, N) String:
The source string.
N:
The number of characters to get from the source string.
Return Value
954
See Also String Functions , Using the Caret Escape Sequence Character
StrSearch
Searches for a string within a string, commencing at a specified offset. The result of the search is the index in the source string, where the first character of the sub-string is found. Index 0 is the first character in the string, index 1 is the second, and so on.
Syntax
String:
The source string.
Substring:
The substring to search for.
Return Value
The index in the search string, or -1 if the sub-string does not exist in the string.
Related Functions
StrLength
Example
Variable=StrSearch(1,"ABCDEF","CD"); ! Sets Variable to 2. Variable=StrSearch(4,"ABCDEF","CD"); ! Sets Variable to -1. Variable=StrSearch(5,"ABCDEF","F"); ! Sets Variable to 5.
See Also String Functions, Using the Caret Escape Sequence Character
StrSetChar
955
Sets a single character into a string or buffer. Use this function to build up a string, character by character, and terminate the string with the end-of-string character 0 (zero). (If you use a string without a terminator in a function that expects a string, or in a Cicode expression, you could get invalid results.) To use the string to build up a buffer, you do not need the terminating 0 (zero).
Syntax
iOffset:
The offset in the string, commencing at 0.
Char:
The ASCII character to set into the string.
Return Value
StrGetChar
Example
! Set chars in buffer, Buf is NOT a valid string ! and cannot be used where a normal string would be used. FOR i = 0 To length DO StrSetChar(Buf, i, 30 + i); END StrSetChar(sStr, 0, 13); ! put CR into string StrSetChar(sStr, 1, 0); ! terminate so may be used as a normal string
See Also String Functions, Using the Caret Escape Sequence Character
StrToChar
Gets the ASCII code of the first character in a string.
Syntax
StrToChar(String) String:
956
Return Value
StrGetChar
Example
Variable=StrToChar("ABC"); ! Sets Variable to 65 (ASCII "A").
See Also String Functions, Using the Caret Escape Sequence Character
StrToDate
Converts a "date" string into a time/date variable. This variable is the same as returned from the TimeCurrent() function. To set the order of the day, month, and year, and the delimiter, use the Windows Control panel. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with the following Cicode:
IF StrToDat(Arg1)>0 THEN ... ELSE ... END
Syntax
StrToDate(String) String:
The source string.
Return Value
StrToPeriod, StrToTime
Example
957
! Australian format (dd/mm/yy) is set in the Windows Control panel. DateVariable=DateAdd(StrToDate("3/11/95"),86400); NewDate= TimeToStr(DateVariable, 2); ! Adds 24 hours to 3/11/95 and sets NewDate to "4/11/95".
See Also String Functions, Using the Caret Escape Sequence Character
StrToFmt
Converts a string into field data for a format template. This function is useful for splitting a string into separate strings. After the string is converted, you can call the FmtGetField() function to extract the individual data from the template fields.
Syntax
String:
The source string.
Return Value
FmtOpen, FmtGetField
Example
StrToFmt(hFmt,"CV101 Raw Coal Conveyor"); Name=FmtGetField(hFmt,"Name"); ! Sets Name to "CV101".
See Also String Functions, Using the Caret Escape Sequence Character
StrToGrp
958
Converts a string into a group and places it into a group number. Any existing values in the group are cleared before the new values are inserted. The group string is a series of numbers separated by " , " to list individual values or " .. " to specify a range of values.
Syntax
Str:
The string to convert.
Return Value
GrpOpen
Example
hGrp=GrpOpen("MyGrp",1); ! Set group to 1 ... 10 and 20, 30 and 40. StrToGrp(hGrp,"1..10,20,30,40");
See Also String Functions, Using the Caret Escape Sequence Character
StrToHex
Converts a hexadecimal string into an integer. This function will search the string for the first non-blank character, and then start converting until it finds the end of the string or a non-hexadecimal numeric character. If the first non-blank character is not one of the following hexadecimal characters, the return value is 0 (zero):
l l l
Syntax
StrToHex(String) String:
959
Return Value
See Also String Functions, Using the Caret Escape Sequence Character
StrToInt
Converts a string into an integer. This function will search the string for the first nonblank character, and then start converting until it finds the end of the string or a nonnumeric character. If the first non-blank character is not a numeric character (0-9), a space, a " + " or a " - " sign, the return value is 0 (zero).
Syntax
StrToInt(String) String:
The string to convert.
Return Value
StrToReal, StrToValue
Example
Variable=StrToInt("45");
960
! Sets Variable to 45. Variable=StrToInt("45.23"); ! Sets Variable to 45. Variable=StrToInt("A45"); ! Sets Variable to 0.
See Also String Functions, Using the Caret Escape Sequence Character
StrToLines
Converts a string into separate lines that contain no more than the number of characters specified in the MaxChars argument. The function splits the string by inserting newline characters into the text string, thus dividing it into separate lines. The string will be split at a whitespace character if possible, and that whitespace will be replaced by the newline character. If no whitespace characters are available then the insertion will be made at the maximum number of characters from the previous line break.
Syntax
MaxChars:
The maximum number of characters permitted in each new line produced by the StrToLines() function.
nLines:
The number of lines produced by the StrToLines() function from the input string.
Return Value
An integer (nLines) containing the number of lines produced by the StrToLines() function from the input string.
Example
BrokenString=StrToLines("Was that a real Stegosaur?", 5, nLines); !The function returns the value 6 in nLines, and Broken String now contains: Was that a real Stego
961
saur? BrokenString=StrToLines("It breaks the string by inserting newline characters into the text.", 16, nLines); !The function returns the value 6 in nLines, and Broken String now contains: It breaks the string by inserting newline characters into the text.
See Also String Functions, Using the Caret Escape Sequence Character
StrToLocalText
Converts a native string into the local version of that string. (The string needs to be contained within quotation marks, as shown in the example below.) The local version is taken from the current language database(as specified using the [Language]LocalLanguage parameter). StrToLocalText(sText) sText:
The string for which you would like the local translation returned. This string needs to be enclosed in quotation marks. For example: "@(Motor Overload)"
Return Value
The local version of the text if it was found, otherwise the native text or "#MESS" is returned, depending on the setting of the [Language]DisplayError parameter.
Related Functions
LanguageFileTranslate
Example
StrToLocalText("@(Motor Overload)"); ! Returns the Local translation of Motor Overload.
See Also String Functions, Using the Caret Escape Sequence Character
StrToPeriod
962
Converts a string into a time period. You would normally use this function to convert operator input, for example, to set a trend period. A valid period string is in the format HH:MM:SS, MM:SS or SS, where HH is the hours, MM is the minutes and SS is the seconds. The colon character (':') represents the time delimiter for these fields, which will be the current system time delimiter as set in the Windows Control Panel. If minutes are specified, seconds need to be in the range 0-59. If hours are specified, minutes need to be in the range 0-59.
Syntax
StrToPeriod(String) String:
The string to convert.
Return Value
StrToTime, StrToDate
Example
Variable=StrToPeriod("200"); ! Sets Variable to 200 (seconds). Variable=StrToPeriod("200:40"); ! Sets Variable to 12040 (12000 + 40 seconds). Variable=StrToPeriod("48:00:40"); ! Sets Variable to 172840 (172800 + 40 seconds).
See Also String Functions, Using the Caret Escape Sequence Character
StrToReal
Converts a string into a floating-point number. This function will search the string for the first non-blank character, and then start converting until it finds the end of the string or a non-numeric character. If the first non-blank character is not a numeric character (09), a space, a decimal point, a " + " or a " - " sign, the return value is 0 (zero).
Syntax
StrToReal(String) String:
963
Return Value
StrToInt, StrToValue
Example
Variable=StrToReal("45"); ! Sets Variable to 45. Variable=StrToReal("45.23"); ! Sets Variable to 45.23 Variable=StrToReal("A45"); ! Sets Variable to 0.
See Also String Functions, Using the Caret Escape Sequence Character
StrToTime
Converts a "time" string into a time/date variable. The value returned is the number of seconds from midnight. You can add this value to the date to get the current time value. To set the time delimiter, use the Windows Control Panel. A valid time string is in the format HH:MM:SS or HH:MM:SS tt, where HH is the hour in the range 0-23, MM is the minute in the range 0-59, SS is the second in the range 0-59 and tt is the time extension; for example,, am or pm. The colon character ':' represents the time delimiter for these fields, which will be the current system time delimiter as set in the Windows control panel. Times may also be passed in the for HH or HH:MM. In other words, you may omit the right-hand fields if they are 0.
Syntax
StrToTime(String) String:
The string to convert.
Return Value
964
Time, Date
Example
Variable=StrToTime("11:43:00"); ! Sets Variable to (11*3600+43*60+0) seconds. Variable=StrToTime("9:02"); ! Sets Variable to (9*3600+2*60) seconds. Variable=StrToTime("2"); ! Sets Variable to (2*3600) seconds.
See Also String Functions, Using the Caret Escape Sequence Character
StrToValue
Converts a string into a floating-point number. This function is similar to the StrToReal() function except that the function halts if it is passed an invalid string. The function will search the string for the first non-blank character, and then start converting until it finds the end of the string or a non-numeric character. If the first non-blank character is not a numeric character (0-9), a space, a decimal point, a " +" or a " - " sign, the function will halt. Use this function to check keyboard input from the operator by setting control points (for example, it minimizes the likelihood of a setpoint being set to 0 if the operator presses ENTER or enters invalid data by mistake).
Syntax
StrToValue(String) String:
The string to convert.
Return Value
StrToReal, StrToInt
Example
System Keyboard
965
F3 ######## Enter SP123 = StrToValue(Arg1); Set setpoint 123 to value unless value is invalid
Note: If value is invalid the Cicode is halted. Any other Cicode after the StrToValue() function will not execute. See Also String Functions, Using the Caret Escape Sequence Character
StrTrim
Removes leading and trailing spaces from a string. Internal spaces are not removed from the string.
Syntax
StrTrim(String) String:
The source string.
Return Value
StrPad, StrFill
Example
Variable=StrTrim(" Test String ! Sets Variable to "Test String". ");
See Also String Functions, Using the Caret Escape Sequence Character
StrTruncFont
Returns the truncated string using a particular font (specified by name) or the specified number of characters.
Syntax
966
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.
iLength:
Length of the Text to display, either in characters or pixels depending on iLengthMode (default -1, no truncation)
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
StrCalcWidth, StrTruncFontHnd See Also String Functions, Using the Caret Escape Sequence Character
StrTruncFontHnd
Returns the truncated string using a particular font (specified by font number) or the specified number of characters.
Syntax
hFont:
The font handle used to calculate the pixel width of the text. (To use the default font, set to -1).
iLength:
967
Length of the Text to display, either in characters or pixels depending on iLengthMode (default -1, no truncation)
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
StrCalcWidth, StrTruncFont, DspFont, DspFontHnd See Also String Functions, Using the Caret Escape Sequence Character
StrUpper
Converts a string to uppercase.
Syntax
StrUpper(String) String:
The source string.
Return Value
StrLower
Example
Variable=StrUpper("abcdef"); ! Sets Variable to "ABCDEF". Variable=StrUpper("AbCdEf"); ! Sets Variable to "ABCDEF".
See Also String Functions, Using the Caret Escape Sequence Character
StrWord
968
Gets the first word from a string. The word is removed from the string to allow the function to be repeated. Word separators can be a space, newline, carriage return, or tab character.
Syntax
StrWord(String) String:
The source string.
Return Value
StrSearch
Example
Str="THIS IS A STRING"; Variable=StrWord(Str); ! Sets Variable to "THIS". Variable=StrWord(Str); ! Sets Variable to "IS". Variable=StrWord(Str); ! Sets Variable to "A". Variable=StrWord(Str); ! Sets Variable to "STRING".
See Also String Functions, Using the Caret Escape Sequence Character
969
970
AssMetadata
AssMetadataPage
AssMetadataPopup
AssMetadataWin
AssChainPage
AssChainPopUp
AssChainWin
AssChainWinFree
AssGetProperty
AssGetScale
971
AssInfo
Gets association information about the current Super Genie (that is information about a variable tag that has been substituted into the Super Genie). Gets association information about the current Super Genie (that is information about a variable tag that has been substituted into the Super Genie). Replacement for AssInfo supporting online changes. Associates up to eight variable tags with a Super Genie and displays the Super Genie in the current window. Associates up to eight variable tags with a Super Genie and displays the Super Genie in a popup window. Gets scale information about the associations of the current Super Genie (that is scale information about a variable tag that has been substituted into the Super Genie). Associates a variable tag with the current Super Genie. The association will be created for the current Super Genie only, and will only come into effect after you re-display the Super Genie. Sets the runtime window title to the tag name of the first variable substituted into the Super Genie. Associates up to eight variable tags with a Super Genie. This association is only made for the next Super Genie you display (either in the current window or in a new window). You can use this function repeatedly to associate more than 8 variable tags to a Super Genie. Associates up to eight variable tags with a Super Genie, and displays the Super Genie in a new window.
AssInfoEx
AssPage
AssPopUp
AssScaleStr
AssTag
AssTitle
AssVarTags
AssWin
Ass
Associates a variable tag with a Super Genie. This association is only made for the next Super Genie you display (either in the current window or in a new window). You cannot create an association for a Super Genie that is already displayed. You needs to call this function once for every Super Genie substitution string in the Super Genie, otherwise the variable (substitution string) will remain uninitialized and it will be displayed as #ASS. This function provides the lowest level of support for associating Super Genie variables with physical tags. The higher level functions (listed below) are simpler to use.
972
Syntax
-3 - for the current window when the page is changed. The page can be changed by using the Page Cicode functions like PageDisplay, PageGoto, etc. -2 - for the next new window or page displayed.
nArg:
The argument number or name (substitution string number or name) of the Super Genie string to be replaced by sTag. For example, to replace ?INT 3? with sTag, set nArg to 3 ,or ?Level? set nArg to Level.
sTag:
The variable tag name , or the equipment and item name of a variable tag (using equipment.item notation) that will replace the Super Genie substitution string. The tag needs to be the same data type as that specified by the Super Genie substitution string. For example, only a digital tag could replace the substitution string ?DIGITAL 4?. Any other type of tag may raise a hardware alarm or display #err. If the substitution string does not specify a type (for example, ?5?), you can use any type except STRING. The name of the tag can be prefixed by the name of the cluster for example, "ClusterName.Tag" or "ClusterName.Equipment.Item".
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. nMode:
The mode of the association. Set to 0.
sClusterName:
Specifies the name of the cluster in which the Variable Tag resides. This is optional if you have one cluster or are resolving the tag via the page's current cluster context. The argument is enclosed in quotation marks "". Resolution of the tag's cluster context occurs when the page is displayed. It is resolved to the page's cluster context, not the context in force when this function is called.
Return Value
AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
//Using a string identifier for the substitution parameter Ass(-2,"Level", "MIlK_LEVEL",0); // Associate variable tag PV123 with the next Genie to display in the current window Ass(-3, 5, "PV123", 0);
AssChain
Chains the associations from the current Super Genie to a new Super Genie. Use this function to display a new Super Genie when you already have one displayed. The new Super Genie will inherit the associations of the first Super Genie. This function provides the lowest level of support for chaining associations from one Super Genie to another. You should call the higher level functions AssChainPage(), AssChainWin(), and AssChainPopUp() - these functions are simpler to use.
Syntax
-3: for the current window when the page is changed. The page can be changed by using the Page Cicode functions like PageDisplay, PageGoto, etc. -2: for the next new window or page displayed.
hSource:
The number of the window containing the source Super Genie (that is the Super Genie from which the associations will be inherited).
nMode:
The mode of the association. Set to 0.
Return Value
974
Ass, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Copy associations from the current Super Genie to !NewGenie AssChain(WinNumber(), WinNumber(), 0); PageDisplay("!NewGenie");
AssMetadata
This non-blocking function performs Super Genie associations using the "Name" and "Value" fields defined on the Object Properties - Metadata tab, and matches it to the 'Name' field in the page associations table. While performing associations any additional metadata entries are ignored.
Syntax
-3: for the current window when the page is changed. The page can be changed by using the Page Cicode functions like PageDisplay, PageGoto, etc. -2: for the next new window or page displayed.
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.This parameter is optional with -2 being the default value.When -2 is specified, it is equivalent to DspGetAnCur() which returns the animation number of the current active command cursor, please refer DspGetAnCur() for usage and limitations.
975
UNINTENDED EQUIPMENT OPERATION If called after other cicode functions in a command expression field, retrieve the animation number first, then pass it through the nAN parameter. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Return Value
Related Functions
Ass, AssChain, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin See Also Super Genie Functions
AssMetadataPage
Uses the metadata information from the current object for the page associations for a new Super Genie page, and displays the new Super Genie (in the current page).
Syntax
nAN:
976
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.This parameter is optional with -2 being the default value. When -2 is specified, it is equivalent to DspGetAnCur() which returns the animation number of the current active command cursor, please refer DspGetAnCur() for usage and limitations.
UNINTENDED EQUIPMENT OPERATION If called after other cicode functions in a command expression field, retrieve the animation number first, then pass it through the nAN parameter. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Return Value
Related Functions
Ass, AssChain, AssMetadata, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin See Also Super Genie Functions
AssMetadataPopUp
Uses the metadata information from the current animation point for the associations for a new Super Genie page, and displays the new Super Genie in a pop up window.
Syntax
nAN:
977
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.This parameter is optional with -2 being the default value. When -2 is specified, it is equivalent to DspGetAnCur() which returns the animation number of the current active command cursor, please refer DspGetAnCur() for usage and limitations.
UNINTENDED EQUIPMENT OPERATION If called after other cicode functions in a command expression field, retrieve the animation number first, then pass it through the nAN parameter. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Return Value
Related Functions
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin See Also Super Genie Functions
AssMetadataWin
Uses the metadata information from the current animation-point for the associations for a new Super Genie page, and displays the new Super Genie in a new window.
Syntax
X:
The x pixel coordinate of the top left corner of the window. Default value is 0.
978
Y:
The y pixel coordinate of the top left corner of the window. Default value is 0.
Mode:
The mode of the window:
0 - Normal page (default value). 1 - Page child window. The window is closed when a new page is displayed, for example, when the PageDisplay() or PageGoto() function is called. The parent is the current active window. 2 - Window child window. The window is closed automatically when the parent window is freed with the WinFree() function. The parent is the current active window. 4 - No re-size. The window is displayed with thin borders and no maximize/minimize icons. The window cannot be re-sized. 8 - No icons. The window is displayed with thin borders and no maximize/minimize or system menu icons. The window cannot be re-sized. 16 - No caption. The window is displayed with thin borders, no caption, and no maximize/minimize or system menu icons. The window cannot be re-sized. 32 - Echo enabled. When enabled, keyboard echo, prompts, and error messages are displayed on the parent window. This mode should only be used with child windows (for example, Mode 1 and 2). 64 - Always on top. 128 - Open a unique window. This mode stops this window from being opened more then once. 256 - Display the entire window. This mode commands that no parts of the window will appear off the screen 512 - Open a unique Super Genie. This mode stops a Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened. 1024 - Disables dynamic resizing of the new window, overriding the setting of the [Page]DynamicSizing parameter. 4096 - Allows the window to be resized without maintaining the current aspect ratio. The aspect ratio defines the relationship between the width and the height of the window, which means this setting allows you to stretch or compress the window to any proportions. This option overrides the setting of the [Page]MaintainAspectRatio parameter.
979
8192 - Text on a page will be resized in proportion with the maximum scale change for a resized window. For example, consider a page that is resized to three times the original width, and half the original height. If this mode is set, the font size of the text on the page will be tripled (in proportion with the maximum scale). This option overrides the setting of the [Page] ScaleTextToMax parameter. 16384 - Hide the horizontal scroll bar. 32768 - Hide the vertical scroll bar. 65536 - Disable horizontal scrolling. 131072 - Disable vertical scrolling.
You can select multiple modes by adding modes together (for example, set Mode to 9 to open a page child window without maximize, minimize, or system menu icons). 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.This parameter is optional with -2 being the default value.When -2 is specified, it is equivalent to DspGetAnCur() which returns the animation number of the current active command cursor, please refer DspGetAnCur() for usage and limitations.
UNINTENDED EQUIPMENT OPERATION If called after other cicode functions in a command expression field, retrieve the animation number first, then pass it through the nAN parameter. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Return Value
/* Example of calling AssMetadataWin after other cicode functions */ An = DspGetAnCur(); SomeVal = TagRead(SomeTag); // do additional work AssMetadataWin(!TestSG, 50, 50, 1, An);
Related Functions
980
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin See Also Super Genie Functions
AssChainPage
Chains the associations from the current Super Genie to a new Super Genie, and displays the new Super Genie (in the current window). Use this function to display a new Super Genie when you already have one displayed. The new Super Genie will inherit the associations of the first Super Genie.
Syntax
AssChainPage(sPage) sPage:
The page name of the Super Genie. If you prefixed your Super Genie page name with an exclamation mark (!), remember to include it here.
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Display new Super Genie in current window, using current associations AssChainPage("!NewGenie");
AssChainPopUp
981
Chains the associations from the current Super Genie to a new Super Genie, and displays the new Super Genie in a new popup window. Use this function to display a new Super Genie in a new popup window when a Super Genie is already displayed. The new Super Genie will inherit the associations of the first. Note: This function helps to prevent the Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened.
Syntax
AssChainPopUp(sPage) sPage
The page name of the Super Genie. If you prefixed your Super Genie page name with an exclamation mark (!), remember to include it here.
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Display new Super Genie in new popup using current associations AssChainPopUp("!NewGenie");
AssChainWin
Chains the associations from the current Super Genie to a new Super Genie, and displays the new Super Genie in a new window. The new window will be of the same type as the current window. Use this function to display a new Super Genie in a new window when a Super Genie is already displayed. The new Super Genie will inherit the associations of the first.
Syntax
AssChainWin(sPage, X, Y, Mode)
982
sPage:
The page name of the Super Genie. If you prefixed your Super Genie page name with an exclamation mark (!), remember to include it here.
l l
X - The x pixel coordinate of the top left corner of the window. Y - The y pixel coordinate of the top left corner of the window.
Mode:
The mode of the window:
0 - Normal page. 1 - Page child window. The window is closed when a new page is displayed, for example, when the PageDisplay() or PageGoto() function is called. The parent is the current active window. 2 - Window child window. The window is closed automatically when the parent window is freed with the WinFree() function. The parent is the current active window. 4 - No re-size. The window is displayed with thin borders and no maximize/minimize icons. The window cannot be re-sized. 8 - No icons. The window is displayed with thin borders and no maximize/minimize or system menu icons. The window cannot be re-sized. 16 - No caption. The window is displayed with thin borders, no caption, and no maximize/minimize or system menu icons. The window cannot be re-sized. 32 - Echo enabled. When enabled, keyboard echo, prompts, and error messages are displayed on the parent window. This mode should only be used with child windows (for example, Mode 1 and 2). 64 - Always on top. 128 - Open a unique window. This mode helps to prevent this window from being opened more then once. 256 - Display the entire window. This mode helps to ensure that no parts of the window will appear off the screen 512 - Open a unique Super Genie. This mode helps to prevent a Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened. 1024 - Disables dynamic resizing of the new window, overriding the setting of the [Page]DynamicSizing parameter.
You can select multiple modes by adding modes together (for example, set Mode to 9 to open a page child window without maximize, minimize, or system menu icons).
Return Value
983
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Displays a new super genie in a new window using the current associations AssChainWin("!NewGenie", 100, 200, 1 + 8);
AssChainWinFree
Stores the tag associations on an existing Super Genie, closes it, then assigns the tags to a new window. This allows a Super Genie popup window to call another popup window, and close the parent popup. This function is effectively the same as the AssChainWin() function, but frees the current Super Genie.
Syntax
X - the x pixel coordinate of the top-left corner of the window. Y - the y pixel coordinate of the top-left corner of the window. Mode:
The mode of the window:
0 - Normal page. 1 - Page child window. The window is closed when a new page is displayed, for example, when the PageDisplay() or PageGoto() function is called. The parent is the current active window. 2 - Window child window. The window is closed automatically when the parent window is freed with the WinFree() function. The parent is the current active window.
984
4 - No re-size. The window is displayed with thin borders and no maximize/minimize icons. The window cannot be re-sized. 8 - No icons. The window is displayed with thin borders and no maximize/minimize or system menu icons. The window cannot be re-sized. 16 - No caption. The window is displayed with thin borders, no caption, and no maximize/minimize or system menu icons. The window cannot be re-sized. 32 - Echo enabled. When enabled, keyboard echo, prompts, and error messages are displayed on the parent window. This mode should only be used with child windows (for example, Mode 1 and 2). 64 - Always on top. 128 - Open a unique window. This mode helps to prevent this window from being opened more then once. 256 - Display the entire window. This mode helps to ensure that no parts of the window will appear off the screen 512 - Open a unique Super Genie. This mode helps to prevent a Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened. 1024 - Disables dynamic resizing of the new window, overriding the setting of the [Page]DynamicSizing parameter.
You can select multiple modes by adding modes together (for example, set Mode to 9 to open a page child window without maximize, minimize, or system menu icons).
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Close the current genie window and display a new genie using the current associations AssChainWinFree("!GeniePopup", 200, 300, 1 + 8);
AssGetProperty
985
This function gets association information about the current Super Genie from the datasource (that is information about a variable tag that has been substituted into the Super Genie). You can only call this function on a Super Genie after the associations are completed. Use this function to display association information as part of the Super Genie. For example, if you have a Super Genie that is a loop controller, you could display the name of the loop at the top of the loop controller box. Each time the Super Genie is used with different associations (specifically a different tag name association) the correct loop name will be displayed. If a constant value is associated, then only the constant value can be retrieved through the TagName property. The remaining properties are not valid. This function replace AssInfo.
Syntax
sProperty:
The property to read. Property names are case sensitive. Supported properties are:
Address - The configured address of the associated tag (as specified in the variable tags form) ArraySize - Array size of the associated tag. Returns 1 for non-array types AssFullName - Full name of the association tag in the form cluster.tagname even if the tag is not resolved ClusterName - Name of the cluster the associated tag resides on. DataBitWidth - Number of bits used to store the value Description - Description of the associated tag EngUnitsHigh - Maximum scaled value EngUnitsLow - Minimum scaled value Equipment - Name of the equipment Format - Format bit string. The format information is stored in the integer as follows: l Bits 0-7 - format width l Bits 8-15 - number of decimal places l Bits 16 - zero-padded l Bit 17 - left-justified l Bit 18 - display engineering units l Bit 20 - exponential (scientific) notation
986
ErrorValUsed - Returns 1 if the defined error value was used for the SuperGenie association. This means that tag name is invalid/unresolved or the substitutions are not complete. This is only relevant for named SuperGenies. 0 is returned if the association string provided a value, or a default value was not defined. FormatDecPlaces - Number of decimal places for default format FormatWidth - Number of characters used in default format FullName - Full name of the association tag in the form cluster.tagname If the association tag is not resolved, returns an empty string. Item - Name of the equipment item associated with the Tag. If the tag is not resolved, returns an empty string. Literal - Returns 1 if the substitution is a literal value, returns 0 if the substitution is a tag name. RangeHigh - Maximum unscaled value RangeLow - Minimum unscaled value TagName - Name of the tag for the specified association. Will retrieve the tag name regardless if you used equipment.item to reference the tag. nType - General type of associated tag. Allowed values are:
l l l l l l l l l
Note: When retrieving bit width ("DataBitWidth" property) or array size ("ArraySize" property) from the local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, is a 16 bit device and does not have native LONG and REAL numbers. So when you have a LONG variable, an array of 2 INTEGERS are needed to store it. In the example, the property "Dat-
987
aBitWidth" against the variable will return 16 and property "ArraySize" will return 2. The combination of these two return values will add up to the correct bits.
-1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Return Value
String representation of the property of the association. On detection of an error, an empty string and an error are set.
Related Functions
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin, TagGetProperty, TagGetScale, TagScaleStr, TagInfo
Example
//Using a string identifier for the substitution parameter AssGetProperty("MILK_LEVEL", "TagName", 0);
// Get the engineering full scale value for the 2nd // argument of the association of the current Super Genie EngFullScale = AssGetProperty(2, "EngUnitsHigh", 0); // Get the cached engineering units for the 3rd argument // of the association of the current Super Genie MeasureUnits = AssGetProperty(3, "Units", 1);
988
AssGetScale
Gets scale information about the associations of the current Super Genie from the datasource (that is scale information about a variable tag that has been substituted into the Super Genie). You can only call this function on a Super Genie after the associations are completed. Use this function to display association scale information as part of the Super Genie. For example, if you have a bar graph illustrating output, you could indicate zero, 50%, and full scale output on the vertical axis of the graph. Each time the Super Genie is used with different associations the correct scale values will be displayed. The value is returned as a formatted string using the association format specification and (optionally) the engineering units. This function replaces AssScaleStr.
Syntax
iPercent:
The percentage of full scale of the returned value.
iEngUnits:
Flag to determine if the value is returned with engineering units:
0 - Return the value without engineering units 1 - Return the value with engineering units iCached:
Optional flag to attempt to retrieve the cached value for the property rather than the current value. 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).
Return Value
989
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin, TagGetProperty, TagGetScale, TagScaleStr, TagInfo
Example
//Using a string identifier for the substitution parameter AssGetScale("MILK_LEVEL", 50, 1, 0);
// Display the zero, 50% and full scale of the 2nd argument // of the association of the current Super Genie DspText(31,0,AssGetScale(2, 0, 1)); DspText(32,0,AssGetScale(2, 50, 1)); DspText(33,0,AssGetScale(2, 100, 1));
AssInfo
Gets association information about the current Super Genie (that is information about a variable tag that has been substituted into the Super Genie). You can only call this function on a Super Genie after the associations are completed. Use this function to display association information as part of the Super Genie. For example, if you have a Super Genie that is a loop controller, you could display the name of the loop at the top of the loop controller box. Each time the Super Genie is used with different associations (specifically a different tag name or equipment.item association) the correct loop name will be displayed. Note: In some cases it may be beneficial to replace AssInfo with either the AssGetProperty or the AssInfoEx function. If the Tag properties are updated, AssInfo does not get the updated values whereas AssGetProperty does. In addition, the function AssInfoEx has been introduced to make it easier to make legacy Cicode compatible with online changes. In a large number of cases AssInfo can be replaced with AssInfoEx using Find and Replace (see Using Find and Replace in a project). Please be aware that if you are replacing an instance of AssInfo with AssInfoEx in a loop, you may want to make AssInfoEx blocking using the iCached argument to verify you are using the correct value for the Tag in your logic.
Syntax
990
sArg:
When you associate variable tags (can use equipment.item to reference the variable tag) with Super Genies, the Super Genie substitution strings are replaced by variable tags. The sArg argument allows you to get information about one of those variable tags. What you need to know is which substitution string it replaced when the association was performed. Enter the argument number or name (substitution string number or name) of the relevant substitution string. For example, if you want information about the variable that replaced substitution string ?INT 3? set sArg to 3. Or ?Level? set sArg to Level
nType:
The type of information to get:
0 - The Tag name of the association. If the association tag is not resolved, returns an empty string. 1 - Engineering units 2 - Raw zero scale 3 - Raw full scale 4 - Engineering zero scale 5 - Engineering full scale 6 - Width of the format 7 - Number of decimal places of format 8 - The Tag format as a long integer. The format information is stored in the integer as follows: l Bits 0-7 - format width l Bits 8-15 - number of decimal places l Bits 16 - zero-padded l Bit 17- left-justified l Bit 18 - display engineering units l Bit 20 - exponential (scientific) notation 9 - Logical Unit Number - I/O device number (for internal use) 10 - Raw Type - Protocol's raw data type number for this tag. Type numbers are: l 0 - Digital l 1 - Integer
991
l l l l l l l l l
2 - Real 3 - BCD 4 - Long 5 - Long BCD 6 - Long Real 7 - String 8 - Byte 9 - Void 10 - Unsigned integer
11 - Bit Width - Tag's size in bits. For example, an INT is 16 bits 12 - Unit Type - Protocol's unit type number for this tag 13 - Unit Address - Tag's address after the protocol DBF's template is applied. 14 - Unit Count - Array size. For example, if the tag's address is I1[50], the unit count is 50. 15 - Record Number - Tag's record number in variable.DBF - 1. That is, the first tag has a record number of 0. 16 - Comment - As defined in the variable tags list. 17 - ClusterName of the tag. If the association tag is not resolved, returns an empty string. 18 - Full name (cluster.tagname) of the associated tag. If the association tag is not resolved, returns an empty string. 19 - Full name (cluster.tagname) of the associated tag even if the association tag is not resolved. 20 - Configured Address of the tag. If the tag is not resolved, returns an empty string. 21 - Network Number - I/O device number (as defined by the Number field of the I/O Devices dialog). 22 - Name of the equipment associated with the Tag. If the association tag is not resolved, returns an empty string. 23 - General Type.
l l l l l l l l l
0 1 2 3 4 5 6 7 8
992
25 - Name of the equipment item associated with the Tag. If the tag is not resolved, returns an empty string.
If the tag is a local variable, mode 9 error code 348 is retrieved when cache mode is 0,1,2,3. Modes 12, 13, 14 and 15 will return an empty string (error 274 is trapped). Type 8 - 16 are only supported when iCachedMode equals to 2 or 3.
iCachedMode:
Optional parameter that specifies from where to retrieve the value for the property.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from the local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, is a 16 bit device and does not have native LONG and REAL numbers. So if you have a LONG variable, 2 INTEGERS are needed to store it. In this case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits. -1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, This is a 16 bit device does not have native LONG and REAL numbers. So when you have a LONG variable, then 2 INTEGERS are needed to store it. In the case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits.
Return Value
993
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin, TagGetProperty, TagGetScale, TagScaleStr, TagInfo, TagInfoEx
Example
//Using a string identifier for the substitution parameter AssInfo("MILK_LEVEL", 1); (to get Engineering Units of the association )
sTag = AssInfo(1, 0); // Get the name of association 1 sEngLow = AssInfo(1, 4); // get the low engineering scale of association 1
AssInfoEx
Gets association information about the current Super Genie (that is information about a variable tag that has been substituted into the Super Genie). You can only call this function on a Super Genie after the associations are completed. Use this function to display association information as part of the Super Genie. For example, if you have a Super Genie that is a loop controller, you could display the name of the loop at the top of the loop controller box. Each time the Super Genie is used with different associations (specifically a different tag name association) the correct loop name will be displayed. Note: When replacing an instance of AssInfo with AssInfoEx in a loop, you may want to make AssInfoEx blocking using the iCached argument to verify you are using the correct value for the Tag in your logic.
Syntax
994
nType:
The type of information to get:
0 - The Tag name from the variables table. This is the same as sName argument. (Returned to be compatible with the AssInfo() function). 1 - Engineering units 2 - Raw zero scale 3 - Raw full scale 4 - Engineering zero scale 5 - Engineering full scale 6 - Width of the format 7 - Number of decimal places of format 8 - The Tag format as a long integer. The format information is stored in the integer as follows:
l l l l l l
Bits 0-7 - format width Bits 8-15 - number of decimal places Bits 16 - zero-padded Bit 17- left-justified Bit 18 - display engineering units Bit 20 - exponential (scientific) notation
9 - Logical Unit Number - I/O device number (for internal use) 10 - Raw Type - Protocol's raw data type number for this tag. Type numbers are: l 0 - Digital l 1 - Integer l 2 - Real l 3 - BCD l 4 - Long l 5 - Long BCD l 6 - Long Real l 7 - String l 8 - Byte l 9 - Void l 10 - Unsigned integer 11 - Bit Width - Tag's size in bits. For example, an INT is 16 bits 12 - Unit Type - Protocol's unit type number for this tag 13 - Unit Address - Tag's address after the protocol DBF's template is applied. 14 - Unit Count - Array size. For example, if the tag's address is I1[50], the unit count is 50.
995
15 - Record Number - Tag's record number in variable.DBF - 1. That is, the first tag has a record number of 0. 16 - Comment - As defined in the variable tags list. 17 - ClusterName of the tag. 18 - Full name (cluster.tagname) of the tag. 19 - Full name (cluster.tagname) of the associated tag even if the association tag is not resolved. 20 - Configured Address of the tag. If the tag is not resolved, returns an empty string. 21 - Network Number - I/O device number (as defined by the Number field of the I/O Devices dialog). 22 - Name of the equipment associated with the Tag. If the association tag is not resolved, returns an empty string.
If the tag is a local variable, mode 9 error code 348 is retrieved when cache mode is 0,1,2,3. Modes 12, 13, 14 and 15 will return an empty string (error 274 is trapped).
23 - General Type.
l l l l l l l l l
0 1 2 3 4 5 6 7 8
24 - Reserved for internal use. 25 - Name of the equipment item associated with the Tag. If the tag is not resolved, returns an empty string. iCachedMode:
Optional parameter that specifies from where to retrieve the value for the property.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from the local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, is a 16 bit device and does not have native LONG and REAL numbers. So if you have a LONG variable, 2 INTEGERS are needed to store it. In this case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits.
996
-1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, This is a 16 bit device does not have native LONG and REAL numbers. So when you have a LONG variable, then 2 INTEGERS are needed to store it. In the case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits.
Return Value
The value of the information as a string. If an error is detected an empty string is returned. The error code can be obtained by calling the IsError Cicode function.
Related Functions
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin, TagGetProperty, TagGetScale, TagScaleStr, TagInfo, TagInfoEx
Example
//Using a string identifier for the substitution parameter
997
sTag = AssInfoEx(1, 0); // Get the name of association 1 in non-blocking mode sEngLow = AssInfoEx(1, 4, 0); // get the low engineering scale of association 1, block until data is available
AssPage
Associates up to eight variable tags or equipment.item tag references with a Super Genie and displays the Super Genie in the current window. The first variable tag (sTag1) replaces Super Genie substitution string 1. The second variable tag (sTag2) replaces substitution string 2, and so on. This function has the same effect as calling Ass() or AssTag() eight times, and then calling the PageDisplay() function. The AssPage() function provides a quick way of associating eight Super Genie variables and displaying the Super Genie - at the same time. If you want to associate more than eight tags with the Super Genie, it is strongly recommended you call the AssVarTags(), AssTag(), or Ass() function to create the associations before you call this function.
Syntax
sTag1..sTag8:
The first eight physical tags to be associated with the Super Genie. For any given Super Genie, the variable tags will replace the Super Genie substitution strings as follows: Variable tag... sTag1 sTag2 sTag3 sTag4 sTag5 replaces substitution string... 1 2 3 4 5
998
6 7 8
Because there is a strict correlation between the variable tag numbers and the substitution string numbers, you need to know how your Super Genie substitutions are numbered. For example, if your Super Genie has three unique substitution strings, numbered 1, 3, & 4, you need to enter a blank ("") for sTag2. The variable tags that you specify here need to be the same data type as that specified by the relevant Super Genie substitution strings. For example, only a digital tag could replace the substitution string ?DIGITAL 4?. If the substitution string does not specify a type (for example, ?5?), you can use any type except STRING. The name of the tag can be prefixed by the name of the cluster for example, "ClusterName.Tag".
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Associate 3 tags with the Super Genie then display the Super Genie AssPage("!MyGenie", "PV123", "OP123", "SP123");
AssPopUp
Associates up to eight variable tags or equipment.item tag references with a Super Genie and displays the Super Genie in a popup window. The first variable tag (sTag1) replaces Super Genie substitution string 1. The second variable tag (sTag2) replaces substitution string 2, and so on.
999
This function has the same effect as calling the Ass() function or the AssTag() function eight times, and then calling the WinNewAt() function to create a window at the position of the mouse. The AssPopUp() function is a quick way of associating eight Super Genie variables and displaying the Super Genie in a new window at the same time. If you want to associate more than eight tags with the Super Genie, you need to call the AssVarTags(), AssTag(), or Ass() function to create the associations before you call this function. Note: This function helps to prevent the Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened.
Syntax
sTag1..sTag8:
The first 8 physical tags to be associated with the Super Genie. For any given Super Genie, the variable tags will replace the Super Genie substitution strings as follows: Variable tag... sTag1 sTag2 sTag3 sTag4 sTag5 sTag6 sTag7 sTag8 replaces substitution string... 1 2 3 4 5 6 7 8
1000
Because there is a strict correlation between the variable tag numbers and the substitution string numbers, you need to know how your Super Genie substitutions are numbered. For example, if your Super Genie has three unique substitution strings, numbered 1, 3, & 4, you have to enter a blank ("") for sTag2. The variable tags that you specify here needs to be the same data type as that specified by the relevant Super Genie substitution strings. For example, only a digital tag could replace the substitution string ?DIGITAL 4?. If the substitution string does not specify a type (for example, ?5?), you can use any type except STRING. The name of the tag can be prefixed by the name of the cluster for example, "ClusterName.Tag".
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssScaleStr, AssTag, AssTitle, AssVarTags, AssWin
Example
// Associate 3 tags with the Super Genie then display it AssPopUp("!MyGenie", "PV123", "OP123", "SP123");
AssScaleStr
Gets scale information about the associations of the current Super Genie (that is scale information about a variable tag that has been substituted into the Super Genie). You can only call this function on a Super Genie after the associations are completed. Use this function to display association scale information as part of the Super Genie. For example, if you have a bar graph illustrating output, you could indicate zero, 50%, and full scale output on the vertical axis of the graph. Each time the Super Genie is used with different associations the correct scale values will be displayed. The value is returned as a formatted string using the association format specification and (optionally) the engineering units. Note: This function is being deprecated and is replaced by the AssGetScale function. If the Tag properties are updated AssScaleStr does not get the updated values
1001
Percent:
The percentage of full scale of the returned value.
EngUnits:
Determines if the value is returned with engineering units:
0 - Do not return the value with engineering units 1 - Return the value with engineering units CachedMode:
Optional parameter that specifies from where to retrieve the value for the property.
-1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour).
1002
3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssTag, AssTitle, AssVarTags, AssWin, TagGetProperty, TagGetScale, TagScaleStr, TagInfo
Example
// Display the zero, 50% and full scale of the variable that was substituted for Super Genie arg no. 3 DspText(31,0,AssScaleStr(3, 0, 1)); DspText(32,0,AssScaleStr(3, 50, 1)); DspText(33,0,AssScaleStr(3, 100, 1));
AssTag
Associates a variable tag or equipment.item tag reference with a Super Genie. The association will only be created for the next Super Genie you display in the current window, and will only come into effect after you re-display the Super Genie. You need to call this function once for every substitution string in the current Super Genie, or the super-genie variable (substitution string) will remain uninitialized and it will display as #ASS. You cannot use this function to create associations for variables that will display in new windows.
Syntax
1003
sTag:
The variable tag or equipment.item tag reference that will replace the Super Genie substitution string. The tag needs to be the same data type as that specified by the Super Genie substitution string. For example, only a digital tag could replace the substitution string ?DIGITAL 4?. If the substitution string does not specify a type (for example, ?5?), you can use any type except STRING. The name of the tag can be prefixed by the name of the cluster for example, "ClusterName.Tag" or "ClusterName.equipment.item".
sClusterName:
Specifies the name of the cluster in which the Variable 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 "". Resolution of the tag's cluster context occurs when the page is displayed. It is resolved to the page's cluster context, not the context in force when this function is called.
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTitle, AssVarTags, AssWin
Example
// Associate variable tag PV123 and PV124 with !MyGenie AssTag(1, "PV123"); AssTag(2, "PV124"); // Re-display the current Super Genie PageDisplay("!MyGenie");
AssTitle
1004
Sets the runtime window title to the tag name of the first variable substituted into the Super Genie.
Note:This function does not support named associations.
See Page Properties - General for information regarding using named associations in the Window Title field.
Syntax
Prefix:
A string to add to the beginning of the title string (optional).
Suffix:
A string to add to the end of the title string (optional).
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssVarTags, AssWin See Also Super Genie Functions
AssVarTags
Associates up to eight variable tags with a Super Genie. This association is only made for the next Super Genie you display (either in the current window or in a new window). This function has an offset that allows you to specify which substitution string the first variable tag will replace. This means that if you have a Super Genie with more than 8 substitution strings, you can use this function repeatedly (while increasing the offset), until you have associated the necessary variable tags. This function has the same effect as calling the Ass() function or the AssTag() function eight times. The AssVarTags() function is a quick way of associating up to eight Super Genie variables at the same time.
1005
Note:This function does not support named associations. To use named associations refer to AssMetadata.
Syntax
-3 - for the current window when the page is changed. The page can be changed by using the Page Cicode functions like PageDisplay, PageGoto, etc. -2 - for the next new window or page displayed. nOffset:
By default, the first variable tag (sTag1) will replace substitution string 1, and sTag2 will replace substitution string 2, and so on. Enter an offset to change this so that sTag1 replaces a substitution string other than the first. For example, an offset of 8 means that sTag1 replaces string 9 instead of the default string 1 (8+1=9), and sTag2 replaces string 10 instead of string 2 (8+2=10) etc. This means that you can use this function repeatedly to associate more than eight variables.
sTag1..8:
The physical variable tags (up to eight) to be associated with the Super Genie. For any given Super Genie, the variable tags will replace the Super Genie substitution strings as follows: If nOffset is 0... sTag1 will replace the substitution string 1, sTag2 will replace the substitution string 2, etc. If nOffset is 8... sTag1 will replace the substitution string 9, sTag2 will replace the substitution string 10, etc.
Because there is a strict correlation between the variable tag numbers and the substitution string numbers, you need to know how your Super Genie substitutions are numbered. For example, if your Super Genie has three unique substitution strings, numbered 1, 3, & 4, you need to enter a blank ("") for sTag2. The name of the tag can be prefixed by the name of the cluster for example, "ClusterName.Tag".
Return Value
No value is returned.
Related Functions
1006
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssWin
Example
// Associate 12 variables to the Super Genie AssVarTags(WinNumber(), 0, "PV123", "SP123", "OP123", "PV124", "SP124", "OP124", "PV125", "SP125"); AssVarTags(WinNumber(), 8, "OP125", "PV126", "SP126", "OP126"); PageDisplay("!MyGenie"); // Display the Super Genie
AssWin
Associates up to eight variable tags or equipment.item tag references with a Super Genie, and displays the Super Genie in a new window. This function has the same effect as calling the Ass() or AssTag() function eight times, and then calling the WinNewAt() function. The AssWin() function is a quick way of associating eight Super Genie variables and creating a new window - at the same time. If you want to associate more than eight tags with the Super Genie you need to call the AssVarTags(), AssTag(), or Ass() function to create the associations before you call this function.
Syntax
X - The x pixel coordinate of the top left corner of the window. Y - The y pixel coordinate of the top left corner of the window. Mode:
The mode of the window:
0 - Normal page. 1 - Page child window. The window is closed when a new page is displayed, for example, when the PageDisplay() or PageGoto() function is called. The parent is the current active window.
1007
2 - Window child window. The window is closed automatically when the parent window is freed with the WinFree() function. The parent is the current active window. 4 - No re-size. The window is displayed with thin borders and no maximize/minimize icons. The window cannot be re-sized. 8 - No icons. The window is displayed with thin borders and no maximize/minimize or system menu icons. The window cannot be re-sized. 16 - No caption. The window is displayed with thin borders, no caption, and no maximize/minimize or system menu icons. The window cannot be re-sized. 32 - Echo enabled. When enabled, keyboard echo, prompts, and error messages are displayed on the parent window. This mode should only be used with child windows (for example, Mode 1 and 2). 64 - Always on top. 128 - Open a unique window. This mode stops this window from being opened more then once. 256 - Display the entire window. This mode commands that no parts of the window will appear off the screen 512 - Open a unique Super Genie. This mode stops a Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened. 1024 - Disables dynamic resizing of the new window, overriding the setting of the [Page]DynamicSizing parameter.
You can select multiple modes by adding modes together (for example, set Mode to 9 to open a page child window without maximize, minimize, or system menu icons).
sTag1..8:
The first eight physical tags to be associated with the Super Genie. For any given Super Genie, the variable tags will replace the Super Genie substitution strings as follows: Variable tag... sTag1 sTag2 sTag3 sTag4 replaces substitution string... 1 2 3 4
1008
5 6 7 8
Because there is a strict correlation between the variable tag numbers and the substitution string numbers, you need to know how your Super Genie substitutions are numbered. For example, if your Super Genie has three unique substitution strings, numbered 1, 3, & 4, you need to enter a blank ("") for sTag2. The variable tags that you specify here need to be the same data type as that specified by the relevant Super Genie substitution strings. For example, only a digital tag could replace the substitution string ?DIGITAL 4?. If the substitution string does not specify a type (for example, ?5?), you can use any type except STRING. The name of the tag can be prefixed by the name of the cluster for example, "ClusterName.Tag".
Return Value
Ass, AssChain, AssMetadata, AssMetadataPage, AssMetadataPopup, AssMetadataWin, AssChainPage, AssChainPopUp, AssChainWin, AssChainWinFree, AssGetProperty, AssGetScale, AssInfo, AssInfoEx, AssPage, AssPopUp, AssScaleStr, AssTag, AssTitle, AssVarTags
Example
// Associate 3 tags with the Super Genie // then display the new window at (100,200) in mode 9 AssWin("!MyGenie", 100, 200, 1 + 8, "PV123", "OP123", "SP123");
1009
1010
Performs mathematical operations on a table, for example, average, maximum, minimum, etc. Shifts a table, left or right.
Note: This function only supports arrays declared in Cicode and not variable tag arrays. See Also Functions Reference
TableLookup
Searches for a value in a table, and returns the position (offset) of the value in the table. Be aware that the first item in a table is offset 0 (zero), the next item is offset 1, etc. Note: This function only supports arrays declared in Cicode and not variable tag arrays.
Syntax
Size:
The maximum number of items in the table.
1011
Value:
The value to locate.
Return Value
The offset to the table value, or -1 if the value does not exist.
Related Functions
TableMath
Example
REAL Levels[5]=10,15,50,100,200; Variable=TableLookup(Levels,5,50); ! Sets Variable to 2. Variable=TableLookup(Levels,5,45); ! Sets Variable to -1.
TableMath
Performs mathematical operations on a table of real (floating-point) numbers. This function supports minimum, maximum, average, standard deviation, and total operations on a table of values. Use this function for operating on tables returned from the trend system with the TrnGetTable() function. You can set the Mode to either accept or ignore invalid or gated data returned from TrnGetTable(). Notes: This function cannot check the length of any arrays passed to it. If the array is shorter than the size argument, unpredictable results can occur, such as data in memory being overwritten, or a general protection fault. This function only supports arrays declared in Cicode and not variable tag arrays.
UNINTENDED EQUIPMENT OPERATION Always confirm that arrays are of appropriate length before passing them to the TableMath function. Failure to follow these instructions can result in death, serious injury, or equipment damage.
1012
Syntax
Size:
The maximum number of items in the table.
Command:
The mathematical operation to perform on the table:
0 - Operate on all data - default 1 - Ignore invalid or gated data returned from the TrnGetTable() function
Return Value
Returns the value related to the requested mathematical operation performed on the table (Minimum, Maximum, Average, Standard deviation or Total).\
Related Functions
TableLookup TrnGetTable
Example
REAL Array[5]=10,15,50,100,200; REAL Min,Avg; ! Get the minimum value. Min=TableMath(Array, 5, 0, 0); ! Get the average value. Avg=TableMath(Array, 5, 2, 0);
TableShift
1013
Shifts table items in a table by a number of positions. You can shift the table left or right. Items shifted off the end of the table are lost. Items within a table that are not replaced by other items (that have moved) are set to 0. Note: This function only supports arrays declared in Cicode and not variable tag arrays.
Syntax
Size:
The maximum number of items in the table.
Count:
The number of positions to shift the table items. A negative Count moves items to the right and a positive Count moves items to the left.
Return Value
TableMath, TableLookup
Example
REAL Levels[5]=10,15,50,100,200; TableShift(Levels,5,2); /* Shifts the table items by 2 positions to the left, that is Levels[0]=50 Levels[1]=100 Levels[2]=200 Levels[3]=0 Levels[4]=0 */
1014
Terminates an active data browse session and cleans up all resources associated with the session. Places the data browse cursor at the first record. Retrieves the value of the specified field from the record the data browse cursor is currently referencing. Moves the data browse cursor forward one record. Gets the number of records for a given browsing session. Initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. Moves the data browse cursor back one record. Displays a dialog which allows you to select any configured tag to read or change (write) its value. Displays a dialog that allows you to select a variable tag and perform some basic read/write operations. Returns a handle to the format of the data used by the TagEventQueue().
TagBrowseFirst TagBrowseGetField
TagBrowsePrev TagDebug
TagDebugForm
TagEventFormat
1015
Opens the tag update event queue. Gets a property for a variable tag from the datasource. Gets the value of a tag at a specified scale from the datasource. Gets information about a variable tag. Gets information about a variable tag. Increments a tag by a percentage amount. Reloads the variable tag database so when TagInfo is called it picks up online changes to the tag database. Reads a variable from an I/O Device. Reads the value, quality and timestamp of a particular tag element. Increments a reference count on a tag to keep it resolved. Gets the value of a tag at a specified scale. Sets a quality Override element for a specified tag to Bad Non Specific. Sets a quality Override element for a specified tag to Good Non Specific. Sets a quality Override element for a specified tag to Uncertain Non Specific. Sets a quality Override element for a specified tag. Subscribes a tag for periodic monitoring and event handling. Unsubscribes a tag for periodic monitoring and event handling. Unresolves a reference count implemented on a tag by TagResolve(). Writes to an I/O Device variable. Opens the tag write event queue.
TagRead TagReadEx
TagSetOverrideGood
TagSetOverrideUncertain
TagUnresolve
TagWrite TagWriteEventQue
SubscriptionAddCallback
Adds a function callback to a tag subscription. When the value change for a subscribed tag is detected, a callback function can be called. This implements change based Cicode and avoids continuously polling a tag value to monitor changes. Multiple callbacks are possible to the same subscription.
1016
sCallback
String stating the name of a function to call when the value is updated. The function should have the structure: FUNCTION evtHandler(INT subsHandle) .. End
Return Value
SubscriptionGetAttribute
Reads the specified attribute value of a subscribed tag. Similar to TagRead. Note: This function has been superseded and may be deprecated in a future release. Please use the following functions: SubscriptionGetInfo, SubscriptionGetTimestamp, SubscriptionGetQuality, SubscriptionGetValue or SubscriptionGetTag as substitutions in new projects.
Syntax
sAttribute
Attribute of the tag to read. Supported Attributes are:
1017
ClusterName - Returns the resultant cluster context of the subscription. For example, for the tag subscribed as "cluster1.tagname", the return value is "cluster1". There are several possible outcomes where no cluster is specified in the subscription:
l
If the tag is a local tag, an empty string will be returned. If the tag is a variable tag and the system only contains one cluster, this cluster will be returned. If the tag is a variable tag and there is a default cluster being run in the Cicode, the default cluster will be returned. If none of these options are true, an empty string will be returned.
FullName - Return the full subscription name. For example, for the tag subscribed as "cluster1.tagname", return value is "cluster1.tagname". If the tag was subscribed without a cluster the return value will be the tagname. TagName - Return the tagname for the subscription. For example, for the tag subscribed as "cluster1.tagname", return value is "tagname". Value - The current value of the tag. ValueQuality - An indication of the current quality of the tag as an integer number. Note: The return value is not compatible with the QUALITY data type or the quality Cicode functions. Use SubscriptionGetQuality.
l l
ValueTimestamp - The time when the tag last changed. It is returned as an integer value compatible with a time/data variable. Note: The return value is not compatible with the TIMESTAMP data type. Use SubscriptionGetTimestamp.
ValueTimestampMS - The millisecond part of the time when the tag last changed.
iOffset
Optional integer expressing the zero based index of an array attribute. This is only valid for the Value attribute. Default value is 0.
1018
Return Value
String representation of the cached value for a subscribed tag. On error, an empty string and an error is set.
Related Functions
SubscriptionGetInfo, SubscriptionGetTimestamp, SubscriptionGetQuality, SubscriptionGetValue, SubscriptionGetTag See Also I/O Device Functions
SubscriptionGetInfo
Reads the specified text information about a subscribed tag.
Syntax
sAttribute
Attribute of the tag to read. Supported Attributes are:
l
ClusterName - Return the cluster context of the subscription. For example, for the tag subscribed as "cluster1.tagname", return value is "cluster1". If the tag was subscribed without a cluster the return value will be an empty string. FullName - Return the full subscription name. For example, for the tag subscribed as "cluster1.tagname.field", return value is "cluster1.tagname.field". If the tag was subscribed without a cluster, the return value will be the tag name and/or element name. If the tag was subscribed without an element, the return value will be the tag name and/or cluster name. TagName - Return the tagname for the subscription. For example, for the tag subscribed as "cluster1.tagname", return value is "tagname". ElementName - Retrieve the element name of the subscription.
Return Value
String representation of the requested information for a subscribed tag. On error, returns an empty string and an error is set.
Related Functions
1019
SubscriptionGetQuality
Reads quality of a subscribed tag.
Syntax
SubscriptionGetQuality(iHandle ) iHandle
Integer handle of the subscription to read from.
Return Value
SubscriptionGetTag
Reads a value, quality and timestamps of a subscribed tag.
Syntax
sOffset
1020
Optional integer expressing the zero based index of an array attribute. This is only valid for the Value attribute. Default value is 0.
Return Value
Returns a value, quality and timestamps of a subscribed tag. The type of the returned value depends on a type of the subscribed tag. The quality and timestamps of the subscribed tag are read and passed with the returned value. Using SubscriptionGetValue gives similar results as using direct reference to a tag without item ex. tag1, tag1.Field. On error, returns either 0 for numerical data types or an empty string for strings.
Related Functions
SubscriptionGetTimestamp
Reads the specified timestamp of a subscribed tag.
Syntax
sAttribute
Attribute of the tag to read. Supported Attributes are:
l
Timestamp - The timestamp when the tag last changed. It is default value used when this argument is not specified. QualityTimestamp - The timestamp when quality of the tag last changed. ValueTimestamp - The timestamp when value of the tag last changed.
l l
Return Value
SubscriptionGetValue
Reads a value of a subscribed tag.
Syntax
sOffset
Optional integer expressing the zero based index of an array attribute. Default value is 0.
Return Value
Returns a value of a subscribed tag. The type of the returned variable depends on a type of the subscribed tag. The quality and timestamps of the subscribed tag are not read i.e. quality of the returned value can be consider as GOOD and its timestamps as 0 (INVALID TIMESTAMP). Using SubscriptionGetValue gives similar results as using direct reference to tags v item ex. tag1.v, tag1.Field.v. On error, returns either 0 for numerical data types or an empty string for strings.
Related Functions
1022
SubscriptionRemoveCallback
Removes a function callback from a tag subscription. The subscription handle and callback function needs to match those used when adding the callback.
Syntax
sCallback
String stating the name of the callback function.
Return Value
TagBrowseClose
The TagBrowseClose function terminates an active data browse session and cleans up resources associated with the session.
Syntax
Return Value
0 if successful -1 if unsuccessful.
Related Functions
1023
Example
// close TBResult = TagBrowseClose(TBHandle); End
TagBrowseFirst
The TagBrowseFirst function places the data browse cursor at the first record.
Syntax
Return Value
0 if successful -1 if unsuccessful.
Related Functions
WHILE (TBResult <> -1) DO ErrLog("Entry " + IntToStr(count) + ": " + "Tag: " + TagBrowseGetField(TBHandle , "TAG") + ", " + "Type: " + TagBrowseGetField(TBHandle , "TYPE") + ", " + "Addr: " + TagBrowseGetField(TBHandle , "ADDR") + ", " + "Error = " + IntToStr(IsError())); TBResult = TagBrowseNext(TBHandle); ErrLog("Next: " + IntToStr(TBResult) +
1024
TagBrowseGetField
The TagBrowseGetField function retrieves the value of the specified field from the record the data browse cursor is currently referencing.
Syntax
Fieldname:
The name of the field that references the value to be returned. Supported fields are: ADDR, ARR_SIZE, CLUSTER, COMMENT, DEADBAND, ENG_FULL, ENG_UNITS, ENG_ ZERO, EQUIPMENT, FORMAT, IODEV, PSI_TYPE, RAW_FULL, RAW_ZERO, SCALED_TYPE, TAG, ITEM, TYPE
For details on these fields refer to the Browse Function Field Reference.
Return Value
The value of the specified field as a string if successful. 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. -1 if unsuccessful.
Related Functions
1025
TagBrowseNext
The TagBrowseNext function moves the data browse cursor forward one record.
Syntax
Return Value
0 if successful -1 if unsuccessful.
Related Functions
TagBrowseNumRecords
The TagBrowseNumRecords function gets the number of records for a given browsing session. This function may not be accurate if the following occurs:
l
1026
The count will be a consolidated sum of all browse records per I/O Device as returned by each I/O Server in response to opening a browse session. The count reconciliation is performed on the basis of the best device status, that is records with the best status are picked and the others are discarded. Best device status is calculated as follows:
l l l
Data Source online state (ONLINE is picked over OFFLINE), then Data Source active state (ACTIVE is picked over INACTIVE), then Data Source priority (higher priority is picked over a lower one, with highest being 1 for primary I/O device).
Syntax
Return Value
TagBrowseOpen
The TagBrowseOpen function initiates a new browse session and returns a handle to the new session that can be used in subsequent data browse function calls. Tag records are sorted on the server and, arrive at the client in the order specified by the sorting fields parameter, or default sorting order as described below under the Sort parameter.
1027
NOTE: In order to conserve memory the following recommendations should be observed, as multiple open tag browsing sessions will use a large amount of memory: 1. Close an opened session at the completion of the browsing session using TagBrowseClose. 2. List only the fields that you wish to browse, not all fields.
Syntax
LONG TagBrowseOpen(STRING Filter, STRING Fields, STRING Sort[, STRING Clusters]) Filter:
Semicolon delimited list of predefined field name filters specifying the records to return during the browsing session. If you do not specify a filter string then all tag records will be displayed. 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*. If any of the filter names are invalid, opening a browsing session will not succeed and will return an invalid handle.
Field:
Comma separated list of record fields to be returned during the browsing session. An empty field string will return all possible fields. Supported fields are: Configuration Fields ADDR, ARR_SIZE, CLUSTER, COMMENT, DEADBAND, ENG_FULL, ENG_UNITS, ENG_ ZERO, EQUIPMENT, FORMAT, IODEV, PSI_TYPE, RAW_FULL, RAW_ZERO, SCALED_TYPE, TAG, TAG ITEM, TYPE
For full details on these fields refer to the Browse Function Field Reference. The fields LOG_UNIT and NET_UNIT available when using the Cicode functions TagInfo and TagInfoEx are also supported.
Runtime Fields Field Value OVR_ MODE CTRL_ MODE Description (predefined values) Override Mode Possible values integer (as per override mode element specification) integer (as per control mode element specification)
1028
Description (predefined values) Number of current subscriptions to the tag Default value Field value Override value Last Valid value Last Status value
as per value type as per value type as per value type as per value type integer (as per status element specification)
Sort:
Comma delimited list of record fields to be returned in order of sorting preferences (each with an indication of whether the sort is A - ascending or D - descending). For example "TYPE:D". By default tag browsing records are sorted by the tag primary key Cluster.TagName. which is implicitly appended to the list of sorting fields, since all the other fields may end up not being unique.
Clusters:
An optional parameter that specifies via a comma delimited string the subset of the clusters to browse. An empty string indicates that the all clusters will be browsed.
Return Value
TagBrowsePrev
1029
The TagBrowsePrev function moves the data browse cursor back one record. If you call this function after you have reached the beginning of a browse, error code 412 is returned (Databrowse session EOF).
Syntax
Return Value
0 if successful -1 if unsuccessful.
Related Functions
TagDebug
Displays a dialog which allows you to select from a list of the configured variable tags in your system. Once you have selected a tag, you can either press the Read button to get the tag's current value; or change the value by entering a new one, and pressing the Write button. This function should only be used for debugging or commissioning. Note: An expanded version of the TagDebug dialog is available via the Cicode function TagDebugForm. To read or change (write) the value of an element in an array variable, type it into the dialog's variable tag field as follows:
1030
Syntax
TagDebug()
Return Value
TagDebugForm
The TagDebugForm Cicode function displays a dialog that allows you to select a variable tag and perform some basic read/write operations on it. This function is useful for debugging or commissioning a project.
When the TagDebug form appears, you can perform the following tasks:
l
Select a tag You can manually enter the name of the tag you would like to debug, or you can select it from the list included in the drop-down menu to the right of the Tag field. Be aware that the drop-down list is limited to 500 tags. You can use the Filter button to help locate specific items from the tags database. A filter allows you to reduce the list of tags included in the tag drop-down menu to only those that match the characters specified in the Tag Filter dialog. To apply a filter, click on the Filter button and enter part of the name of the tag you would like to locate. The text entered can be a common suffix, it does not need to be the start of a tag name.
1031
Click OK to apply the filter, or Clear to remove it. If a filter is currently implemented, an "F" will appear next to the Filter button. An asterix (*) indicates no filter is currently being used. Once you have a tag selected, you can specify additional properties in the field to the right of the Tag field. The drop-down menu includes a list of available extensions (for example, ".Field", ".Valid", ".Override", etc.). To automatically display these additional properties when a read occurs, you should use the drop-down menu in this field instead of manually adding an extension to a tag name.
l
Read a tag The Read button will retrieve the value for the tag you have specified, or an error code will be displayed (for example, <Error 424: Tag not found>). Click on the ErrHelp button for more information about Cicode error codes. If successful, a read will display the following information about the selected tag:
l l l l
Last user request: the time the most recent read occurred. Tag Type: the data type. Base tag: confirmation of the tag name, including the selected extension. .Q (quality), .QT (quality timestamp), .VT (value timestamp), and .T (the object timestamp, which is the most recent of the two timestamps). Click on the TagExtHelp button for more information. Eng Scale: RZ = raw zero; RF = Raw Full Scale; EZ = engineering zero; EF = engineering full scale. Eng Units.
l l
Read from a tag array You view information for a particular item within a tag array using the Array Index field. This field allows you to specify the index number of the required item within the selected tag array.
Write to a tag To write a value to the selected tag, key in the required value and click on the Write button. When a write has occurred, a log entry similar to the following will be added to the syslog.dat file: <timestamp> TagDebug() Write: User 'Engineer' set tag 'Entry_ScrapWeight' to value ' 23.00' - NO ERROR
1032
The Tag's Device Status button allows you to confirm if the host device for the selected tag is currently online. In most cases, this will be useful in determining the cause of an error code, for example, <Error 424: Tag not found>. Clicking the button will update the current status of the device.
l
Use the auto-read feature The form allows for reads to be automatically repeated at a specified interval, allowing you observe how a tag value is changing over time. Clicking the Auto Read button will start the read cycle; the Stop Read button will stop it. To adjust the read period, enter a value (milliseconds) in the field next to the Auto Read button.
Syntax
TagDebugForm()
Return Value
TagEventFormat
Returns a handle to the format of the data used by the TagEventQueue().
Syntax
1033
TagEventQueue
Opens the tag update event queue. The I/O server writes events into this queue as they are processed. These events include tag updates from drivers that support time-stamped data. To read events from this queue, use the QueRead() or QuePeek() functions. The data put into the queue contains the following fields:
l l l l l l l l
Driver (the driver used to communicate with the I/O device) Port (the name of the port to which the I/O device is connected) Unit (the name of the I/O device) Tag (the variable tag name) Seconds (a UTC timestamp representing the number of seconds since 1970) Milliseconds (number of milliseconds since the last second) Value (the tag value) Quality (OPC component only equivalent to QualityGetPart, mode 7)
To use this function, you need to enable the tag update event queue with the [IOServer] EnableEventQueue parameter. This parameter will tell the I/O Server to start placing events into the queue. The function TagEventFormat() returns a handle to the format of the data placed into the string field. Enabling this formatting feature can increase CPU loading and reduce performance of the I/O Server as every tag update event 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 I/O Server will discard events.
Syntax
1034
ReadEvents()
INT status;
INT queue;
INT format;
INT eventId;
STRING event;
INT sec;
INT ms;
TIMESTAMP time;
queue = TagEventQueue();
format = TagEventFormat();
WHILE (true) DO
1035
IF status = 0 THEN
StrToFmt(format, event);
ErrLog("
ErrLog("
ErrLog("
ErrLog("
ms = FmtGetField(format, "Milliseconds");
ErrLog("
ErrLog("
ErrLog("
END
END
END
END
1036
TagGetProperty
This function reads a property of a variable tag from the datasource. This function replaces TagInfo.
Syntax
STRING TagGetProperty(STRING Name, STRING Property [, INT CachedMode] [, STRING ClusterName] ) Name:
The name of the tag or the equipment and item name of a variable tag (using equipment.item notation) from which to get information. The tag can be prefixed by the name of the cluster that is "ClusterName.Tag" or "ClusterName.Equipment.Item".
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Property:
The property to read. Property names are case sensitive. Supported properties are:
Address - Returns the configured address of the tag (as specified in the variable tags form). ArraySize - Array size of the associated tag. Returns 1 for non-array types. ClusterName - Name of the cluster the tag resides on. DataBitWidth - Number of bits used to store the value Description - Tag description EngUnitsHigh - Maximum scaled value EngUnitsLow - Minimum scaled value Equipment - Name of the equipment associated with the Tag. Format - Format bit string. The format information is stored in the integer as follows:
l l l l l
Bits 0-7 - format width Bits 8-15 - number of decimal places Bits 16 - zero-padded Bit 17- left-justified Bit 18 - display engineering units
1037
FormatDecPlaces - Number of decimal places for default format FormatWidth - Number of characters used in default format FullName - Full name of the tag in the form cluster.tagname. Item - Name of the equipment item associated with the Tag. If the tag is not resolved, returns an empty string. RangeHigh - Maximum unscaled value RangeLow - Minimum unscaled value TagName - Name of the tag specified. nType - General type of tag. Allowed values are:
l l l l l l l l l
Note: When retrieving bit width ("DataBitWidth" property) or array size ("ArraySize" property) from the local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, is a 16 bit device and does not have native LONG and REAL numbers. So when you have a LONG variable, an array of 2 INTEGERS are needed to store it. In the example, the property "DataBitWidth" against the variable will return 16 and property "ArraySize" will return 2. The combination of these two return values will add up to the correct bits. -1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable).
1038
1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
String representation of the property of the tag. If unsuccessful, an empty string and an error code is set.
Related Functions
TagGetScale
Gets the value of a tag at a specified scale from the datasource. The value is returned as a formatted string using the tags format specification and (optionally) the engineering units. Use this function to write generic Cicode that will work with any type of tag. This function replaces TagScaleStr.
Syntax
TagGetScale(STRING Name, INT Percent, INT EngUnits [, INT CachedMode] [, STRING ClusterName] ) Name:
The name of the tag, or the equipment and item name of a variable tag (using equipment.item notation). The tag can be prefixed by the name of the cluster that is "ClusterName.Tag".
1039
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Percent:
The percentage of full scale of the returned value.
EngUnits:
Flag to determine if the value is returned with engineering units:
0 - Do not return the value with engineering units 1 - Return the value with engineering units CachedMode:
Optional parameter that specifies from where to retrieve the value for the property.
-1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
1040
TagInfo
Gets information about a variable tag. This function allows you to develop generic Cicode and Super Genies.
Syntax
STRING TagInfo(STRING Name, INT Type [, STRING ClusterName] [, INT CachedMode] ) Name:
The name of the tag or the equipment and item reference of a variable tag (using equipment.item notation) from which to get information. The tag can be prefixed by the name of the cluster that is "ClusterName.Tag" or "ClusterName.Equipment.Item".
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised.
To get information on a particular element in an array, enter the array name here, followed by the number of the element as follows: "PLC_Array[9]" The above example tells the function to get information on the tenth element in PLC_Array (remember, the address of the first element in an array is 0 (zero)).
Type:
The type of information to get:
0 - The Tag name from the variables table. This is the same as sName argument. (Returned to be compatible with the AssInfo() function). 1 - Engineering units 2 - Raw zero scale 3 - Raw full scale 4 - Engineering zero scale 5 - Engineering full scale 6 - Width of the format 7 - Number of decimal places of format 8 - The Tag format as a long integer. The format information is stored in the integer as follows:
1041
l l l l l l
Bits 0-7 - format width Bits 8-15 - number of decimal places Bits 16 - zero-padded Bit 17- left-justified Bit 18 - display engineering units Bit 20 - exponential (scientific) notation
9 - Logical Unit Number - I/O device number (for internal use) 10 - Raw Type - Protocol's raw data type number for this tag. Type numbers are:
l l l l l l l l l l
0 - Digital 1 - Integer 2 - Real 3 - BCD 4 - Long 5 - Long BCD 6 - Long Real 7 - String 8 - Byte 10 - Unsigned integer
11 - Bit Width - Tag's size in bits. For example, an INT is 16 bits 12 - Unit Type - Protocol's unit type number for this tag 13 - Unit Address - Tag's address after the protocol DBF's template is applied. 14 - Unit Count - Array size. For example, if the tag's address is I1[50], the unit count is 50. 15 - Record Number - Tag's record number in variable.DBF - 1. That is, the first tag has a record number of 0. 16 - Comment - As defined in the variable tags list. 17 - ClusterName of the tag. If the tag is not resolved, returns an empty string. 18 - Full name (cluster.tagname) of the tag. If the tag is not resolved, returns an empty string. 19 - Reserved for internal operation. 20 - Configured Address of the tag. If the tag is not resolved, returns an empty string. 21 - Network Number - I/O device number (as defined by the Number field of the I/O Devices dialog). 22 - Name of the equipment associated with the Tag. If the tag is not resolved, returns an empty string.
1042
If the tag is a local variable, mode 9 error code 348 is retrieved when cache mode is 0,1,2,3. Modes 12, 13, 14 and 15 will return an empty string (error 274 is trapped).
23 - General Type.
l l l l l l l l l
0 1 2 3 4 5 6 7 8
24 - Reserved for internal use. 25 - Name of the equipment item associated with the Tag. If the tag is not resolved, returns an empty string. ClusterName
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
CachedMode:
Optional parameter that specifies from where to retrieve the value for the property.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from the local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, is a 16 bit device and does not have native LONG and REAL numbers. So if you have a LONG variable, 2 INTEGERS are needed to store it. In this case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits. -1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour).
1043
3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, This is a 16 bit device does not have native LONG and REAL numbers. So when you have a LONG variable, then 2 INTEGERS are needed to store it. In the case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits.
Return Value
TagInfoEx
This function replaces TagInfo and is identical in operation. It supports online changes. It is recommended therefore that instances of TagInfo in legacy code are migrated to either TagInfoEx or TagGetProperty. New Cicode should use TagGetProperty. Gets information about a variable tag. This function allows you to develop generic Cicode and Super Genies. Execution can be blocking or non-blocking depending on the iCached argument. Note: When replacing an instance of TagInfo with TagInfoEx in a loop, you may want to make TagInfoEx blocking using the iCached argument so that you are using the correct value for the Tag in your logic. You should also be aware that TagInfo has different return values if you are using mode 10 for nType.
Syntax 1044
STRING TagInfoEx(STRING Name, INT Type [, STRING ClusterName] [, INT CachedMode] ) Name:
The name of the tag or the equipment and item name of a variable tag (using equipment.item notation) from which to get information. The name of the tag can be prefixed by the name of the cluster that is "ClusterName.Tag" or "ClusterName.Equipment.Item".
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised.
To get information on a particular element in an array, enter the array name here, followed by the number of the element as follows: "PLC_Array[9]" The above example tells the function to get information on the tenth element in PLC_Array (remember, the address of the first element in an array is 0 (zero)).
Type:
The type of information to get:
0 - The Tag name from the variables table. This is the same as the Name argument. (Returned to be compatible with the AssInfo() function). 1 - Engineering units 2 - Raw zero scale 3 - Raw full scale 4 - Engineering zero scale 5 - Engineering full scale 6 - Width of the format 7 - Number of decimal places of format 8 - The Tag format as a long integer. The format information is stored in the integer as follows:
l l l l l l
Bits 0-7 - format width Bits 8-15 - number of decimal places Bits 16 - zero-padded Bit 17- left-justified Bit 18 - display engineering units Bit 20 - exponential (scientific) notation
9 - Logical Unit Number - I/O device number (for internal use) 10 - General Type - Protocol's general data type number for this tag. Type numbers are:
1045
l l l l l l l l l
11 - Bit Width - Tag's size in bits. For example, an INT is 16 bits 12 - Unit Type - Protocol's unit type number for this tag 13 - Unit Address - Tag's address after the protocol DBF's template is applied. 14 - Unit Count - Array size. For example, if the tag's address is I1[50], the unit count is 50. 15 - Record Number - Tag's record number in variable.DBF - 1. That is, the first tag has a record number of 0. Types 12 to 15 are only supported when iCachedMode equals to 2 or 3. 16 - Comment - As defined in the variable tags list. 17 - ClusterName of the tag. 18 - Full name (cluster.tagname) of the tag. 19 - Reserved for internal operation. 20 - Configured Address of the tag. If the tag is not resolved, returns an empty string. 21 - Network Number - I/O device number (as defined by the Number field of the I/O Devices dialog). 22 - Name of the equipment associated with the Tag. If the tag is not resolved, returns an empty string.
If the tag is a local variable, mode 9 error code 348 is retrieved when cache mode is 0,1,2,3. Modes 12, 13, 14 and 15 will return an empty string (error 274 is trapped).
23 - Reserved for internal use. 24 - Reserved for internal use. 25 - Name of the equipment item associated with the Tag. If the tag is not resolved, returns an empty string. ClusterName
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
CachedMode:
1046
Optional parameter that specifies from where to retrieve the value for the property.
-1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Note: When retrieving bit width (Type 11) or unit count (Type 14) from local configuration (iCachedMode 2), the value is related to the data structure in the device. For example, MODNET, This is a 16 bit device does not have native LONG and REAL numbers. So when you have a LONG variable, then 2 INTEGERS are needed to store it. In the case, Type 11 against the variable will return 16 and Type 14 will return 2. The combination of these two return values will add up to the correct bits.
Return Value
The value of the information as a string. If unsuccessful, an empty string is returned. The error code can be obtained by calling the IsError Cicode function.
Related Functions
TagRamp
1047
This function will increment a Tag by the amount defined by iPercentInc. It is often used for incrementing a tag while a button is held down.
Syntax
PercentInc:
The percentage by which you want to increase the value of the variable. A negative number will decrease the variable. The increment is calculated as a percentage of the full range.
Return Value
TagRDBReload
1048
Works in conjunction with the TagInfo function. Reloads the variable tag database so when TagInfo is called it picks up all online changes to the tag database.
Syntax
TagRDBReload()
Return Value
Returns 1 if the tag database was successfully reloaded, and 0 if the tag database fails to load.
Note: This function will fail and return 0 if the parameter [General]TagDB as been set to 0.
Related Functions
TagRead
Reads a variable from the I/O device. The variable tag needs to be defined in the Variable Tags database. Because the variable tag is specified as a string (not as a tag), you can ignore the data type of the variable. This function is a blocking function. It blocks the calling Cicode task until the operation is complete. TagRead should only be used when the variable tag name is a calculation such as sAlarmExt+".Paging". For simple assignment of variables use the assignment operator. For example, MyString = MyCluster.MyAlarm.MyProperty. Note: If the Tag property has not been initialized the timestamp value displayed for that tag will be equal to the Unix Epoch, January 1st 1970. If you try to read many variables at the same time, the TagRead() function may be slow. The offset index for array variables is checked against the size of the array. Note:TagRead can only return the values of elements for those tags having "Good" quality. If the quality of a tag is not "Good", TagRead returns an empty string. In order to obtain values of tags having not "Good" quality one can use their 'v' item. For example, TagRead("MyBadQualityTag.v"). However, the value returned by a TagRead call on a tag with not Good quality may be obsolete (due to TagRead
1049
asynchronous nature). Use the IsError Cicode function to control the returned error code when using this function.
Syntax
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised.
In the example below, assuming the following variable tag, equipment and item are defined in your project : Tag: PLC_Array Equipment: PLC Item: Array Address: 30000[10] You can refer to the variable tag using the following syntax: "PLC_Array" "PLC.Array" To read a particular element in an array, you can enter the array name here, followed by an index to the element as follows: "PLC_Array[9]" "PLC.Array[9]" The above example tells the function to read the 10th element in the array variable PLC_Array (remember, the address of the first element in an array is 0 (zero)). If you enter an array offset using the nOffset argument, it will be added to the index value specified here. For example, TagRead("PLC_Array[9]", 4) will read the 14th element in PLC_Array (because [9] means the 10th element, and an offset of 4 means 4 elements after the 10th = element 14). If you want to read the value of <Valid> element in the above example, TagRead("PLC_Array.Valid.V[9]", 4)
Offset:
1050
The offset for an array variable. This argument is optional - if not specified, it has a default value of 0. If you enter an array index as part of the sTag argument, it will be added to this offset value. For example, TagRead("PLC_Array[9]", 4) will read the 14th element in PLC_Array (because [9] means the 10th element, and an offset of 4 means 4 elements after the 10th = element 14).
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
The tag element value (depending on the sTag parameter, of the I/O device variable) when the tag has Good quality. The tag element value (depending on the sTag parameter, of the I/O device variable) and the error 257 (can be checked by IsError() built-in function) when the value of the tag is out of the predefined range. An empty string and an error code when the tag has not Good quality.
Related Functions
STRING sStringTagValue;
STRING sStringTagValueField;
INT nIntTagValue;
REAL fRealTagValue;
sStringTagValue = TagRead(Tag1);
1051
sStringTagValueField = TagRead(Tag1.Field);
nIntTagValue = TagRead(Tag2);
fRealTagValue = TagRead(Tag3);
See Also Tag Reference and TagReadEx() behavior in Cicode Expressions Tag Functions
TagReadEx
Reads the value, quality or timestamp of a particular tag from the I/O device. The variable tag needs to be defined in the Variable Tags database. Because the variable tag is specified as a string (not as a tag), you can ignore the data type of the variable. This function is a blocking function. It blocks the calling Cicode task until the operation is complete. TagReadEx should only be used when the variable tag name is a calculation such as sAlarmExt+".Paging". For simple assignment of variables use the assignment operator. For example, MyString = MyCluster.MyAlarm.MyProperty. If you try to read many variables at the same time, the TagReadEx() function may be slow. The offset index for array variables is checked against the size of the array. Note: TagReadEx can only return the values of elements for those tags having "Good" quality. If the quality of a tag is not Good, TagReadEx may return an obsolete value (due to TagRead asynchronous nature).
Syntax
1052
The string can refer to either the alarm name, the alarm property name, the tag name, or the equipment and item name of a variable tag (using equipment.item notation) with optional elements and items as it is defined by Tag Extensions [Cluster.]Tag[.Element][.Item][[N]] (refer to Tag Extensions for more information). If the element name is not specified, it will be resolved at runtime as an unqualified tag reference. The tag can be prefixed by the name of the cluster that is "ClusterName.Tag" or "ClusterName.Equipment.Item".
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised.
In the example below, assuming the following variable tag, equipment and item are defined in your project : Tag: PLC_Array Equipment: PLC Item: Array Address: 30000[10] You can refer to the variable tag using the following syntax: "PLC_Array" "PLC.Array" To read a particular element in an array, you can enter the array name here, followed by an index to the element as follows: "PLC_Array[9]" "PLC.Array[9]" The above example tells the function to read the 10th element in the array variable PLC_Array (remember, the address of the first element in an array is 0 (zero)). If you enter an array offset using the nOffset argument, it will be added to the index value specified here. For example, TagRead("PLC_Array[9]", 4) will read the 14th element in PLC_Array (because [9] means the 10th element, and an offset of 4 means 4 elements after the 10th = element 14). If you want to read the value of <Valid> element in the above example, TagReadEx("PLC_Array.Valid.V[9]", 4)
Offset:
The offset for an array variable. This argument is optional - if not specified, it has a default value of 0. If you enter an array offset using the nOffset argument, it will be added to the index value specified here. For example, TagReadEx("PLC_Array[9]", 4) will read the 14th element in PLC_Array (because [9] means the 10th element, and an offset of 4 means 4 elements after the 10th = element 14).
ClusterName:
1053
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
The tag element value (depending on the sTag parameter, of the I/O device variable) when the tag has Good quality. The tag element value (depending on the sTag parameter, of the I/O device variable) and the error 257 (can be checked by IsError() built-in function) when the value of the tag is out of the predefined range. A value and an error code when the tag does not have Good quality.
Related Functions
STRING sStringTagValue;
STRING sStringTagValueField;
INT nIntTagValue;
REAL fRealTagValue;
sStringTagValue = TagReadEx(Tag1);
sStringTagValueField = TagReadEx(Tag1.Field);
nIntTagValue = TagReadEx(Tag2);
1054
fRealTagValue = TagReadEx(Tag3);
TIMESTAMP t1 = TagReadEx(Tag1.T);
TIMESTAMP t2 = TagReadEx(Tag1.VT);
TIMESTAMP t3 = TagReadEx(Tag1.Qt);
QUALITY q1 = TagReadEx(Tag1.Q);
See Also Tag Reference /TagReadEx() behavior in Cicode Expressions Tag Functions
TagResolve
This function can be used to increment a reference count on a tag to keep it resolved, making it readily available to a client. If a tag is held in a resolved state, it will not be evicted from the client even if it is not being used. This means a client does not need to locate the tag's associated I/O server when a read or write is required. While this allows faster access to a tag, it should be only utilised for priority tags, as a large number of resolved tags will increase the amount of memory used. You can use the function TagUnresolve to decrement the reference count.
Syntax
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised.
Return Value
1055
The returned integer is a handle to the tag that has been resolved, or -1 if an error occurred. The specific error code is accessible by calling IsError().
Related Functions
TagScaleStr
Gets the value of a tag at a specified scale. The value is returned as a formatted string using the tags format specification and (optionally) the engineering units. Use this function to write generic Cicode that will work with any type of tag. Note: This function is being deprecated and is replaced by the TagGetScale function. If the Tag properties are updated TagScaleStr does not get the updated values whereas TagGetScale does.
Syntax
STRING TagScaleStr(STRING Tag, INT Percent , INT EngUnits [,STRING ClusterName] [, INT CachedMode] ) Tag:
The name of the tag, or the equipment and item name of a variable tag (using equipment.item notation).
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Percent:
The percentage of full scale of the returned value.
EngUnits:
Determines if the value is returned with engineering units:
0 - Return the value without engineering units 1 - Return the value with engineering units ClusterName: Name of the cluster CachedMode:
1056
Optional parameter that specifies from where to retrieve the value for the property.
-1 - The mode is determined by the INI parameter [Client] TagReadCachedMode. 0 - The property value is retrieved direct from the server in blocking mode and an error code is returned if it is not on the server (or the server is unavailable). 1 - The property value is retrieved from the cache and an error code is returned if the cache is not loaded yet. 2 - The property value is retrieved from the local configuration and an error code is returned if it is not available (this is the traditional behaviour). 3 - The property value is retrieved from the cache, if the cache is loaded, and from the local configuration, if the cache is not loaded yet.
Default value is -1.
Return Value
TagSetOverrideBad
Sets a quality Override element for a specified tag to Bad Non Specific.
Syntax
1057
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Synch:
An optional boolean argument that specifies whether the command is synchronous (blocking) or asynchronous (non- blocking). If it is specified as synchronous (blocking) the function will wait until the write has completed and returned from the server before further code execution. This parameter is "False", or asynchronous, by default. If you specify this parameter the other parameters need to be explicitly specified.
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
Setting the value of the OverrideMode element to anything other than 3 will overwrite the quality that has been applied to the Override element using this function. See the example below and OverrideMode for more details.
Tag1.OverrideMode = 0;
TagSetOverrideUncertain(Tag1);
1058
Tag1.OverrideMode = 1;
TagSetOverrideBad(Tag1);
TagSetOverrideGood
Sets a quality Override element for a specified tag to Good Non Specific.
Syntax
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Synch:
An optional boolean argument that specifies whether the command is synchronous (blocking) or asynchronous (non- blocking). If it is specified as synchronous (blocking) the function will wait until the write has completed and returned from the server before further code execution. This parameter is "False", or asynchronous, by default. If you specify this parameter the other parameters need to be explicitly specified.
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
1059
Setting the value of the OverrideMode element to anything other than 3 will overwrite the quality that has been applied to the Override element using this function. See the example below and OverrideMode for more details.
Tag1.OverrideMode = 0;
TagSetOverrideGood(Tag1);
Tag1.OverrideMode = 1;
TagSetOverrideGood(Tag1);
TagSetOverrideQuality
Sets a quality of Override element for a specified tag.
Syntax
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. qualityNew The new quality for the tags Override element. Synch
An optional boolean argument that specifies whether the command is synchronous (blocking) or asynchronous (non- blocking). If it is specified as synchronous (blocking) the function will wait until the write has completed and returned from the server before further code execution. This parameter is "False", or asynchronous, by default. If you specify this parameter the other parameters need to be explicitly specified.
ClusterName
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
TagSetOverrideQuality(Tag1, q1);
1061
Setting the value of the OverrideMode element to anything other than 3 will overwrite the quality that has been applied to the Override element using this function. See the example below and OverrideMode for more details.
Tag1.OverrideMode = 0;
QUALITY q1 = QualityCreate(QUAL_UNCR);
TagSetOverrideQuality(Tag1, q1);
Tag1.OverrideMode = 1;
QUALITY q1 = QualityCreate(QUAL_UNCR);
TagSetOverrideQuality(Tag1, q1);
TagSetOverrideUncertain
Sets a quality Override element for a specified tag to Uncertain Non Specific.
Syntax
1062
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Synch:
An optional boolean argument that specifies whether the command is synchronous (blocking) or asynchronous (non- blocking). If it is specified as synchronous (blocking) the function will wait until the write has completed and returned from the server before further code execution. This parameter is "False", or asynchronous, by default. If you specify this parameter the other parameters need to be explicitly specified.
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
Setting the value of the OverrideMode element to anything other than 3 will overwrite the quality that has been applied to the Override element using this function. See the example below and OverrideMode for more details.
Tag1.OverrideMode = 0;
1063
TagSetOverrideUncertain(Tag1);
Tag1.OverrideMode = 1;
TagSetOverrideUncertain(Tag1);
TagSubscribe
Subscribes a tag so that Cicode functions can be called when a tag's value changes. The subscription checks each poll period whether the tag has changed value and if it has, the specified callback function is called. This avoids continuously polling a tag value to monitor changes. To add a function callback to the subscription, use the optional parameter in this command or the SubscriptionAddCallback function. Multiple subscriptions are possible to the same tag. Each new subscription returns a new subscription handle. Multiple callbacks are possible to the same subscription. To unsubscribe a tag use the TagUnsubscribe function.
Syntax
TagSubscribe(STRING TagName [, INT PollTime] [, STRING ScaleMode] [, REAL Deadband] [, STRING Callback] [, INT Lightweight]) TagName
String representing the tag or tag element or the equipment and item name (using equipment.item notation) associated with that tag, to subscribe to in the form of "cluster_name.tag_name.element name" or "cluster_name.equipment. item.element name". If the element name is not specified, it will be resolved at runtime as an unqualified tag reference.
1064
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. PollTime
Optional integer representing the Datasource Poll time in milliseconds (default 250).
ScaleMode
Optional string stating the mode to subscribe. Supported modes are: Raw, Eng, Percent. Default is "Eng".
Deadband
Optional real value specifying the percentage of the variable tag's engineering range that a tag needs to change by for an update to be sent through the system. Default value is -1.0, indicating the deadband specified by the tag definition is to be used.
Callback
Optional string stating the name of a function to call when the value is updated. If an empty string is specified, no handler is registered. Default value is "" (empty string). The function should have the structure: FUNCTION evtHandler(INT subsHandle) ... END Where subsHandle is the subscription that raised the event.
Lightweight
This optional boolean argument indicates whether or not subscription updates use a "lightweight" version of the tag value that does not include a quality timestamp or a value timestamp. If not used, this option is set to 1 which means lightweight tag values will be used by default. For a client to retrieve quality and value timestamps for a tag, you should explicitly specify that a full tag value is required by setting this option to 0.
Return Value
Integer representing the subscription handle that can be used to read values, hook to events or unsubscribe. If unsuccessful, -1 is returned and an error is set. Even though a subscription handle is returned immediately, it can't be used to get attributes until the subscription has been confirmed as this is an asynchronous Cicode function call. The typical Cicode error is 423 when a subscription handled is used too soon. We recommend the use of a callback function or the direct use of the tag extension, e.g <tag>.VT
Related Functions
1065
The following example subscribes the tag "Conveyor1" in order to manually poll for attributes of the tag.
... // Get the last changed value, quality and timestamp for the tag every 1s ... // LOOP START SleepMs(1000); ErrSet(1); convValue = SubscriptionGetAttribute(subsHandle, "Value"); IF IsError() = 0 convQual = SubscriptionGetAttribute(subsHandle, "ValueQuality"); convTime = SubscriptionGetAttribute(subsHandle, "ValueTimestamp"); // Format and use data here
The following example subscribes the "conveyor1" tag as a percentage and polls it every 100ms to check for changes. When the value changes the functions OnValueChanged and ValChanged2 are called. This is the recommended way to do polling of special variables:
... INT subsHandle = TagSubscribe("Conveyor1", 100, "Percent", "OnValueChanged"); ... // Later on if no callback was registered initially, a new one can be added.. SubscriptionAddCallBack(subsHandle, "ValChanged2"); ... Function OnValueChanged(INT handle) STRING sTag; sTag = SubscriptionGetAttribute(handle, "FullName"); // If the name is needed subsVal = SubscriptionGetAttribute(handle, "Value"); subsQual = SubscriptionGetAttribute(handle, "ValueQuality");
1066
... END ... Function ValChanged2(INT handle) STRING sTag; sTag = SubscriptionGetAttribute(handle, "FullName"); // If the name is needed subsVal = SubscriptionGetAttribute(handle, "Value"); subsTime = SubscriptionGetAttribute(handle, "ValueTimestamp"); ... END ... // Remove all callbacks and unsubscribe TagUnsubscribe(subsHandle);
TagUnresolve
This function is used to decrement a reference count implemented on a tag by TagResolve. This will allow the tag to be evicted if the decrement causes its reference count to reach zero (0).
Syntax
Return Value
The returned integer represents any error that occurs when the unresolve is attempted (0 for no error).
Related Functions
TagUnsubscribe
Unsubscribes the tag subscription specified by the integer subscription handle that was returned from the TagSubscribe function. This function also removes any callbacks that are associated with the subscription.
Syntax
1067
Return Value
TagWrite
Writes to an I/O device variable by specifying the variable tag name or the variable tag name and the name of the requested element having read/write access. The variable tag needs to be defined in the Variable Tags database. Note:For this function to be successful a user needs to be logged in. This function completes asynchronously to the caller. It will be unsuccessful if the tag does not exist or if a write request could not be sent. This function does not test whether the write succeeded. In cases where the write does not succeed, TagWrite does not return a driver error code. You can use the TagReadEx function to confirm the write operation took place. TagWrite should only be used when the variable tag name is a calculation such as sAlarmExt+".Paging". For assignment of variables use the assignment operator. For example, MyCluster.MyAlarm.MyProperty = MyString. Note: When using this function and parameter [Code]ScaleCheck is set to 1, the attempt to write an out-of-range value to a device will not occur. No hardware alarm will be generated. This function checks a value before writing it to a PLC.
Syntax
TagWrite(STRING Tag, STRING sValue [, INT Offset] [, INT Synch] [, STRING ClusterName]) Tag:
1068
The string can refer to either: the variable tag name, the equipment and item name (using equipment.item notation) associated with that tag, the alarm name and the alarm property name, the tag name and the tag element name (Refer to Tag Extensions for more information). If the element name is not specified, the writing will be performed to the Field VQT element. The name of the tag can be prefixed by the name of the cluster that is "ClusterName.Tag" or "ClusterName.Equipment.Item".
Note: If the tag name exceeds the length limit of 254 characters the hardware alarm "Tag name exceed length limit" will be raised. Value:
The value to be written to the I/O device variable. The value is specified as a string, however if an integer or real is used the compiler will convert it to a string. The function converts the string into the correct format, and then writes it to the variable. To write to a particular element in an array, you can enter the array name here, followed by an index to the element as follows: "PLC_Array[9] " The above example tells the function to write to the 10th element in the array variable PLC_Array (remember, the address of the first element in an array is 0 (zero)). If you enter an array offset using the nOffset argument, it will be added to the index value. See example below.
Offset:
Optional offset for an array variable. Default is 0.
Note: If you enter an array index as part of the sValue argument, it will be added to this offset value. For example, TagWrite("PLC_Array[9]", 24, 4) will set the 14th element in PLC_Array to 24 (because [9] means the 10th element, and an offset of 4 means 4 elements after the 10th = element 14). Synch:
An optional boolean argument that specifies whether the command is synchronous (blocking) or asynchronous (non- blocking). If it is specified as synchronous (blocking) the function will wait until the write has completed and returned from the server before further code execution. This parameter is "False", or asynchronous, by default. If you specify this parameter the rest of the parameters need to be explicitly specified, including nOffset which should be set as 0 if the tag is not an array tag.
ClusterName:
Specifies the name of the cluster in which the Tag resides. The argument is enclosed in quotation marks.
Return Value
1069
TagWriteEventQue
Opens the tag write event queue. The TagWriteEventQue is a queue of data containing details of tag value changes initiated by the process. To read events from the queue, use the QueRead() or QuePeek() functions. The queue contains timestamp, tagname and value data for each change event. This queue is enabled by the corresponding INI parameter [General]TagWriteEventQue. Writes are logged to the queue for all tags whose IODevices have their Log Write parameter enabled.
Syntax
TagWriteEventQue()
Return Value
The handle of the tag write event queue, or -1 if the queue cannot be opened.
Related Functions
To enable tag logging: 1. On the client, set the INI param [General]TagWriteEventQue = 1. 2. Enable the IODevices that you want to be logged by setting their Log Write parameters to TRUE. See I/O Devices Properties.
1070
To read the queue you need to create a Cicode function. For example:
FUNCTION checkWrite() STRING sTagAndValue = ""; INT nDateTime = 0; INT hQue = TagWriteEventQue(); IF hQue = -1 THEN RETURN; END WHILE 1 DO QueRead(hQue, nDateTime, sTagAndValue, 1); Message("Value written", sTagAndValue, 64); END END
Where:
l l
nDateTime is the timestamp of the tag write. sTagAndValue is the tagname and value written to the queue.
When the function is run, successful writes to tags on the IODevice will show as a message "Value written <tagname> <value>". Note: The TagWriteEventQue is enabled on each process and will only log the data changes initiated by this process. By combining this data with the current user and machine name CitectSCADA can generate a user activity log with respect to setting data within the control system. This functionality can also be combined with CitectSCADA Reports to augment the detail of the historian data. See Also Tag Functions
1071
1072
1073
QueOpen QuePeek QueRead QueWrite ReRead SemClose SemOpen SemSignal SemWait ServerRPC Sleep SleepMS
Creates or opens a queue. Searches a queue for a queue element. Reads elements from a queue. Writes elements to a queue. ReRead is deprecated in this version. Closes a semaphore. Creates or opens a semaphore. Signals a semaphore. Waits on a semaphore. Calls a remote procedure on a Citect server. Suspends the current Cicode task for a specified time. Suspends the current Cicode task for a specified time (in milliseconds). Calls a Cicode function by specifying the function name and providing an arguments string. Gets the name of the cluster context in which the current task is executing. Retrieves a value that indicates the stop signal for a specific task. Gets the handle of a particular task. Kills a running task. Creates a new task. Creates a new task with a subscription rate. Resumes a task. Ends a task by manually triggering its stop signal. Suspends a task.
TaskCall
TaskCluster
1074
CodeSetMode
Sets various execution modes for Cicode tasks in the current thread. Using this function, you can specify whether to:
l l l l
Write to a local image of an I/O device. Check if a variable is within range before writing it to the I/O device. Echo error messages to the operator. Check the case of string data in Cicode.
Syntax
0 - Write to a local image of an I/O device. If you set Value to 1, this mode is enabled, and Cicode writes its local memory image of the I/O device whenever you write to the I/O device. (Cicode assumes that most writes to the I/O device will be done immediately). This local image might produce problems, or you might want to verify that the data was actually written to the I/O device. If you set Value to 0 (zero), this check is disabled, and Cicode does not write to the local memory image. 1 - Check if a variable is within range before writing it to the I/O device. If you set Value to 1, this mode is enabled. When a variable tag is modified, Cicode checks the new value of the variable against the Scales specified in the Variable Tags database. If the value of the variable is out of scale, Cicode generates a hardware error, and does not write to the I/O device. If you set Value to 0 (zero), this check is disabled. Cicode writes the variable to the I/O device without checking if its value is within range. 2 - Echo error messages to the operator. If you set Value to 1, this mode is enabled. When a simple user error occurs (for example, if the PageDisplay() function is passed a bad page name), Cicode displays an error message at the Error AN, and returns an error code from the function. If you set Value to 0 (zero), the echo is disabled. Cicode does not display the error message, and the output of the DspError() function is stopped.
1075
3 - Ignore the case of string data in the current thread of Cicode. If you set Value to 1, this mode is enabled, and CitectSCADA will ignore case in string data. For example, CitectSCADA will equate "Hello" to "HELLO". If you set Value to 0 (zero), CitectSCADA will be case sensitive to string data. Case sensitivity is used when a string comparison operation is performed. For example:
IF sStr1 = sStr2 THEN
(You can also make CitectSCADA case sensitive to strings in all of your Cicode, using the [Code]IgnoreCase parameter.) Value:
The value of the mode:
0 - Disable 1 - Enable
Return Value
EnterCriticalSection
Requests permission for the current thread to have access to a critical section (shared critical resource). If the critical section is already being accessed by another thread (using the EnterCriticalSection() function), the current thread will be granted access when the other thread relinquishes ownership using the LeaveCriticalSection() function. Once a thread has ownership of a critical section, it can access the same section repeatedly (using the EnterCriticalSection() function each time). Remember, however, that LeaveCriticalSection() needs to be called once for each EnterCriticalSection() used. Note: This function is process-based, not computer-based, and so is only effective for threads within the same process. Any threads attempting to gain access to this critical section will be blocked until the thread relinquishes ownership. This function will have no effect on threads running within other processes.
1076
UNINTENDED EQUIPMENT OPERATION Do not attempt to access a critical section that is already in use by another thread. This will cause the thread to be blocked until the critical section is relinquished. Failure to follow these instructions can result in death, serious injury, or equipment damage.
Syntax
EnterCriticalSection(sName) sName:
The name of the critical section. The name needs to be entered in quotation marks.
Return Value
LeaveCriticalSection
Example
/* Request access to critical section, execute code and relinquish ownership of critical section. */ FUNCTION MyCriticalFunction() EnterCriticalSection("MyCritical"); // critical code is placed here LeaveCriticalSection("MyCritical"); END
Halt
Stops the execution of the current Cicode task and returns to CitectSCADA. This function does not affect any other Cicode tasks that are running. Use this function to stop execution in nested function calls. When Halt() is called, Cicode returns to CitectSCADA and does not execute any return function calls.
Syntax
Halt()
1077
Return Value
Assert, TaskKill
Example
INT FUNCTION MyFunc(INT Arg) IF Arg<0 THEN Prompt("Invalid Arg"); Halt(); END ... END
LeaveCriticalSection
Relinquishes the current thread's ownership of a critical section (shared critical resource). Once ownership is relinquished, access to the critical section is available to the next thread that requests it (using the EnterCriticalSection() function). If a thread has been waiting for access, it will be granted at this point. LeaveCriticalSection() needs to be called once for each EnterCriticalSection() used. Note: This function is process-based, not computer-based, and so will only prevent access to a critical section within a single process. This function only works between Cicode tasks within the same process.
Syntax
LeaveCriticalSection(sName) sName:
The name of the critical section. The name needs to be entered in quotation marks.
Return Value
1078
EnterCriticalSection
Example
/* Request access to critical section, execute code and relinquish ownership of critical section. */ FUNCTION MyCriticalFunction() EnterCriticalSection("MyCritical"); // critical code is placed here LeaveCriticalSection("MyCritical"); END
MsgBrdcst
Broadcasts a message to all the clients of a server. You should call this function only on a CitectSCADA server. The message is only received by clients that have a current message session (opened with the MsgOpen() function).
Syntax
nType:
The message number.
Str:
The message text.
Return Value
1079
MsgClose
Closes a message. After the message is closed, the message post function (the callback function specified in the MsgOpen() function) is not called if a message is received. When the server side is closed, all clients are closed. When the client side is closed, only the specified client is closed.
Syntax
hMsg:
The message handle, returned from the MsgOpen() function. The message handle identifies the table where all data on the associated message is stored.
Return Value
MsgGetCurr
Gets the handle of the client message that called the report or remote procedure that is currently running. You can call this function only in a report or a remote procedure call. If the report was called by a client, this function returns that client message handle. The report can then send a message back to the client. If a function was called remotely by MsgRPC(), this function returns the message handle for the remote client.
Syntax
MsgGetCurr()
1080
Return Value
The handle for the client message. The message handle identifies the table where all data on the associated message is stored. The function returns -1 if no client called the report or function.
Related Functions
MsgOpen, MsgRPC
Example
! Send message back to the client. hMsg=MsgGetCurr(); IF hMsg<>-1 THEN MsgRPC(hMsg,"Prompt","^"Hello Client from Report Server^"",1); END
MsgOpen
Opens a message session with a CitectSCADA server. You can specify a message post function - a callback function that is automatically called when a message arrives. In this function you can call MsgRead() to get the message, and perform other tasks common to your message sessions. You can then call MsgWrite() to send a message back to the caller, MsgRPC() to call a procedure on the caller, and so on. Note: For this function to be successful a full control client should be used.
Syntax
MsgOpen(Name, Mode, Fn [, sClusterName] ) You should use MsgState() to check the return value of MsgOpen(). The message post function is set effectively only if MsgState() returns 1, which means the message session is online. You can open a client-server message session or a session between redundant servers. This function does not create extra network sessions; it uses CitectSCADA's existing sessions, so you create sessions to the Alarm Server, Report Server, Trend Server, or a named I/O Server. sName:
The name of the server to open, either:
1081
l l
For Mode 0, 1, or 3: "Alarm", "Report", "Trend", or the name of an I/O Server. For Mode 2: The default computer name, as set in the [Lan]Node parameter.
Mode:
The mode of the message session to open:
0 - Open the client side. 1 - Open the server side. 2 - Open a session from a server to the default computer name. Set Name to the computer name of the computer, as defined by the [LAN]Node parameter. 3 - Open a message session between redundant servers. (Clients cannot tell which server they are connected to or if something has changed on the server. Changes should be performed on the redundant server as well.) 4 - Open a message session from the calling process to the client process. The Name and Fn are ignored in this mode. The message session opened in this mode does not need to call MsgClose. Fn:
The message post function, that is a callback function for the message event. Set Fn to 0 if no event callback function is required.
sClusterName:
The name of the cluster the server being communicated with belongs to, this is used when mode is 0, 1 or 3. This is not required if the client is connected to only one cluster containing a server of the type set in the name parameter.
Return Value
The message handle, or -1 if the session cannot be opened. The message handle identifies the table where data on the associated message is stored.
Related Functions
1082
SELECT CASE nState CASE 1 Prompt("Message session is online!"); //Send a message to the server MsgWrite(hClient, 1, "MyMessage"); CASE -1 Prompt("Message session handle is invalid!"); CASE 0 Prompt("Message session is offline!"); CASE 2 Prompt("Message session is connecting!"); CASE 3 Prompt("Message session is disconnecting!"); CASE ELSE Prompt("Message session has unknown status!"); END SELECT ELSE Prompt("Message session could not be opened!"); END END // This function is called when the client receives a message from //the server INT FUNCTION MsgPostClient() INT Type; STRING Str; MsgRead(Type,Str); Prompt("Client recieved message: Type = "+Type:###+" Str = "+Str); RETURN 0; END
MsgRead
Reads a message from a message session. You can call this function only in a message post function (the callback function specified in the MsgOpen() function), to read the current message. The nType and Str variables of this function return the message number and the text of the message. The return value of this function is the message handle (allowing a response to be sent back if required). you need to open the message session using the MsgOpen() function, to enable the callback function.
Syntax
1083
Str:
The message text.
Return Value
MsgRPC
Calls a remote procedure on another CitectSCADA computer. You can call any of the built-in Cicode functions remotely, or your own functions. You pass the sName of the function as a string, not as the function tag, and pass all the arguments for that function in Arg. You can call the function in synchronous or asynchronous Mode. In synchronous mode, MsgRPC() does not return until the remote function is called and the result is returned. In asynchronous mode, MsgRPC() returns before the function is called, and the result cannot be returned.
Syntax
1084
sName:
The name of the function to call remotely, as a string. If this function returns an error, you should confirm that the name you have used is not a label instead of the actual function name. Some functions are aliased using a label, for example, the function _AlarmGetFieldRec is defined in the labels database as "AlarmGetFieldRec". In this case, only "_AlarmGetFieldRec" should be passed to MsgRPC.
Arg:
The arguments to pass to the function, separated by commas (,). Enclose string arguments in quotes "" and use the string escape character (^) around strings enclosed within a string. If you do not enclose the string in quotes, then the string is only the first tag found.
Mode:
The mode of the call:
The result of the remote function call (as a string). If the function is called in asynchronous mode the result of the remote function cannot be returned, so an empty string is returned.
Related Functions
1085
(Don't forget that servers are also Control Clients.) ! The Alarm tag is passed into the function as a string and a message is sent to the Alarms Server to initialize ! the AlmAckMsg() function. FUNCTION AlmAck(String AlmTag) INT hAlarm1; hAlarm1 = MsgOpen("Alarm", 0, 0); MsgRPC(hAlarm1,"AlmAckMsg",AlmTag,1); MsgClose("Alarm", hAlarm1); END ! The AlmAckMsg() function is executed on the Alarms Server that the client is connected to. This could be ! either the primary or standby Alarms Server. The function performs the alarm acknowledge. FUNCTION AlmAckMsg(String AlmTag) AlarmAckRec(AlarmFirstTagRec(AlmTag,"","")); END
MsgState
Verifies the status of a message session. Use MsgState() to check the return value of MsgOpen(). A message post function is set effectively only if MsgState() returns 1, which means the message session is online.
Syntax
MsgState(hMsg) hMsg:
The message handle, returned from the MsgOpen() function. The message handle identifies the table where all data on the associated message is stored.
Return Value
-1 if the message session handle is invalid 0 if the message session is offline 1 if the message session is online 2 if the message session is connecting 3 if the message session is disconnecting.
Related Functions
MsgOpen
1086
Example
INT hClient = -1; // Open message session on the client, connecting using the existing // message session to the current Alarm server FUNCTION MsgClientOpen() INT nState; hClient = MsgOpen("Alarm", 0, MsgPostClient); IF hClient <> -1 THEN nState = MsgState(hClient); SELECT CASE nState CASE 1 Prompt("Message session is online!"); //Send a message to the server MsgWrite(hClient, 1, "MyMessage"); CASE -1 Prompt("Message session handle is invalid!"); CASE 0 Prompt("Message session is offline!"); CASE 2 Prompt("Message session is connecting!"); CASE 3 Prompt("Message session is disconnecting!"); CASE ELSE Prompt("Message session has unknown status!"); END SELECT ELSE Prompt("Message session could not be opened!"); END END
MsgWrite
Writes a message to a message session. The message is sent to the remote computer's callback function and can be read by calling MsgRead(). If the remote computer has not opened the session, this message is disregarded. This function returns immediately after passing the message to CitectSCADA. CitectSCADA sends the message over the LAN in the background. you need to first open the message session using the MsgOpen() function, to obtain the message handle.
Syntax
1087
hMsg:
The message handle, returned from the MsgOpen() function. The message handle identifies the table where all data on the associated message is stored.
nType:
The integer message data, that is the message number.
Str:
The message text.
Return Value
MsgRead, MsgOpen
Example
MsgWrite(hMsg,10,"MyMsg");
QueClose
Closes a queue opened with the QueOpen() function. All data is flushed from the queue. If a Cicode task is waiting on the QueRead() function, it returns with a "queue empty" status. You should close all queues when they are no longer required, because they consume memory. At shutdown, CitectSCADA closes all open queues.
Syntax
QueClose(hQue) hQue:
The queue handle, returned from the QueOpen() function. The queue handle identifies the table where all data on the associated queue is stored.
Return Value
1088
Example
hQue=QueOpen("MyQue",1); ... QueClose(hQue);
QueLength
Gets the current length of the queue.
Syntax
QueLength(hQue) hQue:
The queue handle, returned from the QueOpen() function. The queue handle identifies the table where all data on the associated queue is stored.
Return Value
The current length of the queue. If the queue is closed then 0 is returned.
Related Functions
QueOpen
Open a queue for reading and writing data elements. Use this function to create a new queue or open an existing queue. Use queues for sending data from one task to another or for other buffering operations.
Syntax
1089
Mode:
The mode of the queue open:
0 - Open existing queue. 1 - Create new queue. 2 - Attempts to open an existing queue. If the queue does not exist, it will create it.
Return Value
The queue handle, or -1 if the queue cannot be opened. The queue handle identifies the table where all data on the associated queue is stored.
Related Functions
QuePeek
Searches a queue for a queue element. You can search for the element by specifying a string, an integer, or both. You can remove the element from the queue by adding 8 to the Mode. Note: This function may modify the arguments Type and Str depending on the Mode. Therefore, these arguments need to be variables. You should consider that they may be impacted by the setting for Mode when calling the function.
Syntax
1090
nType:
The number to search for (if using the search mode for a matching number). If you are using a matching string mode, the number found is returned in Type.
Str:
The string to search for (if using the search mode for a matching string). If you are using a matching number mode, the string found is returned in Str.
Mode:
The mode of the search:
1 - Search for a matching string. 2 - Search for a matching number. 4 - Search for a matching string and use a case-sensitive search. 8 - If the element is found, remove it from the queue. 16 Search the queue, in order, for the element at the offset specified by Type.
Use mode 16 when you know the location of the element you want. For example if you set Type = 0, QuePeek will return the first element in the queue, type = 2, will return the 3rd element in the queue, etc. If you specify an offset which is greater than the length of the queue, the "queue empty" error (296) is returned. You can extend the search by adding modes. For example, set Mode to 3 to search for a matching string and matching number, or set Mode to 11 to also remove the string and number from the queue.
Return Value
1091
QueRead
Reads data from a queue, starting from the head of the queue. Data is returned in the same order as it was written onto the queue and is removed from the queue when read. If the Mode is 0 (non-blocking) and the queue is empty, the function returns with an error. If the Mode is 1 (blocking) the function does not return until another Cicode task writes data onto the queue. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
nType:
The integer variable to read from the queue (written to the queue as Type by the QueWrite() function).
Str:
The string variable to read from the queue (written to the queue as Str by the QueWrite() function).
Mode:
The mode of the read:
1092
QueWrite
Writes an integer and string onto the end of a queue. The integer and string have no meaning to the queue system, they are just passed from QueWrite() to QueRead(). Queue data is written to the end of the queue. When the data is later read from the queue, it is returned on a first-in-first-out basis. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
nType:
The integer to put into the queue.
Str:
The string to put into the queue.
Return Value
ReRead
ReRead is deprecated in this version of CitectSCADA.
1093
Tags are now subscribed at the start of a function and updated tag values are sent to the subscribing function. Tag subscriptions are made at the update rate of:
l l
the graphics page if called from a page the default subscription rate as determined by [Code]TimeData if called from Cicode (default 250ms) the update rate requested of a task created using TaskNewEx the update rate requested of a subscription created using TagSubscribe
l l
You will want to verify that the subscription update rate matches the requirements of your system. After removing ReRead from looping code you may need to extend the period of the Sleep function. This is to replace the pause ReRead created while it read all the tag values.
Syntax
ReRead(Mode) Mode:
The mode of the read:
SemClose
Closes a semaphore opened with SemOpen(). You should close all semaphores when they are no longer required, because they consume memory. If any Cicode tasks are waiting on this semaphore, the tasks are released with an error. Note: This function is process-based, not computer-based, and so will only prevent access to an importantsection within a single process. This function only works between Cicode tasks within the same process.
Syntax
SemClose(hSem) hSem:
1094
The semaphore handle, returned from the SemOpen() function. The semaphore handle identifies the table where all data on the associated semaphore is stored.
Return Value
SemOpen
Opens a semaphore for access control. When the semaphore is opened, it is initially signalled. Use a semaphore for controlling access to a restricted device, for example, to stop another Cicode task accessing a device while it is in use. You might require semaphores for some Cicode operations, because they can access a device that is critical. (Cicode is a multi-tasking system.) Note: This function is process-based, not computer-based, and so will only prevent access to a critical section within a single process. This function only works between Cicode tasks within the same process.
Syntax
Mode:
The mode of the open:
0 - Open existing semaphore. 1 - Create new semaphore. 2 - Attempts to open an existing semaphore. If the semaphore does not exist, it will create it.
Return Value
1095
The semaphore handle, or -1 if the semaphore was not opened successfully. The semaphore handle identifies the table where all data on the associated semaphore is stored.
Related Functions
SemSignal
Signals a semaphore. If several Cicode tasks are waiting on this semaphore, the first task is released. This function is a blocking function. It will block the calling Cicode task until the operation is complete. Note: This function is process-based, not computer-based, and so will only prevent access to a critical section within a single process. This function only works between Cicode tasks within the same process.
Syntax
SemSignal(hSem) hSem:
The semaphore handle, returned from the SemOpen() function. The semaphore handle identifies the table where all data on the associated semaphore is stored.
Return Value
1096
SemWait
Waits on a semaphore to be signalled. This function is a blocking function. It will block the calling Cicode task until the operation is complete. Note: This function is process-based, not computer-based, and so will only prevent access to a critical section within a single process. This function only works between Cicode tasks within the same process.
Syntax
Timeout:
Semaphore time-out time:
-1 - Wait until semaphore is clear (regardless of how long). 0 - Do not wait - return immediately. (This timeout can be used to check the state.) > 0 - The number of seconds to wait if semaphore is not signalling, then return.
Return Value
0 (zero) if the semaphore has been gained, otherwise an error code is returned.
Related Functions
ServerRPC
1097
Calls a remote procedure on the Citect server specified by the ServerName argument. You can call any of the built-in Cicode functions remotely, or your own functions. You pass the Name of the function as a string and pass the arguments for that function in Arg. You can call the function in synchronous or asynchronous Mode. In synchronous mode, ServerRPC() does not return until the function call has completed on the server and the result is returned. In asynchronous mode, ServerRPC() returns before the function is called, an empty string is returned as the result cannot be returned.
Syntax
sName:
The name of the Cicode function to call remotely as string.
sArg:
The arguments to pass to the function, separated by commas (,).Enclose string arguments in quotes "" and use the string escape character (^) around strings enclosed within a string. If you forget to enclose the string in quotes, then the string is only the first tag found.
iMode:
The mode of the call:
Return Value
The result of the remote function call (as a string). If the function is called in asynchronous mode the result of the remote function cannot be returned, so an empty string is returned. If the function cannot work due to an error, empty string is also returned and the error can be obtained by calling the IsError function.
Related Functions
TaskNew, TaskNewEx
1098
Sleep
Suspends the current Cicode task for a specified number of seconds. After the time delay, the Cicode task wakes and continues execution. If the sleep time is 0, the Cicode task is pre-empted for 1 time slice only. This function does not affect any other Cicode tasks - only the task calling Sleep() is suspended. If you have Cicode that runs continuously in a loop, you should call the Sleep() function somewhere within the loop, to pause the loop and allow other tasks to run. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
Sleep(Seconds) Seconds:
The number of seconds. Set to 0 to pre-empt the task for one time-slice.
Return Value
Buttons Text Command Comment Step PLCBit=1;Sleep(2);PLCBit=0; Switch Bit ON and then OFF 2 seconds later
! Display "Hello" 10 times at 60 second intervals. WHILE I < 10 DO Sleep(60); Prompt("Hello"); I = I + 1; END
1099
! Sleep a while in polling loops WHILE < waiting for event or time> DO ! do what ever here ... Sleep(10); ! sleep a while to give other tasks a go. ! the longer the sleep the better for other tasks. END
SleepMS
Suspends the current Cicode task for a specified number of milliseconds. After the time delay, the Cicode task wakes and continues execution. This function is similar to the Sleep function but with greater resolution. Although a value of 0 milliseconds is accepted, it is not recommended. Try to use at least a value of 1. This function does not affect any other Cicode tasks; only the task calling SleepMS() is suspended. If you have Cicode that runs continuously in a loop, you should call the SleepMS() or Sleep() function somewhere within the loop, to pause the loop and allow other tasks to run. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
SleepMS(Milliseconds) Milliseconds:
The number of milliseconds (1000 milliseconds per second). Set to 0 to pre-empt the task for one time-slice. Be careful not to use a value that is too small. Setting the value to 0 would generally have no desirable effect.
Return Value
1100
Buttons Text Command Comment Step PLCBit=1;SleepMS(500);PLCBit=0; Switch Bit ON and then OFF 500 milliseconds later.
! Increment a memory variable by ten, 120 times over one minute (twice a second). I = 0; WHILE I < 180 DO SleepMS(500); iRamp = iRamp + 10; I = I + 1; END ! sleep a while in polling loops WHILE < waiting for event or time> DO ! do what ever here ... SleepMS(200); ! sleep a while to give other tasks a go. ! the longer the sleep the better for other tasks. END
TaskCall
Calls a Cicode function by specifying the function name and providing an arguments string. The function will be executed in a new Cicode task with the same cluster context as the current task. The current task will be blocked until the new task completes and a value can be returned. This function cannot be called from page foreground animation code. If this is attempted, a hardware alarm will be raised and IsError() will return 282 (Foreground Cicode cannot block). TaskCall allows the function to be called and the arguments to be provided to be specified dynamically by the cicode logic. This may be useful in some cases where the function needed is not known until runtime. CitectSCADA requests the required I/O device data and waits for the data to be returned before starting the function.
Syntax
1101
TaskCall(sName, sArgs)
sName:
The name of the function to call, as a string.
sArgs;
The arguments to pass to the function, separated by commas (,). Enclose string arguments in quotes "" and use the string escape character (^) around strings enclosed within a string.
Return Value
The result of the function call (as a string). If a void function is called, an empty string is returned. To see if an error occurred (such as an invalid function name or invalid arguments) call IsError()..
Related Functions
TaskNew, TaskNewEx
Example
STRING result; result = TaskCall(StrFill, ^"abc^",10); // result will be set to "abcabcabca"
TaskCluster
Gets the name of the cluster context in which the current task is executing.
Syntax
TaskCluster()
Return Value
The cluster name of the current context or an empty string if the task is executing without a cluster context.
Related Functions
ClusterActivate, ClusterDeactivate, ClusterFirst, ClusterGetName, ClusterIsActive, ClusterNext, ClusterServerTypes, ClusterSetName, ClusterStatus, ClusterSwapActive, TaskNew, TaskNewEx
Example
1102
TaskGetSignal
Retrieves a value that indicates the signal that is currently set for a specific task. This function can be used to check the value of the current signal before using TaskSetSignal to apply a new signal.
Syntax
TaskGetSignal(Hnd) Hnd:
The task's handle. To retreive this use the function TaskHnd().
Return Value
The value of the current signal. (0 (zero) represents normal operation, 1 indicates the task is stopped).
Related Functions
TaskHnd
Gets the task handle of a specific task. You can then use the task handle with other task functions to control the task. If you do not specify a thread name, it will default to that of the current task.
Syntax
1103
then: hTask=TaskHnd("MyTask"); will return the handle of this task. If you do not specify a thread name, it will default to that of the current task.
Return Value
The task handle, identifying the table where all data on the task is stored.
Related Functions
TaskKill
Kills a task. The Cicode task will be stopped and will not run again.
Syntax
TaskKill(hTask) hTask:
The task handle, returned from the TaskNew() or TaskHnd() function. The task handle identifies the table where all data on the associated task is stored.
Return Value
0 (zero) if successful, otherwise an error code is returned. Note: TaskKill is an abrupt way to stop a Cicode task. It can cause system errors and may have unintended consequences. Whenever possible, use TaskGetSignal and TaskSetSignal to stop Cicode tasks. Use TaskKill as a last resort and after observing the following:
1104
Do not use TaskKill to stop Cicode tasks until you have attempted the alternative methods stated above. Place the processes and devices controlled by CitectSCADA into a state preventing unintended operation before using TaskKill to stop a Cicode task.
Failure to follow these instructions can result in death, serious injury, or equipment damage.
Related Functions
TaskNew
Creates a new Cicode task and returns the task handle. You pass the sName of the function (that creates the task) as a string, not as the function tag, and pass the arguments for that function in Arg. After the task is created, it runs in parallel to the calling task. The new task will run forever unless it returns from the function or is killed by another task. By default, CitectSCADA requests necessary I/O device data and waits for the data to be returned before starting the task - the task is provided with the correct data, but there will be a delay in starting the task. If you add 16 to the Mode, CitectSCADA starts the task immediately, without waiting for any data from the I/O devices - any I/O device variable that you use will either contain 0 (zero) or the last value read.
1105
UNINTENDED EQUIPMENT OPERATION When mode 16 is used, ensure either appropriate delays are applied before processing references to tags or check qualities of tags. Otherwise, the execution system may process invalid data and returns incorrect results. Failure to follow these instructions can result in death, serious injury, or equipment damage.
You can specify that if the task is already running, the function will exit without launching a new task and an error will display. This is useful when you want only a single instance of the function running at any point in time. It is also possible to run the task within the context of a particular cluster in a multi cluster system by setting the ClusterName parameter. If a cluster is not specified, the task will use the cluster context of the caller, be it a page or Cicode task. Please be aware that the cluster context cannot be changed once the code is running. Any animation output for the new task is displayed in the window where it was created. If you want to send output to other windows, use the WinSelect() function.
Syntax
sArg:
The set of arguments to be passed to the function. Individual arguments need to be separated by commas (,). Enclose string arguments in quotes "" and use the string escape character (^) around strings enclosed within a string. If the string in quotes is not enclosed, then the string is only the first tag found. The entire set of arguments need to be enclosed in quotes ("").
Mode:
The mode of the task:
0 - Task runs forever. 1 - Task runs until the current page is changed. 2 - Task runs until the current window is freed. 4 - This mode is deprecated and not active. Currently, by default, task requests I/O device data before starting. 8 - If the task already exists, the function will exit without launching the new task. 16- Task doesn't wait for necessary I/O device data and starts immediately.
1106
You can select any one of modes 0, 1 or 2 and may add mode 4 and/or mode 8 and/or mode 16. For example, set Mode to 6 to request I/O device data before starting the task, and to run the task until the current window is freed.
sClusterName:
The name of the cluster context to be applied to the new Cicode task. This is optional if you have one cluster or are resolving the task via the current cluster context. The argument is enclosed in quotation marks "". You may pass "-" as the ClusterName argument to run the requested Cicode task without a cluster context.
Return Value
The task handle, or -1 if the task cannot be successfully created. The task handle identifies the table where data on the associated task is stored.
Related Functions
TaskNewEx
1107
Creates a new Cicode task with an individual subscription rate and returns the task handle. You pass the sName of the function (that creates the task) as a string, not as the function tag, and pass the arguments for that function in Arg. After the task is created, it runs in parallel to the calling task. The new task will run forever with tags updated at the specified time interval unless it returns from the function or is killed by another task. By default, CitectSCADA requests necessary I/O device data and waits for the data to be returned before starting the task - the task is provided with the correct data, but there will be a delay in starting the task. If you add 16 to the Mode, CitectSCADA starts the task immediately, without waiting for any data from the I/O devices - any I/O device variable that you use will either contain 0 (zero) or the last value read. Use Mode 16 when the task has to start immediately.
UNINTENDED EQUIPMENT OPERATION When mode 16 is used, ensure either appropriate delays are applied before processing references to tags or check qualities of tags. Otherwise, the execution system may process invalid data and return incorrect results. Failure to follow these instructions can result in death, serious injury, or equipment damage.
You can specify that if the task is already running, the function will exit without launching the new task and an error will display. This is useful when you want only a single instance of the function running at any point in time. It is also possible to run the task within the context of a particular cluster in a multi cluster system by setting the ClusterName parameter. If a cluster is not specified, the task will use the cluster context of the caller, be it a page or Cicode task. Please be aware that the cluster context cannot be changed once the code is running. Any animation output for the new task is displayed in the window where it was created. If you want to send output to other windows, use the WinSelect() function.
Syntax
sArg:
1108
The set of arguments to be passed to the function. Individual arguments need to be separated by commas (,). Enclose string arguments in quotes "" and use the string escape character (^) around strings enclosed within a string. If you do not enclose the string in quotes, then the string is only the first tag found. The entire set of arguments need to be enclosed in quotes ("").
Mode:
The mode of the task:
0 - Task runs forever. 1 - Task runs until the current page is changed. 2 - Task runs until the current window is freed. 4 -This mode is deprecated and not active. Currently, by default, task requests all I/O device data before starting. 8 - If the task already exists, the function will exit without launching the new task. 16- Task doesn't wait for necessary I/O device data and starts immediately.
You can select any one of modes 0, 1 or 2 and may add mode 4 and/or mode 8, and/or mode 16. For example, set Mode to 6 to request I/O device data before starting the task, and to run the task until the current window is freed.
SubscriptionRate
The subscription rate for the task, between 0 and 60000 milliseconds, which determines the frequency at which the I/ O Server reads I/O device data in order to provide tags with up-to-date Cicode variables. A value of -1 may be passed which will use the current task's subscription rate or the default value as set by the existing parameter [CODE]TimeData which defaults to 250.
sClusterName:
The name of the cluster context to be applied to the new Cicode task. This is optional if you have one cluster or are resolving the task via the current cluster context. The argument is enclosed in quotation marks "". You may pass "-" as the ClusterName argument to run the requested Cicode task without a cluster context.
Return Value
The task handle, or -1 if the task cannot be successfully created. The task handle identifies the table where data on the associated task is stored.
Related Functions
1109
TaskResume
Resumes a task that was suspended by the TaskSuspend() function. After a task is resumed, it runs on the next time-slice.
Syntax
TaskResume(hTask) hTask:
The task handle, returned from the TaskNew() or TaskHnd() function. The task handle identifies the table where all data on the associated task is stored.
Return Value
TaskSetSignal
Manually applies a signal to a specified task.
Syntax
nSignal:
Allows you to signal a specified task. Set to 0 (zero) for normal operation, 1 to stop the task or any other number that represents a defined signal.
Return Value
1110
Related Functions
TaskGetSignal, TaskHnd, TaskKill, TaskSuspend, TaskNew, TaskResume See Also Task Functions
TaskSuspend
Suspends a task. The task will stop running and will start again only when TaskResume () is called.
Syntax
TaskSuspend(hTask) hTask:
The task handle, returned from the TaskNew() or TaskHnd() function. The task handle identifies the table where all data on the associated task is stored.
Return Value
1111
1112
Marks the start of an event. Calculates the time-span of an event. Gets the current system time in string format. Gets the current time/date value.
1113
Gets hours from a time. Returns the time format currently in effect on the CitectSCADA Server. Converts a time variable into the time at midnight. Gets minutes from a time. Gets seconds from a time. Sets the new system time. Converts a time/date value to an OLE DATE value Converts a time/date variable into a string. Determines the local time bias from UTC at a specified time.
Date
Gets the current date in string format. Note: Time/Date functions can only be used with dates between 1980 and 2035. You should check that the date you are using is valid with Cicode similar to the following:
Syntax
Format of the string: 0 - Short time format, hh:mm AM/PM. 1 - Long time format, hh:mm:ss AM/PM.
1114
2 - Short date format, dd/mm/yy. 3 - Long date format, day month year. 4 - Time and date, weekday month day year hh:mm:ss AM/PM. 5 - Long time period, hh:mm:ss. Time needs to be in seconds. 6 - Millisecond time period, hh:mm:ss.xxx ("xxx" represents milliseconds). Time needs to be in milliseconds. 7 - Short time period, hh:mm. Time needs to be in seconds. 8 - Long time period, "xxxxx Days hh Hours mm min ss sec where xxxxx = number of days since 1/1/1970". Time needs to be in seconds. 9 - Extended date format, dd/mm/yyyy. 10 - Local TimeDate format, yyyy-mm-dd hh:mm:ss 11 - Time of Day, hh:mm:ss tt format with no date UTC:
Coordinated Universal Time (optional)
0 - Display the string as a local date/time (default). 1 - Display the string as a UTC date/time (valid for formats 0-4 and 9).
If omitted, the default Format is 2. These formats follow the Regional Settings found in the Windows Control Panel.
Return Value
DateAdd
1115
Adds time (in seconds) to a time/date value. The return value is in time/date variable format. Use this function for time and date calculations.
Syntax
AddTime:
The time to add, in seconds.
Return Value
TimeToStr, DateSub
Example
DateVariable=DateAdd(StrToDate("3/11/91"),86400); ! Adds 24 hours to 3/11/91. NewDate=TimeToStr(DateVariable); ! Sets NewDate to 4/11/91.
DateDay
Gets the day of the month from a time/date variable. Time/date functions can only be used with dates between 1980 and 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
DateDay(Time) Time:
The time/date variable.
1116
Return Value
Date
Example
! If the current system date is 3rd November 1991; Variable=DateDay(TimeCurrent()); ! Sets Variable to 3.
DateInfo
Returns the date format currently used on the CitectSCADA Server.
Syntax
1 - The current date order: l "0" - MMDDYY l "1" - DDMMYY l "2" - YYMMDD. 2 - The current date delimiter. 3 - The current short date format. 4 - The current long date format. 5 - The current extended date format. 6 - The short weekday string. The particular weekday returned is determined by the nExtra argument. 7 - The long weekday string. The particular weekday returned is determined by the nExtra argument. 8 - The short month string. The particular month returned is determined by the nExtra argument. 9 - The long month string. The particular month returned is determined by the nExtra argument. nExtra:
1117
When an nInfo argument of 6 or 7 is specified, the nExtra argument determines which weekday (17) is returned by the DateInfo() function. When an nInfo argument of 8 or 9 is specified, the nExtra argument determines which month (1-12) is returned by the DateInfo() function. The nExtra argument is ignored if any other nInfo value is passed to the function.
Return Value
Current date order ("0" for MMDDYY, "1" for DDMMYY, "2" for YYMMDD; Current date delimiter; Current short date format; Current long date format; Current extended date format; Short weekday string; Long weekday string; Short month string; Long month string;
TimeInfo
Example
! If the current system date is the fourth of December 2002; TwelfthMonth=DateInfo(9,12); ! Sets TwelfthMonth to "December".
DateMonth
Gets the month from a time/date variable. Note: Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
1118
Syntax
DateMonth(Time) Time:
The time/date variable.
Return Value
Date
Example
! If the current system date is 3rd November 1991; Variable=DateMonth(TimeCurrent()); ! Sets Variable to 11.
DateSub
Subtracts time (in seconds) from a time/date value. The return value is in time/date variable format. Use this function for time and date calculations.
Syntax
SubTime:
The time to subtract, in seconds.
Return Value
1119
Related Functions
Date, DateAdd
Example
Variable=DateSub(StrToDate("05/11/91"),StrToDate("03/11/91")); ! Sets Variable to number of seconds between 2 date/times. Str=TimeToStr(Variable,5); ! Sets Str to "48:00:00".
DateWeekDay
Gets the day of the week from a time/date variable. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
DateWeekDay(Time) Time:
The time/date variable.
Return Value
An integer representing the day of the week as follows: 1 - Sunday 2 - Monday 3 - Tuesday 4 - Wednesday 5 - Thursday 6 - Friday 7 - Saturday
Related Functions 1120
Date, TimeCurrent
Example
! If the current system date is Sunday, 3rd November 1991; Variable=DateWeekDay(TimeCurrent()); ! Sets Variable to 1.
DateYear
Gets the year from a time/date variable. Time/date functions can only be used with dates between 1980 and 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
Mode:
The format required:
0 - Short year, yy. If you use this mode during the year 2000, 0 (zero) will be returned. 1 - Long year, yyyy
If omitted, the default Mode is 0.
Return Value
The year as an integer. Note: In the year 2000, this function will return 0 (zero) if mode 0 (zero) is used.
Related Functions
Date
1121
Example
! If the current system date is 3rd November 1991; Variable=DateYear(TimeCurrent(),0); ! Sets Variable to 91. ! If the current system date is 18th October 2000; Variable=DateYear(TimeCurrent(),0); ! Sets Variable to 0. Variable=DateYear(TimeCurrent(),1); ! Sets Variable to 1991.
OLEDateToTime
Converts an OLE DATE value (stored in a REAL) to a CitectSCADA time/date value. Note: An OLE DATE representing a local time in the daylight savings(DST) to standard time(Std) transition period will be converted to the DST value internally. For example, if the DST transition is 30/3/2003 2:00:00 Std, the local time will behave in the following manner: 2:00:00 DST -> 2:59:59 DST -> 2:00:00 Std. Because of this, a value representing the period between 2:00:00 and 2:59:59 on that date will be interpreted as 2:00:00 DST, not Std.
Syntax
Local:
0 - OleDate represents a UTC time. 1 - OleDate represents a Local time.
Return Value
TimeCurrent, TimeToOLEDate
Example
1122
Real = TimeToOLEDate(TimeCurrent(), 1); ! Sets Real to the local date/time value TimeVariable = OLEDateToTime(Real, 1); ! Sets TimeVariable to the value of Real when interpreted as Local time.
SysTime
Gets the CitectSCADA internal system millisecond counter. The counter is not based on time, but counts from 0 up to the maximum integer value and then back to 0. You can use this function to time events down to the millisecond level, either by subtracting the current SysTime from the SysTime at the start of the event, or by using the SysTimeDelta() function (which will give the same result). The SysTime() function does not return the time of day. Use the Time() or TimeCurrent() function to obtain the time of day. Time/date functions can only be used with dates between 1980 and 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
SysTime()
Return Value
1123
SysTimeDelta
Calculates the time difference between a start time and the current time, and updates the start time to the current time. You can time continuous events in a single operation. See the SysTime() function for information on its use. Time/date functions can only be used with dates between 1980 and 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
SysTimeDelta(Start) Start:
The start time returned from the SysTime() function.
Return Value
The time difference from a start time and the current time.
Related Functions
SysTime
Example
Start=SysTime(); ! Gets the current time. ... Delay1=SysTimeDelta(Start); ! Sets Delay1 to the time difference from Start. ... Delay2=SysTimeDelta(Start); ! Sets Delay2 to the time difference from the last SysTimeDelta() call.
Time
1124
Gets the current time in string format. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
0 - Short time format, hh:mm AM/PM 1 - Long time format., hh:mm:ss AM/PM
If omitted, the default Format is 0.
Return Value
Date, TimeToStr
Example
! If the current time is 10:45:30; Variable=Time(); ! Sets Variable to "10:45". Variable=Time(0); ! Sets Variable to "10:45 AM". Variable=Time(1); ! Sets Variable to "10:45:30 AM".
TimeCurrent
Gets the current system time/date in time/date variable format. Please be aware that CitectSCADA stores time as the number of seconds since 01/01/1970. You can convert this value into usable date and time variables by using the various Date and Time functions.
1125
Time/date functions can only be used with dates between 1980 and 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
TimeCurrent()
Return Value
A time/date variable.
Related Functions
StrToDate, StrToTime
Example
! If the current system time is 11:43:10 a.m.; TimeVariable=TimeToStr(TimeCurrent(),0); ! Sets TimeVariable to "11:43".
TimeHour
Gets the hour value from a time/date variable. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
TimeHour(Time) Time:
The time/date variable.
1126
Return Value
TimeCurrent
Example
! If the current system time is 11:43:10 a.m.; HoursVariable=TimeHour(TimeCurrent()); ! Sets HoursVariable to 11.
TimeInfo
Returns the time format currently used on the CitectSCADA Server.
Syntax
TimeInfo(nInfo) nInfo:
Determines the contents of the string returned by the TimeInfo() function. Valid values and resulting strings are:
1- The current time hour format: l "0" - 12 hour l "1" - 24 hour 2- The current time delimiter. 3- The current morning time extension. 4- The current evening time extension.
Return Value
Current time hour format ("0" for 12 hour, "1" for 24 hour) Current time delimiter Current morning time extension Current evening time extension
Related Functions
DateInfo
1127
Example
! If the current system time is 15:43:10.; ClockType=TimeInfo(1); ! Sets ClockType to "1".
TimeMidNight
Returns the number of seconds between midnight on January 1, 1970, and the midnight immediately prior to the specified time/date. This function is useful for performing calculations with the time and date. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
TimeMidNight(Time) Time:
The time/date variable.
Return Value
A time/date variable.
Related Functions
TimeCurrent
Example
timeNow = TimeCurrent(); ! get the time variable at 7am today time7am = TimeMidNight(timeNow) + 7*60*60; IF timeNow > time7am AND timeNow < time7am + 10 THEN Beep(); Prompt("Wake Up!"); END
1128
TimeMin
Gets the minutes value from a time/date variable. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
TimeMin(Time) Time:
The time/date variable.
Return Value
TimeCurrent
Example
! If the current system time is 11:43:10 a.m. MinutesVariable=TimeMin(TimeCurrent()); ! Sets MinutesVariable to 43.
TimeSec
Gets the seconds value from a time/date variable. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ...
1129
Syntax
TimeSec(Time) Time:
The time/date variable.
Return Value
TimeSet
Sets the new system time. You can set the time only on the computer which this function is called. Time/date functions can only be used with dates from 1980 to 2035. If you call TimeSet without the required privileges to change the system time you will receive a hardware alarm indicating this. Note: that when using Vista, UAC needs to be disabled in order for the time to be set.
Syntax
TimeSet(Time) Time:
The time/date variable to which the new time is set. Sets the time on this computer only.
Return Value
1130
DateInfo
Example
! set the time to 11:43 on June 23 1993 time = StrToTime("11:43:00") + StrToDate("23/6/93"); TimeSet(time);.
TimeToOLEDate
Converts a CitectSCADA time/date value to an OLE DATE value (this should be stored in a REAL).
Syntax
Local: 0 - The return value is output as UTC time. 1 - The return value is output as Local time.
Return Value
TimeCurrent, OLEDateToTime
Example
Real = TimeToOLEDate(TimeCurrent(), 1); ! Sets Real to the local date/time value
TimeToStr
1131
Converts a time/date variable into a string. Use this function for calculating time differences or run times, and so on. Set Format to 6 to convert time periods that are in milliseconds, such as the times that are returned from the SysTime() and SysTimeDelta() functions. Note: Once a date/time is retrieved as UTC, the string cannot be used by the Cicode functions StrToDate and StrToTime to synthesize a date/time value as these functions support local time only. Time/date functions can only be used with dates from 1980 to 2035. You should check that the date you are using is valid with Cicode similar to the following:
IF StrToDate(Arg1)>0 THEN ... ELSE ... END
Syntax
Format:
Format of the string:
0 - Short time format, hh:mm AM/PM. 1 - Long time format, hh:mm:ss AM/PM. 2 - Short date format, dd/mm/yy. 3 - Long date format, day month year. 4 - Time and date, weekday month day year hh:mm:ss AM/PM. 5 - Long time period, hh:mm:ss. Time needs to be in seconds. 6 - Millisecond time period, hh:mm:ss.xxx ("xxx" represents milliseconds). Time needs to be in milliseconds. 7 - Short time period, hh:mm. Time needs to be in seconds. 8 - Long time period, "xxxxx Days hh Hours mm min ss sec where xxxxx = number of days since 1/1/1970". Time needs to be in seconds. 9 - Extended date format, dd/mm/yyyy. 10 - Local TimeDate format, yyyy-mm-dd hh:mm:ss 11 - Time of Day, hh:mm:ss tt format with no date UTC:
1132
0 - Display the string as a local date/time (default). 1 - Display the string as a UTC date/time (valid for formats 0-4 and 9).
Return Value
A string containing the converted time/date or period variable, or an empty string if invalid.
Related Functions
TimeUTCOffset
Determines the local time bias from UTC that was in force at a specified time. For example, US Pacific Standard Time is -8 hrs from UTC, so -28800 would be returned (-8 hours x 60 minutes x 60 seconds). However, if the specified time occurred during daylight saving, the returned value would be -7 hours (or -25200 seconds).
Syntax
TimeUTCOffset(Time) Time:
The time/date variable.
Return Value
1133
1134
TimestampSub TimestampToTimeInt
VariableTimestamp
StrToTimestamp
This function converts timestamp in a STRING format into a TIMESTAMP format. This function can be used in browsing functions to convert timestamp fields returned as a string.
Syntax
1135
TIMESTAMP StrToTimestamp(STRING String [, INT Format [, INT UTC]]) String: The date and time as a STRING or TIMESTAMP Format: The format of the string. Should be 15. Other types reserved for future use. UTC: If 1, the date is considered to be in UTC. Otherwise, local time is used. This field is only applicable for format STRING formats (i.e. format is not equal 15).
Return Value
This function returns a date in TIMESTAMP format if successful, otherwise returns TIMESTAMP of January 1, 1601, 00:00:00 (UTC). If the function is unsuccessful you can call the IsError() function to get the actual error code.
Related Functions
SchdSpecialItemAdd, SchdSpecialItemDelete, SchdSpecialItemGetField, SchdConfigGetField, SchdGetField, SchdOpen, SchdSpecialItemAdd, ScheduleItemAdd, ScheduleItemModify, ScheduleItemSetRepeat See Also Scheduler Functions Timestamp Functions
TimeIntToTimestamp
Converts a time INTEGER which is represented as a number of seconds since 01/01/1970 to a TIMESTAMP
Syntax
Millesecond:
The number of milliseconds since last second (optional).
UTC:
Coordinated Universal Time (optional): 0 The given time INTEGER is a local date/time.
1136
Return Value
TIMESTAMP t1 = TimeIntToTimestamp(TimeInt);
TimestampAdd
Adds an offset to a TIMESTAMP variable.
Syntax
Offset:
The offset to add, expressed in units of the part parameter
Part:
Indicates which part to add:
1137
0 Offset is in years. 1 Offset is in months. 2 Offset is in days. 3 - Offset is in hours. 4 - Offset is in minutes. 5 - Offset is in seconds (default) 6 - Offset is in milliseconds
Return Value
TimestampCurrent
Return the current system date and time as a TIMESTAMP variable.
Syntax
TimestampCurrent()
Return Value
1138
TimestampCreate
Returns a TIMESTAMP variable created from the parts.
Syntax
TimestampCreate(INT Year, INT Month, INT Day, INT Hour, INT Minute, INT Second, INT Millisecond [, INT bUtc]) Timestamp:
The timestamp from which the part will be extracted.
Year:
The year part.
Month:
The month part.
Day:
The day part.
Hour:
The hour part.
Minute:
The minute part.
Second:
The second part.
Millisecond:
The millisecond part.
1139
UTC:
Coordinated Universal Time (optional): 0 The given time INTEGER is a local date/time. 1 The given time INTEGER is a UTC date/time (default).
Return Value
TimestampDifference
Returns the difference between two TIMESTAMP variables as a number of milliseconds.
Syntax
Timestamp 2:
The TIMESTAMP variable 2.
Part:
The type of time units being used for the result:
1140
0 Result is in years. 1 Result is in months. 2 Result is in days. 3 - Result is in hours 4 - Result is in minutes. 5 - Result is in seconds (default). 6 - Result is in milliseconds.
bCumulative: Defines how to pass results which values are greater than their time units (see example below). 0 Non-cumulative 1 Cumulative mode (default).
Return Value
The time period between Timestamp1 and Timestamp2. The value is equal or greater than zero. If error, returns 0 with an error code.
Related Functions
1141
TimestampFormat
Format a TIMESTAMP variable into a string.
Syntax
Format:
The format of the string is the same as .NET Framework DateTime format. Specifically be reminded that the format is case sensitive. For example 'MM' is the zero padded month number, whereas 'mm' is the zero padded current minute within the hour. Therefore no Year, Day or Seconds will be displayed if they are specified in uppercase as: YYYY, DD, SS. The correct display will only occur when they are specified in lowercase as: yyyy, dd, ss. A short list of formats are included below extracted from the"Custom Date and Time Format Strings" in the Microsoft .NET Framework Developer's Guide from the MSDN Library. It is recommended that you confirm its currency by consulting the source information periodically. Use the following single-character format strings by themselves to choose predefined standard date and time formats:
l l l l l l l l l l l l l l l
d Short date pattern. Ex. "6/15/2009" D Long date pattern. Ex. "Monday, June 15, 2009" f Full date/time pattern (short time). Ex. "Monday, June 15, 2009 1:45 PM" F Full date/time pattern (long time). Ex. "Monday, June 15, 2009 1:45:30 PM" g General date/time pattern (short time). Ex. "6/15/2009 1:45 PM" G General date/time pattern (long time). Ex. "6/15/2009 1:45:30 PM" M or m Month/day pattern. "June 15" O or o Round-trip date/time pattern. Ex. "2009-06-15T13:45:30.0900000" R or r RFC1123 pattern. Ex. "Mon, 15 Jun 2009 20:45:30 GMT" s Sortable date/time pattern. Ex. "2009-06-15T13:45:30" t Short time pattern. Ex. "1:45 PM" T Long time pattern. Ex. "1:45:30 PM" u Universal sortable date/time pattern. Ex. "2009-06-15 20:45:30Z" U Universal full date/time pattern. Ex. "Monday, June 15, 2009 8:45:30 PM" Y or y Year month pattern. Ex. "June, 2009"
1142
For all the examples above, the input time/date is assumed to be 6/15/2009 1:45:30 PM with Windows set to the en-US locale. Many of the formats will change according to the current Windows locale. You may combine the following format specifiers to make up custom format specifications:
l l l l l l
d The day of the month, from 1 through 31. dd The day of the month, from 01 through 31. ddd The abbreviated name of the day of the week. dddd The full name of the day of the week. f Fraction of a second. Returns one decimal place for each 'f', up to 'fffffff' F Fraction of a second, if non-zero. Returns one decimal place for each 'f', up to 'fffffff' g, gg The period or era. h The hour, using a 12-hour clock from 1 to 12. hh The hour, using a 12-hour clock from 01 to 12. H The hour, using a 24-hour clock from 0 to 23. HH The hour, using a 24-hour clock from 00 to 23. K Time zone information. m The minute, from 0 through 59. mm The minute, from 00 through 59. M The month, from 1 through 12. MM The month, from 01 through 12. MMM The abbreviated name of the month. MMMM The full name of the month. s The second, from 0 through 59. ss The second, from 00 through 59. t The first character of the AM/PM designator. tt The AM/PM designator. y The year, from 0 to 99. yy The year, from 00 to 99. yyy The year, with a minimum of three digits. yyyy The year as a four-digit number. yyyyy The year as a five-digit number. z Hours offset from UTC, with no leading zeros. zz Hours offset from UTC, with a leading zero for a single-digit value. zzz Hours and minutes offset from UTC. : The time separator. / The date separator. "string" or 'string' Literal string delimiter. % Defines the following character as a custom format specifier.
l l l l l l l l l l l l l l l l l l l l l l l l l l l l
1143
l l
\ The escape character. Any other character The character is copied to the result string unchanged.
UTC:
Coordinated Universal Time (optional): 0 - Returns the time as a local date/time (default). 1 - Returns the time as a UTC date/time.
Return Value
TimestampGetPart
Returns one part (year, month, day, etc) of the TIMESTAMP variable.
Syntax
Part:
Indicates which part to extract: 0 The year part
1144
1 The month part. 2 The day part. 3 The hour part. 4 The minute part. 5 The second part. 6 The millisecond part. 7 - The number of milliseconds since midnight last occurred.
UTC:
Coordinated Universal Time (optional): 0 The given time INTEGER is a local date/time.(default). 1 The given time INTEGER is a UTC date/time.
Return Value
TimestampSub
Subtracts an offset from a TIMESTAMP variable.
Syntax
1145
Offset:
The offset to subtract, expressed in units of the part parameter
Part:
Indicates which part to subtract: 0 Offset is in years. 1 Offset is in months. 2 Offset is in days. 3 - Offset is in hours. 4 - Offset is in minutes. 5 - Offset is in seconds (default) 6 - Offset is in milliseconds
Return Value
TimestampToStr
Converts a TIMESTAMP variable into a string.
Syntax
1146
Format:
The format number determines which of date/time patterns are used for formatting returned string. Date/time patterns are defined in regional settings on a particular computer and can vary depend on national or individual preferences. The possible format numbers together with examples based on en-US regional settings are listed below: 0 Short time format, hh:mm. 1 Long time format, hh:mm:ss. 2 Short date format, dd/MM/yyyy. 3 Long date format, dddd, dd MMMM yyyy. 4 Short date & short time format, dd/MM/yyyy hh:mm. 5 Short date & long time format, dd/MM/yyyy hh:mm:ss. 6 Long date & short time format, dddd, dd MMMM yyyy hh:mm. 7 Long date & long time format, dddd, dd MMMM yyyy hh:mm:ss. 8 Month day format, dd MMMM. 9 Year month format, MMMM yyyy. 10 RFC1123 format, ddd, dd MMM yyyy hh:mm:ss GMT 11 Sortable date time format, yyyy-MM-ddThh:mm:ss 12 Short universal format, yyyy-MM-dd hh:mm:ssZ 13 Long universal format, dddd, dd MMMM yyyy hh:mm:ss 14 Long Time & millisecond, hh:mm:ss.fff 15 - Date and time as a 64-bit value specified by the number of 100-nanosecond intervals since January 1, 1601 .
Return Value
A string containing the converted time/date or period variable, or an empty string if invalid.
Related Functions
1147
TimestampToTimeInt
Converts a TIMESTAMP variable into a time INTEGER which is represented as a number of seconds since 01/01/1970.
Syntax
UTC:
Coordinated Universal Time (optional): 0 Returns the time as a local date/time. 1 Returns the time as a UTC date/time (default)
Return Value
Time as a number of seconds since 01/01/1970 in UTC or local time depending on the last input parameter,-1 if invalid.
Related Functions
1148
VariableTimestamp
Extracts the timestamp from a given variable.
Note: This function is designed to be used within Cicode; using it on graphical pages may result in displaying an error message instead of an expected timestamp message when either its argument has not good quality or an execution error is set.
Syntax
nType:
The type of timestamp: 0 The elements date/time (default) 1 The elements quality date/time 2 The elements value date/time
Return Value
A TIMESTAMP of the given variable depending on the type. If Variable is NULL, returns INVALID_TIMESTAMP. Timestamps of uninitialized stack variables, uninitialized code variables and constants are equal to 0 - invalid timestamp, while their qualities are GOOD
Related Functions
1149
Example
INT codeVariable = 1;
INT
FUNCTION
MyFunction(REAL arg1)
TIMESTAMP ts;
ts = VariableTimestamp(codeVariable, 0);
//code variable
ts = VariableTimestamp(arg1, 0);
//function argument
ts = VariableTimestamp(str, 0);
//stack variable
ts = VariableTimestamp(Tag1, 0);
RETURN 1;
END
1150
Opens a trend browse session. Gets the previous trend entry in the browse session. Gets information about the trend that is being displayed at the AN point. Prints two trends (one overlaid on the other), each with up to four trend tags. Deletes a trend created by the TrnNew() function. Deletes an old history file from the trend system. Enables and disables the echo on the trend display. Stores event trend data and the associated time stamp in an event table and time table, for a specified trend tag.
TrnComparePlot
1151
Stores event trend data and time data (including milliseconds) for a specified trend tag. Sets trend data from a table, for a specified trend tag. Sets event trend data and time data (including milliseconds) for a specified trend tag. Exports trend data to the clipboard. Exports trend data to a file in CSV (comma separated values) format. Exports trend data to a file in dBASE III format. Exports trend data to applications via DDE. Flushes the trend to disk. Gets the event number of a trend at an offset for a pen. Gets the trend time at an offset for a pen. Gets the trend value at an offset for a pen. Gets the name of the cluster the trend graph is associated with. Gets the event number of a trend at the trend cursor. Gets the time (in milliseconds from the previous midnight) at a trend cursor for a specified pen. Gets the position of the trend cursor. Gets the time/date at the trend cursor. Gets the current trend cursor value of a pen. Gets the current trend cursor value of a pen as a formatted string. Gets the default engineering zero and full scales of a trend tag. Gets the display mode of a trend.
TrnExportClip TrnExportCSV
TrnExportDBF TrnExportDDE TrnFlush TrnGetBufEvent TrnGetBufTime TrnGetBufValue TrnGetCluster TrnGetCursorEvent TrnGetCursorMSTime TrnGetCursorPos TrnGetCursorTime TrnGetCursorValue TrnGetCursorValueStr TrnGetDefScale TrnGetDisplayMode
1152
TrnGetEvent
Gets the event number of a trend at a percentage along the trend. Gets the format of a pen. Returns the internally stored value for <GATED>. Returns the internally stored value for <TRN_NO_VALUES>. Gets the display mode of trends (historical or real-time). Gets the time (in milliseconds from the previous midnight) of the trend (plotted by a specified pen) at a percentage along the trend,using the time and date of the latest sample displayed. Gets the trend tag of a pen. Gets the comment of a trend pen. Gets the number of the pen currently in focus. Gets the pen number of a pen name. Gets the display period of a trend. Gets the scale of a pen. Gets the scale of a pen as a formatted string. Gets the span time of a trend. Stores trend data in an array. Gets the time/date of a pen. Gets the data units of a trend pen. Gets the configured values of a trend tag. Determines whether a logged trend value is <VALID>, <GATED>, or invalid <TRN_NO_VALUES>. Creates a new trend at run time.
TrnGetPen TrnGetPenComment TrnGetPenFocus TrnGetPenNo TrnGetPeriod TrnGetScale TrnGetScaleStr TrnGetSpan TrnGetTable TrnGetTime TrnGetUnits TrnInfo TrnIsValidValue
TrnNew
1153
TrnPlot TrnPrint TrnSamplesConfigured TrnScroll TrnSelect TrnSetCursor TrnSetCursorPos TrnSetDisplayMode TrnSetEvent TrnSetPen TrnSetPenFocus TrnSetPeriod TrnSetScale TrnSetSpan TrnSetTable TrnSetTime
Prints a plot of one or more trend tags. Prints a trend that is displayed on the screen. Gets the number of samples configured for the currently displayed trend. Scrolls a trend pen. Sets up a page for a trend. Moves the trend cursor a specified number of samples. Moves the trend cursor to the given x-axis position. Specifies how trend samples will be displayed on the screen. Sets the start event of a trend pen. Sets a trend pen to a new trend tag. Sets the pen focus. Sets the display period (time base) of a trend. Re-scales a pen. Sets the span time of a trend. Sets trend data from an array. Sets the starting time/date of a pen.
The following trend functions are used on standard trend templates. Use these functions only if you create your own trend templates (These functions are written in Cicode and can be found in the include project.)
TrendDspCursorComment TrendDspCursorScale TrendDspCursorTag Displays the Trend Comment for the currently selected pen.
Displays a scale value for the current pen. Displays the tag name of the current pen.
1154
Displays the cursor time of the current pen. Displays the cursor value of the current pen. Gets the AN number of the trend under the mouse position. Displays a pop-up trend with the specified trend pens. Initializes the cursor and rubber-band features on a trend page. Sets the starting date for the pens on a trend. Sets the scale of one or more pens on a trend. Sets the span time of a trend. Sets the starting time for the pens on a trend. Sets a new sampling period for a trend. Displays a trend page (in a new window) with the specified trend pens. Zooms a trend in either one or both axes.
TrendZoom
TrendDspCursorScale
Displays a scale value for the current pen in the current pen font.
Syntax
Percent:
The percentage of full scale to display for the current pen, as an integer.
Return Value
1155
Related Functions
TrendDspCursorScale, TrendDspCursorComment, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendDspCursorTag
Displays the trend tag name of the current pen in the pen font.
Syntax
Mode:
An optional argument used to specify whether the trend tag name is displayed with a cluster prefix. Set:
l l
0 display tag without cluster prefix (default) 1 display tag with cluster prefix.
Return Value
TrendDspCursorScale, TrendDspCursorComment, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendDspCursorTime
Displays the cursor time of the current pen in the current pen font.
1156
Syntax
Format:
Format of the string:
0 - Short time format, hh:mm AM/PM. 1 - Long time format, hh:mm:ss AM/PM. 2 - Short date format, dd/mm/yy. 3 - Long date format, day month year. 4 - Time and date, weekday month day year hh:mm:ss AM/PM. 5 - Long time period, hh:mm:ss. Time needs to be in seconds. 6 - Millisecond time period, hh:mm:ss:xxx ("xxx" represents milliseconds). Time needs to be in milliseconds. 7 - Short time period, hh:mm. Time needs to be in seconds. 8 - Long time period, days:hh:mm:sec. Time needs to be in seconds. 9 - Extended date format, dd/mm/yyyy. Note: If Format is set to 1, 2, or 3, the mode will be ignored when the sampling period of the trend changes to less than 1 second. Instead, the time is displayed as hh:min:ss.xxx, that is, displayed as mode 6.
Return Value
TrendDspCursorScale, TrendDspCursorComment, TrendDspCursorTag, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendDspCursorValue
1157
Display the cursor value of the current pen in the current pen font.
Syntax
TrendDspCursorValue(nAN) AN:
The AN of the trend.
Return Value
TrendDspCursorScale, TrendDspCursorComment, TrendDspCursorTag, TrendDspCursorTime, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendGetAn
Gets the AN number of the trend beneath the current mouse position.
Syntax
TrendGetAn()
Return Value
The AN of the trend, or 0 (zero) if the mouse is not positioned over a valid trend.
Related Functions
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendPopUp
1158
Displays a pop-up trend with the specified trend pens. You need to create the trend page with the graphic builder and set the pen names to blank.
Syntax
sTag1:
The First trend tag to display on the page.
sTag2..sTag8:
The trend tags to display on the page.
Return Value
Buttons Text Command Comment Popup Trend TrendPopUp("MyPop", "PV1", "PV2", "PV3") Display a popup trend with three trend pens
TrendRun
Initializes the cursor and rubber-band features on a trend page. This function is included as a Cicode Object on all new trend pages. Only use this function when configuring a trend template that requires this functionality.
Syntax
TrendRun(iPageType) iPageType:
1159
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendSetDate
Sets the end date for all pens on a trend. Samples taken after this date will not be displayed. You can enter the date in the Value argument, or leave the Value blank - a form is then displayed in run time for the operator to enter an end date.
Syntax
Value:
The new date, as a string. Samples taken after date will not be displayed. This argument is optional.
Return Value
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendSetScale
Sets the scale of the current pen or of all pens on a trend. You can enter a scale in the Value argument, or leave the Value blank. A form is then displayed in run time for the operator to enter a value for the scale.
Syntax
Percent:
The scale to be set:
Return Value
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetSpan, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendSetSpan
Sets the span time of the trend. The span time is the time period covered in the trend window. You can enter a span time in the Value argument, or leave the Value blank - a form is then displayed in run time for the operator to enter a value for the span time.
Syntax
1161
Value:
An optional value for the span time, as a string.
Return Value
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetTime, TrendSetTimebase, TrendZoom
Example
TrendSetTime
Sets the end time for all the pens on a trend. Samples taken after this time will not be displayed. You can enter an end time in the Value argument, or leave the Value blank - a form is then displayed in run time for the operator to enter a value for the end time.
Syntax
Value:
An optional value for the end time, as a string. Samples taken after this time will not be displayed.
Return Value
1162
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTimebase, TrendZoom
Example
TrendSetTimebase
Sets a new sampling period for a trend. You can enter a sampling period in the Value argument, or leave the Value blank. A form is then displayed in run time for the operator to enter a value for the sampling period.
Syntax
Value:
An optional value for the sampling period, as a string.
Return Value
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendZoom
Example
TrendWin
1163
Displays a trend page (in a new window) with the specified trend pens. You need to create the trend page with the graphic builder and set the pen names to blank. You then display that page by calling this function and pass the required trend tags. The function will create a new window with the specified window mode.
Syntax
X:
The x pixel coordinate of the top left corner of the window.
Y:
The y pixel coordinate of the top left corner of the window.
Mode:
The mode of the window:
0 - Normal page. 1 - Page child window. The window is closed when a new page is displayed, for example, when the PageDisplay() or PageGoto() function is called. The parent is the current active window. 2 - Window child window. The window is closed automatically when the parent window is freed with the WinFree() function. The parent is the current active window. 4 - No re-size. The window is displayed with thin borders and no maximize/minimize icons. The window cannot be re-sized. 8 - No icons. The window is displayed with thin borders and no maximize/minimize or system menu icons. The window cannot be re-sized. 16 - No caption. The window is displayed with thin borders, no caption, and no maximize/minimize or system menu icons. The window cannot be re-sized. 32 - Echo enabled. When enabled, keyboard echo, prompts, and error messages are displayed on the parent window. This mode should only be used with child windows (for example, Mode 1 and 2). 64 - Always on top. 128 - Open a unique window. This mode helps prevent this window from being opened more then once. 256 - Display the entire window. This mode commands that no parts of the window will appear off the screen
1164
512 - Open a unique Super Genie. This mode helps prevent a Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened. 1024 - Disables dynamic resizing of new window, overriding the setting of the [Page]DynamicSizing parameter.
You can select multiple modes by adding modes together (for example, set Mode to 9 to open a page child window without maximize, minimize, or system menu icons).
sTag1:
The firs trend tag to display on the page.
sTag2..sTag8:
The trend tags to display on the page.
Return Value
Buttons Text Command Comment Trend Window TrendWin("MyTrend", 0, 0, 4, "PV1", "PV2", "PV3") Display a trend page in a new window with no maximize and minimize icons
TrendZoom
"Zooms" a specified trend in either one or both axes. Set the zoom values (TimeZoom and/or ScaleZoom) to greater than one to "zoom in" or to less than one to "zoom out". If you specify a destination AN, you can zoom one trend (at SourceAn) onto another (at DestAn), in the same way as on the standard zoom trend page.
Syntax
SourceAN:
The AN on which the source trend is located.
TimeZoom:
The scale by which the Time axis will be changed (as a real number).
ScaleZoom:
The scale by which the Scale axis will be changed (as a real number).
DestAn:
The AN on which the destination or target trend is located. If you do not enter a DestAn, it is set to the same AN as SourceAn.
Return Value
TrendDspCursorScale, TrendDspCursorTag, TrendDspCursorTime, TrendDspCursorValue, TrendGetAn, TrendRun, TrendSetDate, TrendSetScale, TrendSetSpan, TrendSetTime, TrendSetTimebase
Example
TrendZoom(30, 2.0, 2.0); /* Zoom in by a factor of 2 on both the time and scale axes. */ TrendZoom(30, 0.5, 0.5); /* Zoom out by a factor of 2 on both the time and scale axes. */
TrnAddHistory
Adds an old (backed up) trend history file to the trend system so that its data can be used. When you back-up a trend file, change its extension so that it indicates the age of the file's trend data (for example, the month and year). An archived trend file does not need to reside in the same directory as existing active trends. CitectSCADA retrieves the trend name from the header of the specified file and adds its data to the trend history. Please be aware that only a reference to the archived file, and not the file itself, is kept in the trend history. Therefore, care needs to be taken if using this function to access archived files residing on removable storage media. When you remove the media, the archived data is no longer available for display.
1166
This function can only be used if the Trend Server is on the current machine. When the Trend Server is not in the calling process, this function will become blocking and cannot be called from a foreground task. In this case, the return value will be undefined and a Cicode hardware alarm will be raised.
Syntax
sClusterName:
Specifies the name of the cluster in which the Trend Server resides. This is optional if you have one cluster or are resolving the trend server via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
TrnDelHistory, MsgRPC
Example
TrnAddHistory("C:\CITECT\DATA\TR1.MAY91"); ! Adds the file TR1.MAY91 to the trend system.
TrnBrowseClose
The TrnBrowseClose 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. TrnBrowseClose(iSession) iSession
The handle to a browse session previously returned by a TrnBrowseOpen call.
Return Value
0 (zero) if the trend browse session exists, otherwise an error code is returned.
1167
Related Functions
TrnBrowseFirst, TrnBrowseGetField, TrnBrowseNext, TrnBrowseNumRecords, TrnBrowseOpen, TrnBrowsePrev See Also Trend Functions
TrnBrowseFirst
The TrnBrowseFirst 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
TrnBrowseFirst(iSession) iSession
The handle to a browse session previously returned by a TrnBrowseOpen call.
Return Value
0 (zero) if the trend browse session exists, otherwise an error code is returned.
Related Functions
TrnBrowseClose, TrnBrowseGetField, TrnBrowseNext, TrnBrowseNumRecords, TrnBrowseOpen, TrnBrowsePrev See Also Trend Functions
TrnBrowseGetField
The TrnBrowseGetField 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
FieldName
The name of the field that references the value to be returned. Supported fields are:
1168
ACQERROR, AREA, EQUIPMENT, EXPRESSION, FILENAME, FILES, LSL, PRIV, RANGE, SDEVIATION, SPCFLAG, STORMETHOD, SUBGRPSIZE, TIME, TRIGGER, USL, XDOUBLEBAR.
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. This should be checked in this instance to determine if an error has actually occurred.
Related Functions
TrnBrowseNext
The TrnBrowseNext 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
TrnBrowseNext(iSession) iSession
The handle to a browse session previously returned by a TrnBrowseOpen call.
0 (zero) if the trend browse session exists, otherwise an error code is returned.
Related Functions
TrnBrowseClose, TrnBrowseFirst, TrnBrowseGetField, TrnBrowseNumRecords, TrnBrowseOpen, TrnBrowsePrev See Also Trend Functions
TrnBrowseNumRecords
The TrnBrowseNumRecords 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
TrnBrowseNumRecords(iSession) iSession
The handle to a browse session previously returned by a TrnBrowseOpen 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
1170
TrnBrowseOpen
The TrnBrowseOpen 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
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:
ACQERROR, AREA, EQUIPMENT, EXPRESSION, FILENAME, FILES, LSL, NAME, PRIV, RANGE, SDEVIATION, SPCFLAG, STORMETHOD, SUBGRPSIZE, TAGGENLINK, TIME, TRIGGER, TYPE, USL, XDOUBLEBAR.
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 if unsuccessful. The returned entries will be ordered alphabetically by name.
Related Functions
1171
... iSession = TrnBrowseOpen("NAME=ABC*", "NAME,TYPE", "ClusterA,ClusterB"); IF iSession <> -1 THEN // Successful case ELSE // Function did not succeed END ...
TrnBrowsePrev
The TrnBrowsePrev 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
TrnBrowsePrev(iSession) iSession
The handle to a browse session previously returned by a TrnBrowseOpen call.
Return Value
0 (zero) if the trend browse session exists, otherwise an error code is returned.
Related Functions
TrnBrowseClose, TrnBrowseFirst, TrnBrowseGetField, TrnBrowseNext, TrnBrowseNumRecords, TrnBrowseOpen See Also Trend Functions
TrnClientInfo
Gets information about the trend that is being displayed at the AN point.
Syntax
1172
Pen:
The trend pen number:
1 - The number of samples configured for the trend. If you select Type 1, the Data argument is ignored. Data:
For future enhancements; is currently ignored.
Error:
An output argument. If the function is successful, the error is set to 0 (zero). If unsuccessful, an error value is set, and a hardware alarm is triggered.
Return Value
The requested information (as a string) if successful, otherwise a hardware alarm is generated.
Related Functions
TrnInfo
Example
INT nError; INT nSamples; INT nTime; !Gets the number of samples configured for the current pen of the trend displayed at AN 30. nSamples = TrnClientInfo(30, 0, 1, "", nError); IF nError = 0 THEN nTime = nSamples * 50; ELSE nTime = 0; END
TrnComparePlot
1173
Prints two trends, one overlaid on the other. Each trend can have up to four tags configured on it. The significance of this type of plot is that the two trends show different times and display periods. It is possible to compare a trend tag or tags over different time slots. Each trend line is drawn with a different pen style and marker as appropriate. The trend plot includes a comment and a legend, and you can specify the vertical high and low scales. For more advanced trend plotting, you can use the low-level plot functions.
Syntax
TrnComparePlot(sPort, sTitle, sComment, AN, iMode, nSamples, iTime1, rPeriod1, iTime2, rPeriod2, Tag1......Tag8, rLoScale1, rHiScale1,......rLoScale8, rHiScale8) sPort:
The name of the printer port to which the plot 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.
sTitle:
The title of the trend plot.
sComment:
The comment that is to display beneath the title of the trend plot. You do not have to enter a comment.
nAN:
Sets the display mode. A value of 0 causes the default display mode to be used. Otherwise, the display mode of the specified AN is set.
iMode:
The color mode of the printer.
iTime1:
The end point in time (the most recent point) for the first trend.
rPeriod1:
The period (in seconds) of the first trend. This can differ from the actual trend period. If you do not enter a period, it defaults to the sample period of Tag1.
iTime2:
1174
The end point in time (the most recent point) for the second trend.
rPeriod2:
The period (in seconds) of the second trend. This can differ from the actual trend period. If you do not enter a period, it defaults to the sample period of Tag5.
Tag1. . .Tag8:
The trend tags for the plot. Tags 1 to 4 needs to be for the first trend, and tags 5 to 8 needs to be for the second.
The minimum and maximum on the vertical scale for the trend line of each of the tags (Tag1. . . Tag8)
Return Value
TrnDelete
Deletes a trend that is displayed on a current page. This trend may have been created by the TrnNew() function or by a trend object.
Syntax
1175
TrnDelete(nAN) nAN:
The AN where the trend is located.
Return Value
TrnNew
Example
TrnDelete(20); ! Deletes the trend at AN20.
TrnDelHistory
Removes a trend history file that has been added to the trend system by the TrnAddHistory() function. This function does not delete the file completely, it only disconnects it from the historical trend system. This function can only be used if the Trend Server is on the current machine. When the Trend Server is not in the calling process, this function will become blocking and cannot be called from a foreground task. In this case, the return value will be undefined and a Cicode hardware alarm will be raised.
Syntax
sClusterName:
Specifies the name of the cluster in which the Trend Server resides. This is optional if you have one cluster or are resolving the trend server via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
1176
TrnAddHistory, MsgRPC
Example
TrnDelHistory("C:\CITECT\DATA\TR1_91.MAY"); ! Disconnects the file from the trend system.
TrnEcho
Enables and disables the echo of the trend display. Use this function when you need to make many changes to a trend display, so that the display updates only once. You should first disable the trend echo, do all the trend changes, and then enable the echo to show the changes.
Syntax
nMode:
The mode of the echo:
0 - Disable echo of the trend display. 1 - Enable echo of the trend display, to show changes.
Return Value
The current echo mode, otherwise 0 (zero) is returned, and an error code is set. You can call the IsError() function to get the actual error code.
Related Functions
TrnSetScale, TrnSetPeriod
Example
! Disable echo of trend display at AN40 TrnEcho(40,0); ! Change the scales on pens 1 and 2 TrnSetScale(40,1,0,-1000); TrnSetScale(40,1,100,-1000); TrnSetScale(40,2,0,-1000); TrnSetScale(40,2,100,-1000); ! Enable echo to show changes to the display
1177
TrnEcho(40,1);
TrnEventGetTable
Stores event trend data in an event table and the associated time stamp in a time table, for a specified trend tag. Data is stored at the specified Period, working backwards from the starting point specified by EventNo. If Period differs from the trend period configured in the Trend Tags database, the values to be stored are calculated from the trend data. Values are either averaged or interpolated. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax
EventNo:
The starting event number for entries in the trend table.
Period:
The time difference between tabulated trend values (in seconds). For example, if you set this period to 30 seconds, CitectSCADA will get the last trend value (sampled at the end of the trend section), then get the trend value that was sampled 30 seconds before that, and so on until it reaches the start time of the trend section. If this period is different to the trend's sampling period, the trend values will be averaged or interpolated. Set to 0 (zero) to default to the actual trend period.
Length:
The number of trend values to store in the trend table, from 1 to the maximum number of items in the table.
Table:
The Cicode array in which the trend data is stored. You can enter the name of an array here (see the example).
TimeTable:
The table of integer values in which the time stamp is stored.
1178
Mode:
The Display Mode parameters allow you to enter a single integer to specify the display options for a trend (for a maximum of eight trends). To calculate the integer that you should enter for a particular trend, select the options you want from the list below, adding their associated numbers together. The resulting integer is the DisplayMode parameter for that trend. Invalid/Gated trend options:
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Ordering trend sample options:
0 - Order returned trend samples from oldest to newest. 2 - Order returned trend samples from newest to oldest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option :
n - the number of missed samples that the user wants to gap fill) x 4096.
The options listed in each group are mutually exclusive. The default value for each Display Mode is 258 (0 + 2 + 256).
sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
The actual number of samples read. The return value is 0 if an error is detected. You can call the IsError() function to get the actual error code. If EventNo is 0 (zero) then the EventNo will be set to the current event number.
Related Functions
1179
TrnEventGetTableMS
Stores event trend data and time data (including milliseconds) for a specified trend tag. The event trend data is stored in an event table, and the time stamp in time tables. Data is stored at the specified Period, working backwards from the starting point specified by EventNo. If Period differs from the trend period configured in the Trend Tags database, the values to be stored are calculated from the trend data. Values are either averaged or interpolated. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax
TrnEventGetTableMS(Tag, EventNo, Period, Length, Table, TimeTable, Mode, MSTimeTable [, sClusterName] ) Tag:
The trend tag enclosed in quotation marks "" (can be prefixed by the name of the cluster that is ClusterName.Tag).
EventNo:
The starting event number for entries in the trend table.
Period:
The time difference between tabulated trend values (in seconds). For example, if you set this period to 30 seconds, CitectSCADA will get the last trend value (sampled at the end of the trend section), then get the trend value that was sampled 30 seconds before that, and so on until it reaches the start time of the trend section. If this period is different to the trend's sampling period, the trend values will be averaged or interpolated. Set to 0 (zero) to default to the actual trend period.
Length:
The number of trend values to store in the trend table, from 1 to the maximum number of items in the table.
Table:
The Cicode array in which the trend data is stored. You can enter the name of an array here (see the example).
TimeTable:
The table of integer values in which the time stamp is stored.
1180
Mode:
The Display Mode parameters allow you to enter a single integer to specify the display options for a trend (for a maximum of eight trends). To calculate the integer that you should enter for a particular trend, select the options you wish to use from those listed below, adding their associated numbers together. The resulting integer is the DisplayMode parameter for that trend. Invalid/Gated trend options:
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Ordering trend sample options:
0 - Order returned trend samples from oldest to newest. 2 - Order returned trend samples from newest to oldest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option :
n - the number of missed samples that the user wants to gap fill) x 4096.
Note: Options listed in each group are mutually exclusive. The default value for each Display Mode is 258 (0 + 2 + 256).
MSTimeTable:
The table of integer values in which the millisecond component of the time stamp is stored.
sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
The actual number of samples read. The return value is 0 if an error is detected. You can call the IsError() function to get the actual error code.
Related Functions
1181
TrnEventSetTable
Adds new event to a trend, or overwrites existing points with new values. To add new events, set 'EventNo' to zero. The events are inserted at a point determined by the time stamp associated with each event. If the timestamp of a new event is identical to that of an existing event, the new event will overwrite the old one. To overwrite specific existing events, set 'EventNum' to the last event number of the block of events to be overwritten, and set the times of the new events to zero. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax
EventNo:
Event Number:
l l
When adding new events to a trend, set EventNo to 0. When overwriting existing values, set EventNo to the last event number to be overwritten. For example, if overwriting events 100 to 110, set EventNo to 110.
Length:
The number of trend values in the trend table.
Table:
The table of floating-point values in which the trend data is stored. You can enter the name of an array here (see the example).
TimeTable:
The table of integer values in which the time stamp is stored. If you would like events to stay in correct time-stamp order, sort the values in this table in ascending order. When EventNo is non-zero the values in this table may be zero. This will result in the values of the requested events being overwritten but the time-stamps staying the same.
sClusterName:
1182
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
The actual number of samples written. The return value is 0 if an error is detected. You can call the IsError() function to get the actual error code.
Related Functions
TrnEventGetTable
Example
REAL TrendTable1[100]; INT TimeTable[100]; /* Defines an array of a maximum of 100 entries. Assume that TrendTable1 has been storing data from a source. */ TrnEventSetTable("OP1",nEventNo, 1,10,TrendTable1[0], TimeTable[0], "ClusterXYZ"); /* A set of 10 trend data values are set for the OP1 trend tag. */
TrnEventSetTableMS
Sets event trend data and time data (including milliseconds) for a specified trend tag. The event trend data is set in an event table, and the time stamp in time tables. Data is set at the period specified, working backwards from the starting point specified by EventNo. If the period of setting data differs from the trend period (defined in the Trend Tags database), the values to be set are calculated from the trend data, either averaged or interpolated. The user needs to have the correct privilege (as specified in the Trend Tags form), otherwise the data is not written. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax
1183
EventNo:
Event Number:
l l
When adding new events to a trend, set EventNo to 0. When overwriting existing values, set EventNo to the last event number to be overwritten. For example, if overwriting events 100 to 110, set EventNo to 110.
Period:
This will be the interval (in seconds) between trend values when they are set (that is it will be the perceived sampling period for the trend). This period can differ from the actual trend period. Set to 0 (zero) to default to the actual trend period.
Length:
Number of trend values in the trend table.
Table:
Table of floating-point values in which the trend data is stored. You can enter the name of an array here (see example).
TimeTable:
Table of integer values in which the time stamp is stored. If you would like events to stay in correct time-stamp order, sort the values in this table in ascending order. When EventNo is non-zero the values in this table may be zero. This will result in the values of the requested events being overwritten but the timestamps staying the same.
MSTimeTable:
The table of integer values in which the millisecond component of the time stamp is stored.
sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
The actual number of samples written. The return value is 0 if an error is detected. You can call the IsError() function to get the actual error code.
Related Functions
TrnEventGetTable
Example
// Arrays for trend data
1184
REAL garSingleValue[1]; INT ganSingleTime[1]; INT ganSingleMS[1]; // Push the data in the trend system INT FUNCTION LogTrend(STRING sTagName, REAL rValue, INT nDateTime, INT nMS) INT nSamplesWritten; garSingleValue[0] = rValue; ganSingleTime[0] = nDateTime; ganSingleMS[0] = nMS; nSamplesWritten = TrnEventSetTableMS (sTagname, 0, 0, 1, garSingleValue[0], ganSingleTime[0], ganSingleMS[0], "ClusterXYZ"); RETURN nSamplesWritten; END
TrnExportClip
Exports trend data to the Windows Clipboard. The data is set at the specified Time and Period, and listed from earliest to latest. Any gated or invalid data is written as 0.0. Data is stored as a grid, with each row time-stamped. The first column/field is the date, followed by the time, followed by the tags 1 to 8. You can use the ClipMode argument to make the output more useful. For example, to paste the data into Excel, use ClipMode 2 for CSV format. If you use ClipMode 1 or 3, the default paste menu option causes data to be pasted into the user's spreadsheet as text. If you use ClipMode 3, use the Paste Special option to paste the required format. Please be aware that not all packages support multiple clipboard formats in this way.
Syntax
TrnExportClip(Time, Period, Length, Mode, ClipMode, sTag1 ... sTag8, iDisplayMode1 ... iDisplayMode 8) Time:
The starting time for the data being exported.
Period:
The period (in seconds) of the entries being exported. (This period can differ from the actual trend period.)
Length:
1185
The length of the data table, that is The number of rows of samples to be exported. for example if you put the length as 12, and you declare two tags to be exported, you get a grid with 12 rows of samples. Each row has values for each of the two tags making a total of 24 samples.
Mode:
The format mode to be used: Periodic trends
1 - Export the Date and Time, followed by the tags. 2 - Export the Time only, followed by the tags. 4 - Ignore any invalid or gated values. (Only supported for periodic trends.) 8 - The time returned will have millisecond accuracy.
Event trends
1 - Export the Time, Date and Event Number, followed by the tags. 2 - Export the Time and Event Number, followed by the tags. 8 - The time returned will have millisecond accuracy. ClipMode:
The format for the data being exported.
1 - Text 2 - CSV
You can add these modes for a combination of formats.
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Invalid and gated samples that are not converted to zero will appear in the destination file as the string "na" (for invalid) or "gated". Ordering trend sample options:
1186
0 - Order returned trend samples from newest to oldest. 2 - Order returned trend samples from oldest to newest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option :
n - the number of missed samples that the user wants to gap fill) x 4096.
Display as Periodic options:
0 - Display according to trend type. 1048576 - Display as periodic regardless of trend type.
Return Value
0 (zero) if successful, otherwise an error code is returned. Note: If using this function to export trends by using event numbers, you need to specify a valid event number in the Time argument, rather than a time.
Related Functions
ClipSetMode, TrnExportCSV
Example
TrnExportClip(TimeCurrent(), 2, 60 * 60/2, 2, 3, "Feed", "Weight"); /* Export the last hour of data from the trend tags Feed and Weight to the clipboard in both Text and CSV formats. Be aware that the 60 * 60/2 is a decomposed way or writing 1800, which is the number of 2 second samples in 1 hour. */
TrnExportCSV
1187
Exports trend data to a file in CSV (Comma Separated Variable) format. The data is set at the specified Time and Period, and listed from earliest to latest. Any gated or invalid data is written as 0.0. Data is stored as a grid, with each row time-stamped. The first column/field is the date, followed by the time, followed by the tags 1 to 8. You can view the CSV file with a text editor, and import the file directly into other packages such as Excel for data analysis and presentation. If you're using this function to export trends by using event numbers, you need to specify a valid event number in the Time argument, rather than a time.
Syntax
TrnExportCSV(Filename, Time, Period, Length, Mode, sTag1 ... sTag8, iDisplayMode1 ... iDisplayMode 8) Filename:
The name of the destination path and file.
Time:
The starting time for the data being exported.
Period:
The period (in seconds) of the entries being exported. (This period can differ from the actual trend period.)
Length:
The length of the data table, that is, The number of rows of samples to be exported. for example if you put the length as 12, and you declare two tags to be exported, you get a grid with 12 rows of samples. Each row has values for each of the two tags making a total of 24 samples.
Mode:
The format mode to be used: Periodic trends
1 - Export the Date and Time, followed by the tags. 2 - Export the Time only, followed by the tags. 4 - Ignore any invalid or gated values. (This mode is only supported for periodic trends.) 8 - The time returned will have millisecond accuracy.
Event trends
1 - Export the Time, Date and Event Number, followed by the tags. 2 - Export the Time and Event Number, followed by the tags.
1188
8 - The time returned will have millisecond accuracy. sTag1 ... sTag8:
The trend tag names for the data being exported.
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Invalid and gated samples that are not converted to zero will appear in the destination file as the string "na" (for invalid) or "gated". Ordering trend sample options:
0 - Order returned trend samples from newest to oldest. 2 - Order returned trend samples from oldest to newest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option:
n - the number of missed samples that the user wants to gap fill) x 4096.
Options listed in each group are mutually exclusive.
Return Value
1189
TrnExportDBF, TrnPrint
Example
TrnExportCSV("c:\TrnData.CSV", TimeCurrent(), 2, 60 * 60/2, 2, "Feed", "Weight"); /* Export the last hour of data from the trend tags Feed and Weight. The 60 * 60/2 is a decomposed way or writing 1800, which is the number of 2 second samples in 1 hour. */
TrnExportDBF
Exports trend data to a file in dBASE III format. The data is set at the specified Time and Period, and listed from earliest to latest. Any gated or invalid data is written as 0.0. Data is stored as a grid, with each row time-stamped. The first column/field is the date, followed by the time, followed by the tags 1 to 8. You can import the DBF file directly into other packages such as Excel, for data analysis and presentation.
Syntax
TrnExportDBF(Filename, Time, Period, Length, Mode, sTag1 ... sTag8, iDisplayMode1 ... iDisplayMode 8) Filename:
The name of the destination path and file.
Time:
The starting time for the data being exported.
Period:
The period (in seconds) of the entries being exported. (This period can differ from the actual trend period.)
Length:
The length of the data table, that is The number of rows of samples to be exported. for example if you put the length as 12, and you declare two tags to be exported, you get a grid with 12 rows of samples. Each row has values for each of the two tags making a total of 24 samples.
Mode:
The format mode to be used:
1190
Periodic trends
1 - Export the Date and Time, followed by the tags. 2 - Export the Time only, followed by the tags. 4 - Ignore any invalid or gated values. (This mode is only supported for periodic trends.) 8 - The time returned will have millisecond accuracy.
Event trends
1 - Export the Time, Date and Event Number, followed by the tags. 2 - Export the Time and Event Number, followed by the tags. 8 - The time returned will have millisecond accuracy. sTag1 ... sTag8:
The trend tag names for the data being exported. Tag names longer than 10 characters will be truncated, as the standard DBF field format is 10 characters.
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Invalid and gated samples that are not converted to zero will appear in the destination file as the string "na" (for invalid) or "gated". Ordering trend sample options:
0 - Order returned trend samples from newest to oldest. 2 - Order returned trend samples from oldest to newest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples.
Stretch method options:
1191
128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option:
n - the number of missed samples that the user wants to gap fill) x 4096.
Options listed in each group are mutually exclusive.
Return Value
TrnExportCSV, TrnPrint
Example
TrnExportDBF("c:\TrnData.DBF", TimeCurrent(), 2, 60 * 60/2, 2, "Feed", "Weight"); /* Export the last hour of data from the trend tags Feed and Weight. Be aware that the 60 * 60/2 is a decomposed way or writing 1800, which is the number of 2 second samples in 1 hour. */
TrnExportDDE
Exports trend data via DDE. The data is set at the specified Time and Period, and listed from earliest to latest. Any gated or invalid data is written as 0.0. Data is stored as a grid, with each row time-stamped. The first column/field is the date, followed by the time, followed by the tags 1 to 8. You can use the DDEMode argument to make the output more useful. For example; to paste the data into Excel, use DDEMode 2 for CSV format. If you use DDEMode 1, data will be put into the user's spreadsheet as text. Note: If you're using this function to export trends by using event numbers, you need to specify a valid event number in the Time argument, rather than a time.
Syntax
TrnExportDDE(sApplication, sDocument, sTopic, Time, Period, Length, Mode, DDEMode, sTag1 ... sTag8, iDisplayMode1 ... iDisplayMode 8) sApplication:
The application name to export the data.
1192
sDocument:
The document in the application to export the data.
sTopic:
The topic in the application to export the data. Be aware you may have to use a special topic format to make the data export correctly. See your application documentation for details; For example with Excel you need to specify the matrix of rows and columns as "R1C1:R8C50" depending on the size of the data.
Filename:
The name of the destination path and file.
Time:
The starting time for the data being exported.
Period:
The period (in seconds) of the entries being exported. (This period can differ from the actual trend period.)
Length:
The length of the data table, that is The number of rows of samples to be exported. for example if you put the length as 12, and you declare two tags to be exported, you get a grid with 12 rows of samples. Each row has values for each of the two tags making a total of 24 samples.
Mode:
The format mode to be used: Periodic trends
1 - Export the Date and Time, followed by the tags. 2 - Export the Time only, followed by the tags. 4 - Ignore any invalid or gated values. (This mode is only supported for periodic trends.) 8 - The time returned will have millisecond accuracy.
Event trends
1 - Export the Time, Date and Event Number, followed by the tags. 2 - Export the Time and Event Number, followed by the tags. 8 - The time returned will have millisecond accuracy. DDEMode:
The format for the data being exported. CSV format allows the application to separate the data into each individual element, however not every application will support this mode. See you applications documentation for details.
1193
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Invalid and gated samples that are not converted to zero will appear in the destination file as the string "na" (for invalid) or "gated". Ordering trend sample options:
0 - Order returned trend samples from newest to oldest. 2 - Order returned trend samples from oldest to newest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option :
n - the number of missed samples that the user wants to gap fill) x 4096.
Options listed in each group are mutually exclusive.
Return Value
1194
Related Functions
TrnFlush
Writes acquired trend data to disk without waiting for the trend buffer to be filled. CitectSCADA normally buffers the trend data in memory and only writes to disk when required, to give optimum performance. Because this function reduces the performance of the Trends Server, use it only when necessary.
Syntax
sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
TrnSetTable
Example
TrnFlush("Trend1", "ClusterXYZ"); ! Forces the Trend1 data to be written to disk.
1195
TrnGetBufEvent
Gets the event number of a trend at an offset for a specified pen. This function only operates on an event-based trend.
Syntax
Pen:
The trend pen number:
Return Value
The event number. If Offset is not within boundaries, 0 (zero) is returned. If AN or Pen is invalid, 0 (zero) is returned and an error code is set.
Related Functions
TrnGetBufTime
Gets the time and date of a trend at an offset for a specified pen. The Offset should be a value between 0 (zero) and the number of samples displayed on the trend.
1196
Syntax
Pen:
The trend pen number:
Return Value
A time/date variable. If Offset is not within boundaries, 0 (zero) is returned. If nAN or Pen is invalid, 0(zero) is returned and an error code is set.
Related Functions
TrnGetCursorTime
Example
! For the trend at AN20 INT time; time = TrnGetBufTime(20,0,10); IF time <> 0 THEN DspText(31,0,TimeToStr(time,2)); END /* Displays the trend date at offset 10 for the pen currently in focus. The time will display at AN31. */
TrnGetBufValue
Gets the value of a trend at an offset for a specified pen. The offset should be a value between -1 and the number of samples displayed on the trend.
Syntax
1197
Pen:
The trend pen number:
Return Value
The trend value. If the actual value is gated or invalid, the standard invalid or gated values are returned (no error is set). You can check this return value using TrnIsValidValue().
Related Functions
TrnGetCursorValue, TrnIsValidValue
Example
! For the trend at AN20 DspText(31,0,TrnGetBufValue(20,0,10):###.#); /* Displays the trend value at offset 10 for the pen currently in focus. */
TrnGetCluster
Gets the cluster name of a trend graph on a page.
Syntax
TrnGetCluster(nAN) nAN:
The AN of the chosen trend graph.
Return Value
1198
The name of the cluster the trend graph is associated with. See Also Trend Functions
TrnGetCursorEvent
Gets the event number of a trend, at the trend cursor position for a specified pen. This function only operates on an event-based trend.
Syntax
Pen:
The trend pen number:
TrnGetCursorMSTime
Gets the time (in milliseconds from the previous midnight) at a trend cursor for a specified pen.
Syntax
TrnGetCursorMSTime(nAN, Pen)
1199
nAN:
The AN where the trend is located.
Pen:
The trend pen number:
The number of milliseconds since the previous midnight. If the trend cursor is disabled, 0 (zero) is returned. If nAN or Pen is invalid, 0 (zero) is returned and an error code is set.
Related Functions
TrnGetCursorTime
Example
! For the trend at AN20 STRING timeStr; STRING msecStr; timeStr = TimeToString(TrnGetCursorTime(20,1),2) + " "; msecStr = TimeToString(TrnGetCursorMSTime(20,1),6); DspText(31,0,timeStr + msecStr); ! Returns "23/02/01 10:53:22.717"
TrnGetCursorPos
Gets the offset of a trend cursor from its origin, in samples.
Syntax
TrnGetCursorPos(nAN) nAN:
The AN where the trend is located.
Return Value
The offset of a trend cursor from its origin, in samples, or -1 if the trend cursor is disabled.
Related Functions
TrnSetCursorPos
1200
Example
! For the trend at AN20 ! If the trend cursor is disabled Offset=TrnGetCursorPos(20); ! Sets Offset to -1. ! If the trend cursor is 50 samples from the origin Offset=TrnGetCursorPos(20); ! Sets Offset to 50.
TrnGetCursorTime
Gets the time and date at a trend cursor for a specified pen.
Syntax
Pen:
The trend pen number:
A time/date variable. If the trend cursor is disabled, 0 (zero) is returned. If nAN or Pen is invalid, 0 (zero) is returned and an error code is set.
Related Functions
TrnGetBufTime
Example
! For the trend at AN20 INT time; time = TrnGetCursorTime(20,1); DspText(31,0,TimeToStr(time,2)); ! Displays the trend cursor date for Pen1. DspText(32,0,TimeToStr(time,1)); ! Displays the trend cursor time for Pen1.
1201
TrnGetCursorValue
Gets the value at a trend cursor for a specified pen.
Syntax
Pen:
The trend pen number:
The trend value. If the actual value is gated or invalid, the standard invalid or gated values are returned (no error is set). You can check this return value using TrnIsValidValue().
Related Functions
TrnGetBufValue
Example
! For the trend at AN20 DspText(31,0,TrnGetCursorValue(20,0)); ! Displays the value at the trend cursor for the focus pen.
TrnGetCursorValueStr
Gets the value at a trend cursor for a specified pen. The value is returned as a formatted string using the pen's format specification and (optionally) the engineering units.
Syntax
1202
Pen:
The trend pen number:
0 - Do not include the engineering units at the end of the formatted string. 1 - Include the engineering units at the end of the formatted string.
Return Value
The trend value (as a string). If trend data is invalid, or an argument passed to the function is invalid "<na>" is returned. If the actual value is gated (not triggered) "<gated>" is returned. If the trend cursor is disabled, an empty string is returned.
Related Functions
TrnGetCursorValue
Example
! For the trend at AN20 DspText(31,0,TrnGetCursorValueStr(20,0,1)); /* Displays the value at the trend cursor for the focus pen. The value will display as a formatted string (including the engineering units).*/
TrnGetDefScale
Gets the default engineering zero and full scales of a trend tag. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
1203
LoScale:
The engineering zero scale.
HiScale:
The engineering full scale.
sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
TrnGetScale, TrnInfo
Example
REAL LoScale; REAL HiScale; TrnGetDefScale("PV1",LoScale,HiScale,"ClusterXYZ"); /* Returns engineering zero and full scales of the trend tag "PV1". */
TrnGetDisplayMode
Returns the display mode of the selected trend pen. The display mode is set using TrnSetDisplayMode.
Syntax
PenNumber:
The trend pen number:
An integer representing the trend's display mode: Invalid/Gated trend options: 0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are. Ordering trend sample options: 0 - Order returned trend samples from oldest to newest. 2 - Order returned trend samples from newest to oldest. Condense method options: 0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples. Stretch method options: 0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples. Gap Fill Constant option: n - the number of missed samples that the user wants to gap fill) x 4096. Display as Periodic options: 0 - Display according to trend type. 1048576 - display as periodic regardless of trend type.
Related Functions
TrnSetDisplayMode
Example
int DisplayMode = TrnGetDisplayMode (10, 7) /* Returns The Display Mode of pen 7 for the trend at AN 10.*/
TrnGetEvent
1205
Gets the event number of the trend at a percentage along the trend, using the current event as the base point. This function only operates on an event-based trend. The first recorded event (the start event) would be event number 1 and the highest number would be the latest event. The event number is stored in a LONG and would eventually wrap around if you have enough events.
Syntax
Pen:
The trend pen number:
Return Value
TrnGetFormat
Gets the format of a trend tag being plotted by a specified pen.
Syntax
1206
Pen:
The trend pen number:
DecPlaces:
The number of decimal places in the format.
Return Value
TrnGetScale, TrnGetUnits
Example
/* If the trend tag being plotted by Pen1 of the trend at AN20 has a format of "###.#" */ TrnGetFormat(20,1,Width,DecPlaces); ! Sets Width to 5 and DecPlaces to 1.
TrnGetGatedValue
Returns the internally stored value for <GATED>. If the internally stored value changes in the future, you will not need to modify your Cicode, as this function will return the correct value.
Syntax
TrnGetGatedValue()
Return Value
TrnGetInvalidValue, TrnIsValidValue
Example
1207
REAL MyTrendValue; IF MyTrendValue = TrnGetGatedValue() THEN Prompt ("This value is <GATED>") ELSE IF MyTrendValue = TrnGetInvalidValue() THEN Prompt("This value is <TRN_NO_VALUES>") ELSE Prompt("Trend value is = " + RealToStr(MyTrendValue, 10, 1)); END END
TrnGetInvalidValue
Returns the internally stored value for <INVALID>. If the internally stored value changes in the future, you will not need to modify your Cicode, as this function will return the correct value.
Syntax
TrnGetInvalidValue()
Return Value
TrnGetGatedValue, TrnIsValidValue
Example
REAL newArray[100]; REAL oldArray[90]; INT trigger; INT FUNCTION DoubleArray() INT i; FOR i = 0 TO 99 DO IF TrnIsValidValue(oldArray[i]) = 1 OR trigger = 0 THEN newArray[i] = TrnGetGatedValue(); ELSE IF i >= 90 OR TrnIsValidValue(oldArray[i]) = 2 THEN newArray[i] = TrnGetInvalidValue(); ELSE newArray[i] = oldArray[i] * 2; END END END
1208
RETURN i; END
TrnGetMode
Gets the mode (real-time or historical trending) of the trend pen.
Syntax
Pen:
The trend pen number:
TrnScroll
Example
! For the trend at AN20 INT Mode; Mode=TrnGetMode(20,0); ! Gets the current mode of the pen in focus. IF Mode=0 THEN DspText(31,0,"Real Time Trending"); ELSE DspText(31,0,"Historical Trending"); END
TrnGetMSTime
1209
Gets the time (in milliseconds from the previous midnight) of the trend (plotted by a specified pen) at a percentage along the trend, using the time and date of the right-most sample displayed. The time associated with the right-most sample displayed is known as the end time. The start time is the time of the left-most sample displayed. Percent 0 (zero) will correspond to the end time, and Percent 100 will correspond to the start time
Syntax
Pen:
The trend pen number:
Return Value
The number of milliseconds since the previous midnight. Zero (0) is returned if an error is detected.
Related Functions
TrnGetTime
Example
1210
! For Pen 1 at AN20 STRING timeStr; STRING msecStr; timeStr = TimeToString(TrnGetTime(20,1,100),2) + " "; msecStr = TimeToString(TrnGetMSTime(20,1,100),6); DspText(31,0,timeStr + msecStr);
returns
"23/02/01 10:53:22.717"
TrnGetPen
Gets the trend tag being plotted by a specified pen.
Syntax
Pen:
The trend pen number:
0 return tag without cluster prefix (default) 1 return tag with cluster prefix.
Return Value
The trend tag (as a string) being plotted by Pen. If nAN or Pen is invalid, an empty string is returned, and an error code is set. You can call the IsError() function to get the actual error code.
Related Functions
TrnSetPen
Example
1211
! For the trend at AN20 DspText(31,0,TrnGetPen(20,0,1)); ! Displays the trend tag with cluster prefix of the focus pen.
TrnGetPenComment
Retrieves the comment of a pen.
Syntax
TrnGetPenComment(nAN, Pen) AN
The AN of the chosen trend.
Pen:
The trend pen number:
TrnGetPen
Example
! For the trend at AN18 DspText(31,0,TrnGetPen(18,0)); ! Displays the trend comment of the focus pen.
TrnGetPenFocus
Gets the number of the pen currently in focus.
Syntax
TrnGetPenFocus(nAN) AN:
1212
Return Value
The pen currently in focus (between 1 and 8). If nAN is invalid, -1 is returned and an error code is set.
Related Functions
TrnSetPenFocus
Example
! For the trend at AN20 DspText(31,0,TrnGetPenFocus(20)); ! Displays the pen currently in focus.
TrnGetPenNo
Gets the pen number of a pen name. The pens on a trend are either defined in the Page Trends database or set by the TrnSetPen() function.
Syntax
Tag:
The trend tag.
Return Value
TrnSetPen
Example
/* Assume that 8 trend fonts, Pen1TrendFont ... Pen8TrendFont are defined in the Fonts database. The following code will display the trend tag using the matching font for that pen. */ ! For the trend at AN20
1213
STRING sFont; INT iPen; iPen = TrnGetPenNo(20,"PV1"); IF 0 < iPen AND iPen < 9 THEN sFont = "Pen" + IntToStr(iPen) + "TrendFont"; DspStr(31,sFont,"PV1"); END
TrnGetPeriod
Gets the current display period of a trend. (To obtain the sampling period, use the TrnInfo function.)
Syntax
TrnGetPeriod(nAN) AN:
The AN of the chosen trend.
Return Value
The current display period of a trend (in seconds), or 0 (zero) if an error code is detected.
Related Functions
TrnSetPeriod, TrnInfo
Example
/* For the trend at AN20, get and display the current display period. */ ! If the period is 10 seconds INT Period; STRING Str; Period=TrnGetPeriod(20); Str=TimeToStr(Period,5); DspStr(31,"",Str);
TrnGetScale
Gets the display scale of the trend tag being plotted by a specified pen.
Syntax
1214
Pen:
The trend pen number:
Return Value
The scale of the trend tag being plotted by Pen. If nAN or Pen is invalid, 0 (zero) is returned and an error code is set.
Related Functions
TrnSetScale, TrnGetDefScale
Example
! For the trend at AN20 DspText(31,0,TrnGetScale(20,0,0)); ! Displays the zero scale of the focus pen. DspText(32,0,TrnGetScale(20,0,50)); ! Displays the 50% scale of the focus pen. DspText(33,0,TrnGetScale(20,0,100)); ! Displays the full scale of the focus pen.
TrnGetScaleStr
Gets the scale of the trend tag being plotted by a specified pen. The value is returned as a formatted string using the pen's format specification and (optionally) the engineering units.
Syntax
1215
Pen:
The trend pen number:
EngUnits:
Engineering units mode:
0 - Do not include the engineering units at the end of the formatted string. 1 - Include the engineering units at the end of the formatted string.
Return Value
The scale of the trend tag being plotted by Pen (as a string). If nAN or Pen is invalid, <na> is returned and an error code is set.
Related Functions
TrnGetScale
Example
! For the trend at AN20 DspText(31,0,TrnGetScaleStr(20,0,0,1)); /* Displays the zero scale of the focus pen. The scale displays as a formatted string (including the engineering units). */ DspText(32,0,TrnGetScaleStr(20,2,50,1)); /* Displays the 50% scale of Pen2. The scale displays as a formatted string (including the engineering units). */ DspText(33,0,TrnGetScaleStr(20,0,100,0)); /* Displays the full scale of the trend tag being plotted by the focus pen. The scale displays as a formatted string (excluding the engineering units). */
TrnGetSpan
Gets the span time of a trend (if the span was set by the TrnSetSpan() function). The span time is the total time displayed in the trend window. Note: If you call the TrnSetPeriod() function after the TrnSetSpan() function, the span
1216
TrnGetSpan(nAN) AN:
The AN of the chosen trend.
Return Value
The span time, in seconds. 0(zero) is returned if the AN is invalid or if the span was not set by the TrnSetSpan() function.
Related Functions
TrnGetTable
This function allows you to tabulate values from a specific section of trend. The values in the table (possibly an array variable) are arranged by time. If the period (Period) is different to the trend's sampling period (configured in the Trend Tags database), the returned values are determined by DisplayMode. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
Time:
1217
The end time and date (long integer) of the desired trend section. Once you have entered the end time and date (Time), period (Period), and number of trend tag values collected (Length), the start time and date will be calculated automatically. For example, if Time = StrToDate("18/12/96") + StrToTime("09:00"), Period = 30, and Length = 60, the start time would be 08:30. In other words, the trend values for the period between 8.30am and 9am (on December 18, 1996) would be tabulated. If this argument is set to 0 (zero), the time used will be the current time.
Period:
The time difference between tabulated trend values (in seconds). For example, if you set this period to 30 seconds, CitectSCADA will get the last trend value (sampled at the end of the trend section), then get the trend value that was sampled 30 seconds before that, and so on until it reaches the start time of the trend section. If this period is different to the trend's sampling period, the trend values will be averaged or interpolated. Set to 0 (zero) to default to the actual trend period.
Length:
The number of trend values to store in the trend table, from 1 to the maximum number of items in the table. This argument has a max of 4000 (in v6). Specifying a length of greater than 4000 results in a return value of 0 and IsError()=274 (INVALID_ARGUMENT). This limit can be configured using the citect.ini parameter [Trend]MaxRequestLength.
Table:
The Cicode array in which the trend data is stored. You can enter the name of an array here (see the example).
DisplayMode:
The Display Mode parameters allow you to enter a single integer to specify the display options for a trend (for a maximum of eight trends). To calculate the integer that you should enter for a particular trend, select the options you want to use from those listed below, adding their associated numbers together. The resulting integer is the DisplayMode parameter for that trend. Invalid/Gated trend options:
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Ordering trend sample options:
0 - Order returned trend samples from oldest to newest. 2 - Order returned trend samples from newest to oldest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples.
1218
8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option :
n - the number of missed samples that the user wants to gap fill) x 4096.
Options listed in each group are mutually exclusive. The default value for each Display Mode is 258 (0 + 2 + 256).
Milliseconds:
This argument allows you to set your sample request time with millisecond precision. After defining the time and date in seconds with the Time argument, you can then use this argument to define the milliseconds component of the time. For example, if you wanted to request data from the 18/12/96, at 9am, 13 seconds, and 250 milliseconds you could set the Time and Milliseconds arguments as follows: Time = StrToDate("18/12/96") + StrToTime("09:00:13") Milliseconds = 250 If you don't enter a Milliseconds value, it defaults to 0 (zero). There is no range constraint, but as there are only 1000 milliseconds in a second, you should keep your entry between 0 (zero) and 999.
sClusterName:
Name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
The actual number of samples read. 0(zero) is returned if an error occurs. You can call the IsError() function to get the actual error code.
Related Functions
TrnSetTable, TrnGetDisplayMode
Example
REAL TrendTable1[100]; /* Defines an array of a maximum of 100 entries in which the trend data is stored. */ TrnGetTable("OP1",StrToDate("18/12/91") +StrToTime("09:00"),2,10,TrendTable1[0],0, "ClusterXYZ"); /* Stores the values of trend tag "OP1" in Table TrendTable1. Data
1219
is stored at the following times: 18/12/91 09:00:00 TrendTable1[0] 08:59:58 TrendTable1[1] 08:59:56 TrendTable1[2] ... 18/12/91 08:59:42 TrendTable1[9] */ Average=TableMath(TrendTable1[0],100,2); /* Gets the average of the trend data. */
TrnGetTime
Gets the time and date of the trend (plotted by a specified pen) at a percentage along the trend, using the time and date of the right-most sample displayed. The time associated with the rightmost sample displayed is known as the end time. The start time is the time of the left-most sample displayed. Percent 0 (zero) will correspond to the end time, and Percent 100 will correspond to the start time.
Syntax
Pen:
The trend pen number:
1220
The percentage of the trend from the time and date of the right-most sample displayed (end time), from 0 to 100.
Return Value
TrnSetTime
Example
! For the trend at AN20 DspText(31,0,TimeToStr(TrnGetTime(20,0,0),2)); ! Displays the trend current date for the focus pen. DspText(32,0,TimeToStr(TrnGetTime(20,0,0),1)); ! Displays the trend current time for the focus pen. DspText(33,0,TimeToStr(TrnGetTime(20,0,50),1)); ! Displays the time 50% along the trend for the focus pen.
TrnGetUnits
Gets the data units for the trend tag plotted by a specified Pen.
Syntax
Pen:
The trend pen number:
The data units for the trend tag plotted by Pen, otherwise an empty string is returned, and an error code is set. You can call the IsError() function to get the actual error code.
Related Functions
TrnGetFormat, TrnGetScale
Example
1221
! For the trend at AN20 DspText(31,0,TrnGetUnits(20,0)); ! Displays the data units for the focus pen.
TrnInfo
Gets the configured values of a trend tag. This function is a blocking function. It blocks the calling Cicode task until the operation is complete.
Syntax
nType:
The type of information required:
1 - Trend Type 2 - Sample Period (to obtain the Display Period, use the TrnGetPeriod function) 3 - Trend File Name (without file extension) 4 - Area 5 - Privilege 6 - Current Event Number. Valid only for event type trends 7 - Engineering Units 8 - The storage method used for the tag. A returned value of 2 represents two byte storage (scaled), 8 represents eight byte storage (floating point). 9 - The file period of the tag in seconds. If the file period is set to monthly or yearly, a file period cannot be calculated as months and years vary in length. Therefore, a file period of 0 will be returned for trends with such file periods. sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
1222
The value (as a string), otherwise an empty string is returned, and an error code is set. You can call the IsError() function to get the actual error code.
Example
! Get the file name of trend tag LT131 sFileName = TrnInfo("LT131", 3, "ClusterXYZ");
TrnIsValidValue
Determines whether a logged trend value is:
l l
<VALID> - an actual trend value; <GATED> - if a periodic trend has a trigger condition, and that condition is FALSE, a standard substitute (or GATED) value is logged instead of the actual value; or <INVALID> - for some reason, no value was logged.
Syntax
TrnIsValidValue(TrendValue) TrendValue:
A trend value (of type REAL).
Return Value
TrnGetGatedValue, TrnGetInvalidValue
Example
INT FUNCTION DoubleArray() INT i; FOR i = 0 TO 99 DO IF TrnIsValidValue(oldArray[i]) = 1 OR trigger = 0 THEN newArray[i] = TrnGetGatedValue(); Prompt ("This value is <GATED>"); ELSE
1223
IF i >= 90 OR TrnIsValidValue(oldArray[i]) = 2 THEN newArray[i] = TrnGetInvalidValue(); ELSE newArray[i] = oldArray[i] * 2; Prompt ("This value is <TRN_NO_VALUES>"); END END END RETURN i; END
TrnNew
Creates a new trend at run time. This function performs the same operation as an entry in the Page Trends database. After the trend is created by the TrnNew() function, all the other trend functions can access and control the trend.
Syntax
Trend:
The trend definition number (as a STRING).
Tag1 . . .Tag8:
The trend tags. (These tags cannot be prefixed with cluster name, cluster should be specified with the ClusterName argument).
sClusterName:
The name of the cluster in which all the trend tags reside. This is optional if you have one cluster or are resolving the trends via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
TrnDelete
Example
1224
TrnNew(20,"trn002","PV1","OP1", "ClusterXYZ"); /* Creates a new trend at AN20 using trend definition 2, plotting "PV1" on Pen1 and "OP1" on Pen2. */
TrnPlot
Prints the trend line of one or more trend tags. Each trend line is drawn with a different pen style and marker as appropriate. The trend plot includes a comment and a legend, and you can specify the vertical high and low scales. The Mode defines the color mode of the printer. The default mode is black and white. Note: The TrnPlot() function is used only for sending trends to a printer, and cannot be used for embedding a trend plot in a report. For more advanced trend plotting, you can use the low-level plot functions.
Syntax
TrnPlot(sPort, nSamples, iTime, rPeriod, sTitle, AN, Tag1......Tag8, iMode, sComment, rLoScale1, rHiScale1, ......rLoScale8, rHiScale8) sPort:
The name of the printer port to which the plot 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.
nSamples:
The number of data points on the plot.
rPeriod:
The period (in seconds) of the trend plot. This can differ from the actual trend period. If you omit the period, it defaults to the sample period of Tag1.
sTitle:
1225
Tag1. . .Tag8:
The trend tags.
AN:
The AN of the chosen trend. If you enter 0 (zero), the display mode will default to 258. (This is the display mode that is passed into TrnGetTable() when it is called internally by TrnPlot().) If you call TrnPlot() from a report, you need to enter 0 (zero) here.
iMode:
The color mode of the printer.
Return Value
TrnPrint
1226
Prints the trend that is displayed on the screen (at nAN) using the current display mode for each trend. You can specify the trend title, the target printer, whether to print in color or black and white, and whether to display the Plot Setup form when the function is called.
Syntax
sTitle:
The title to print at the top of the trend plot. If you omit the title in sTitle, the page title will be used.
AN:
The AN where the trend plot is located.
iModeColor:
The color mode of the printer.
-1 - Color to be decided (Default). CitectSCADA refers to the [GENERAL]PrinterColorMode parameter to determine print color. If there is no setting for this parameter, it will default to black and white. 0 - Black and White 1 - Color DisplayForm:
Defines whether or not the Plot Setup form will display when the function is called. This form allows you to enter the color mode of the printer, and define the printer setup etc. (See Printing Trend Data for more information on this form.)
-1 - CitectSCADA refers to the [GENERAL]DisablePlotSetupForm parameter to determine if the form will display. 0 - Do not display form 1 - Display form
Return Value
1227
TrnSamplesConfigured
Gets the number of samples configured for the currently displayed trend.
Syntax
TrnSamplesConfigured(nAN) AN:
The AN where the trend is located.
Return Value
The number of samples configured for the trend, or 0 (zero) if an error is detected. You can call the IsError() function to get the actual error code.
Example
/* For the trend at AN20, get and display the number of samples */ INT nSamples; nSamples=TrnSamplesConfigured(20); DspStr(31,"",IntToStr(nSamples));
TrnScroll
Scrolls the trend pen by a specified percentage (of span), or number of samples.
Syntax
Pen:
1228
nScroll:
The amount by which the trend will be scrolled. Use nMode to specify whether the trend will be scrolled by percentage or by number of samples. Because the resolution of Client requests is 1 second, requests of millisecond accuracy are rounded to 1 second. For example, if requested to scroll 2 samples of 400 milliseconds (a total of 0.8 seconds), the trend will actually scroll 1 second.
nMode
The type of scrolling to be performed.
1 - The trend will be scrolled by a percentage of span. Default. 2 - The trend will be scrolled by a number of samples. This mode is not available if the user puts the trend into the 'trend span' mode by setting the span. In this case no scrolling would take place; the user needs to use nMode 1.
Return Value
TrnSetTime
Example
! Scroll all pens (of the trend at an20) 100% forwards. TrnScroll(20,-1,100); or TrnScroll(20,-1,100,1); ! Scrolls all pens (of all trends on the current trend page) 300% backwards. TrnScroll(-1, -1, -300); or TrnScroll(20,-1.-300,1); !Scrolls all pens (of all trends on the current trend page) 3 samples forwards. TrnScroll(20,-1,3,2); !Scrolls all pens (of all trends on the current trend page) 1 sample backwards. TrnScroll(20,-1,-1,2);
TrnSelect
Sets up a page for a trend. This function allows you to set up a trend before the trend page is displayed. You can therefore use a single trend page to display any trend in the project by selecting the trend first, and then displaying the trend page. The PageTrend() function uses this function to display the standard trend pages.
1229
Call this function and a set of TrnSetPen() functions before you display a trend page. When the trend page is displayed, all pens set by the TrnSetPen() functions are displayed. You can use the TrnSelect() function to configure different set of pens to be displayed on one generic trend page. The pen settings in the Page Trend database are overridden. Note: Trend functions used after the TrnSelect() function needs to use the special value -2 as their AN. (See the example below).
Syntax
-3 - for the current window. -2 - for the next window displayed. Page:
The name of the page that displays the trend.
AN:
The AN where the trend displays, or -3 for the first trend on the page.
sClusterName:
The name of the cluster that is associated with any trend tag for this trend graph. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
1230
TrnSetCursor
Moves the trend cursor by a specified number of samples. If the trend cursor is disabled, this function enables it. If the cursor is enabled and the number of samples is 0 (zero), the cursor is disabled. If the cursor is moved off the current trend frame, the trend scrolls.
Syntax
Samples:
The number of samples to move the cursor.
Return Value
TrnSetCursorPos
Moves the trend cursor to a specified x-axis point, offset from the trend cursor origin. If the trend cursor is disabled, this function enables it. If the position is outside of the trend frame, it sets the trend cursor to half of the frame.
Syntax
TrnSetCursorPos(nAN, Position)
1231
AN:
The AN where the trend is located. Set to -1 for all trends on the current page.
Position:
The x-axis point at which to position the trend cursor, offset from the trend cursor origin.
Return Value
TrnGetCursorPos, TrnSetCursor
Example
! For the trend at AN20, if the trend frame is 400 points TrnSetCursorPos(20,0); ! Moves the trend cursor to its origin. TrnSetCursorPos(20,200); ! Moves the trend cursor to half of its frame size (200 points).
TrnSetDisplayMode
Specifies how raw trend samples are displayed on the screen.
Syntax
PenNumber:
The pen number of the chosen trend. Specify:
1232
To calculate the integer you should enter, select the options you want to use from the list below, adding their associated numbers together. The resulting integer is the DisplayMode parameter for that trend.
Note: Options listed in each group are mutually exclusive. The default value for each Display Mode is 258 (0 + 2 + 256).
Invalid/Gated trend options:
0 - Convert invalid/gated trend samples to zero. 1 - Leave invalid/gated trend samples as they are.
Ordering trend sample options:
0 - Order returned trend samples from oldest to newest. 2 - Order returned trend samples from newest to oldest.
Condense method options:
0 - Set the condense method to use the mean of the samples. 4 - Set the condense method to use the minimum of the samples. 8 - Set the condense method to use the maximum of the samples. 12 - Set the condense method to use the newest of the samples.
Stretch method options:
0 - Set the stretch method to step. 128 - Set the stretch method to use a ratio. 256 - Set the stretch method to use raw samples.
Gap Fill Constant option:
n - the number of missed samples that the user wants to gap fill) x 4096.
Display as Periodic options:
0 - Display according to trend type. 1048576 - display as periodic regardless of trend type.
Since the Display as Periodic options are read-only, they cannot be set using TrnSetDisplayMode. They can be retrieved using TrnGetDisplayMode() and also used with the TrnExport group of functions.
Return Value
TrnGetDisplayMode, TrnGetTable
1233
TrnSetEvent
Sets the start event of a trend pen. This function only operates on an event-based trend.
Syntax
Pen:
The trend pen number:
Return Value
TrnSetPen
Sets the trend tag of a trend pen. The trend pen changes to the specified tag and the trend is refreshed. The trend pen needs to be in the operator's area to be displayed. If outside of the operator's area, data is not displayed. You cannot mix periodic trends and event trends in the same trend window.
1234
This function may sometimes return before the pen is actually set when called on a PC which is not the trend server. This may create difficulties for following functions such as TrnSetScale. A wrapper function can be used to confirm the pen is set before returning. See example 2 below.
Syntax
-1 - All trends on the current trend page. -2 - The function being called is using the special AN setup by the TrnSelect() function. Pen:
The pen for which the trend tag will be changed.
-2 - The first available pen (This value is automatically changed to 0 for SPC trends because they have only one pen per trend.) -1 - All pens on the trend. (Not allowed for SPC trends.) 0 - The pen currently in focus. 1...8 - Pen1....Pen8 Tag:
The trend tag. If Tag = ! the pen is deleted.
Return Value
0 (zero) if successful, otherwise an error code is returned. Be aware that if a mixture of periodic and event trends is detected, the return value is 0 (zero), but the hardware alarm #329 is set.
Related Functions
TrnGetPen, TrnSelect
Example 1
! For the trend at AN20 TrnSetPen(20,1,"PV1"); ! Sets the trend tag of Pen1 to "PV1".
Example 2
1235
INT FUNCTION BlockedTrnSetPen(INT hAN, INT nPen, STRING sTrend) INT timeout = 5000 INT sleepTime = 10 INT error = -1 INT elapsed = 0 INT currentTime STRING sPenName error = TrnSetPen(hAN, nPen, sTrend) IF error = 0 THEN error = -1 currentTime = SysTime() WHILE error <> 0 AND elapsed < timeout DO sPenName = TrnGetPen(hAN, nPen) IF sPenName = sTrend THEN error = 0 ELSE SleepMS(sleepTime) elapsed = elapsed + SysTimeDelta(currentTime) END END END RETURN error END
TrnSetPenFocus
Sets the focus to a specified pen. After the focus is set, the focus pen is used with other trend functions.
Syntax
Pen:
The trend pen:
-4 - Make the next pen the focus pen; without skipping blank pens. -3 - Make the previous pen the focus pen; without skipping blank pens. -2 - Make the next pen the focus pen; skip blank pens. -1 - Make the previous pen the focus pen; skip blank pens. 0 - Keep the current focus. 1...8 - Change Pen1. . .8 to be the focus pen.
1236
Return Value
The old pen focus number, or -1 if an error is detected. You can call the IsError() function to get the actual error code.
Related Functions
TrnGetPenFocus
Example
System Keyboard Key Sequence Command Comment NextPen TrnSetPenFocus(20, -2) For the trend at AN20, make the next pen the focus pen
TrnSetPeriod
Sets the display period (time base) of a trend. When the period is changed, CitectSCADA reads the historical data to reconstruct the trend data, and refreshes the trend. Every pen has the same display period. This function clears the span set by the TrnSetSpan() function.
Syntax
Period:
The new sampling period (in seconds) of the trend. To set the display period to the sampling period, set this argument to 0 (zero),
Return Value
1237
Example
System Keyboard Key Sequence Command Comment ## Enter TrnSetPeriod(20, Arg1) Set a new sampling period for the trend at AN20
TrnSetScale
Sets a new scale for a trend pen. In the automatic scaling mode, the zero and full scales are automatically generated.
Syntax
Pen:
The trend pen number:
-2 - Set both zero and full scales to the default scales. -1 - Place the trend into automatic scale mode. 0 - Set the zero scale. 100 - Set the full scale. Scale:
The new value of the scale. Scale is ignored if Percent is -2.
Return Value
Related Functions
TrnSetSpan
Sets the span time of a trend. The span time is the total time displayed in the trend window. You can set the period to contain fractions of a second. For example, if you set a trend with 240 samples to a span of 10 minutes, then each sample would be 2.5 seconds. Choose a span long enough to provide a sufficient sample rate to capture accurate real time data.
Syntax
Span:
The span time (in seconds).
Return Value
1239
TrnSetTable
Writes trend tag data from a table to the trend logging system (starting at the top of the table, and continuing to the bottom). Each value is written with a time and date, as specified by Period. If Period differs from the trend sampling period (defined in the Trend Tags database), the trend's sample values will be calculated (averaged or interpolated) from the tabulated trend data. The user needs to have the correct privilege (as specified in the database), otherwise the data is not written. This function is a blocking function. It will block the calling Cicode task until the operation is complete.
Syntax
Time:
The time and date (long integer) to be associated with the first value in the table when it is set. Once you have entered the end time and date (Time), set period (Period), and number of trend tag values to be set (Length), the start time and date will be calculated automatically. For example, if Time = StrToDate("18/12/96") + StrToTime("09:00"), Period = 30, and Length = 60, the start time would be 08:30. In other words, the first value from the table would be set with time 9am, and the last would be set with time 8.30am (on December 18, 1996). If this argument is set to 0 (zero), the time used will be the current time.
Period:
This will be the interval (in seconds) between trend values when they are set (that is it will be the perceived sampling period for the trend). This period can differ from the actual trend period. Set to 0 (zero) to default to the actual trend period.
Length:
The number of trend values in the trend table.
Table:
The table of floating-point values in which the trend data is stored. You can enter the name of an array here (see the example).
Milliseconds:
1240
This argument allows you to set the time of the first sample in the table with millisecond precision. After defining the time and date in seconds with the Time argument, you can then use this argument to define the milliseconds component of the time. For example, if you wanted to set data from the 18/12/96, at 9am, 13 seconds, and 250 milliseconds you could set the Time and Milliseconds arguments as follows: Time = StrToDate("18/12/96") + StrToTime("09:00:13") Milliseconds = 250 If you don't enter a milliseconds value, it defaults to 0 (zero). There is no range constraint, but as there are only 1000 milliseconds in a second, you should keep your entry between 0 (zero) and 999.
sClusterName:
The name of the cluster in which the trend tag resides. This is optional if you have one cluster or are resolving the trend via the current cluster context. The argument is enclosed in quotation marks "".
Return Value
The actual number of samples written. The return value is 0 if an error is detected. You can call the IsError() function to get the actual error code.
Related Functions
TrnGetTable
Example
REAL TrendTable1[100]; /* Defines an array of a maximum of 100 entries. Assume that TrendTable1 has been storing data from a source. */ TrnSetTable("OP1",StrToDate("18/12/91") +StrToTime("09:00"),2,10,TrendTable1,0,"ClusterXYZ"); /* A set of 10 trend data values are set for the OP1 trend tag. */
TrnSetTime
Sets the end time and date of a trend pen. If you set a time less than the current time, the trend display is set to historical mode and samples taken after this time and date will not be displayed. If you set the time to the current time, for example by using the TimeCurrent or TrendZoom cicode functions, the trend is displayed in real-time mode and samples after this date and time will display.
Syntax
1241
AN:
The AN where the trend is located, or:
-1 - All trends on the current page 0 - The trend where the cursor is positioned Pen:
The trend pen number:
-1 - All pens 0 - The pen currently in focus 1...8 - Pen1. . .Pen8 Time:
The end time and date of the trend. Samples taken after this time and date will not be displayed. Set to 0 (zero) to set the trend to the current time (real-time mode).
Return Value
TrnGetTime, TrnSetTime
Example
TrnSetTime(20,1,TimeCurrent()-60*30); /* Sets Pen1 to 30 minutes before the current time (30 minutes ago). */ TrnSetTime(20,1,0); /* Sets the trend to real-time mode. */
1242
Changes the active window. Sets the display mode of the active window. Moves the active window. Opens a display window. Opens a display window at specified coordinates. Makes the next window active. Gets the window number of the active CitectSCADA window. Positions a window on the screen.
1243
Makes the previous window active. Prints the active window. Prints a file to the printer. Selects a window for Cicode output. Associates a name with a particular window by its window number. Sizes a window. Switches on and off scrolling and scroll bar features for existing windows. Sets the title of the active window. Gets the Windows number of any window in any application. Gets a profile string from any .INI file.
WinTitle WndFind WndGetFileProfile WndGetProfile WndHelp WndInfo WndMonitorInfo WndPutFileProfile WndPutProfile WndShow WndViewer
This function is obsolete from this version of the product. Invokes the Windows Help application. Gets the Windows system metrics information. Returns information about a particular monitor.
This function is obsolete from this version of the product. Sets the display mode of any window of any application. Invokes the Windows Multimedia application.
GetWinTitle
Returns the name of the active window as a string.
1244
GetWinTitle()
Return Value
The title of the active window as a string if successful; otherwise, an error is returned.
Related Functions
HtmlHelp
Invokes the Microsoft HTML Help application (hh.exe) to display a specific topic from a specific HTML help file (.chm).
Syntax
nCommand:
The type of help:
0 - Display a topic identified by an internal file name in the sData field. This is the name of the file within the .chm file. For example: "CitectSCADAPowerLogic_SCADA_Help_Overview.html" 1 - Display a topic identified by the Mapped Topic ID in the sData field. For example: "1000" 2 - Terminate the help application 3 - Display the index sData:
Optional data, depending on the value of nCommand. See above.
Return Value
1245
Related Functions
WndHelp
Example
The following example displays the overview page of the CitectSCADA help:
HtmlHelp("C:\Program Files\Citect\CitectSCADA 7.30Schneider Electric\PowerSCADA Expert 7.30 \bin\CitectSCADA.chm", 0, "CitectSCADAPowerLogic_SCADA_Help_Overview.html");
MultiMonitorStart
Displays a CitectSCADA window on each of the configured monitors when a display client starts up. It sets up the windows according to the Multi-Monitor Parameters [MultiMonitors]Monitors and [MultiMonitors]StartPage#.
Syntax
MultiMonitorStart()
Return Value
WinCopy
Copies the graphics image of the active window to the Windows Clipboard. You can paste this Clipboard image into other applications. Notes:
l
This function might not work as expected if called directly from the Kernel; instead, this function should be called from a graphics page. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
1246
The x scaling factor for the item being copied. This argument is optional, as a default setting of 1 is used to maintain the current horizontal scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the width of the image.
yScale:
The y scaling factor for the item being copied. This argument is optional, as a default setting of 1 is used to maintain the current vertical scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the height of the image.
bSwapBlackWhite:
Swaps the colors black and white for the purpose of printing pages with a lot of black content. Use the default value of 1 to swap black and white (optional).
sMap:
The file name or path of a text based map file used to specify colors to swap when printing. By default CitectSCADAwill look in the bin directory for the map file. The format for the map file is: RRR GGG BBB RRR GGG BBB [HHH] [SSS] [LLL]// RRR GGG BBB RRR GGG BBB [HHH] [SSS] [LLL]//
Where: RRRis a decimal red intensity value between 000 and 255. GGGis a decimal green intensity value between 000 to 255. BBB is a decimal blue intensity value between 000 to 255. HHH, SSS and LLL are optional tolerance values to enable swapping a range of colors. Default values are shown below. HHH is a decimal value representing the Hue tolerance. Valid range is 0 to 360. Default = 0. SSS is a decimal value representing the Saturation tolerance. Valid range is 0 to 255. Default = 2 * Hue tolerance. LLL is a decimal value representing the Luminance tolerance. Valid range is 0 to 255. Default = 2 * Hue tolerance. Leading zeros are not required, however they aid readability. The first three RGB values specify the FROM color, and the second three RGB values specify the TO color. The tolerance values are applied to the FROM color when replacing individual pixels in the image. Comments may be placed at the end of each line, or on individual lines, and needs to be proceeded with // or !. Example map file to swap the CSV_Include project:
1247
043 043 255 155 205 255 025 000 025 //Change dark blue to light blue using Hue and Luminance tolerance of 25. (Converts the CSV title bar) 000 000 000 255 255 255 //Swap black to white with no tolerance
Note:If swap color ranges overlap, the behavior is undefined (i.e. a color that falls in both ranges may end up as either color)
Return Value
WinPrint
Example
WinCopy(); ! Copies the active window to the Windows Clipboard. WinCopy(0.5,0.5); ! Copies the active window to the Windows Clipboard at half the current size.
WinFile
Writes the graphics image of the active window to a file. The file is saved in the CitectSCADA compressed .bmp format. Notes:
l
This function might not work as expected if called directly from the Kernel; instead, this function should be called from a graphics page. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
xScale:
1248
The x scaling factor for the item being printed. This argument is optional, as a default setting of 1 is used to maintain the horizontal scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the width of the image .
yScale:
The y scaling factor for the item being printed. This argument is optional, as a default setting of 1 is used to maintain the current vertical scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the height of the image.
bSwapBlackWhite:
Swaps the colors black and white for the purpose of printing pages with a lot of black content. Use the default value of 1 to swap black and white (optional).
sMap:
The file name or path of a text based map file used to specify colors to swap when printing. By default CitectSCADAwill look in the bin directory for the map file. The format for the map file is: RRR GGG BBB RRR GGG BBB [HHH] [SSS] [LLL]// RRR GGG BBB RRR GGG BBB [HHH] [SSS] [LLL]//
Where: RRRis a decimal red intensity value between 000 and 255. GGGis a decimal green intensity value between 000 to 255. BBB is a decimal blue intensity value between 000 to 255. HHH, SSS and LLL are optional tolerance values to enable swapping a range of colors. Default values are shown below. HHH is a decimal value representing the Hue tolerance. Valid range is 0 to 360. Default = 0. SSS is a decimal value representing the Saturation tolerance. Valid range is 0 to 255. Default = 2 * Hue tolerance. LLL is a decimal value representing the Luminance tolerance. Valid range is 0 to 255. Default = 2 * Hue tolerance. Leading zeros are not required, however they aid readability. The first three RGB values specify the FROM color, and the second three RGB values specify the TO color. The tolerance values are applied to the FROM color when replacing individual pixels in the image. Comments may be placed at the end of each line, or on individual lines, and needs to be proceeded with // or !. Example map file to swap the CSV_Include project:
1249
043 043 255 155 205 255 025 000 025 //Change dark blue to light blue using Hue and Luminance tolerance of 25. (Converts the CSV title bar) 000 000 000 255 255 255 //Swap black to white with no tolerance
Note:If swap color ranges overlap, the behavior is undefined (i.e. a color that falls in both ranges may end up as either color)
Return Value
WinPrint
Example
WinFile("DUMP"); /* Writes the active window to a file named DUMP in the current directory. */
WinFree
Removes the active display window. Be aware that the last window (and any child windows owned by the last window) cannot be removed. You cannot call this function as an exit command (see Page Properties) or from a Cicode Object. Notes
l l
This function cannot be used in the CitectSCADA Web Client. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
WinFree()
Return Value
WinNew, WinNewAt
1250
Example
WinFree(); ! Removes the active display window.
WinGetFocus
Gets the number of the CitectSCADA window that has the keyboard focus.
Syntax
WinGetFocus()
Return Value
The window number of the CitectSCADA window that has the keyboard focus. Be aware that this is not the same as the window handle, returned from the WndFind() function.
Related Functions
WndFind
Example
nCitectWin=WinGetFocus(); ! Gets the number of the CitectSCADA window that has the keyboard focus
WinGetWndHnd
Gets the window handle for the current window. The window handle may be used by 'C' programs and CitectSCADA Wnd... functions. You may pass the windows handle to a 'C' program by using the DLL functions.
Syntax
WinGetWndHnd()
Return Value
The window handle if successful, otherwise 0 (zero) is returned. Be aware that this is not the same as a CitectSCADA window number returned from the WinNumber() function.
Related Functions 1251
WinGoto
Changes the active window. The specified window is placed in front of all other windows and all keyboard commands will apply to this window. You cannot call this function as an exit command (see Page Properties) or from a Cicode Object. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
WinGoto(Window) Window:
The window number (returned from the WinNumber() function). Be aware that this is not the same as the window handle, returned from the WndFind() function.
Return Value
WinNew
Example
! If two windows are displayed; WinGoto(1); ! Changes the active window to Window 1. WinGoto(0); ! Changes the active window to Window 0.
1252
WinMode
Sets the display mode of the active CitectSCADA window. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
WinMode(Mode) Mode:
The mode:
0 - Hide the window. 2 - Activate the window in an iconized state. 3 - Activate the window in a maximized state. 4 - Display the window in its previous state without activating it. 5 - Activate the window in its current state. 6 - Iconize the window. 7 - Display the window in an iconized state without activating it. 8 - Display the window in its current state without activating it. 9 - Activate the window in its previous state.
Return Value
WinNew
Example
! Iconize the active CitectSCADA window. WinMode(7);
WinMove
1253
Moves the active window to a new location and sizes the window in a single operation. This is the same as calling the WinPos() and the WinSize() functions. You use PageInfo to get the current window position. Notes
l l
This function cannot be used in the CitectSCADA Web Client. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
Width:
The width of the window, in pixels.
Height:
The height of the window, in pixels.
Return Value
WinNew
Opens a new display window, with a specified page displayed. The window can later be destroyed with the WinFree() function.
1254
You can also specify if the displayed page operates within the context of a particular cluster in a multiple cluster project. When the page is displayed during runtime, the ClusterName argument is used to resolve any tags that do not have a cluster explicitly defined. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
WinNew(Page,ClusterName) Page:
The name or page number of the page to display (in quotation marks ""). Can be prefixed by the name of a host cluster, that is "ClusterName.Page". This will take precedence over the use of the ClusterName parameter if the two differ.
sClusterName:
The name of the cluster that will accommodate the page at runtime. This is optional if you have one cluster or are resolving the page via the current cluster context. The argument is enclosed in quotation marks "". If the Page parameter is prefixed with the name of a cluster, this parameter will not be used.
Return Value
The window number of the window, or -1 if the window cannot be opened. Be aware that this is not the same as the window handle returned from the WndFind() function.
Related Functions
WinFree, WinNewAt
Example
! If the display window being opened is window number 2: Window=WinNew("Alarm"); ! Displays the Alarm page and sets Window to 2.
WinNewAt
Opens a new display window at a specified location, with a selected page displayed. The window can later be destroyed with the WinFree() function.
1255
You can also specify if the displayed page operates within the context of a particular cluster in a multiple cluster project. When the page is displayed during runtime, the ClusterName argument is used to resolve any tags that have a cluster omitted. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
X:
The x pixel coordinate of the top left corner of the window.
Y:
The y pixel coordinate of the top left corner of the window.
Mode:
The mode of the window:
0 - Normal page. 1 - Page child window. The window is closed when a new page is displayed, for example, when the PageDisplay() or PageGoto() function is called. The parent is the current active window. 2 - Window child window. The window is closed automatically when the parent window is freed with the WinFree() function. The parent is the current active window. 4 - No re-size. The window is displayed with thin borders and no maximize/minimize icons. The window cannot be re-sized. 8 - No icons. The window is displayed with thin borders and no maximize/minimize or system menu icons. The window cannot be re-sized. 16 - No caption. The window is displayed with thin borders, no caption, and no maximize/minimize or system menu icons. The window cannot be re-sized. 32 - Echo enabled. When enabled, keyboard echo, prompts, and error messages are displayed on the parent window. This mode should only be used with child windows (for example, Mode 1 and 2).
1256
64 - Always on top. 128 - Open a unique window. This mode helps to prevent this window from being opened more than once. 256 - Display the entire window. This mode commands that no parts of the window will appear off the screen 512 - Open a unique Super Genie. This mode helps to prevent a Super Genie from being opened more than once (at the same time). However, the same Super Genie with different associations can be opened. 1024 - Disables dynamic resizing of the new window, overriding the setting of the [Page]DynamicSizing parameter. 4096 - Allows the window to be resized without maintaining the current aspect ratio. The aspect ratio defines the relationship between the width and the height of the window, which means this setting allows you to stretch or compress the window to any proportions. This option overrides the setting of the [Page]MaintainAspectRatio parameter. 8192 - Text on a page will be resized in proportion with the maximum scale change for a resized window. For example, consider a page that is resized to three times the original width, and half the original height. If this mode is set, the font size of the text on the page will be tripled (in proportion with the maximum scale). This option overrides the setting of the [Page] ScaleTextToMax parameter. 16384 - Hide the horizontal scroll bar. 32768 - Hide the vertical scroll bar. 65536 - Disable horizontal scrolling. 131072 - Disable vertical scrolling.
You can select multiple modes by adding modes together (for example, set Mode to 9 to open a page child window without maximize, minimize, or system menu icons).
sClusterName:
The name of the cluster that will accommodate the page at runtime. This is optional if you have one cluster or are resolving the page via the current cluster context. The argument is enclosed in quotation marks "". If the Page parameter is prefixed with the name of a cluster, this parameter will not be used.
Return Value
The window number of the window, or -1 if the window cannot be opened. Be aware that this is not the same as the window handle returned from the WndFind() function.
Related Functions
WinFree, WinNew
Example 1257
Buttons Text Command Comment Buttons Text Command Comment Buttons Text Command Comment Pop Page WinNewAt("Popup", 100, 200, 4) Pop Page WinNewAt("Popup", 100, 200, 2) Mimic Page WinNewAt("Mimic", 100, 20, 0)
Display the popup page in a new window with no maximize and minimize icons
1258
Comment
Display a specified popup page in a new window with no maximize and minimize icons
WinNext
Makes the next window (in order of creation) active.
Syntax
WinNext()
Return Value
The window number of the window, or -1 if there is no next window. Be aware that this is not the same as the window handle returned from the WndFind() function.
Related Functions
WinNew, WinPrev
Example
! If the display window being made active is window number 2: Window=WinNext(); ! Makes the next window active and sets Window to 2.
WinNumber
Gets the window number of the active CitectSCADA window. This number can be used with other functions to control the window.
Syntax
WinNumber([sName]) sName:
String name previously associated with a window number using WinSetName().
Return Value
1259
Window Number associated with the Name provided. If no Name is specified then the active window number is returned. If there isn't a valid window number associated with the name provided then -1 is returned.
Related Functions
WinPos
Moves the active window to a new location. You use PageInfo() to get the current window position. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
WinPos(X, Y) X, Y:
The new x and y pixel coordinates of the top-left corner of the active window.
Return Value
1260
WinPrev
Makes the previous window (in order of creation) active.
Syntax
WinPrev()
Return Value
The window number of the window, or -1 if there is no next window. Be aware that this is not the same as the window handle returned from the WndFind() function.
Related Functions
WinNext
Example
! If the display window being made active is window number 2: Window=WinPrev(); ! Makes the previous window active and sets Window to 2.
WinPrint
Sends the graphics image of the active window to a printer. Notes:
l
This function might not work as expected if called directly from the Kernel; instead, this function should be called from a graphics page. This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
1261
xScale:
The x scaling factor for the print. The default value of 0 (zero) automatically scales the print to fit the page. A value of 1 is used to maintain the current horizontal scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the width of the image (optional).
yScale:
The y scaling factor for the print. The default value of 0 (zero) automatically scales the print to fit the page. A value of 1 is used to maintain the current horizontal scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the width of the image (optional).
bSwapBlackWhite:
Swaps the colors black and white for the purpose of printing pages with a lot of black content. Use the default value of 1 to swap black and white (optional).
sMap:
The file name or path of a text based map file used to specify colors to swap when printing. By default CitectSCADAwill look in the bin directory for the map file. The format for the map file is: RRR GGG BBB RRR GGG BBB [HHH] [SSS] [LLL]// RRR GGG BBB RRR GGG BBB [HHH] [SSS] [LLL]//
Where: RRRis a decimal red intensity value between 000 and 255. GGGis a decimal green intensity value between 000 to 255. BBB is a decimal blue intensity value between 000 to 255. HHH, SSS and LLL are optional tolerance values to enable swapping a range of colors. Default values are shown below. HHH is a decimal value representing the Hue tolerance. Valid range is 0 to 360. Default = 0. SSS is a decimal value representing the Saturation tolerance. Valid range is 0 to 255. Default = 2 * Hue tolerance. LLL is a decimal value representing the Luminance tolerance. Valid range is 0 to 255. Default = 2 * Hue tolerance. Leading zeros are not required, however they aid readability. The first three RGB values specify the FROM color, and the second three RGB values specify the TO color. The tolerance values are applied to the FROM color when replacing individual pixels in the image. Comments may be placed at the end of each line, or on individual lines, and needs to be proceeded with // or !. Example map file to swap the CSV_Include project:
1262
043 043 255 155 205 255 025 000 025 //Change dark blue to light blue using Hue and Luminance tolerance of 25. (Converts the CSV title bar) 000 000 000 255 255 255 //Swap black to white with no tolerance
Note:If swap color ranges overlap, the behavior is undefined (i.e. a color that falls in both ranges may end up as either color)
Return Value
WinPrintFile
Example
WinPrint("LPT3:",0,0,0); ! Prints the active window on printer "LPT3". The print will be scaled to fit the largest possible page area and will retain the orientation of the printer, aspect ratio and colors that are displayed on screen.
WinPrint("LPT3:"); !Prints the page as in the first example, but swaps black and white on the printout.
WinPrintFile
Prints a file to the system printer. The file needs to be saved with the WinFile() function. Note: This function might not work as expected if called directly from the Kernel; if the WinFile function does not succeed, WinPrintFile either doesnt print anything or prints a previously saved page. This function should be called from a graphics page.
Syntax
1263
sPort:
The name of the printer port to which the window 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. sPort may not contain spaces
xScale:
The x scaling factor for the print. The default value of 0 (zero) automatically scales the print to fit the page. A value of 1 is used to maintain the current horizontal scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the width of the image (optional).
yScale:
The y scaling factor for the print. The default value 0 (zero) automatically scales the print to fit the page. A value of 1 is used to maintain the current horizontal scaling of the image. The outcome is proportional to 1; for example, 0.5 halves the width of the image (optional).
bSwapBlackWhite:
Swaps the colors black and white for the purpose of printing pages with a lot of black content. Use the default value of 1 to swap black and white (optional).
fromColor
The hex RGB color value (0xRRGGBB) to change into toColor. The default value of -1 results in no color change (optional).
toColor
The hex RGB color value (0xRRGGBB) into which fromColor is changed. The default value of -1 results in no color change (optional).
Note: To change a color, a value needs to be specified for both fromColor and toColor.
Return Value
WinPrint
Example
! Save image to disk then print. WinFile("temp"); WinPrintFile("temp", "LPT3:",0,0,0); ! Prints the file "temp" on printer "LPT3". The print will be scaled to fit the largest possible page area and will retain the orientation of the printer, aspect ratio and colors that are
1264
displayed on screen. WinPrintFile("temp","LPT3:"); ! Prints the page as in the first example, but swaps black and white on the printout. WinPrintFile("temp","LPT3:",0,0,0,0x00FF00,0xFF0000); ! Changes green to red. WinPrintFile("temp","LPT3:",0,0,1,0x00FF00,0xFF0000); ! Changes green to red and black to white.
Window Functions
WinSelect
Selects a window to make active. This function only affects the output of Cicode functions. It does not change the screen focus of the windows, or move a background window to the foreground. Always re-select the original window if it is called from a Page database (Page Numbers, Page Symbols, and so on), because other Cicode tasks will assume it is the correct window. This function only changes the active window for the Cicode task that called it. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
WinSelect(Window) Window:
The window number to select. Be aware that this is not the same as the window handle returned from the WndFind() function.
Return Value
WinGoto, WinNumber
Example
OldWindow=WinSelect(1); ! Selects window number 1. Prompt("Message to Window 1"); ! Sends message to window number 1. WinSelect(2);
1265
! Selects window number 2. Prompt("Message to Window 2"); ! Sends message to window number 2. WinSelect(OldWindow); ! Selects original window.
WinSetName
Associates a name with a particular window by its window number. An association with a window is removed when the window is free.
Syntax
iWinNum:
An optional parameter which specifies the window number with which to associate Name. If no number is specified the name is associated with the currently selected window number..
Return Value
WinSize
Sizes the active window. The origin of the window does not move. Note: This function is not supported in the server process in a multiprocessor environment. Calling this function from the server process results in a hardware alarm being raised.
Syntax
1266
The new width and height of the window, in pixels. Mode: Specifies if the size refers to the viewable area or the total window. 0 - the size to refer to the viewable area. 1 - the size to refer to the total window size. Default - 1
Return Value
WinMove, WinPos
Example
WinSize(200,100); ! Sizes the active window to 200 pixels wide x 100 pixels high.
WinStyle
Switches on and off scrolling and scrollbar features for existing windows.
Syntax
1 - Hide horizontal scroll bars. 2 - Hide vertical scroll bars. 3 - Disable horizontal scrolling. 4 - Disable vertical scrolling. Mode:
The mode of the option:
1267
Return Value
WinNewAt
Example
To turn horizontal and vertical scroll bars off for the current window:
WinStyle(1, 1); WinStyle(2, 1);
WinTitle
Sets the title of the active window. If a window title has been set with the [Page]WinTitle parameter, CitectSCADA uses this title when it refreshes the page (overriding the window title set with the WinTitle() function). To minimize the likelihood of CitectSCADA from overriding the title, set the parameter [Page]WinTitle to *.
Syntax
WinTitle(sTitle) sTitle:
The new title for the window.
Return Value
WinNew, GetWinTitle
Example
WinTitle(Time()+" "+Date()); ! Places the current time and date into the window title.
1268
WndFind
Gets the Windows handle of any window of any application, so that the window can be manipulated. The window handle is not the same as the CitectSCADA window number and cannot be used with functions that expect the CitectSCADA window number (the Win... functions). The window title (caption) needs to be an exact match of the window name (including any blank spaces) for this function to find the window. You should therefore check that the other application does not change the title of the window during execution. Be aware that if the title banner of a CitectSCADA window is set with the CitectSCADA parameter [Page] WinTitle, you should not specify justification (for example, use {TITLE, 32,N}). If justification is not disabled (that is the N is omitted), you need to pass the full title of the window (including leading and trailing blanks) to this function.
Syntax
WndFind(sTitle) sTitle
The title (caption) of the window.
Return Value
The window handle. Be aware that this is not the same as a CitectSCADA window number returned from the WinNumber() function.
Related Functions
WinNew
Example
hWndExcel=WndFind("Microsoft Excel - Book1"); ! Gets the Windows number of the window titled "Microsoft Excel Book1"
WndGetFileProfile
Gets a profile string from any .ini file.
Syntax
1269
sName:
The name of the variable.
sDefault:
The default value.
sFile:
The .ini file name.
Return Value
WndPutFileProfile
Example
! get this user startup page from USER.INI File sStartup = WndGetFileProfile(Name(),"Startup","menu","[Run]:\USER.INI"); PageDisplay(sStartup);
WndHelp
Invokes the Windows Help application (WinHlp32.EXE) to display a specific topic from a specific help file.
Syntax
Command:
The type of help:
1 - Displays the help topic identified by the context string/number in the Data field. The context string/number needs to be defined in the [MAP] section of the help's .HPJ file. 2 - Closes the Help application. Enter an empty string for the Data argument.
1270
3 - Displays the help contents topic defined by the CONTENTS option in the [OPTIONS] section of the .HPJ file. 4 - Displays the contents topic of the designated How to Use Help file. The context string/number (specified in the Data field) needs to be defined in the [MAP] section of the .HPJ file. 5 - Changes the current help contents topic to match the context string/number specified in the Data field. This topic is used instead of the one defined by the CONTENTS option in the [OPTIONS] section of the .HPJ file. This will affect Command 3 (see above). The context string/number needs to be defined in the [MAP] section of the help's .HPJ file, and the help file needs to already be open. The change will last only until the help file is closed. 8 - Displays, in a pop-up window, the help topic identified by the context string/number in the Data field. The context string/number needs to be defined in the [MAP] section of the .HPJ file. 9 - Tests that the correct help file is displayed. If the correct help file is currently displayed, this command merely makes the help the active window. If the incorrect help file is displayed, WinHelp opens the correct file, and displays the help contents topic defined by the CONTENTS option in the [OPTIONS] section of the .HPJ file. Note: This command will not distinguish between two files of the same name, regardless of their paths. 11 - Displays the CitectSCADA Help Topics with either the Contents, the Index, or the Find tab selected, depending on which one was last used. Enter an empty string for the Data argument. 257 - Searches the help index for your keyword (as specified in the Data field) and displays the first topic in the index with an identical match. If there is no match, displays the index with your keyword already entered. To display the index without passing a keyword, enter an empty string for the Data argument. 258 - Executes the Help macro string specified in the Data field. Help needs to be running and the help file needs to be open, or the message is ignored. 260 - Displays, in a pop-up window, the help topic identified by the context string/number in the Data field. 261 - Searches the help index for your keyword (as specified in the Data field) and displays the first topic in the index with an identical match. If there is no match, displays the index with your keyword already entered. To display the index without passing a keyword, enter an empty string for the Data argument.
1271
Data:
The context string/number or keyword of the help topic that is requested.
Return Value
WndViewer
Example
WndHelp("MyHelp.HLP", 3, 1); ! Displays the "MyHelp" Contents page. WndHelp("C:\Help\Process.HLP", 8, 239); ! Displays topic labelled "239" in the "Process" help file.
WndInfo
Gets information on the window system (such as the widths and heights of the various elements displayed by Windows). WndInfo() can also return flags that indicate whether the current version of the Windows operating system is a debugging version, whether a mouse is present, or whether the functions of the left and right mouse buttons have been exchanged.
Syntax
WndInfo(iType) iType:
The system measurement to be retrieved. Measurements are in pixels. The system measurement needs to be one of the following values:
0 - Width of the screen. 1 - Height of the screen. 2 - Width of the arrow bitmap on a vertical scroll bar. 3 - Height of the arrow bitmap on a horizontal scroll bar. 4 - Height of the window title. This is the title height plus the height of the window frame that cannot be sized (SM_CYBORDER). 5 - Width of the window frame that cannot be sized. 6 - Height of the window frame that cannot be sized. 7 - Width of the frame when the window has the WS_DLGFRAME style.
1272
8 - Height of the frame when the window has the WS_DLGFRAME style. 9 - Height of the scroll box on vertical scroll bar. 10 - Width of the scroll box (thumb) on horizontal scroll bar. 12 - Height of the icon. 13 - Width of the cursor. 14 - Height of the cursor. 15 - Height of a single-line menu bar. This is the menu height minus the height of the window frame that cannot be sized (SM_CYBORDER). 16 - Width of the window client area for a fullscreen window. 17 - Height of the window client area for a fullscreen window (equivalent to the height of the screen minus the height of the window title). 18 - Height of a Kanji window. 19 - Non-zero if the mouse hardware is installed. 20 - Height of arrow bitmap on a vertical scroll bar. 21 - Width of arrow bitmap on a horizontal scroll bar. 22 - Non-zero if the Windows version is a debugging version. 23 - Non-zero if the left and right mouse buttons are swapped. 24-27 - Not Used 28 - Minimum width of the window. 29 - Minimum height of the window. 30 - Width of bitmaps contained in the title bar. 31 - Height of bitmaps contained in the title bar. 32 - Width of the window frame that can be sized. 33 - Height of the window frame that can be sized. 34 - Minimum tracking width of the window. 35 - Minimum tracking height of the window. 76 - x co-ordinate of upper left corner of virtual screen 77 - y co-ordinate of upper left corner of virtual screen 78 - width of virtual screen 79 - height of virtual screen 80 - number of monitors available
Return Value
1273
height = WndInfo(1); ! get height of screen WinPos(width/2, height/2); ! move window to centre of screen monitors = WndInfo(80); ! get number of monitors available
WndMonitorInfo
Returns information about a particular monitor.
Syntax
iType:
Type The monitor measurement to be retrieved:
0 - x co-ordinate of upper left corner of monitor. 1 - y co-ordinate of upper left corner of monitor. 2 - width of monitor. 3 - height of monitor. 4 - x co-ordinate of upper left corner of monitor working area. 5 - y co-ordinate of upper left corner of monitor working area. 6 - width of monitor working area. 7 - height of monitor working area.
Return Value
Requested information about the selected monitor. See Also Window Functions
WndPutFileProfile
Puts a profile string into any .INI file.
Syntax
1274
sName:
The name of the variable.
sData:
The variable data.
sFile:
The .INI file name.
Return Value
WndGetFileProfile
Example
WndPutFileProfile(Name(), "What", "100", "USER.INI");
WndShow
Sets the display mode of any window of any application.
Syntax
nMode:
The window mode:
0 - Hide the window. 1 - Activate the window in normal mode. 2 - Activate the window in an iconized state. 3 - Activate the window in a maximized state. 4 - Display the window in its previous state without activating it.
1275
5 - Activate the window in its current state. 6 - Iconize the window. 7 - Display the window in an iconized state without activating it. 8 - Display the window in its current state without activating it. 9 - Activate the window in its previous state.
Return Value
WndFind
Example
WndShow(WndFind("Microsoft Excel"), 0); ! Hides the "Microsoft Excel" window.
WndViewer
Invokes the Microsoft Multimedia application.
Syntax
Command:
The type of help:
1 - Displays a Viewer topic (specified in the Data field) in the main Viewer window. 2 - Displays a Viewer topic (specified in the Data field) in a pop-up window. Data:
The context string of the Multimedia Viewer topic.
Return Value
1276
Note: CitectSCADA cannot test if the topic has been found or displayed correctly. For example, if you pass an invalid topic, the viewer will open with "Viewer topic does not exist" - but this function will return 0.
Related Functions
WndHelp
Example
WndViewer("MyFile.MVB",1, "Contents"); ! Displays the contents topic in the Multimedia file "MyFile.MVB". WndViewer("HelpFile.MVB",2, "HelpTip"); ! Displays the HelpTip topic in the Multimedia file "HelpFile.MVB" in a popup.
1277
XMLGetAttributeCount
XMLGetAttributeName
XMLGetAttributeValue
XMLGetChild
XMLGetChildCount
XMLGetParent
XMLGetRoot XMLNodeAddChild
XMLNodeFind
XMLNodeGetName XMLNodeGetValue
XMLNodeRemove
1278
XMLSetAttribute
Sets the value of specified attribute of the node in the XML document. If the attribute does not exist, it will be created.
XMLNodeAddChild
Creates an element node with the specified Name and Namespace and appends the node to the end of the list of child nodes of specified parent node in the XML document.
Syntax
INT XMLNodeAddChild(INT hDoc, INT hNode, STRING sName[, STRING sNamespace = "" ]) hDoc
Handle of the XML document the parent node belongs to. Returned by XMLCreate or XMLOpen.
hNode
Handle of the parent node.e.g. <shapes>, <polygons>, <polygon>. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
sName
The qualified name of the new element node.
sNamespace
Optional parameter. The namespace URI of the new node.E.g.<shapes xmlns="http://schneider-electric.com/shapes/v1">.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
The example adds a new element node to the root of XML document and then adds two new element nodes to the first created node.
1279
INT hDoc, hRoot, hNode; hDoc = XMLCreate(shapes, http://schneider-electric.com/shapes/v1); IF hDoc <> -1 THEN hRoot = XMLGetRoot(hDoc); IF hRoot <> -1 THEN hNode = XMLNodeAddChild(hDoc, hRoot, polygons); IF hNode <> -1 THEN XMLNodeAddChild(hDoc, hNode, polygon); XMLNodeAddChild(hDoc, hNode, polygon); END END END
<?xml version="1.0" encoding="utf-8" ?> <shapes xmlns="http://schneider-electric.com/shapes/v1"> <polygons> <polygon/> <polygon/> </polygons> </shapes>
XMLCreate
Use this function to create a new XML document in memory.
Syntax
INT XMLCreate(STRING sRootElement, STRING sNamespace = "") sRootElement: Root element of the XML document. sNamespace:
Optional. Namespace URI of root element.
Return Value
1280
XMLClose, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an empty XML document and sets root element to shapes and namespace of root element to http://schneider-electric.com/shapes/v1.
INT hDoc=XMLCreate("shapes",http://schneider-electric.com/shapes/v1);
XMLOpen
Reads an XML file from disk to create XML document.
Syntax
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLSave, XMLSetAttribute
Example
1281
XMLClose
Use this function to delete an XML document in memory
Syntax
Return Value
XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an empty XML document and sets root element to shapes and namespace of root element to http://schneider-electric.com/shapes/v1, then destroys the XML document.
XMLGetAttribute
Retrieves the attribute value of the node from an XML document in memory.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
1282
sAttributeName
Name of attribute.
Return Value
XMLClose, XMLCreate, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/, then gets value of the nodes attribute Language.
INT hDoc, hNode; STRING sValue; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hDoc <> -1 THEN sValue=XMLGetAttribute(hDoc,hNode,"Language"); End End
XMLGetAttributeCount
Gets number of attribute of specified XML node.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/, then gets number of attribute of the node.
INT hDoc, hNode; INT nCount; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hDoc <> -1 THEN nCount=XMLGetAttributeCount(hDoc,hNode); End End
XMLGetAttributeName
Gets name of specified XML Nodes attribute by using attribute index.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
iAttribute
The attribute index.
Return Value
1284
Related Functions
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/, then gets name of the first attribute of the node.
INT hDoc, hNode; STRING sName; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hNode <> -1 THEN sName=XMLGetAttributeName(hDoc,hNode,0); End End
XMLGetAttributeValue
Gets the value of the specified XML node's attribute by using attribute index.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
iAttribute
The attribute index.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/, then gets value of the first attribute of the node.
INT hDoc, hNode; STRING sValue; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hNode <> -1 THEN sValue=XMLGetAttributeValue(hDoc,hNode,0); End End
XMLGetChild
Retrieves the child node for the specified parent node in XML document in memory.
Syntax
hNode
Handle of the parent node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
iChild
The child index.
Return Value
1286
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then gets the root node, then gets the first child node of the root node.
INT hDoc, hRoot, hChild; hDoc = XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hRoot = XMLGetRoot(hDoc); IF hRoot <> -1 THEN hChild = XMLGetChild(hDoc,hRoot,0); End End
XMLGetChildCount
Retrieves the total number of child nodes for the specified parent node in an XML document in memory.
Syntax
hNode
Handle of the parent node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
Return Value
1287
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/, then gets the number of children of the node.
INT hDoc, hNode; INT nCount; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hDoc <> -1 THEN nCount=XMLGetChildCount(hDoc,hNode); End End
XMLGetRoot
Gets the root element of the specified XML document.
Syntax
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
1288
Following example creates an XML document from local file H:\Data\books.xml, then gets the root element.
XMLNodeGetName
Gets the name of the specified node.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/, then gets the name of the node.
1289
STRING sName; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hDoc <> -1 THEN sName=XMLNodeGetName(hDoc,hNode); End End
XMLNodeGetValue
Gets value of specified node.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matchs XPath expression /bookstore/book/, then gets the value of the node.
1290
IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hDoc <> -1 THEN sValue=XMLNodeGetValue(hDoc,hNode); End End
XMLGetParent
Gets the parent of specified node. If specified node is the root node in the tree, the parent is the document node.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matchs XPath expression /bookstore/book/, then gets the parent of the node.
1291
XMLNodeRemove
Removes specified XML node from its parent and XML document.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
INT hDoc, hNode; hDoc=XMLOpen(H:\Data\books.xml); IF hDoc <> -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hDoc <> -1 THEN XMLNodeRemove(hDoc,hNode); End End
XMLSave
1292
sQuery
Absolute path of the disk file that XML document is written to.
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSetAttribute
Example
INT hDoc, hNode; hdoc=XMLOpen("H:\Data_Backup\books.xml"); IF hDoc <> -1 THEN XMLSave(hDoc, "H:\Data_Backup\books.xml"); END
XMLNodeFind
Use this function to select the first XML node that matches the XPath expression.
Syntax
sQuery
1293
XPath Expression
Return Value
Handle of the first XML node that matches the XPath expression, or BAD HANDLE on error.
Related Functions
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave, XMLSetAttribute
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/
XMLSetAttribute
Use this function to set the value of specified attribute of the node in the XML document. If the attribute does not exist, it will be created.
Syntax
INT XMLSetAttribute(INT hDoc, INT hNode, STRING sName, STRING sValue) hDoc
Handle of the XML document. Returned by XMLCreate or XMLOpen.
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent or XMLNodeFind.
sName
The name of the attribute.
sValue
1294
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLNodeSetValue, XMLOpen, XMLSave
Example
Following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/ and sets the value of the nodes attribute Language to English.
INT hDoc, hNode; hDoc = XMLOpen(H:\Data\books.xml); IF hDoc less -1 THEN hNode = XMLNodeFind(hDoc,/bookstore/book/); IF hNode less -1 THEN XMLSetAttribute(hDoc, hNode, Language, English); END END
XMLNodeSetValue
Sets the value of the specified node.
Syntax
hNode
Handle of the node. Returned by XMLGetRoot, XMLGetChild, XMLGetParent, XMLNodeFind.
sValue
Value of the element node.
1295
Return Value
XMLClose, XMLCreate, XMLGetAttribute, XMLGetAttributeCount, XMLGetAttributeName, XMLGetAttributeValue, XMLGetChild, XMLGetChildCount, XMLGetParent, XMLGetRoot, XMLNodeAddChild, XMLNodeFind, XMLNodeGetName, XMLNodeGetValue, XMLNodeRemove, XMLOpen, XMLSave, XMLSetAttribute
Example
The following example creates an XML document from local file H:\Data\books.xml, then selects the first node that matches XPath expression /bookstore/book/title and sets the nodes value to Harry Potter.
INT hDoc, hNode; hDoc = XMLOpen("H:\Data\books.xml"); IF hDoc <> -1 THEN hNode=XMLNodeFind(hDoc,"/bookstore/book/title"); IF hNode <>-1 THEN XMLNodeSetValue(hDoc,hNode,"Harry Potter"); End End
1296
Part: 4
Technical Reference
This section contains information for Users and describes the following:
Cicode Errors Browse Function Field Reference
1297
1298
Hardware related errors Cicode and general errors Mail API errors
Hardware/Cicode Errors
CitectSCADA 'traps' system errors automatically. When CitectSCADA detects a system error, it generates a hardware alarm, and the corresponding error message is placed in the alarm description. Each error has an associated (unique) error number. You can use the IsError() function to get the number of the last error. Alternatively, you can trap and process errors within your user functions. Use the ErrSet() function to enable or disable error trapping.CitectSCADA 'traps' system errors automatically. When a system error occurs, CitectSCADA generates a hardware alarm, and the corresponding error message is placed in the alarm description. Each error has an associated (unique) error number. Number 0 means no error, errors start from 1.
Range Source PLC or I/O Device Generic errors General Cause
1 - 31
The I/O Device is reporting an error, or CitectSCADA is experiencing the reported error trying communicate with an I/O Device. Often caused by incorrect configuration or poor cabling. For a detailed list of these errors see Generic Errors.
256 -511
General errors are wide ranging, from animation to server problems. However, there are two main causes of general errors: 1. Device External devices such as printers, databases, and files can cause many different hardware errors since they are beyond the control of CitectSCADA. Often the device itself is improperly configured or non-existent. 2. Cicode
1299
Cicode errors are generated when your project configuration calls a Cicode function in an invalid way, or when a Cicode function returns an error or does illegal operations. For a detailed list of these errors see Cicode and General Errors. 382 - 383 Invalid tag data This will indicate that the tag data validation process has identified a discrepancy with the tag index values. See Validating distributed project data for tag-based drivers for more information.
You can use the IsError() function to get the number of the last error. Alternatively, you can trap and process errors within your user functions. Use the ErrSet() function to enable or disable error trapping.
53
The tag is not known by the server being talked to at this time.
55 256
257
1300
Error No.
Error title
Description disable range checking on PLC variables with the CodeSetMode() function.
258
A buffer has been overrun. More data has been passed to a function than it can write to its temporary buffers. Try again by calling the function twice, with half the data in each call. An array passed to a function is too small for the data requested. Define a larger array or reduce the maximum data size requested. The specified path to a device or file does not exist. During a function call (that tried to open a file), a non-existent path was specified. Call the function again with the correct path. The specified file or device does not exist. During a function call (that tried to open a file), the file could not be found. Call the function again with the correct file name. This error will also be detected if you try to call TrnDelHistory() on a file that has not been added using TrnAddHistory(). The specified file cannot be opened. During a function call (that tried to open a file), the file could not be opened. There may be a mode error (for example, from trying to open a read-only file in write mode), or the file may be open by others, or the operating system resources may be too low to open the file. Check that the file does exist (use File Manager), and that you have the correct rights to open it. (Check with your network supervisor that you have correct rights to open the file).
259
260
261
262
263
The specified file cannot be read. Either an error has been detected during a read operation, or the end of file was unexpectedly found, or a disconnection from of the file server occurred, or the operating system is out of resources.
1301
Description The specified file cannot be written to. During a function call (that tried to write to a file), a write error has been detected. There could be a disk full error, or a disconnection from of the file server may have occurred, or the operating system is out of resources. An attempt was made to open a file of the wrong type, for example, you tried to open an ASCII file as a dBASE file. The specified field does not exist in the device or database. A function that is trying to access an individual field in a database cannot find that field. Check that you have specified the correct field name and database name. An operation has been attempted on a file or device that is of the wrong mode, for example, you tried to perform a seek on a printer device. The requested key was not found when a key search was performed on a database device, that is the record specified on an indexed search cannot be found. Either the record does not exist or you have specified the wrong key. A bad handle has been passed to a function. You have called a function that requires a device handle, font handle, window handle, etc., but you passed a number that does not associate with a read device, font, or window (for example, you called WinGoto(100) when no window with the handle "100" exists). Check where the handle or number was retrieved from, and verify that it is the same handle. This error may also be detected if you have closed or destroyed the resource and you then try to access it. All the available file handles have been used, that is too many files or databases are open at the same time. Open fewer
265
266
267
268
269
271
1302
Error No.
Error title
Description files at one time or increase the number of file handles in the [CtEdit]DBFiles parameter.
272
Out of memory
CitectSCADA is out of memory. Increase the amount of memory in the computer or use smaller databases. An attempt has been made to divide a number by zero. An invalid argument has been passed to a Cicode function. This is a general error message and is generated when arguments passed to a function are out of range or are invalid. Check the value of arguments being passed to the function. If arguments are input directly from the operator, you should check that the correct arguments are being passed to the function. A calculation has resulted in a numeric value overflow. Check for operations that will generate large numbers. A user has requested an operation for which he or she has no privilege. A user has requested data that does not belong to the current user area. A request has been made to run a report that is already running. You can get the current state of a report with the RepGetControl() function. You can ignore this error message (because the report is already running). The report cannot run at the rate requested in the configuration. An attempt could have been made to run a report too frequently, and the required data cannot be read from the I/O Device (s) in time for the next report.
273
Divide by zero
274
275
Overflow
276
277
278
279
1303
Description The specified report name does not exist, or the user has no privilege to run the report, or the report is not in the current user area. Check the name of the report and the current user's privilege and areas. The specified CitectSCADA server cannot be found. Either the server is not running or there is some disturbance in the network. Check that the network is set up correctly, and you are using the same Server Name on both the client and server. You cannot block the foreground CitectSCADA task. You may have called a blocking function from one of the Page animation databases. The trend cannot run at the rate requested in the configuration. An attempt could have been made to trend the data too frequently, and the required data cannot be read from the I/O Device (s) in time for the next trend. Either increase the performance of the communication link to the PLCs or slow the rate of trend data acquisition. An attempt was made to access a device that is disabled. You can disable any devices (printers and other logging devices) with the DevDisable() function. When CitectSCADA (or your Cicode function) tries to access a disabled device, this message returns and all output is lost. The foreground Cicode task is taking too long to animate the display page. The Cicode is too complex and is taking too long to execute. Simplify the Cicode that is animating the page, or increase the [Code] TimeSlice parameter. If you cannot simplify the Cicode, you can create a separate task using TaskNew() to calculate your complex operation, and then use the Display functions to display the
281
282
283
284
Device is disabled
285
1304
Error No.
Error title
Description results. Cicode running from a TaskNew() call is in background mode and can run as long as required.
286
CitectSCADA has run out of Cicode tasks. Run fewer tasks (for example, reports, key commands, and Cicode tasks) in parallel, or increase the number of tasks with the [Code]Threads parameter. This error can be caused by a configuration error if you keep creating tasks that do not finish. An invalid floating-point number has been found. Check the floating-point data from the I/O Device. CitectSCADA is out of dynamic buffers. You have called a function that requests buffer space but no buffers are available. Check which function is causing the error and increase the associated buffers, or slow the rate of transfer to that function. If the error occurs on a server or LAN device, increase the number of buffers with the [Lan]ReadPool parameter. This error can also be detected if something is stopping the release of the buffers, for example, if network communication has stopped or a PLC has just come off-line. The error 'Out of buffers' can also be generated in the following ways: Calling QueWrite() when the queue functions have run out of buffers. You can increase the number of queue buffers with the [Code] Queue parameter. Calling WinFree() to free the last Cicode window. If WinFree() did free the last window, CitectSCADA would have no windows left. To verify which function is causing the hardware error, display the {ERRPAGE} and {ERRDESC} fields on the hardware alarm.
287
288
Out of buffers
289
1305
Error No.
Error title
290
Not finished
A request has been made for trend data that has not yet finished trending. The specified file is not in CitectSCADA format. The file (trend, graphic, or any other file) is in an invalid format. Check that the name of the file is valid or that the file has not become corrupted. The specified function name does not exist. You have tried to create a task, or called a remote procedure, or set an event function that does not exist. A general file error has been detected. Either a general hardware error has occurred, or the operating system is out of resources, or the file server is down. The end of the file was found. An attempt was made to read data off the end of a file or database. A Cicode evaluation stack overflow has occurred. There are too many local function variables or nested function calls. Reduce the number of local variables or increase the [Code] Stack parameter. The Cicode stack is used to store local function variables and function calls. If you have many nested functions and a large number of local function variables, the Cicode stack may overflow. When the Cicode stack overflows, the Cicode that caused the overflow is halted. You can estimate the size of the stack by counting the maximum number of local function variables in the deepest function calls. For example, if function A has 10 variables and calls function B with 30 variables, which calls function C with 40 variables, the stack needs to be 10 + 30 + 40 = 80 deep.
291
292
Invalid function
293
File error
294
File EOF
295
1306
Description An attempt has been made to read an element from an empty queue. The owner of a Cicode semaphore was halted, killed, or returned without releasing the semaphore. Reset the shared resource back to a known state (because the task that died may have left it in a mess), and then continue. For example, if you are sharing a printer, do a form feed. The requested semaphore was still in use after the specified timeout. Either try to get the semaphore again or abort the operation and tell the operator of the detected error. The specified form or command was cancelled. This error is returned when a user presses the Cancel button on a form. The normal procedure is to abort the operation. The trend does not exist at the specified AN and page. A trend function may have been called when the trend is not defined for that AN. The required trend pen name does not exist in the Trends database or is not in the current user area. Check that the pen name exists and check the current user's privilege and area. The requested trend data is not valid. Either the I/O Device data was bad, or the CitectSCADA trend server was shut down, or the trend data was disabled. The AN specified in the function is not defined. You called one of the DspXXX animation functions, but you specified an animation number that was out of range or that had been deleted. CitectSCADA has detected that a file
297
298
Semaphore timeout
299
Cancelled
300
301
302
303
304
1307
Error No.
Error title
Description server has become inoperative, and will switch to the standby file server. The file server's inoperative condition is due to errors of the network or of the file server computer. This error is displayed only if you have enabled redundant file servers. If a redundant file server is not enabled, CitectSCADA and Windows become inoperative when the file server becomes inoperative. You should report this error to the operators to fix the file server.
305
The same AN is being used for two different types of animation. This error is detected if you try to display two (or more) incompatible types of animation on the same AN (for example, you try to display a symbol at a AN where a bar graph is already displayed). Check the configuration. If you need to display a new animation, you need to first delete the old animation with the DspDel() function. A maximum of 1000bytes (1Kb) can be returned from a single field call. If the field data is larger than this limit, it is truncated. You have tried to access a database where one of the fields is greater than 1000 bytes in size. Change the database field size to less than 1000 bytes so it can be accessed. In fact, you should change the field size to less than 256 bytes, the maximum allowable length of a Cicode string. A general SQL error. Call the SQLErrMsg() function for details of the detected error. Data has been requested from a field that contained no data, or the SQL server does not support this type of field data. CitectSCADA will return an empty string. Call the SQLFieldInfo() function to list the fields in the database. You have requested trend data that was gated (set to logging disabled) by the trigger expression (that is when it was acquired). The data is returned with the
306
307
308
309
1308
Error No.
Error title
310
Two servers are running incompatible versions of the CitectSCADA software. Install the latest version on each server. Contact Citect Technical Support to arrange for an upgrade. When the Alarm server shuts down it writes an alarm save file. If the alarm server is in tag mode (rather than record mode) this message will display. You can set the mode with the [Alarm]SaveStyle parameter. You can ignore this message as it is an alert only. A generic MAPI error has been detected. Call the MailError() function to retrieve the MAPI error. The MAPI mail system is not installed, or incorrectly installed on the computer. The computer is not logged on to the MAPI mail system. Call the MailLogon() function to log on to the MAPI mail system. No mail was available. This message is returned from the MailRead() function if no mail is available. The dBASE file is being accessed by another user. Check if the dBASE file has been opened in exclusive mode by the other user. This error can also be detected if another user is updating the dBASE file, and will usually occur if it is an indexed database, and the file is on a slow file server. You can adjust dBASE access with the [General]LockRetry and [General]LockDelay parameters. The operation is not supported in this version of CitectSCADA. You need to upgrade to a higher version.
311
312
313
No MAPI
314
MAPI offline
315
MAPI no mail
316
317
1309
Description You have called the PageGoto(), PageNext (), PagePrev(), PageDisplay(), or PageLast() as an exit command in the Pages database. CitectSCADA is low on physical memory. Increase available physical memory (not virtual memory). Reduce the size of SMARTDRV cache, close any other windows programs that are running, or add more RAM to your computer. You can set the minimum size of memory required by CitectSCADA with the [Memory]MinPhyK parameter. This parameter sets a value for the minimum physical memory before CitectSCADA will generate this error message. This error may also be detected if your swap file is large (that is greater than 20 Mb). Reduce the size of your swap file. The swap file is configured with the Windows Control Panel (386 Enhanced icon).
319
320
The WinFree() function has been called but CitectSCADA has no windows left. (Be aware that the last window and any child windows owned by the last window cannot be removed.) The specified font cannot be found. Check the font name. CitectSCADA has detected an error on the network. A Super Genie variable has not been associated correctly. This error can be detected if a variable passed to the Super Genie is the wrong data type or the variable does not exist. The error will also be detected if the Ass() function has not been called for the variable. Changes have been made to the project while the system was running. Either restart the system or shutdown and recompile.
321
322
323
325
1310
Description The CitectSCADA compiler could not be found. Either the computer has run out of memory, or the compiler has been removed from its directory. An attempt was made to create a user of a type that has not been defined in the users database. An attempt was made to create a new user with the same name as an existing user. An attempt was made to display both a periodic trend and an event trend in the same trend window. Check the project configuration (Trend Tags and Page Trends databases) for mixed trends displayed in a trend window. One of the arguments passed to this trend function is only valid for event type trends. The trend name inside the trend file does not exist in the trend database. It is likely that the trend file belongs to a trend which is deleted from the system configuration. Plot functions are to be written in sequence since they depend on the data set up by other plot functions. Please refer to the description section for each Plot Function for the order of plot functions. An undefined plot marker symbol has been used. Use the PlotSetMarker function before the PlotLine, PlotXYLine or PlotMarker functions. The subgroup size specified for this SPC trend is not valid. The trend cursor is currently disabled.
327
328
329
336
337
338
339
340
341
1311
Description The DebugBreak() Cicode function has been called. This indicates an invalid condition detected in user written Cicode. Enable the Cicode debugger to find the cause of the problem. A breakpoint has been hit in foreground Cicode. Foreground Cicode cannot be blocked. You can disable this error message in Debug Options, accessed through the Debug menu in the Cicode Editor. This error occurs when the string being used to return an error message is not long enough for the information to go into it. This error is returned when the requested data is not ready to be returned. Try again later. The dynamic point count has exceeded the point limit. See CitectSCADA Licence Point Count. An assertion in your Cicode has been proven FALSE, and the task terminated. Assertions are made using the Assert() function. If you set the [Code]DebugMessage parameter to 1, the assertion is logged and the operator prompted. The tag property does not exist. A RDB file is not found. Try a full compile and re-start. Problems connecting to the FTP server for file copy. Check that the service is running correctly by using a 3rd party tool outside CitectSCADA. The automation object to be used is not known or registered. The automation objects interface no longer exists. This is either a logic or code
343
344
Format overflow
345
346
347
348 350
353
354
355
1312
Error No.
Error title
Description error.
356
Generic automation exception code for logging issues. Formatting issues likely due to too many arguments (automation) Less arguments available than expected (automation) An object tried to be created when it was already existed and it was not expected to exist. Check your cicode (automation) The name of an object did not match the internal records. Check your cicode (automation). An animation object id was not found in the records. Try a full compile and restart. CitectSCADA has run out of Cicode tasks while processing ActiveX events. Create fewer concurrent ActiveX events, or increase the number of tasks with the [Code]Threads parameter. Internal error in cicode handling of objects. Try a full recompile and restart. Internal error in cicode handling of objects. Try a full recompile and restart. Unable to print the specified file on the specified port. Unable to display the animation at the given AN. Unable to display the given animation as text. There are no FileFind instances to close.
357
358
359
360
361
362
363
364
367
368
369
370
1313
Error No.
Description
371
The retry count for the dialback response has been exceeded. The ActiveX graphics data was unable to be loaded as it is an unrecognised object. A Date and/or time conflict has been detected. If you are attempting a TrnAddHistory(), verify that the file you are adding does not have a conflicting time or date with existing trend files. The password has expired. Change password or adjust the [General]PasswordExpiry settings. An error has occurred while attempting to write to a trend file. An error has occurred while attempting to read from a trend file. The Users.DBF cannot be modified by direct user manipulation. The user name specified already exists in the Users.DBF. The file is not in the desired format. It may be corrupted. Page data / variable tag data mismatch with tag-based driver. Cicode task has been flagged as locked or inactive. This will not apply if a Cicode task was killed deliberately by the Cicode logic. Unable to download the webclient signature file. Attempting to open a DBF file without checking to see if it has changed.
372
374
375
Password Expired
376
Error Writing to Files of Trend Error Reading Files of Trend Cannot modify field
377
379
380
Name Exists
381
382
Page data / variable tag data mismatch The code this queue/semaphore was waiting for exited due to an error
384
385
388
1314
Description A number of Cicode functions can only be run in a non Web context. This error is flagging that such a function was tried from a Web client. The timeout for receiving alarm data from the redundant alarm server has been exceeded. The RDB page version does not match the one expected after compilation. The remote licence can not be found. The operation could not be completed because the project or file is read only. The redundant server is current not available or was not found. Cicode call is ambiguous because no cluster was specified. The provided cluster name was not seen as a valid cluster name. A cluster name and a tag with a cluster name prefix were both passed, but they do not match each other. The operation cannot continue as the cluster is not connected. The operation cannot continue as the cluster is already connected. Databrowse session currently being connected and is not yet available for further commands. This normally means that data has been requested from the wrong client / server type, that is a client request on a server or vice versa.
392
393
RDB and associated page mismatch Remote license lost Project or file is ReadOnly Redundant server not found Cluster not specified
394 400
401
402
403
404
405
406
407
408
1315
Error title Databrowse type not found Databrowse session not found Databrowse session exists Databrowse session EOF
Description Browse type unknown. Check that the versions of citect32 are the same.
410
411
412
Cannot browse beyond end of file. No more records left in the browse. The specified field is not present in the file. The specified field is not valid for this browse function. Browse command unknown. Check that the versions of citect32 are the same. Internal flag that all clusters have been processed. Users use this in cicode to determine that there are no more clusters. The operation cannot continue as the cluster is required for operation of a server. There is no server of the required type configured on the server. An ID given to a Cicode function is not of the correct type. This functionality is not available outside a process boundary for example, AlarmFirstCatRec is only able to be called from inside the Alarm Server process. Citect's internal communications subsystem detected an error while trying to send a message.
413
414
415
Databrowse no command
416
417
418
No server of type on cluster Client / Server ID mismatch Not available outside process
419
420
421
1316
Description An attempt to make a call to a remote I/O device did not succeed. You can find more information on the cause of this problem (if it is reproducible) by setting [Dial]Debug=1 and [Dial]DebugLevel=3 and looking in the syslog.dat. Occurs when attempted to read the value before the initial value has been retrieved from the device. Occurs when attempt to read or subscribe to a tag that does not exist. Not used. An attempt to send a message via a name pipe has did not succeed. A function cannot be redirected to another component as a proxy RPC unless it is in the context of a Cicode call. The specified record is not valid for this browse function. The Cicode PlotMarker() function can only plot a symbol to the display. This error occurs when the PlotMarker() Cicode function is used with a user-defined marker and a printer was specified as the output when PlotOpen() was called. The [Alarm]SortMode parameter value on client is different as compared to the value on the alarm server. This value should be same in order to display alarms in correct order on the client. Values for [Alarm]SummarySort and [Alarm]SummarySortMode parameters on client are different as compared to the values on the alarm server. These values should be same in order to display alarm summary in correct order on the client. A specific tag property has been read in
423
424
425 426
No connector Write to named pipe did not succeed Redirect from non-Cicode task
427
428
429
430
431
432
1317
Error No.
Error title
Description synchronous mode, before the value has been retrieved from the server. (similar to subscription value is pending)
433
Some server side changes are now allowed for cicode, without restarting the client. This means that now it is possible to change a tag type to one that now cannot be converted as it was before. Eg val = TagA - TagB, If TagA has been converted from Integer to String, then the cicode will raise a cicode type mismatch as the '-' operation is not supported for strings Attempt to convert a value to a type that cannot store the value for example, ULong to Long, and the value is greater than the Long type can handle. The password is incorrect. Check that the user name and password are typed in correctly. Cannot load or initialize the Windows security provider. This indicates that the installation of operating system may be corrupted or the Windows security provider was not included. Cannot authenticate the given Windows user name and password. Check that the user name and password are typed in correctly Cannot find the authentication session during the authentication process for the Windows user. This indicates that there was miscommunications in between client and server. Cannot perform the role-check process for the Windows user. Check that the roles database in the project is not corrupted. The given Windows user is not linked to any role defined in the project.
434
436
437
439
440
441
442
No linked role
1318
Error title Acquire user credentials did not succeed Acquire user access token did not succeed
Description Cannot obtain the user credential handle from Windows. Cannot obtain the user access token. This indicates that the security context of the Windows user was invalid. Cannot encrypt the user information during the Windows user authentication process. This indicates that the security context of the Windows user was invalid. Cannot decrypt the user information during the Windows user authentication process. This indicates that the security context of the Windows user was invalid. Cicode UsrKernelTableInfo() has asked for a table that does not exist.
444
445
446
447
The name of the table can not be found in the kernel. Invalid logout
449
The logout was called when there is no one logged in or the logged on user is system default user. Invalid tag data has been detected. Occurs when a tag has been subscribed to, and attempted to read the value before the initial value has been retrieved from the server. An attempt has been made to terminate a SQL session by calling SQLDisconnect when it was opened by SQLCreate and SQLOpen, or by calling SQLClose and SQLDispose when it was opened by SQLConnect. Did not execute requested action on time. Access denied to perform requested action. Can not write to view-only client. User needs to login with valid user credentials to get write access.
450 453
457
512 513
514
Write unsuccessful
1319
Error title Can't swap pages from foreground Too Many arguments for function
Description Cannot swap the page on foreground cicode. Too many arguments have been passed to a Cicode function. Check the number of arguments being passed to the function. If arguments are input directly from the operator, you should check that the correct number of arguments are being passed to the function. Cicode call that triggers an RPC remote call is interrupted before the expected result is returned. A category number is out of its valid range (from 0 to 16375 inclusively). A record is deleted during reload of ART server. A trend records archive properties are changed during start-up or reload. A category priority is out of its valid range (from 0 to 255 inclusively). [Page]ComBreak and [Page]ComBreakText are obsolete parameters. Tag quality is uncertain and its value is the last usable value. Login did not authenticate correctly.
518
519
520
Alarm category out of range Data browse record is deleted Trend archive property mismatch Alarm priority out of range ComBreak is obsolete parameter Tag in Last Usable Value
521
522
523
524
525
526
Tran authentication unsuccessful High watermark reached on Tran Reduced size of resized page
527
High watermark is reached on transaction, network is overloaded. The specified resized page has been reduced in size to fit the constrains of the maximum height and width of 4096. Too few arguments have been passed to a Cicode function. Check the number of arguments being passed to the function.
528
529
1320
Error No.
Error title
Description If arguments are input directly from the operator, you should check that the correct number of arguments are being passed to the function.
530
A string with invalid pointer has been passed to SCADA execution system. Server responses to tag exists requests have timed out. The attempt to initiate a server side online change did not succeed because the server has not been fully initialized. The attempt to reload the main alarm server when the non-main alarm server is not reloaded first. An alarm command has succeeded on at least one cluster but has been unsuccessful on at least one other cluster in a multi cluster environment.
532 533
534
535
536
No record found for the oper- Indicates that for the given scope there is no ation record found for the requested operation. Operation unsuccessful Indicates that the requested operation was unsuccessful. The connection to database, such as the alarm runtime database has not been established. This could be the hosting server such as the alarm server is not available, or the logon to the database was unsuccessful. Load or parse error in the xml. Invalid Xpath expression. Invalid operation on an XML document Exceeded the boundary, unable to add more to xmlDocument or xmlNode. Cannot create a new connection or transaction, boundary exceeded. Specified dll is not a valid proxy dll. Specified method cannot be found in proxy dll. Specified method cannot be invoked from proxy dll.
537
540
XML Exception Invalid Xpath expression Invalid XML operation Exceeded XML Boundary
547
Exceeded Boundary
548 549
550
1321
Description More than one method in proxy dll matches the binding criteria. The method in proxy dll has one or more unspecified parameters Cannot load proxy dll.For example, proxy dll may have a dependency that cannot be found. Other errors occurred when processing a transaction. The transaction cannot be processed. Web service address provided is not valid/well formed URI Not all parameters are loaded before processing the transaction Tag name exceeds the 254 character length limit.
552
553
554
555
Invalid URI
556
557
The following CitectSCADA error codes are mapped to standard Windows socket errors. Generally these errors are beyond CitectSCADA's control, that is, there is a external reason why CitectSCADA cannot use the TCP/IP connection (assuming there are no Citect configuration issues).
Error No. 1330 1331 1332 Error title WSAENETDOWN Socket unreachable Network reset Description (10050) Network is down. (10051) Network is unreachable. (10052) Network dropped connection on reset. (10053) Software caused connection abort. (10054) Connection reset by peer. (10055) No buffer space available. (10060) Connection timed out.
1322
Error title Connection refused Name too long Host down Host unreachable
Description (10061) Connection refused. (10063) Item Name too long. (10064) Host is down. (10065) No route to host.
MAPI Errors
The table below describes the MAPI errors in Cicode.
Error number 0 Error title Description
The login did not succeed, either the login user is unknown, misspelt, or the password is incorrect.
The disk is full. The mail system will copy files into the temporary directory when mail is read. This can fill up the local hard disk. Insufficient memory to complete the command.
1323
MAPI_E_TOO_ MANY_SESSIONS MAPI_E_TOO_ MANY_FILES MAPI_E_TOO_ MANY_RECIPIENTS MAPI_E_ ATTACHMENT_NOT_ FOUND MAPI_E_ ATTACHMENT_OPEN_ FAILURE MAPI_E_ ATTACHMENT_ WRITE_ FAILURE MAPI_E_ UNKNOWN_ RECIPIENT MAPI_E_BAD_ RECIPTYPE MAPI_E_NO_ MESSAGES MAPI_E_ INVALID_MESSAGE MAPI_E_ TEXT_TOO_ LARGE MAPI_E_ INVALID_SESSION
You have tried to open too many sessions to the mail system.
10
11
12
Cannot open the specified attached file. Often because the file does not exist.
13
14
Recipient of the mail message is unknown. Check if the user is configured in the mail system or check the spelling of the user's name. Unknown recipient type.
15
16
17
18
Text message is too large to be sent. If you want to send large text messages, write the text to a file and attach the file to the mail message. Mail session is invalid. You should not get this error message; contact Technical Support for this product.
19
1324
20
MAPI_E_ TYPE_NOT_ SUPPORTED MAPI_E_ AMBIGUOUS_ RECIPIENT MAPI_E_MESSAGE_IN_USE MAPI_E_NETWORK_FAILURE MAPI_E_ INVALID_EDITFIELDS MAPI_E_ INVALID_ RECIPS MAPI_E_NOT_ SUPPORTED
You should not get this error message; contact Technical Support for this product.
21
The recipient of the mail message is ambiguous. Specify the exact user name to which the mail is to be sent.
22
Mail message is in use. You should not get this error message: contact Technical Support for this product. Mail cannot be sent or received as the network has experienced an error.
23
24
You should not get this error message; contact Technical Support for this product.
25
You should not get this error message; contact Technical Support for this product.
26
1325
1326
ACKTIME
12
hh:mm:ss [am|pm]. Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise ""
ACKUTC
12
Integer that represents a "time" value - the number of seconds since Jan 1, 1970 in UTC format not Local. Numeric value (integer) "Digital", "Analog", "Advanced", "Multi-Digital", "Time Stamped", "Time Stamped Digital", "Time Stamped Analog"
ACQERROR ALARMTYPE
6 16
1327
CATEGORY CLUSTER
16 32
COMMENT
64
CUSTOM1
Alarm custom field #1 Alarm custom field #2 Alarm custom field #3 Alarm custom field #4 Alarm custom field #5 Alarm custom field #6 Alarm custom field #7 Alarm custom field #8 Alarm Date in default format
64
CUSTOM2
64
CUSTOM3
64
CUSTOM4
64
CUSTOM5
64
CUSTOM6
64
CUSTOM7
64
CUSTOM8
64
DATE
12
short: dd-mm-yy [default] extended: dd-mm-yyyy Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise "". Note: The format can be changed by setting ExtendedDate to FALSE under the section [Alarm] in the citect.ini file.
DATEEXT
Extended Alarm
12
dd-mm-yyyy
1328
date DEADBAND Alarm deadband 12 For Analog, and Timestamped Analog alarms: Numeric value (real) hh:mm:ss
DELTATIME
12
DESC
254
For Analog Alarms "OFF", "ON", "ON State 2", "ON State 3", "ON State 4", "ON State 5", "ON State 6", "ON State 7", "DEVIATION", "RATE OF CHANGE", "LOW", "HIGH", "LOW LOW", "HIGH HIGH", "Invalid". For others - configured descriptions.
DEVIATION
Alarm deviation
12
For Analog, and Timestamped Analog alarms: Numeric value (real) Numeric value (real)
ENG_FULL
11
ENG_UNITS
The predefined values (see below) are in the Help.dbf of the bin directory but the user may specify it as a free text: %, Amps, deg, ft, ft/min, ft/s, ft/sec, gal, gal/h, gal/min, gal/s, gal/sec, Hz, kg, kg/h, kg/min, kg/s, kg/sec, km/h, kPa, kW, litres, lt, lt/h, lt/min, lt/s, lt/sec, m/min, m/s, m/sec, metres, Rev, Rev/h, RPM, t, t/h, Tonnes, Volts, Watts.
ENG_ZERO
The engineering zero scale for this value Extra Citect info
11
ERRDESC
80
1329
on alarms
description according to the configuration. 80 For Hardware alarms: the Citect page the alarm is assigned to. The logged variable name (clustername.tagname). If the expression contains simple Cicode containing a single tag name, such as "LT131" or "LT131<1000", the tag name is returned (in both these cases LT131). If the expression contains a function call or more than one tag name, an empty string is returned.
ERRPAGE
EXPRESSION
65
FILENAME
File where the trend data is to be stored The number of history files stored on the hard disk (for this tag) Alarm format
231
FILES
FORMAT
12
For Analog, and Timestamped Analog alarms: Numeric value (real) For non-Hardware alarms the configured full name of the event user if exists. Otherwise "System".
FULLNAME
20
GROUP
Alarm group
16
For Argyle (Multi-digital) Digital alarms: Numeric value The name of the help page. For Analog, and Timestamped Analog alarms: Numeric value (real) For Analog, and Timestamped
HELP HIGH
254 12
HIGHHIGH
Alarm highhigh
12
1330
Analog alarms: Numeric value (real) LOCALTIMEDATE Alarm Date and Time 24 yyyy-mm-dd hh:mm:ss[.ttt]. Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise "" LOGSTATE Log state text 13 "ACTIVE", "INACTIVE", "DISABLED", "ENABLED", "ACKNOWLEDGED", "LOW", "HIGH", "LOW LOW", "HIGH HIGH", "RATE", "DEVIATION", "CLEARED", "UNACKNOWLEDGED" For Analog, and Timestamped Analog alarms: Numeric value (real) For Analog, and Timestamped Analog alarms: Numeric value (real)
LOW
Alarm low
12
LOWLOW
Alarm lowlow
12
LSL
16
MILLISEC
80 64 For non-Hardware alarms: the event description. Analog alarm - Alarm state text. Otherwise - Configured alarm description.
Alarm description
80
NATIVE_NAME NATIVE_SUMDESC
80 80
Configured alarm name. For non-Hardware Analog alarms: the event state string. For non-Hardware other alarms: the event [or if it does not exist] the alarm description short: dd-mm-yy [default] extended: dd-mm-yyyy Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise "".
1331
OFFDATE
Event on date
12
Note: The format can be chaged by setting ExtendedDate to FALSE under the section [Alarm] in the citect.ini file. For non-Hardware alarms: ddmm-yyyy For High Resolution, Timestamped Digital and Timestamped Analog alarms it is the milliseconds part of the off time hh:mm:ss [am|pm]. Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise ""
OFFDATEEXT
12
OFFMILLI
OFFTIME
12
OFFTIMEDATE
12
For non-Hardware alarms: HH:MM:SS. Note: The format can be configured in the citect.ini file by specifying TimeDate under the section [Alarm].
OFFUTC
Integer that represents a "time" value - the number of seconds since Jan 1, 1970 in UTC format not Local. 8 "Invalid", "OFF", "ON", "ON State 2", "ON State 3", "ON State 4", "ON State 5", "ON State 6", "ON State 7" short: dd-mm-yy [default] extended: dd-mm-yyyy Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise "". Note: The format can be chaged by setting ExtendedDate to FALSE under the section [Alarm] in the citect.ini file.
OLD_DESC
ONDATE
Event on date
12
ONDATEEXT
12
1332
ONMILLI
For High Resolution, Timestamped Digital and Timestamped Analog alarms it is the milliseconds part of the on time hh:mm:ss [am|pm]. Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise ""
ONTIME
Event on time
12
ONTIMEDATE
12
For non-Hardware alarms: HH:MM:SS. Note: The format can be configured in the citect.ini file by specifying TimeDate under the section [Alarm].
ONUTC
Event on time
Integer that represents a "time" value - the number of seconds since Jan 1, 1970 in UTC format not Local. 8 A flag to indicate that the alarm is going to be paged. Values are 1 (TRUE) or 0 (FALSE). A freeform text field indicating the sequence of people to notify in the event the alarm occurred. In hh:mm:ss (hours:minutes:seconds). Numeric value (integer)
PAGING
PAGINGGROUP
80
PERIOD
The period of the history file Alarm category priority Alarm privilege PSI type code Process range Alarm rate
32
PRIORITY
16
16 12 For Analog, and Timestamped Analog alarms: Numeric value (real) Numeric value (real)
RAW_FULL
11
1333
value RAW_ZERO The raw zero scale for this value Running time in seconds Sample period of the trend in seconds PSI type code (of a scaled value, if scaling is applicable) Standard deviation Indicates tag is a Statistical Process Control (SPC) tag Number of starts Alarm state string 16 Numeric value (real) 16 11 Numeric value (real)
RUNNING
16
SAMPLEPER
16
SCALED_TYPE
Integer
SDEVIATION
SPCFLAG
STARTS
STATE
16
"OFF", "ON", "ON State 2", "ON State 3", "ON State 4", "ON State 5", "ON State 6", "ON State 7", "DEVIATION", "RATE OF CHANGE", "LOW", "HIGH", "LOW LOW", "HIGH HIGH", "Invalid" "Invalid", "OFF", "ON", "ON State 2", "ON State 3", "ON State 4", "ON State 5", "ON State 6", "ON State 7" For Argyle (Multi-digital) Digital alarms: "OFF". For others: "INVALID"
STATE_DESC
STATE_DESC0
Argyle state 0
64
STATE_DESC1
Argyle state 1
64
1334
For others: "INVALID" STATE_DESC2 Argyle state 2 64 For Argyle (Multi-digital) Digital alarms: "ON state 2". For others: "INVALID" STATE_DESC3 Argyle state 3 64 For Argyle (Multi-digital) Digital alarms: "ON state 3". For others: "INVALID" STATE_DESC4 Argyle state 4 64 For Argyle (Multi-digital) Digital alarms: "ON state 4". For others: "INVALID" STATE_DESC5 Argyle state 5 64 For Argyle (Multi-digital) Digital alarms: "ON state 5". For others: "INVALID" STATE_DESC6 Argyle state 6 64 For Argyle (Multi-digital) Digital alarms: "ON state 6". For others: "INVALID" STATE_DESC7 Argyle state 7 64 For Argyle (Multi-digital) Digital alarms: "ON state 7". For others: "INVALID" STORMETHOD Storage method for the SPC data The size of each subgroup Event description text 16 "Scaled" or "Floating Point"
SUBGRPSIZE
SUMDESC
80
Analog alarm - Event state text. Otherwise - Configured event [or alarm in case event not defined] description
SUMSTATE
16
Displays the last active state of the Alarm. "OFF", "ON", "ON State 2", "ON State 3", "ON State 4", "ON State 5", "ON State 6", "ON State 7", "DEVIATION", "RATE OF
1335
CHANGE", "LOW", "HIGH", "LOW LOW", "HIGH HIGH", "Invalid" SUMTYPE Event state 16 For non-Hardware alarms: "DISABLED", "UNACKNOWLEDGED", "ACKNOWLEDGED", "CLEARED".
TAG TAGEX
TAGGENLINK
TIME
hh:mm:ss [am|pm]. Note: works between: UTC time 1/1/1980 - UTC time 31/12/2037, otherwise ""
TIMEDATE
24
HH:MM:SS. Note: The format can be configured in the citect.ini file by specifying TimeDate under the section [Alarm].
TOTALISER
Running total of value Last trigger value, used to check for rising edge of the trigger code The variable tag that triggers data logging
16
0 OR 1
65
The variable tag (clustername.tagname) that triggers data logging. If the trigger contains simple Cicode containing a single tag name, such as "LT131<50", the tag name is returned (in this case LT131). If the expression con-
1336
tains a function call or more than one tag name, an empty string is returned. TYPE Alarm, Trend or Tag type string 16 For Alarms: "DISABLED", "UNACKNOWLEDGED", "ACKNOWLEDGED", "CLEARED" For Trends: "1" - Periodic, "2" - Event, "3" Periodic Event For Tags: RDT_DIGITAL 0 RDT_INTEGER 1 RDT_REAL 2 RDT_BCD 3 RDT_LONG 4 RDT_LONG_BCD 5 RDT_STRING 7 RDT_BYTE 8 RDT_UINTEGER 10 RDT_ULONG 18 TYPENUM USERNAME Alarm type Event user name 4 16 Numeric value (integer) For non-Hardware alarms the configured name of the event user if exists. Otherwise "System". USL Upper specification limit Formatted alarm value 16
16
Analog Alarms - numeric value formatted according to configuration. Numeric value (real)
The value to be added to the totaliser while trigger is true Process mean
16
XDOUBLEBAR
16
1337
The name of the cluster to which the server belongs. Comment The port number the server is listening on for legacy connections. If no legacy port number was configured, this field contains the default legacy port number for the server type. Indicates whether the server is configured as a primary or standby.
16
COMMENT LEGACYPORT
MODE
16
For Alarm, Report and Trend servers: 1 - primary 0 - standby For I/O servers the MODE field is set to "0".
NAME NETADDR
The name of the server The network addresses associated with the server.
16 70 A comma-separated list of one or more names. The field contains the network address names as configured, and not IP addresses. Number between 1 and 65535.
PORT
The port number the server is listening on. If no port number was configured, this field contains the default port number for the server type. Specifies the purpose of the server
16
TYPE
16
1338
Index
:
: operator 81
_
_ObjectCallMethod Cicode function 159 _ObjectGetProperty Cicode function 161 _ObjectSetProperty Cicode function 161
A
Abs Cicode function 618 AccControl Cicode function 151 AccumBrowseClose Cicode function 152 AccumBrowseFirst Cicode function 153 AccumBrowseGetField Cicode function 153 AccumBrowseNext Cicode function 154 AccumBrowseNumRecords Cicode function 155 AccumBrowseOpen Cicode function 156 AccumBrowsePrev Cicode function 157 Accumulator Cicode functions 151 ActiveX Cicode functions 159 Alarm Cicode functions 173 Alarm Filter Cicode functions 178 AlarmAck Cicode function 179 AlarmAckRec Cicode function 182 AlarmAckTag Cicode function 183 AlarmActive Cicode function 183 AlarmCatGetFormat Cicode function 184 AlarmClearRec Cicode Function 187 AlarmComment Cicode function 188 AlarmCount Cicode Function 189 AlarmCountList Cicode Function 192 AlarmDisable Cicode function 193 AlarmDisableRec Cicode function 195 AlarmDsp Cicode function 196 AlarmDspClusterAdd Cicode function 198 AlarmDspClusterInUse Cicode function 199 AlarmDspClusterRemove Cicode function 199 AlarmDspLast Cicode function 200 AlarmDspNext Cicode function 202
AlarmDspPrev Cicode function 203 AlarmEnable Cicode function 203 AlarmEnableRec Cicode function 206 AlarmEventQue Cicode function 207 AlarmFilterClose Cicode function 208 AlarmFilterEditAppend Cicode function 209 AlarmFilterEditClose Cicode function 209 AlarmFilterEditCommit Cicode function 210 AlarmFilterEditFirst Cicode function 211 AlarmFilterEditLast Cicode function 212 AlarmFilterEditNext Cicode function 212 AlarmFilterEditOpen Cicode function 213 AlarmFilterEditPrev Cicode function 214 AlarmFilterEditSet Cicode function 215 AlarmFilterOpen Cicode function 216 AlarmFirstCatRec Cicode function 217 AlarmFirstPriRec Cicode function 218 AlarmFirstTagRec Cicode function 220 AlarmGetDelay Cicode function 221 AlarmGetDelayRec Cicode function 221 AlarmGetDsp Cicode function 223 AlarmGetFieldRec Cicode function 226 AlarmGetFilterName Cicode function 229 AlarmGetInfo Cicode function 230 AlarmGetOrderbyKey Cicode function 231 AlarmGetThreshold Cicode function 232 AlarmGetThresholdRec Cicode function 232 AlarmHelp Cicode function 234 AlarmNextCatRec Cicode function 234 AlarmNextPriRec Cicode function 236 AlarmNextTagRec Cicode function 237 AlarmNotifyVarChange Cicode function 239 AlarmQueryFirstRec Cicode function 240 AlarmQueryNextRec Cicode function 241 alarms, hardware 1299 AlarmSetDelay Cicode function 243 AlarmSetDelayRec Cicode function 243 AlarmSetInfo Cicode function 244 AlarmSetThreshold Cicode function 249 AlarmSetThresholdRec Cicode function 251 AlmBrowseAck Cicode function 252
1339
Index
AlmBrowseClose Cicode function 253 AlmBrowseDisable Cicode function 253 AlmBrowseEnable Cicode function 254 AlmBrowseFirst Cicode function 254 AlmBrowseGetField Cicode function 255 AlmBrowseNext Cicode function 256 AlmBrowseNumRecords Cicode function 256 AlmBrowseOpen Cicode function 257 AlmBrowsePrev Cicode function 259 AlmSummaryAck Cicode function 260 AlmSummaryClear Cicode function 260 AlmSummaryClose Cicode function 261 AlmSummaryDelete Cicode function 261 AlmSummaryDeleteAll Cicode function 262 AlmSummaryDisable Cicode function 263 AlmSummaryEnable Cicode function 263 AlmSummaryFirst Cicode function 264 AlmSummaryGetField Cicode function 265 AlmSummaryLast Cicode function 266 AlmSummaryNext Cicode function 266 AlmSummaryNumRecords Cicode function 267 AlmSummaryOpen Cicode function 268 AlmSummaryPrev Cicode function 269 AlmTagsAck Cicode function 270 AlmTagsClear Cicode function 271 AlmTagsClose Cicode function 271 AlmTagsDisable Cicode function 272 AlmTagsEnable Cicode function 272 AlmTagsFirst Cicode function 273 AlmTagsGetField Cicode function 273 AlmTagsNext Cicode function 275 AlmTagsNumRecords Cicode function 275 AlmTagsOpen Cicode function 276 AlmTagsPrev Cicode function 278 AnByName Cicode function 162 ArcCos Cicode function 619 ArcSin Cicode function 619 ArcTan Cicode function 620 AreaCheck Cicode function 651 argument structure 54 arguments default values 58 key sequences as 25 passing data to 33
arguments, string 33 Ass Cicode function 972 AssChain Cicode function 974 AssChainPage Cicode function 981 AssChainPopUp Cicode function 982 AssChainWin Cicode function 982 AssChainWinFree Cicode function 984 Assert Cicode function 652 Assert function 148 AssGetProperty Cicode function 986 AssGetScale Cicode function 989 AssInfo Cicode function 990 AssInfoEx Cicode function 994 AssMetadata Cicode function 975 AssMetadataPage Cicode Function 976 AssMetadataPopUp Cicode function 977 AssMetadataWin Cicode function 978 AssPage Cicode function 998 AssPopUp Cicode function 999 AssScaleStr Cicode function 1001 AssTag Cicode function 1003 AssTitle Cicode function 1005 AssVarTags Cicode function 1005 AssWin Cicode function 1007
B
background tasks 101 Beep Cicode function 653 bit operators 89 Breakpoint window 114 breakpoints 124 browse function field reference 1327
C
calculations variables in 22 CallEvent Cicode function 475 caret (^) character 34 ChainEvent Cicode function 479 CharToStr Cicode function 945 Cicode Editor toolbar options 113 Cicode errors 1300
1340
Index
Cicode keywords restricted Cicode keywords 16 CitectColourToPackedRGB Cicode function 293 CitectInfo Cicode function 654 CitectVBA Watch window 117 Clipboard Cicode functions 281 ClipCopy Cicode function 281 ClipPaste Cicode function 282 ClipReadLn Cicode function 282 ClipSetMode Cicode function 283 ClipWriteLn Cicode function 284 cluster Cicode functions 285 ClusterActivate Cicode function 285 ClusterDeactivate Cicode function 286 ClusterFirst Cicode function 286 ClusterGetName Cicode function 287 ClusterIsActive Cicode function 288 ClusterNext Cicode function 288 ClusterServerTypes Cicode function 289 ClusterSetName Cicode function 289 ClusterStatus Cicode function 290 ClusterSwapActive Cicode function 291 code debugging 122 CodeSetMode Cicode function 1075 CodeTrace Cicode function 659 cohesion 141 color Cicode functions 293 ComClose Cicode function 299 comments 45 formatting 134 communication Cicode functions 299 ComOpen Cicode function 300 Compile Errors window 117 ComRead Cicode function 302 ComReset Cicode function 303 ComWrite Cicode function 304 constants, standards for 130 controlling tasks 102 converting integers to strings 81 copying variables 21 Cos Cicode function 620 coupling 142 CreateControlObject Cicode function 162
D
data displaying, using expressions 27 logging expression 28 returning 36 data operators 87 data types 51, 64 Date Cicode function 1114 date functions 39 DateAdd Cicode function 1116 DateDay Cicode function 1116 DateInfo Cicode function 1117 DateMonth Cicode function 1118 DateSub Cicode function 1119 DateWeekDay Cicode function 1120 DateYear Cicode function 1121 DDE Cicode functions 307 DDEExec Cicode function 308 DDEhExecute Cicode function 308 DDEhGetLastError Cicode function 309 DDEhInitiate Cicode function 310 DDEhPoke Cicode function 312 DDEhReadLn Cicode function 313 DDEhRequest Cicode function 313 DDEhSetMode Cicode function 314 DDEhTerminate Cicode function 315 DDEhWriteLn Cicode function 315 DDEPost Cicode function 316 DDERead Cicode function 318 DDEWrite Cicode function 319 DebugBreak Cicode function 661 debugging 125 error trapping 147 debugging breakpoints 124 debugging code 122 debugging functions 46 DebugMsg Cicode function 661 DebugMsg function 147 DebugMsgSet Cicode function 662 decision-making 28 declaration standards, variable 128
1341
Index
declaration, function 52 declarations, formatting 131 default values for arguments 58 default variable values 66 defensive programming 143 DegToRad Cicode function 621 DelayShutdown Cicode function 663 DevAppend Cicode function 322 DevClose Cicode function 323 DevControl Cicode function 324 DevCurr Cicode function 325 DevDelete Cicode function 326 DevDisable Cicode function 326 DevEOF Cicode function 327 DevFind Cicode function 328 DevFirst Cicode function 329 DevFlush Cicode function 329 DevGetField Cicode function 330 DevHistory Cicode function 331 device Cicode functions 321 DevInfo Cicode function 332 DevModify Cicode function 333 DevNext Cicode function 335 DevOpen Cicode function 336 DevOpenGrp Cicode function 338 DevPrev Cicode function 339 DevPrint Cicode function 339 DevRead Cicode function 340 DevReadLn Cicode function 341 DevRecNo Cicode function 342 DevSeek Cicode function 342 DevSetField Cicode function 343 DevSize Cicode function 344 DevWrite Cicode function 345 DevWriteLn Cicode function 346 DevZap Cicode function 346 display Cicode functions 351 displaying data 27 DisplayRuntimeManager 664 DLL Cicode functions 441 DLLCall Cicode function 441 DLLCallEx Cicode Function 442 DLLOpen Cicode function 444 DriverInfo Cicode function 583
DspAnCreateControlObject Cicode function 355 DspAnFree Cicode function 356 DspAnGetArea Cicode function 357 DspAnGetMetadata Cicode function 358 DspAnGetMetadataAt Cicode function 358 DspAnGetPos Cicode function 359 DspAnGetPrivilege Cicode function 360 DspAnInfo Cicode function 361 DspAnInRgn Cicode function 362 DspAnMove Cicode function 362 DspAnMoveRel Cicode function 363 DspAnNew Cicode function 364 DspAnNewRel Cicode function 365 DspAnSetMetadata Cicode function 365 DspAnSetMetadataAt Cicode function 366 DspBar Cicode function 367 DspBmp Cicode function 368 DspButton Cicode function 369 DspButtonFn Cicode function 371 DspChart Cicode function 372 DspCol Cicode function 373 DspDel Cicode function 374 DspDelayRenderBegin Cicode function 375 DspDelayRenderEnd Cicode function 376 DspDirty Cicode function 377 DspError Cicode function 378 DspFile Cicode function 378 DspFileGetInfo Cicode function 379 DspFileGetName Cicode function 380 DspFileScroll Cicode function 381 DspFileSetName Cicode function 382 DspFont Cicode function 383 DspFontHnd Cicode function 384 DspFullScreen Cicode function 385 DspGetAnBottom Cicode function 386 DspGetAnCur Cicode function 387 DspGetAnExtent Cicode function 388 DspGetAnFirst Cicode function 389 DspGetAnFromPoint Cicode function 389 DspGetAnHeight Cicode function 390 DspGetAnLeft Cicode function 391 DspGetAnNext Cicode function 391 DspGetAnRight Cicode function 392 DspGetAnTop Cicode function 392
1342
Index
DspGetAnWidth Cicode function 393 DspGetEnv Cicode function 393 DspGetMouse Cicode function 394 DspGetMouseOver Cicode function 395 DspGetNearestAn Cicode function 395 DspGetParentAn Cicode function 396 DspGetSlider Cicode function 397 DspGetTip Cicode function 397 DspGrayButton Cicode function 398 DspInfo Cicode function 399 DspInfoDestroy Cicode function 401 DspInfoField Cicode function 402 DspInfoNew Cicode function 403 DspInfoValid Cicode function 404 DspIsButtonGray Cicode function 405 DspKernel Cicode function 406 DspMarkerMove Cicode function 407 DspMarkerNew Cicode function 408 DspMCI Cicode function 409 DspPlaySound Cicode function 410 DspPopupConfigMenu Cicode function 411 DspPopupMenu Cicode function 412 DspRichText Cicode function 414 DspRichTextEdit Cicode function 415 DspRichTextEnable Cicode function 416 DspRichTextGetInfo Cicode function 416 DspRichTextLoad Cicode function 417 DspRichTextPgScroll Cicode function 418 DspRichTextPrint Cicode function 419 DspRichTextSave Cicode function 420 DspRichTextScroll Cicode function 421 DspRubEnd Cicode function 422 DspRubMove Cicode function 422 DspRubSetClip Cicode function 423 DspRubStart Cicode function 424 DspSetSlider Cicode function 425 DspSetTip Cicode function 426 DspSetTooltipFont Cicode function 426 DspStatus Cicode function 427 DspStr Cicode function 428 DspSym Cicode function 429 DspSymAnm Cicode function 430 DspSymAnmEx Cicode function 431 DspSymAtSize Cicode function 432
DspText Cicode function 434 DspTipMode Cicode function 435 DspTrend Cicode function 436 DspTrendInfo Cicode function 438 DumpKernel Cicode function 664
E
EngToGeneric Cicode function 665 EnterCriticalSection Cicode function 1076 EquipBrowseClose Cicode function 448 EquipBrowseFirst Cicode function 448 EquipBrowseGetField Cicode function 449 EquipBrowseNext Cicode function 450 EquipBrowseNumRecords Cicode function 450 EquipBrowseOpen Cicode function 451 EquipBrowsePrev Cicode function 452, 461 EquipCheckUpdate Cicode function 453 EquipGetProperty Cicode function 453, 455 Equipment Database Cicode functions 447 EquipStateBrowseFirst Cicode function 457 EquipStateBrowseGetField Cicode function 457 EquipStateBrowseNext Cicode function 459 EquipStateBrowseNumRecords Cicode function 459 ErrCom Cicode function 463 ErrDrv Cicode function 464 ErrGetHw Cicode function 465 ErrHelp Cicode function 467 ErrInfo Cicode function 467 ErrLog Cicode function 468 ErrMsg Cicode function 469 error Cicode functions 463 error handling 144 error messages 1299 error trapping 147 errors Cicode 1300 general 1300 Hardware Cicode errors 1299 MAPI 1323 ErrSet Cicode function 469 ErrSetHw Cicode function 470 ErrSetLevel Cicode function 472
1343
Index
ErrTrap Cicode function 473 escape sequence character 34 escape sequences 85 evaluating functions 32 event Cicode functions 475 events handling 99 triggering 29 Exec Cicode function 666 ExecuteDTSPkg Cicode function 875 Exp Cicode function 621 expression data, logging 28 expressions 27 decision-making with 28 triggering events using 29 expressions, formatting 133
F
Fact Cicode function 622 fields for browse functions 1327 file Cicode functions 493 file headers 44 FileClose Cicode function 494 FileCopy Cicode function 495 FileDelete Cicode function 496 FileEOF Cicode function 496 FileExist Cicode function 497 FileFind Cicode function 497 FileFindClose Cicode function 498 FileGetTime Cicode function 499 FileMakePath Cicode function 499 FileOpen Cicode function 500 FilePrint Cicode function 501 FileRead Cicode function 502 FileReadBlock Cicode function 503 FileReadLn Cicode function 504 FileRename Cicode function 504 FileRichTextPrint Cicode function 505 files include 23 using 16 Files window 118 FileSeek Cicode function 506
FileSetTime Cicode function 506 FileSize Cicode function 507 FileSplitPath Cicode function 508 FileWrite Cicode function 509 FileWriteBlock Cicode function 509 FileWriteLn Cicode function 510 FmtClose Cicode function 551 FmtFieldHnd Cicode function 552 FmtGetField Cicode function 553 FmtGetFieldCount Cicode function 553 FmtGetFieldHnd Cicode function 554 FmtGetFieldName Cicode function 554 FmtGetFieldWidth Cicode function 555 FmtOpen Cicode function 556 FmtSetField Cicode function 557 FmtSetFieldHnd Cicode function 558 FmtToStr Cicode function 558 for...do 94 foreground tasks 101 form Cicode functions 513 FormActive Cicode function 514 FormAddList Cicode function 515 format Cicode functions 551 format operator (:) 81 format templates 136 formatting comments 134 expressions 133 function headers 139 functions 134 simple declarations 131 text strings 83 formatting statements 132 FormButton Cicode function 516 FormCheckBox Cicode function 517 FormComboBox Cicode function 518 FormCurr Cicode function 520 FormDestroy Cicode function 521 FormEdit Cicode function 521 FormField Cicode function 522 FormGetCurrInst Cicode function 524 FormGetData Cicode function 525 FormGetInst Cicode function 526 FormGetText Cicode function 527
1344
Index
FormGoto Cicode function 528 FormGroupBox Cicode function 528 FormInput Cicode function 530 FormListAddText Cicode function 531 FormListBox Cicode function 532 FormListDeleteText Cicode function 533 FormListSelectText Cicode function 534 FormNew Cicode function 535 FormNumPad Cicode function 536 FormOpenFile Cicode function 538 FormPassword Cicode function 538 FormPosition Cicode function 539 FormPrompt Cicode function 540 FormRadioButton Cicode function 541 FormRead Cicode function 542 FormSaveAsFile Cicode function 543 FormSecurePassword 544 FormSecurePassword Cicode function 544 FormSelectPrinter Cicode function 545 FormSetData Cicode function 546 FormSetInst Cicode function 546 FormSetText Cicode function 547 FormWndHnd Cicode function 548 FTP Cicode functions 561 FTPClose Cicode function 561 FTPFileCopy Cicode function 562 FTPFileFind Cicode function 562 FTPFileFindClose Cicode function 564 FTPOpen Cicode function 564 FullName Cicode function 830 function headers 139 function libraries 43 functions arguments and 33 Assert 148 debugging 46 DebugMsg 147 declaration 52 evaluating 32 event handling 99 formatting 134 groups 43 keyboard 39 libraries 43
miscellaneous 39 page 38 report 39 returning values 60 scope of 50 structure of 41 syntax 49 table 74 time and date 39 FuzzyClose Cicode function 567 FuzzyGetCodeValue Cicode function FuzzyGetShellValue Cicode function FuzzyOpen Cicode function 569 FuzzySetCodeValue Cicode function FuzzySetShellValue Cicode function FuzzyTech Cicode functions 567 FuzzyTrace Cicode function 572
G
general errors 1300 GetArea Cicode function 667 GetBlueValue Cicode function 294 GetEnv Cicode function 668 GetEvent Cicode function 479 GetGreenValue Cicode function 294 GetLogging Cicode function 668 GetPriv Cicode function 831 GetRedValue Cicode function 294 GetWinTitle Cicode function 1244 Global variable window 115 group Cicode functions 573 groups of functions 43 GrpClose Cicode function 573 GrpDelete Cicode function 574 GrpFirst Cicode function 575 GrpIn Cicode function 575 GrpInsert Cicode function 576 GrpMath Cicode function 577 GrpName Cicode function 578 GrpNext Cicode function 578 GrpOpen Cicode function 579 GrpToStr Cicode function 580
1345
Index
H
Halt Cicode function 1077 handling events 99 handling, error 144 hardware alarms 1299 Hardware Cicode errors 1299 headers, file 44, 138 headers, function 139 HexToStr Cicode function 945 HighByte Cicode function 622 HighWord Cicode function 623 HtmlHelp Cicode function 1245 HwAlarmQue Cicode function 278
I
I/O device Cicode functions 583 if...then 93 IFDEF macro 75 IFDEFAdvAlm macro 76 IFDEFAnaAlm macro 77 IFDEFDigAlm 78 include files 23 InfoForm Cicode function 669 InfoFormAn Cicode function 670 Input Cicode function 671 input, runtime operator 25 integer data type 51, 64 integers 81 IntToReal Cicode function 672 IntToStr Cicode function 946 IODeviceControl Cicode function 584 IODeviceInfo Cicode function 588 IODeviceStats Cicode function 593 IsError Cicode function 474
keyboard functions 39 KeyBs Cicode function 596 KeyDown Cicode function 597 KeyGet Cicode function 598 KeyGetCursor Cicode function 599 KeyLeft Cicode function 599 KeyMove Cicode function 600 KeyPeek Cicode function 600 KeyPut Cicode function 601 KeyPutStr Cicode function 602 KeyReplay Cicode function 602 KeyReplayAll Cicode function 603 KeyRight Cicode function 604 KeySetCursor Cicode function 604 KeySetSeq Cicode function 605 KeyUp Cicode function 606
L
labels, standards for 131 LanguageFileTranslate Cicode function 675 LeaveCriticalSection Cicode function 1078 libraries of functions 43 LLClose Cicode function 443 Ln Cicode function 623 Log Cicode function 624 logging expression data 28 logic 28 logical operators 91 Login Cicode function 833 LoginForm Cicode function 833 Logout Cicode function 835 LogoutIdle Cicode function 835 LowByte Cicode function 624 LowWord Cicode function 625
K
KerCmd Cicode function 672 KernelQueueLength Cicode function 673 KernelTableInfo Cicode function 673 KernelTableItemCount Cicode function 675 KeyAllowCursor Cicode function 596 keyboard Cicode functions 595
M
macro arguments 79 mail Cicode functions 611 MailError Cicode function 611 MailLogoff Cicode function 612 MailLogon Cicode function 612 MailRead Cicode function 613 MailSend Cicode function 614
1346
Index
MakeCitectColour Cicode function 295 MAPI errors 1323 math/trigonometry Cicode functions 617 mathematical operators 87 Max Cicode function 626 menu Cicode functions 633 MenuGetChild Cicode function 634 MenuGetFirstChild Cicode function 634 MenuGetGenericNode Cicode function 635 MenuGetNextChild Cicode function 636 MenuGetPageNode Cicode function 636 MenuGetParent Cicode function 637 MenuGetPrevChild Cicode function 637 MenuGetWindowNode Cicode function 638 MenuNodeAddChild Cicode function 639 MenuNodeGetProperty Cicode function 640 MenuNodeHasCommand Cicode function 640 MenuNodeIsDisabled Cicode function 641 MenuNodeIsHidden Cicode function 642 MenuNodeRemove Cicode function 642 MenuNodeRunCommand Cicode function 643 MenuNodeSetDisabledWhen Cicode function 644 MenuNodeSetHiddenWhen Cicode function 645 MenuNodeSetProperty Cicode function 646 MenuReload Cicode function 647 Message Cicode function 676 messages, error 1299 Min Cicode function 626 miscellaneous Cicode functions 649 miscellaneous functions 39 modular programming 140-142 module variables 67 MsgBrdcst Cicode function 1079 MsgClose Cicode function 1080 MsgGetCurr Cicode function 1080 MsgOpen Cicode function 1081 MsgRead Cicode function 1083 MsgRPC Cicode function 1084 MsgState Cicode function 1086 MsgWrite Cicode function 1087 MultiMonitorStart Cicode function 1246
multiple arguments'arguments multiple 35 multiple statements 23 MultiSignatureForm 836 MultiSignatureTagWrite 837 multitasking 101-102
N
Name Cicode function 838 naming standards, variables 129
O
object data type 51, 64 ObjectAssociateEvents Cicode function 166 ObjectAssociatePropertyWithTag Cicode function 168 ObjectByName Cicode function 169 ObjectHasInterface Cicode function 170 ObjectIsValid Cicode function 170 ObjectToStr Cicode function 171 OLEDateToTime Cicode function 1122 one-dimensional variable arrays 72 OnEvent Cicode function 483 operator precedence 92 operator, format 81 operators bit 89 logical 91 relational 90 operators, data 87 Output window 115
P
PackedRGB Cicode function 296 PackedRGBToCitectColour Cicode function 296 page Cicode functions 701 page functions 38 PageAlarm Cicode function 703 PageBack Cicode function 704 PageDisabled Cicode function 705 PageDisplay Cicode function 706 PageFile Cicode function 708 PageFileInfo Cicode function 709
1347
Index
PageForward Cicode function 710 PageGetInt Cicode function 710 PageGetStr Cicode function 711 PageGoto Cicode function 712 PageHardware Cicode function 713 PageHistoryDspMenu Cicode function 714 PageHistoryEmpty Cicode function 715 PageHome Cicode function 715 PageInfo Cicode function 715 PageLast Cicode function 718 PageListCount Cicode function 719 PageListCurrent Cicode function 720 PageListDelete Cicode function 723 PageListDisplay Cicode function 722 PageListInfo Cicode function 721 PageMenu Cicode function 724 PageNext Cicode function 725 PagePeekCurrent Cicode function 726 PagePeekLast Cicode function 727 PagePopLast Cicode function 728 PagePopUp Cicode function 729 PagePrev Cicode function 729 PageProcessAnalyst Cicode function 731 PageProcessAnalystPens Cicode function 732 PagePushLast Cicode function 733 PageRecall Cicode function 734 PageRichTextFile Cicode function 735 PageSelect Cicode function 737 PageSetInt Cicode function 737 PageSetStr Cicode function 738 PageSOE Cicode function 739 PageSummary Cicode function 740 PageTask Cicode function 741 PageTransformCoords Cicode function 742 PageTrend Cicode function 743 ParameterGet Cicode function 677 ParameterPut Cicode function 678 passing data to arguments 33 PathToStr Cicode function 946 Pi Cicode function 627 plot Cicode functions 747 PlotClose Cicode function 747 PlotDraw Cicode function 748 PlotGetMarker Cicode function 750
PlotGrid Cicode function 750 PlotInfo Cicode function 753 PlotLine Cicode function 754 PlotMarker Cicode function 756 PlotOpen Cicode function 758 PlotScaleMarker Cicode function 761 PlotSetMarker Cicode function 762 PlotText Cicode function 763 PlotXYLine Cicode function 764 Pow Cicode function 627 pre-emptive multitasking 102 precedence, operator 92 Print Cicode function 347 PrintFont Cicode function 348 PrintLn Cicode function 349 private scope 50 Process Analyst Cicode functions 769 ProcessAnalystLoadFile Cicode function 769 ProcessAnalystPopup Cicode function 770 ProcessAnalystSelect Cicode function 771 ProcessAnalystSetPen Cicode function 773 ProcessAnalystWin Cicode function 774 ProcessIsClient Cicode function 679 ProcessIsServer Cicode function 679 ProcessRestart Cicode function 680 ProductInfo Cicode function 680 programming standards 127 programming, modular 140 ProjectInfo Cicode function 681 ProjectRestartGet Cicode function 682 ProjectRestartSet Cicode function 682 ProjectSet Cicode function 683 Prompt Cicode function 683 pseudocode 44 public scope 50 Pulse Cicode function 684
Q
Quality Cicode functions 777 quality data type 51, 64 QualityCreate Cicode function 777 QualityGetPart Cicode function 778 QualityIsBad Cicode function 780
1348
Index
QualityIsControlMode Cicode function 779 QualityIsGood Cicode function 780 QualityIsOverrride Cicode function 781 QualityIsUncertain Cicode function 782 QualitySetPart Cicode function 782 QualityToStr Cicode function 783 QueClose Cicode function 1088 QueLength Cicode function 1089 QueOpen Cicode function 1089 QuePeek Cicode function 1090 QueRead Cicode function 1092 QueWrite Cicode function 1093
R
RadToDeg Cicode function 628 Rand Cicode function 628 real data type 51, 64 RealToStr Cicode function 947 relational operators 90 RepGetControl Cicode function 793 Report Cicode function 793 report Cicode functions 791 report functions 39 ReportGetCluster Cicode function 791 RepSetControl Cicode function 794 ReRead Cicode function 1093 returning data from functions 36 returning values from functions 60 Round Cicode function 629 runtime operator input 25 runtime operator input triggering 31
S
SchdClose Cicode function 798 SchdConfigClose Cicode function 798 SchdConfigFirst Cicode function 799 SchdConfigGetField Cicode function 799 SchdConfigNext Cicode function 800 SchdConfigNumRecords Cicode function 801 SchdConfigOpen Cicode function 801 SchdConfigPrev Cicode function 805 SchdFirst Cicode function 806 SchdGetField Cicode function 806
SchdNext Cicode function 807 SchdNumRecords Cicode function 807 SchdOpen Cicode function 808 SchdPrev Cicode function 810 SchdSpecialAdd Cicode function 810 SchdSpecialClose Cicode function 811 SchdSpecialDelete Cicode function 811 SchdSpecialFirst Cicode function 812 SchdSpecialItemAdd Cicode function 813, 817 SchdSpecialItemClose function 814 SchdSpecialItemDelete Cicode function 815 SchdSpecialItemFirstCicode function 815 SchdSpecialItemGetField function 812, 816 SchdSpecialItemNext Cicode function 818 SchdSpecialItemNumRecords function 818 SchdSpecialItemOpen Cicode function 819 SchdSpecialItemPrev function 819 SchdSpecialModify Cicode function 820 SchdSpecialNext Cicode function 821 SchdSpecialNumRecords Cicode function 821 SchdSpecialOpen Cicode function 822 SchdSpecialPrev Cicode function 823 ScheduleItemAdd Cicode function 823 ScheduleItemModify Cicode function 825 ScheduleItemSetRepeat Cicode function 826 Scheduler Cicode functions 796 scope 66, 128 scope, function 50 security Cicode functions 829 select case 96 SemClose Cicode function 1094 SemOpen Cicode function 1095 SemSignal Cicode function 1096 SemWait Cicode function 1097 SendKeys Cicode function 606 Sequence of Events Cicode functions 855 sequences, escape 85 SerialKey Cicode function 305 server Cicode functions 857 ServerBrowseClose Cicode function 858 ServerBrowseFirst Cicode function 859 ServerBrowseGetField Cicode function 861 ServerBrowseNext Cicode function 860 ServerBrowseNumRecords Cicode function 861
1349
Index
ServerBrowseOpen Cicode function 858 ServerBrowsePrev Cicode function 860 ServerDumpKernel Cicode function 685 ServerGetProperty Cicode function 862 ServerInfo Cicode function 863 ServerInfoEx Cicode function 866 ServerIsOnline Cicode function 868 ServerReload Cicode function 869 ServerRestart Cicode function 871 ServerRPC Cicode function 1098 ServiceGetList Cicode function 686 SetArea Cicode function 687 SetEvent Cicode function 488 SetLogging Cicode function 688 setting variables 21 Shutdown Cicode function 689 ShutdownForm Cicode function 691 ShutdownMode Cicode function 692 Sign Cicode function 629 Sin Cicode function 630 Sleep Cicode function 1099 SleepMS Cicode function 1100 SOEArchive 855 SOEDismount 855 SOEEventAdd Cicode Function 856 SOEMount 856 source file headers 138 SPC Cicode functions 927 SPCAlarms Cicode function 927 SPCClientInfo Cicode function 929 SPCGetHistogramTable Cicode function 930 SPCGetSubgroupTable Cicode function 931 SPCPlot Cicode function 932 SPCProcessXRSGet Cicode function 934 SPCProcessXRSSet Cicode function 935 SPCSetLimit Cicode function 936 SPCSpecLimitGet Cicode function 937 SPCSpecLimitSet Cicode function 938 SPCSubgroupSizeGet Cicode function 939 SPCSubgroupSizeSet Cicode function 940 SQL Cicode functions 873 SQLAppend Cicode function 877 SQLBeginTran Cicode function 879
SQLCall Cicode function 880 SQLCancel Cicode function 881 SQLClose Cicode function 882 SQLCommit Cicode function 882 SQLConnect Cicode function 883 SQLCreate Cicode function 887 SQLDisconnect Cicode function 889 SQLDispose Cicode function 890 SQLEnd Cicode function 891 SQLErrMsg Cicode function 892 SQLExec Cicode function 892 SQLFieldInfo Cicode function 897 SQLGetField Cicode function 899 SQLGetRecordset Cicode function 900 SQLGetScalar Cicode function 902 SQLInfo Cicode function 903 SQLIsNullField Cicode function 905 SQLNext Cicode function 906 SQLNoFields Cicode function 907 SQLNumChange Cicode function 907 SQLNumFields Cicode function 908 SQLOpen Cicode function 909 SQLParamsClearAll Cicode function 910 SQLParamsSetAsInt Cicode function 911 SQLParamsSetAsReal Cicode function 916 SQLParamsSetAsString Cicode function 917 SQLPrev Cicode function 919 SQLQueryCreate Cicode function 919 SQLQueryDispose Cicode function 920 SQLRollBack Cicode function 921 SQLRowCount Cicode function 921 SQLSet Cicode function 922 SQLTraceOff Cicode function 924 SQLTraceOn Cicode function 925 Sqrt Cicode function 631 Stack window 115 standards, for constants, variables and labels 130 standards, naming, for variables 129 standards, programming 127 statements using multiple 23 statements, executable 132
1350
Index
stepping through code 125 StrCalcWidth Cicode function 948 StrClean Cicode function 948 StrFill Cicode function 949 StrFormat Cicode function 949 StrGetChar Cicode function 950 string arguments 33 string Cicode functions 943 string data type 51, 64 strings 81 strings, formatting 83 StrLeft Cicode function 951 StrLength Cicode function 951 StrLower Cicode function 952 StrMid Cicode function 953 StrPad Cicode function 953 StrRight Cicode function 954 StrSearch Cicode function 955 StrSetChar Cicode function 956 StrToChar Cicode function 956 StrToDate Cicode function 957 StrToFmt Cicode function 958 StrToGrp Cicode function 959 StrToHex Cicode function 959 StrToInt Cicode function 960 StrToLines Cicode function 961 StrToLocalText Cicode function 962 StrToPeriod Cicode function 963 StrToReal Cicode function 963 StrToTime Cicode function 964 StrToTimestamp 1135 StrToValue Cicode function 965 StrTrim Cicode function 966 StrTruncFont Cicode function 966 StrTruncFontHnd Cicode function 967 structure of functions 41 structure, argument 54 StrUpper Cicode function 968 StrWord Cicode function 969 SubscriptionAddCallback Cicode function 1016 SubscriptionGetAttribute Cicode function 1017 SubscriptionGetInfo Cicode function 1019 SubscriptionGetQuality Cicode function 1020 SubscriptionGetTag Cicode function 1020
SubscriptionGetTimestamp Cicode function 1021 SubscriptionGetValue Cicode function 1022 SubscriptionRemoveCallback Cicode function 1023 SuperGenie Cicode functions 971 SwitchConfig Cicode function 693 syntax 47 SysTime Cicode function 1123 SysTimeDelta Cicode function 1124
T
table (array) Cicode functions 1011 TableLookup Cicode function 1011 TableMath Cicode function 1012 TableShift Cicode function 1014 Tag Cicode functions 1015 Tag Reference /TagReadEx() behaviour in Cicode Expressions 46 TagBrowseClose Cicode function 1023 TagBrowseFirst 1024 TagBrowseNext 1026 TagBrowseNumRecords 1026 TagBrowseOpen Cicode function 1027 TagBrowsePrev 1030 TagDebug Cicode function 1030 TagDebugForm Cicode function 1031 TagEventFormat Cicode function 1033 TagEventQueue Cicode function 1034 TagGetProperty Cicode function 1037 TagGetScale Cicode function 1039 TagInfo Cicode function 1041 TagInfoEx Cicode function 1044 TagRamp Cicode function 1048 TagRDBReload Cicode function 1049 TagRead Cicode function 1049 TagReadEx Cicode function 1052 TagResolve Cicode function 1055 TagScaleStr Cicode function 1056 TagSetOverrideBad Cicode function 1057 TagSetOverrideGood Cicode function 1059 TagSetOverrideQuality Cicode function 1061 TagSetOverrideUncertain Cicode function 1062
1351
Index
TagSubscribe Cicode function 1064 TagUnresolve Cicode function 1067 TagUnsubscribe Cicode function 1067 TagWrite Cicode function 1068 TagWriteEventQue Cicode function 1070 Tan Cicode function 631 task Cicode functions 1073 TaskCall Cicode function 1101 TaskCluster Cicode function 1102 TaskGetSignal Cicode function 1103 TaskHnd Cicode function 1103 TaskKill Cicode function 1104 TaskNew Cicode function 1105 TaskNewEx Cicode function 1108 TaskResume Cicode function 1110 tasks controlling 102 tasks, foreground and background 101 TaskSetSignal Cicode function 1110 TaskSuspend Cicode function 1111 TegBrowseGetField 1025 TestRandomWave Cicode function 693 TestSawWave Cicode function 694 TestSinWave Cicode function 695 TestSquareWave Cicode function 696 TestTriangWave Cicode function 697 text files 23 text strings, formatting 83 Thread window 116 threads 101 time and date Cicode functions 1113 Time Cicode function 1125 time functions 39 TimeCurrent Cicode function 1125 TimeHour Cicode function 1126 TimeInfo Cicode function 1127 TimeIntToTimestamp Cicode functions 1136 TimeMidNight Cicode function 1128 TimeMin Cicode function 1129 TimeSec Cicode function 1129 TimeSet Cicode function 1130 Timestamp Cicode functions 1135 timestamp data type 51, 64 TIMESTAMP data type 64-65
TimestampAdd Cicode function 1137, 1144 TimestampCreate Cicode function 1139 TimestampCurrent Cicode function 1138 TimestampDifference Cicode function 1140 TimestampFormat Cicode function 1142 TimestampSub Cicode function 1145 TimestampToStr Cicode function 1146 TimestampToTimeInt Cicode function 1148 TimeToOLEDate Cicode function 1131 TimeToStr Cicode function 1132 TimeUTCOffset Cicode function 1133 Toggle Cicode function 697 TraceMsg Cicode function 698 trapping, error 147 trend Cicode functions 1151 TrendDspCursorScale Cicode function 1155 TrendDspCursorTag Cicode function 1156 TrendDspCursorTime Cicode function 1156 TrendDspCursorValue Cicode function 1158 TrendGetAn Cicode function 1158 TrendPopUp Cicode function 1159 TrendRun Cicode function 1159 TrendSetDate Cicode function 1160 TrendSetScale Cicode function 1161 TrendSetSpan Cicode function 1161 TrendSetTime Cicode function 1162 TrendSetTimebase Cicode function 1163 TrendWin Cicode function 1164 TrendZoom Cicode function 1165 triggering runtime operator input 31 triggering events 29 TrnAddHistory Cicode function 1166 TrnBrowseClose Cicode function 1167 TrnBrowseFirst Cicode function 1168 TrnBrowseGetField Cicode function 1168 TrnBrowseNext Cicode function 1169 TrnBrowseNumRecords Cicode function 1170 TrnBrowseOpen Cicode function 1171 TrnBrowsePrev Cicode function 1172 TrnClientInfo Cicode function 1172 TrnComparePlot Cicode function 1174 TrnDelete Cicode function 1175 TrnDelHistory Cicode function 1176
1352
Index
TrnEcho Cicode function 1177 TrnEventGetTable Cicode function 1178 TrnEventGetTableMS Cicode function 1180 TrnEventSetTable Cicode function 1182 TrnEventSetTableMS Cicode function 1183 TrnExportClip Cicode function 1185 TrnExportCSV Cicode function 1188 TrnExportDBF Cicode function 1190 TrnExportDDE Cicode function 1192 TrnFlush Cicode function 1195 TrnGetBufEvent Cicode function 1196 TrnGetBufTime Cicode function 1196 TrnGetBufValue Cicode function 1197 TrnGetCluster Cicode function 1198 TrnGetCursorEvent Cicode function 1199 TrnGetCursorMSTime Cicode function 1199 TrnGetCursorPos Cicode function 1200 TrnGetCursorTime Cicode function 1201 TrnGetCursorValue Cicode function 1202 TrnGetCursorValueStr Cicode function 1202 TrnGetDefScale Cicode function 1203 TrnGetDisplayMode Cicode function 1204 TrnGetEvent Cicode function 1206 TrnGetFormat Cicode function 1206 TrnGetGatedValue Cicode function 1207 TrnGetInvalidValue Cicode function 1208 TrnGetMode Cicode function 1209 TrnGetMSTime Cicode function 1210 TrnGetPen Cicode function 1211 TrnGetPenComment Cicode function 1212 TrnGetPenFocus Cicode function 1212 TrnGetPenNo Cicode function 1213 TrnGetPeriod Cicode function 1214 TrnGetScale Cicode function 1214 TrnGetScaleStr Cicode function 1215 TrnGetSpan Cicode function 1216 TrnGetTable Cicode function 1217 TrnGetTime Cicode function 1220 TrnGetUnits Cicode function 1221 TrnInfo Cicode function 1222 TrnIsValidValue Cicode function 1223 TrnNew Cicode function 1224 TrnPlot Cicode function 1225 TrnPrint Cicode function 1227
TrnSamplesConfigured Cicode function 1228 TrnScroll Cicode function 1228 TrnSelect Cicode function 1229 TrnSetCursor Cicode function 1231 TrnSetCursorPos Cicode function 1231 TrnSetDisplayMode Cicode function 1232 TrnSetEvent Cicode function 1234 TrnSetPen Cicode function 1234 TrnSetPenFocus Cicode function 1236 TrnSetPeriod Cicode function 1237 TrnSetScale Cicode function 1238 TrnSetSpan Cicode function 1239 TrnSetTable Cicode function 1240 TrnSetTime Cicode function 1241
U
UserCreate Cicode function 839 UserCreateForm Cicode function 840 UserDelete Cicode function 841 UserEditForm Cicode function 842 UserInfo Cicode function 842 UserLogin Cicode function 843 UserPassword Cicode function 846 UserPasswordExpiryDays Cicode function 847 UserPasswordForm Cicode function 848 UserSetStr Cicode function 848 UserUpdateRecord Cicode function 849 UserVerify Cicode function 850 using files 16 multiple statements 23
V
variable arrays functions 74 one-dimensional 72 variable scope 66 variable tags, standards for 130 VariableQuality Cicode function 788 variables 63, 85 copying 21 declaration standards 128 default values for 66
1353
Index
in calculations 22 module 67 naming standards 129 scope standards 128 setting 21 VariableTimestamp Cicode function 1149 VerifyPrivilegeForm 851 VerifyPrivilegeTagWrite 852 Version Cicode function 699
X
XML Cicode functions 1278 XMLClose Cicode function 1282 XMLCreate Cicode function 1280 XMLGetAttribute Cicode function 1282 XMLGetAttributeCount Cicode function 12831284 XMLGetAttributeValue Cicode function 1285 XMLGetChild Cicode function 1286 XMLGetChildCount Cicode function 1287 XMLGetParent Cicode function 1291 XMLGetRoot Cicode function 1288 XMLNodeAddChild Cicode function 1279 XMLNodeFind Cicode function 1293 XMLNodeGetName Cicode function 1289 XMLNodeGetValue Cicode function 1290 XMLNodeRemove Cicode function 1292 XMLNodeSetValue Cicode function 1295 XMLOpen Cicode function 1281 XMLSave Cicode function 1293 XMLSetAttribute Cicode function 1294
W
while...do 95 WhoAmI Cicode function 854 WinCopy Cicode function 1246 WinFile Cicode function 1248 WinFree Cicode function 1250 WinGetFocus Cicode function 1251 WinGetWndHnd Cicode function 1251 WinGoto Cicode function 1252 WinMode Cicode function 1253 WinMove Cicode function 1254 WinNew Cicode function 1254 WinNewAt Cicode function 1255 WinNext Cicode function 1259 WinNumber Cicode function 1259 WinPos Cicode function 1260 WinPrev Cicode function 1261 WinPrint Cicode function 1261 WinPrintFile Cicode function 1263 WinSelect Cicode function 1265 WinSetName Cicode function 1266 WinSize Cicode function 1266 WinStyle Cicode function 1267 WinTitle Cicode function 1268 WndFind Cicode function 1269 WndGetFileProfile Cicode function 1269 WndHelp Cicode function 1270 WndInfo Cicode function 1272 WndMonitorInfo Cicode function 1274 WndPutFileProfile Cicode function 1274 WndShow Cicode function 1275 WndViewer Cicode function 1276 writing functions 43
1354