CitectSCADA v7.0 - Cicode Reference Guide
CitectSCADA v7.0 - Cicode Reference Guide
July 2007
DISCLAIMER
Citect 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, Citect Pty. Ltd reserves the right to
revise this publication at any time without incurring an obligation to notify any person of the revision.
COPYRIGHT
© Copyright 2007 Citect Pty. Ltd. All rights reserved.
TRADEMARKS
Citect Pty. Ltd has made every effort to supply trademark information about company names, products and services mentioned in this manual.
Citect, CitectHMI, and CitectSCADA are registered trademarks of Citect Pty. Ltd.
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.
Novell, Netware and Netware Lite are are either registered trademarks or trademarks of Novell, Inc. in the United States and other countries..
All other brands and products referenced in this document are acknowledged to be the trademarks or registered trademarks of their respective holders.
GENERAL NOTICE
Some product names used in this manual are used for identification purposes only and may be trademarks of their respective companies.
Introducing Cicode
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Using Cicode Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Multitasking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Foreground and background tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Controlling tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Pre-emptive multitasking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Index 841
Introducing Cicode
Getting Started
Use the following sections as a quick start to using Cicode in your CitectSCADA
projects:
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 in-built functions, you
can write your own functions. See Writing Functions.
The Cicode Editor is the code editing tool provided with CitectSCADA for
the writing, editing and debugging of your Cicode code. For details, see The
Cicode Editor.
See Also Performing Advanced Tasks
Using Cicode Programming Standards
2
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:
<VAR_TAG> is the name of the variable, and Val is the value being assigned to the
variable.
6
Examples
To set a digital variable (named BIT_1) to ON (1), use the command:
BIT_1 = 1;
To set a digital variable (named BIT_1) to OFF (0), use the command:
BIT_1 = 0;
To set a digital variable (named B1_PUMP_101_M) to ON (1), use the command:
B1_PUMP_101_M = 1;
To set a digital variable (named B1_PUMP_101_M) to OFF (0), use the command:
B1_PUMP_101_M = 0;
To set an analog variable (named B1_TIC_101_SP) to a value of ten (10), use the
command:
B1_TIC_101_SP = 10;
You can copy a variable to another by assigning (setting) the value of a variable
to the value of another variable, for example:
B1_PUMP_101_COUNT = B1_PUMP_101_CLIMIT;
The value of B1_PUMP_101_COUNT is set to the value of
B1_PUMP_101_CLIMIT only when that command is issued.
Note: The value of B1_PUMP_101_CLIMIT could change immediately after, but
B1_PUMP_101_COUNT remains unchanged and storing the original value,
until this command is issued again.
Performing Calculations
Mathematical calculations can be performed between variables in a Cicode
statement. For example:
B1_TIC_101_SP = B1_TIC_101_PV + B1_TIC_102_PV - 100;
When this command is executed, the variable B1_TIC_101_SP is set to a value
that is the sum of variables B1_TIC_101_PV and B1_TIC_102_PV minus 100.
@<filename>
where <filename> is any valid DOS file name. Note that the bracket characters
(< >) are part of the syntax.
You can use include files with most properties (except record names), but they
are most commonly used for commands and expressions, for example:
Key sequence: F5 ENTER
Command: @<setvars.cii>
In the above example, the setvars.cii include file would contain commands to
be substituted for the Command property when you compile your project, for
example:
PV12 = 10;
PV22 = 20;
PV13 = 15;
PV23 = 59;
PageDisplay("Mimic");
Notes
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('). You do not need to include the .cii
extension, but if the file is not in the project directory, you must 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.
Don’t try to open an include file within the Cicode Editor.
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 issues 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.
You should always 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
must 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 required. 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 ( , ):
Key sequence: F2 ###,## Enter
Command: B1_TIC_101_SP = Arg1; B1_TIC_101_PV = Arg2;
To set both variables, the operator can type:
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.
10
Chapter 2: Using Cicode Expressions
Decision-Making
Some expressions return only one of two logical values, either TRUE(1) or
FALSE(0). You can use these expressions to make decisions, and to perform one
of two actions, depending on whether the return value is TRUE or FALSE. For
example, you can configure a text object with appearance as follows:
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
A Cicode function can perform more complex tasks than a simple command or
expression allows. Functions give you access to CitectSCADA graphics pages,
alarms, trend data, and so on.
CitectSCADA has several hundred pre-built functions that display pages,
acknowledge alarms, make calculations, and so on. You can also write your own
functions to meet your specific needs.
See Also Working with Commonly Used Functions
Writing Functions
where:
FunctionName is the name of the function
Arg1, Arg2, ... are the arguments you pass to the function
Command PageNext();
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 AlarmActive(0)
Note: All functions return a value. This value is often just an indication of the
success or failure of the function, and in many cases (e.g. when used in a
command) the return value can be ignored. You must 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 faulty
conditions and act on them.
This function displays the graphics page called "Boiler 1". Note that when you
pass a string to a function, you must always enclose the string in double quotes.
17
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");
String assignment You can also assign string variables in commands. For example, if
BATCH_NAME is a variable tag defined as a string data type, you can use the
following command to set the tag to the value "Bread":
BATCH_NAME = "Bread";
Note: You must enclose a string in double quotation marks ( " ).
The order of the arguments is important to 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.
Command PageDisplay(Arg1);
When the command executes, the page name is passed to the function as Arg1.
The operator can then display any page, for example:
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.
20
Chapter 4: Working with Commonly Used
Functions
Cicode has many functions that perform a variety of tasks. Many of these are
used for building complex CitectSCADA systems. The functions you will most
often use are divided into six categories:
Alarm Functions
Page Functions
Keyboard Functions
Report Functions
Time/date Functions
Miscellaneous Functions
See Also Cicode Function Categories
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, to ensure 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.
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. You must ensure 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.
22
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).
PageSummary: Displays summary alarm information on the alarm page
configured in the project.
PageTrend: Displays a standard trend page.
23
Keyboard Functions
Keyboard functions control the processing of keyboard entries and the
movement of the keyboard cursor on the graphics page.
KeyBs: Backspaces (removes) the last key from the key command line. You
should 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:
Report: Runs the report on the report server.
Time/date Functions
The following functions return the current date and time:
Date: Returns the current date as a string.
Time: Returns the current time as a string.
Miscellaneous Functions
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.
24
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. You should always use this function,
or the ShutdownForm() function, to shut down your system.
ShutdownForm: Displays a dialog box to allow a user to shut down your
CitectSCADA system.
Chapter 5: Writing Functions
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 always ends 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.
All the lines 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. Most 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:
IF COUNTER < 100 THEN COUNTER =
Command
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 ( );
To be able to use the function like this, you must 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
Note 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
27
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).
1:GetVariableTag ( )
Argument:cursor position
Return:name of variable tag at cursor
2:GetAlarmThresholds ( )
Argument:tag name
Return:threshold value of alarm
3:DisplayAlarmThresholds ( )
Argument:threshold value of alarm
Displays threshold values in prompt line
Return:success or failure
*/
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.
You should also 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:
/*
** FILE: Recipe Download.Ci
**
** AUTHOR:AJ Smith
**
** DATE: March 1996
**
** REVISION:1.0for CitectSCADA v5.0
**
** This file contains functions to allow the operator to load the
** recipe data from the SQL server to the PLC.
*/
Following the file header are the functions in series:
/*
** Main function
*/
FUNCTION
RecipeDownload ( )
! {body of function}
! .
END
/*
** Function to open the SQL connection.
29
*/
FUNCTION
RecipeConnectSQL ( )
! {body of function}
! .
END
! (and so on)
*/
END
END
The complete ELSE condition of the IF conditional executor will be ignored (and
not execute) so long as the block comment markers are used in this example.
Note: The inline ( // ) comments have no effect within the block ( /* and */ )
comments (as the whole section is now one big comment), and should remain
unchanged, so that when you do remove the block comments, the inline
comments will become effective again.
! call the page Cicode pagedisplay function and store the result
Status = PageDisplay ( sPage ) ;
! determine if the page display was successful
IF Status < > 0 THEN ! failed
! display an error message at the prompt AN
DspError ( "Cannot Display " + sPage ) ;
END
! return the staus to the caller
RETURN Status;
END
The rules for formatting statements in Cicode functions are simple, and ensure
that the functions compile without error.
You should use white space to make your code more readable. In the example
above, all 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. You should develop a pattern of
indentation - and stick to it. Extra blank lines in the code make it easier to read
(and understand).
End of line markers Most statements within the function are separated by semicolons ( ; ) but some
exceptions exist. The FUNCTION and END Statements (the start and end of the
function) have no semicolons, nor does the Scope or Return Data Type
Statements, nor any statement that ends with a reserved word.
Where a statement is split over several lines (for example, within the IF THEN
conditional executor), each line ends with a semicolon - unless it ends in a
reserved word.
33
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 (e.g. Alarm.dbf).
Because functions are public by default, to make a function public requires no
specific declaration. To make a function private however, you must prefix the
FUNCTION Statement with the word PRIVATE.
PRIVATE
FUNCTION
FunctionName ( <Arguments> )
<Statement> ;
<Statement> ;
<Statement> ;
END
should not be included in the statement, and are shown only for your
information.
To declare the data type that will be returned to the calling code, prefix the
FUNCTION Statement with one of the Cicode data type keywords, in the
<ReturnDataType> placeholder in the following example.
<ReturnDataType>
FUNCTION
FunctionName ( <Arguments> )
<Statement> ;
<Statement> ;
<Statement> ;
END
The following example returns an integer of value 5:
INT
FUNCTION
FunctionName ( <Arguments> )
<Statement> ;
INT Status = 5;
<Statement> ;
RETURN Status;
END
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 do not specify a 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 all
35
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
36
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 not important to 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:
Variable tags. When you call a function by the same name as a variable tag,
the function has precedence. The variable tag can never be referred to
because the function executes each time the name is used.
Prebuilt functions. You can give your function the same name as any pre-
built Cicode function. Your function takes precedence over the pre-built
function - the pre-built function cannot be called. Because pre-built Cicode
functions cannot be changed, this provides a method of 'modifying' any pre-
built 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 utilises 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 must 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.
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.
Cicode function argument statements have the following syntax:
<ArgumentDataType>
<ArgumentName>
[ = <InitialDefaultValue> ]
where:
<ArgumentDataType> = Argument Data Type Statement: required, INT or
REAL or STRING. See the section titledDeclaring 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 Initialisation Statement: optional,
preceded by equals ( = ) assignment operator, a value to assign to the
argument variable when first initialised, must 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.
38
The Argument Statement in a Cicode function must 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 must 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:
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 utilised any number of times from
any number of locations in CitectSCADA. Write once, use many.
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 Initialisation 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.
40
call to the function will restore the default values originally declared in the
function.
If more than one argument is used in a function, each must also be separated by
a comma. Equally, if a function containing more than one argument is called,
each argument must be accounted for by the caller. In this case, if an argument
value is to be omitted from the call, (to utilise the default value), comma
placeholders must be used appropriately in the call to represent the proper
order of the arguments.
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.
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
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 must replace
the <ReturnValue> placeholder in the following example with an appropriate
data value to match the Return Data Type as declared in the function.
<ReturnDataType>
FUNCTION
FunctionName ( <Arguments> )
<Statement> ;
<Statement> ;
RETURN <ReturnValue> ;
END
The following example returns an integer of value 5:
INT
FUNCTION
FunctionName ( <Arguments> )
<Statement> ;
INT Status = 5;
<Statement> ;
RETURN Status;
END
The RETURN statement passes a value back to the calling procedure (either
another function, command or expression). Outside of the function, the return
value can be read by the calling statement. For example, it can be used by the
caller as a variable (in a command), or animated (in an expression).
44
Chapter 6: Using Variables
STRING Text string (128 bytes maximum, including null ASCII (null terminated)
termination character)
OBJECT ActiveX control
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 minimise the
loss of data during floating point calculations.
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 sStr;
REAL Result;
INT x, y;
OBJECT hObject;
The first 32 characters of a variable name must 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
(e.g. Alarm.dbf).
47
Global Cicode variables are prefixed with the keyword GLOBAL, and must 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);
END
RETURN iStatus;
END
The variable sDefaultPage could then be used in any function of any Cicode file
in the system.
Note: Use global variables with caution: 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 only 128 bytes, instead of 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()
48
PageDisplay(sDefaultPage);
END
Use module variables with caution; 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
A local Cicode variable is only recognised by the function within which it is
declared, and can only be used by that function. You must declare local variables
before you can use them.
Any variable defined within a function (i.e., after the function name) is a local
variable, therefore no prefix is needed. Local variables are destroyed when the
function exits.
Local variables always 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.
See Also Variable Scope Standards
A Cicode variable array is a collection of Cicode variables of the same data type,
in the form of a list or table. You name and declare an array of variables in the
same way as any other Cicode variable. You can then refer to each element in the
array by the same variable name, with a number (index) to indicate its position
in the array.
See Also Variable Declaration Standards
Declaring Array Properties
Declaring the Array Data Type
Naming Arrays
Declaring the Variable Array Size
Setting Default (Initial) Array Values
Passing Array Elements as Function Arguments
Using One-dimensional Arrays
Using Two-dimensional Arrays
Using Three-dimensional Arrays
Using Array Elements in Loops
Using the Table (Array) Functions
Using Cicode Files
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 (i.e. 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 StrArray[5];! list
REAL Result[5][2];! 2-D table
INT IntArray[4][3][2];! 3-D table
See Also Using Arrays
Using Cicode Files
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
51
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
must write.
See Also Using Arrays
Using Cicode Files
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.
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
56
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.
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.
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.
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.
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.
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
variation of IFDEF to check for the existence of alarm tags. See IFDEFDigAlm for
digital alarms, or IFDEFAdvAlm for advanced alarms.
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
58
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.
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.
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.
Related macros
IFDEFAnaAlm, IFDEFAdvAlm, IFDEF
Macro Arguments
The Cicode macros use the following arguments.
TagName
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:
Generate any variable, constant, or expression.
Generate the current value for the specified tag by leaving the argument
blank.
CitectSCADA provides four functions for converting integers and real numbers
into strings, and vice versa.
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 total 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
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.
If the two strings (as used in the previous example), were formatted using
appropriate escape sequences positioned within the strings, and subsequently
64
Strings and string variables can also be concatenated as in the previous example.
Notice 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
With Cicode, you can use the data operators that are standard in most
programming languages: mathematical, bit, relational, and logical operators.
See Also Using Mathematical Operators
Using Bit Operators
Using Relational Operators
Using Logical Operators
Order of Precedence of Operators
Note: Cicode uses the standard order of precedence, i.e. 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.
68
You can also use the addition operator (+) to concatenate (join) two strings.
Operator Description
+ Concatenate
For example:
Command Message = "For info see " + "Supervisor";
Comment Message now equals "For info see Supervisor"
See Also Working with Operators
Using Cicode Files
For example
Command Tag3 = Tag1 BITAND Tag2;
Command Tag3 = Tag1 BITAND 0xFF;
Command Tag3 = Tag1 BITOR Tag2;
Command Tag3 = Tag1 BITXOR Tag2;
See Also Working with Operators
Using Cicode Files
Examples:
Command Result = (PV12 = 10 AND PV13 = 2);
Comment If PV12 equals 10 and PV13 equals 2 then Result is TRUE(1)
Expression Motor_1 AND Motor_2;
Comment If both Motor_1 and Motor_2 are TRUE, i.e. Digital bits are 1 or ON, then the
expression is TRUE
Expression PV12 = 1 OR PV13 > 2 OR Counter <> 0;
Comment If either PV12 equals 1 or PV13 is greater than 2 or Counter is not equal to 0,
then the expression is TRUE
Command Result = (Motor1_Ol OR Motor2_Ol);
Comment If either Motor1_Ol or Motor2_Ol is TRUE, i.e. Digital bit is 1 or ON, then Result
is TRUE (1)
Command IF NOT PV12 = 10 THEN ...
Comment If PV12 does not equal 10 then the result is TRUE. This is functionally identical
to IF PV12 <> 10 THEN . . .
Expression NOT Tag_1;
Comment This expression is TRUE if Tag_1 = 0. This is most commonly used for testing
digital variables
See Also Working with Operators
Using Cicode Files
70
The statements that control decisions and loops in your functions are called
conditional executors. Cicode uses four conditional executors: IF, FOR, WHILE,
and SELECT CASE.
See Also Formatting Executable Statements
Setting IF ... THEN Conditions
Using FOR ... DO Loops
Using WHILE ... DO Conditional Loops
Using the SELECT CASE statement
Using Cicode Files
Report("Shift");
END
END
In this example, the report runs when the Counter increments, i.e. 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
WHILE Expression DO
Statement(s);
END
The following code fragment uses a WHILE loop:
INT Counter;
WHILE DevNext(hDev) DO
Counter = Counter + 1;
END
/* Count the number of records in the device (hDev)*/
Be careful when using WHILE loops in your Cicode functions: WHILE loops can
cause excessive loading of the CPU and therefore reduce system performance. If
you use a WHILE loop to loop forever, you should call the Cicode function
Sleep() so that CitectSCADA can schedule other tasks. The Sleep() function
increases the performance of your CitectSCADA system if you use many
WHILE loops.
See Also Working with Conditional Executors
Nested Loops
You can "nest" one loop inside the other. That is, a conditional statement can be
placed completely within (nested inside) a condition of another statement.
See Also Working with Conditional Executors
Where the TO keyword specifies an inclusive range of values. The smaller value
must 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
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 must
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
CASE1
Prompt("Waiting");
CASE2
Prompt("Berthed");
CASE3
Prompt("Loading");
CASE4
Prompt("Loaded");
CASE Else
Prompt("No Status");
END SELECT
See Also Working with Conditional Executors
Chapter 12: Performing Advanced Tasks
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 - you do not
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.
See Also Performing Advanced Tasks
76
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 MS-Excel 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, all you have to do is call the functions.
77
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 then when they are
finished, most users will not need to be concerned with them.
Sometimes it is desirable to manually 'spawn' a new task. For example, suppose
your Cicode is polling an I/O Device (an operation which must be continuous),
but a situation arises that require 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
Performing Advanced Tasks
Task Functions
78
Pre-emptive multitasking
Cicode supports pre-empted multitasking. If a Cicode task is running, and a
more important task is scheduled, CitectSCADA will suspend the original task,
complete the more important task and return to the original task.
Preemption is supported between Cicode threads and other internal process
performed by CitectSCADA. You can, therefore, write Cicode that runs forever
(e.g. 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
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
Chapter 13: Editing and Debugging Code
This section describes how to edit and debug your Cicode using the Cicode
Editor.
Changing the default CitectSCADA allows you to use any text editor supported by Windows (for
Cicode Editor example, ED for Windows, Windows Notepad, or Microsoft Word), instead of
the default Cicode Editor.
To change the default Cicode Editor:
1 Click the Project Editor button.
2 Choose Tools | Options.
3 Enter the editor application file name in the Cicode Editor field.
Note: The application name of the default Cicode Editor is ctcicode.exe
located in the CitectSCADA bin folder. The application name for Notepad is
notepad.exe, located in the Microsoft Windows winnt folder. The relative
path to the editor app must be included if the application is not stored in the
CitectSCADA bin folder.
4 Click OK to save the changes and close the form, or Cancel to abort changes
without saving.
Make sure you save the Cicode file after creating it. The file is only stored on
disk after you save it.
3 Select a file from the list. You can use the dialog controls to open other
projects and directories.
4 Click the Open button to open the file, or Cancel to abort.
Note: Double clicking on any Cicode file (*.ci) in the Citect Explorer will
launch the Cicode Editor and open the Cicode file. However, be careful not
to confuse a Cicode file with an Include file (*.cii), as you should not open an
Include file in the Cicode Editor.
Free floating windows are those that are not docked to the editor, nor are
necessarily constrained by the editor boundaries. Free floating windows can be
resized manually, and are subject to layering (Z-order), in which they can be
partly or wholly obscured by another window, and they could partly or wholly
obscure the view of another window themselves. The window or toolbar with
the current focus, is the one completely visible at the top of all other display
window layers, partly or wholly obscuring all those beneath it in the Z-order.
Windows and toolbars can be moved about in the Cicode Editor environment by
clicking and dragging the titlebar of a window, or non-button area of a button
bar. Docking behaviour is by default, and can be overridden by holding down
the CTRL key during the drag-and-drop to force the window or bar to be free
floating.
The position of the mouse during the drop action determines which side the
window or toolbar docks to. Docking outlines of the window or toolbar are
displayed with gray lines during the drag action to indicate the potential docked
position.
Debugging Cicode
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
86
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.
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:
Breakpoint window
Output window
Global Variable window
Stack window
Thread window
Compile Errors window
CitectVBA Watch window
Files window
Viewing Editor windows You can choose to view Editor windows or hide them to give you more room on
your screen.
To view/hide an Editor Window:
1 Run the Cicode Editor.
2 From the View menu, select the appropriate Window, or click the toggle
button you want in the View toolbar.
Breakpoint window
Displays the Breakpoint Window, which is used to list all breakpoints that are
currently set within the project. Double clicking an item in the list loads the file
87
into the editor and jumps to the breakpoint position. Right-clicking an item
allows the enable/disable/removal of the list item.
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:
Global variable is processed, its value will be updated in the Global Variable
Window.
Note: You must be in debug mode to view global variable values in this window.
Stack window
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
Displays the Threads History window.
89
variable under watch. As it comes into scope, its value is updated and appears in
the Value column.
Files window
Displays the Files window containing three tabs.
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
always 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.
91
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 intend 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 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.
94
Debugging Cicode
To help you locate Cicode errors, you can switch the Cicode Editor to debug
mode to analyse running Cicode. You can toggle debugging on and off as
required, but CitectSCADA must 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 You can debug functions remotely if both computers are running identical
remotely projects and the CitectSCADA Path is the same on both machines.
To remotely debug Cicode:
1 Click the Cicode Editor button on the computer that will be running Cit-
ectSCADA (the remote).
95
Using breakpoints
There are three ways for a processing thread to halt:
Manually inserting a breakpoint.
Using the DebugBreak() Cicode function.
If a hardware error occurs.
To debug a function, you must 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 and do not
need to be saved with the file.
For a hardware error to halt a function, you must 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
96
break point line displayed. To launch the debugger in this case, you must have
the CitectSCADA will start debugger on hardware errors option set.
Inserting or removing You can insert and remove breakpoints to halt processing.
breakpoints To insert/remove a breakpoint:
1 Open the Cicode Editing window.
2 Position the cursor on the line where you want the breakpoint to be placed
or removed.
3 Click the Debug indicator bar. Alternatively, you can press F9 or choose
Debug | Insert/Remove Breakpoint.
The breakpoint appears as a large red dot at the beginning of the line.
Enabling/disabling You can enable or disable breakpoints you have inserted into your Cicode.
breakpoints 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.
Note: Parts contained within square brackets are optional. For example, you do
not have to specify the variable scope (it defaults to local if you do not). 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, all 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:
ModuleintmiRecipeMax=100;
intiRecipeMax;
stringsRecipeDefault="Tasty";
See Also Using Cicode Programming Standards
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
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 difficult. These labels
are: TRUE, FALSE, BAD_HANDLE, XFreak, XOutsideCL, XAboveUCL,
XBelowLCL, XOutsideWL, XUpTrend, XDownTrend, XGradualUp,
XGradualDown, XErratic, XStratification, XMixture, ROutsideCL,
RAboveUCL, RBelowLCL
INThFile,hForm;// WRONG
INThFile;// RIGHT
INThForm;// RIGHT
The reasons for this are:
All but the first identifier in the WRONG case are hidden and are often
missed in a quick glance;.
It is harder to add a comment or initialisation to an item in the WRONG
case.
All types, items, and initialisation within a group of declarations should be
vertically aligned.
For example:
STRING sFileName = "temp.dat";// WRONG
INT iOffset = -1; // WRONG
INT iState = 3; // WRONG
STRINGsFileName= "temp.dat";// RIGHT
INTiOffset= -1;// RIGHT
INTiState= 3;// RIGHT
See Also Using Cicode Commands
Using Cicode Programming Standards
IF-THEN-ELSE block
IF <expression> THEN
.
.
ELSE
.
.
END
To simulate ELSEIF blocks, use nested statements. For example:
IF <expression> THEN
.
.
ELSE
IF <expression> THEN
.
.
ELSE
IF <expression> THEN
.
.
ELSE
.
.
END
END
END
For WHILE and FOR statements see Working with Conditional Executors.
See Also Using Cicode Commands
Working with Conditional Executors
Using Cicode Programming Standards
Formatting Expressions
The following conventions should be observed when formatting Cicode
functions:
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. Operator should be surrounded by spaces. For example:
i= i*10+c-'0';// WRONG
i = i * 10 + c - '0';// RIGHT
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:
103
a = b * ( c - d );// WRONG
a = b * (c - d);// RIGHT
The round brackets which surround the arguments of a function all attract
no spaces, for example:
DisplayText( "hello" );// WRONG
DisplayText("hello");// 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);// WRONG
DevSeek(hDev, Offset);// 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 become lost 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]
The scope of the function. If you do not specify a scope, the function will be
Public by default. That is, it will be available to all Cicode files, pages, and
CitectSCADA databases (e.g. Alarm.dbf). To make a function Private (i.e. only
available within the file in which it is declared), you must 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.
104
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,
you do not have to specify the function scope (it will default to Public if you do
not). 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)
INThPlot = _BAD_HANDLE;
.
hPlot = …..;
.
RETURN hPlot;
END
PRIVATE
STRING
FUNCTION
WasteInfoName(INT nType, INT nMode)
STRINGsName = "Sydney";
.
sName = …..;
.
RETURN sName;
END
See Also Writing Functions
Using Cicode Functions
Using Cicode Programming Standards
105
//**ReadRecipeData
//**WriteRecipeData
//**GatherRecipeData
//**RecipeForm
//**OpenRecipeDatabase
//**
//**PRIVATE
//**ButtonCallback
//**
//*************** MODULE CONSTANTS***********************
moduleintcmiRecipeMax=100;//Maximum number of recipes
//**************** MODULE VARIABLES ***********************
moduleintmiRecipeNumber=0;//Minimum number of recipes
//*********************************************************
Function headers
Functions should have a descriptive header, formatted as follows:
//**FUNCTION :<name of function>
//**
//**DESCRIPTION :<suggests the operation, application source and
//**multi-tasking issues>
//**REVISIONDATEBYCOMMENTS
//**<revision number><date><author><comments about the change>
//**
//**ARGUMENTS:<argument description>
//**
//**RETURNED VALUE:< description of possible return values>
//**
//**NOTES:
The order of functions in a file is important:
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:
//**FUNCTION :OpenRecipeDatabase
//**
//**DESCRIPTION :Opens the specified database.
//**
//**REVISIONDATEBYCOMMENTS
//**1 28/09/97BSOriginal
//**2 05/10/97SFAAdded INI checking
//**
//**ARGUMENTS:
//**
//** STRING sNameName of the recipe database.
//**
107
Modular Programming
The best way to solve a problem is to partition the problem into smaller, more
manageable problems and to solve these smaller problems. 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:
Reduced Complexity - Once the function is created and tested, the detailed
operation about how it works can be forgotten. Users need only be
concerned with calling the function as they can be assured the tested
function will yield predictable results.
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 is because in a multitasking environment, the user
cannot guarantee 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, preventing 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.
108
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:
Number of tasks the function performs.
Similarity of the tasks.
The following table illustrates the different levels of cohesion:
Number of tasks Similarity Cohesion level Example
1 n/a high Sin(x)
More than 1 Similar Moderate SinAndTan(x).
More than 1 Dissimilar Low SinAndLength(x)
Many Radically different None SinAndDateAndTimeAndSQLNext(x)
For example, the function Sin(x) will perform one task - return the trigonometric
Sine value of x. This is an example of a highly cohesive function. The function
SinAndTan(x) performs two tasks - calculate the trigonometric Sine and Tan of
the value X. This function has lower cohesion than Sin(x) because it performs
two tasks.
Highly cohesive function are more reliable, easier to modify, and easier to debug
than functions that have lower levels of cohesion and are hence acceptable and
encouraged.
109
Low cohesion functions are typically complex, prone to errors, and are more
costly to fix. Low cohesion functions are regarded as unacceptable 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.
Very little can go wrong with this function; it only returns a time/date variable
with no error codes to worry about. In the unlikely event that the function fails,
it would be through no fault 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 fail of its own accord, or fail if the
function calling it passes bad data to it. Tightly coupled functiosn 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:
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 broken up 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 be a hazardous exercise. When functions write to
110
Defensive Programming
Ensure that your code never produces 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 always achievable.
Never write the same code twice. 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 cut the size of the code in question by a third or
more, which reduces complexity and therefore maintenance and debugging
time. The most effective method to achieve this is to convert the identical
code to a new function.
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 minimised. This may require the use of
semaphores to 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).
See Also Using Cicode Programming Standards
Modular Programming
Function Error handling
111
.
.
IF <an error has occurred> THEN
nError = 299;
END
RETURN nError;
END
Example of handles
INT
FUNCTION
ExampleInit()
INThFile= BAD_HANDLE;
…
hFile = ExampleFileOpen("MyFile.txt");
IF hFile <> BAD_HANDLE THEN
…
…
END
END
FUNCTION
ExampleFileOpen(STRING sName)
INThFile = BAD_HANDLE;
hFile = FileOpen(sName, "r+");
IF hFile = BAD_HANDLE THEN
hFile = FileOpen(sName, "r");
END
RETURN hFile;
END
Example of random values
INT
FUNCTION
ExampleInit()
INTnSamples= 0;
…
…
ErrSet(1);
nSamples = ExampleSamples();
IF IsError() = 0 THEN
…
…
END
ErrSet(0);
END
INT
FUNCTION
ExampleSamples()
113
INTnSamples = 0;
INTnError = 0;
…
…
ErrTrap(nError);
RETURN nSamples;
END
See Also Debugging Cicode
DebugMsg function
DebugMsg() 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:
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)
INThFile;
INThDev;
STRINGStr1;
END
FileClose(hFile);
DevClose(hDev);
RETURN 0;
END
Assert function
Assert reports an error if the test passed by the argument fails. The
implementation of this function can be found in DEBUG.CI in the INCLUDE
project.
For example:
INT
FUNCTION
FileDisplayEx(STRING sFileName)
INThFile;
Accumulator Functions
The following are functions relating to accumulators.
AccControl Controls accumulators e.g. motor run hours.
AccumBrowseClose Closes an accumulator browse session.
AccumBrowseFirst Gets the oldest accumulator entry.
AccumBrowseGetField Gets the field indicated by the cursor position in the browse session.
AccumBrowseNext Gets the next accumulator entry in the browse session.
AccumBrowseNumRecords Returns the number of records in the current browse session.
AccumBrowseOpen Opens an accumulator browse session.
AccumBrowsePrev Gets the previous accumulator entry in the browse session.
See Also Cicode Function Categories
118
ActiveX Functions
ActiveX functions enable you to create and interact with ActiveX objects, using
CitectSCADA as an ActiveX container.
_ObjectCallMethod Calls a specific method for an ActiveX object.
_ObjectGetProperty Retrieves a specific property of an ActiveX object.
_ObjectSetProperty Sets a specific property of an ActiveX object.
AnByName Retrieves the animation point number of an ActiveX object.
CreateControlObject Creates a new instance of an ActiveX object.
CreateObject Creates the automation component of an ActiveX object.
ObjectAssociateEvents Allows you to change the ActiveX object’s event class.
ObjectAssociatePropertyWith Establishes an association between a variable tag and an ActiveX object
Tag property.
ObjectByName Retrieves an ActiveX object.
ObjectHasInterface Queries the ActiveX component to determine if its specific interface is
supported.
ObjectIsValid Determines if the given handle for an object is valid.
ObjectToStr Converts an object handle to a string.
See Also Cicode Function Categories
Alarm Functions
Alarm functions display alarms and their related alarm help pages, and
acknowledge, disable, and enable alarms. They provide information about
alarms and allow your operators to add comments to alarm records. You can
also access alarms at the record level (on the alarms server) for more complex
operations.
AlarmAck Acknowledges alarms.
AlarmAckRec Acknowledges alarms by record number.
AlarmActive Determines if any alarms are active in the user's area.
AlarmClear Clears acknowledged, inactive alarms from the active alarm list.
AlarmClearRec Clear an alarm by its record number.
AlarmComment Allows users to add comments to alarm summary entries.
AlarmDelete Deletes alarm summary entries.
AlarmDisable Disables alarms.
AlarmDisableRec Disables alarms by record number.
AlarmDsp Displays alarms.
AlarmDspLast Displays the most recent, unacknowledged alarms.
AlarmDspNext Displays the next page of alarms.
AlarmDspPrev Displays the previous page of alarms.
AlarmEnable Enables alarms.
AlarmEnableRec Enables alarms by record number.
119
Clipboard Functions
With the Clipboard functions, you can copy data to, and paste data from, the
Windows Clipboard.
ClipCopy Copies a string to the Windows clipboard.
ClipPaste Pastes a string from the Windows clipboard.
ClipReadLn Reads a line of text from the Windows clipboard.
ClipSetMode Sets the format of data sent to the Windows clipboard.
ClipWriteLn Writes a line of text to the Windows clipboard.
See Also Cicode Function Categories
121
Cluster Functions
ClusterActivate Allows the user to activate an inactive cluster.
ClusterDeactivate Allows the user to deactivate an active cluster.
ClusterFirst Allows the user to retrieve the first configured cluster in the project.
ClusterGetName Returns the names of the primary and standby cluster servers.
ClusterIsActive Allows the user to determine if a cluster is active.
ClusterNext Allows the user to retrieve the next configured cluster in the project.
ClusterSetName Connects to a specific cluster server.
ClusterServerTypes Allows the user to determine which servers are defined for a given cluster.
ClusterStatus Allows the user to determine the connection status from the client to a server
on a cluster.
ClusterSwapActive Allows the user to deactivate an active cluster at the same time as activating
a deactive cluster.
See Also Cicode Function Categories
Color Functions
Allow manipulation of colors (e.g. to convert CitectSCADA colors to the format
required by ActiveX objects).
CitectColourToPackedRGB Converts a CitectSCADA colour into a packed RGB colour value that can be
used by an ActiveX object.
GetBlueValue Returns the Blue component of a packed RGB colour.
GetGreenValue Returns the Green component of a packed RGB colour.
GetRedValue Returns the Red component of a packed RGB colour.
MakeCitectColour Creates a colour from red, green and blue component parts.
PackedRGB Returns a packed RGB colour based on specified red, green, and blue
values.
PackedRGBToCitectColour Converts a packed RGB colour into the nearest equivalent CitectSCADA
colour.
See Also Cicode Function Categories
Communication Functions
The communication functions give you direct access to the communication ports
on your computer(s). You can use these functions to communicate with external
equipment, such as low speed devices (e.g. bar code readers), serial keyboards,
and dumb terminals. You should not use these functions to communicate with
high speed PLCs, because the performance may not be adequate.
Note: The Communication functions can only be called from an I/O server.
122
DDE Functions
The Cicode DDE (Dynamic Data Exchange) functions permit you to exchange
data between CitectSCADA and other Windows applications running on the same
computer in real time, continuously, and with no operator intervention. For
example, you can send your run-time data to a DDE compliant spreadsheet or
word processing application, either by posting the data to memory for DDE
access by other applications, or by writing the data directly into another
application. Conversely, you could read data from a DDE compliant application
like a spreadsheet or document directly into a CitectSCADA variable.
You could also run processes in any DDE compliant Windows application
running on the same computer by using the Cicode DDEExec() function to send
commands to that application. Similarly, you can call any Cicode function (in-
built or user-written) in CitectSCADA from any Windows application (running on
the same computer), that supports a DDE Execute command.
The DDERead(), DDEPost(), DDEWrite(), and DDEExec() functions each
perform a single exchange of data. Each of these functions starts a DDE
conversation with the external application, sends or receives the data (or
command), and ends the conversation - all in one operation.
The DDE handle (DDEh...) functions return a handle to the conversation - a DDE
channel number. You should use the DDE handle functions for Network DDE,
in particular for Access DDE.
Note: CitectSCADA runtime automatically behaves as a DDE Server and makes its
variable tag database available for DDE Client applications to link with.
Device Functions
The device functions provide access to devices. They allow access to SQL,
dBASE, and ASCII files through database-like operations, and provide more
control over output to printers.
With these functions you can open and close any device, and read from and
write to any record or field in the device. You can store recipes or any other data
in a database, and then down-load or up-load the data as required to an I/O
device on the plant floor, or to the operator. You can also update the database
with real-time data for data exchange with other applications.
DevAppend Appends a blank record to the end of a device.
DevClose Closes a device.
DevControl Controls a dBASE or SQL device.
DevCurr Gets the current device number.
DevDelete Deletes the current record in a database device.
DevDisable Disables (and re-enables) a device from any access.
DevEOF Checks for the end of a file.
DevFind Finds a record in a device.
DevFirst Finds the first record in a device.
DevFlush Flushes buffered data to a device.
DevGetField Gets field data from the current record.
DevHistory Renames a device file and any subsequent history files.
DevInfo Gets device information.
DevModify Modifies the attributes of a device.
DevNext Gets the next record in a device.
DevOpen Opens a device for access.
DevOpenGrp Opens a group of devices.
DevPrev Gets the previous record in a device.
DevPrint Prints free-format data to a group of devices.
DevRead Reads characters from a device.
124
Display Functions
Display functions control the display and processing of graphics pages and
objects. You can use these functions to display graphics pages, print them on
your printer, send them to a file, or copy them to the Windows Clipboard. You
can also display text files on screen.
Note: The properties defined for an object will override any conflicting Cicode
Display functions.
You can create and move ANs (animation-point numbers), and obtain runtime
information about graphics pages and their associated ANs.
DspAnCreateControlObject Creates a new instance of an ActiveX object. If the object already exists for
the given Animation Point Number, then that object will be used (a new
object is not created).
DspAnFree Frees (removes) an AN from the current page.
DspAnGetArea Gets the area configured for an object at a specific AN (animation-point
number).
DspAnGetPos Gets the x and y coordinates of an AN (animation-point number).
DspAnGetPrivilege Gets the privileges configured for an object at a specific AN (animation-point
number).
DspAnInfo Gets information on the state of the animation at an AN.
DspAnInRgn Checks if an AN is within a specified region.
DspAnMove Moves an AN.
DspAnMoveRel Moves an AN relative to its current position.
DspAnNew Creates an AN.
DspAnNewRel Creates an AN relative to another AN.
DspBar Displays a bar graph at an AN.
DspBmp Displays a bitmap at a specified AN.
125
DspButton Displays a button at an AN and puts a key into the key command line (when
the button is selected).
DspButtonFn Displays a button at an AN and calls a function when the button is selected.
DspChart Displays a chart at an AN.
DspCol DspCol is deprecated in this version.
DspDel Deletes all objects at an AN.
DspDelayRenderBegin Delays screen updating until DspDelayRenderEnd() is called.
DspDelayRenderEnd Ends the screen update delay set by DspDelayRenderBegin().
DspDirty Forces an update to an AN.
DspError Displays an error message at the prompt AN.
DspFile Defines the screen attributes for displaying a text file.
DspFileGetInfo Gets the attributes of a file to screen display.
DspFileGetName Gets the name of the file being displayed in the display "window".
DspFileScroll Scrolls a file (displayed in the display "window") by a number of characters.
DspFileSetName Sets the name of the file to display in the display "window".
DspFont Creates a font.
DspFontHnd Gets a font handle.
DspFullScreen Enables or disables the full screen mode of the active window.
DspGetAnBottom Gets the bottom extent of the object at the specified AN.
DspGetAnCur Gets the current AN.
DspGetAnExtent Gets the extent of the object at a specified AN.
DspGetAnFirst Returns the first AN on the current page.
DspGetAnFromPoint Gets the AN of the object at a specified set of screen coordinates.
DspGetAnHeight Gets the height of the object at a specified AN.
DspGetAnLeft Gets the left extent of the object at the specified AN.
DspGetAnNext Returns the AN following a specified AN.
DspGetAnRight Gets the right extent of the object at the specified AN.
DspGetAnTop Gets the top extent of the object at the specified AN.
DspGetAnWidth Gets the width of the object at a specified AN.
DspGetEnv Gets a page environment variable.
DspGetMouse Gets the mouse position.
DspGetMouseOver Determines if the mouse is within the boundaries of a given AN.
DspGetNearestAn Gets the nearest AN.
DspGetParentAn Gets the parent animation number (if any), for the specified AN.
DspGetSlider Gets the current position (value) of a slider at an AN.
DspGetTip Gets the tool tip text associated with an AN.
DspGrayButton Greys and disables a button.
DspInfo Gets object display information from an AN.
DspInfoDestroy Deletes an object information block created by DspInfoNew().
DspInfoField Gets stored and real-time data for a variable tag.
DspInfoNew Creates an object information block for an AN.
DspInfoValid Checks if an object information block is still valid.
126
DLL Functions
The DLL (Dynamic Link Library) functions allow you to call any DLL, including
the Windows standard functions, any third-party library, or your own library.
127
With the DLL functions, you can write functions in 'C', Pascal, or any other
language that supports DLLs, and then call those functions from CitectSCADA.
DLLCall Calls a DLL function.
DLLCallEx Calls a DLL function, and passes the specified arguments to that function.
DLLClose Closes a link to a DLL function.
DLLOpen Opens a link to a DLL function.
See Also Cicode Function Categories
Error Functions
The error functions trap and process errors. You can use these functions to check
the status of any other function.
ErrCom Gets the communication status for the current Cicode task.
ErrDrv Gets a protocol-specific error message.
ErrGetHw Gets a hardware error code.
ErrHelp Displays help information about a hardware error.
ErrInfo Gets error information.
ErrLog Logs a system error.
ErrMsg Gets the error message associated with a hardware error.
ErrSet Sets the error mode.
ErrSetHw Sets a hardware error.
ErrSetLevel Sets the error level.
ErrTrap Generates an error trap.
IsError Checks for an error.
See Also Cicode Function Categories
Event Functions
The event functions trap and process asynchronous events.
CallEvent Calls the event function for an event type.
ChainEvent Calls an event function, by function number.
GetEvent Gets the function number of the current callback event.
OnEvent Sets an event callback function, by event type.
SetEvent Sets an event callback function, by function number.
See Also Cicode Function Categories
File Functions
The file functions provide access to standard ASCII files. You can open or create
files and then read and write data in free format. Use these functions when you
require more complex file operations than are possible with the device
128
functions; e.g., importing and exporting data to and from other programs (that
support ASCII files).
You can build complex I/O functionality by combining these functions with the
format functions.
FileClose Closes a file.
FileCopy Copies a file or group of files.
FileDelete Deletes a file.
FileEOF Checks for the end of a file.
FileExist Checks if a file exists.
FileFind Finds a file that matches a specified search criteria.
FileFindClose Closes a find (started with FileFind) that did not run to completion.
FileGetTime Gets the time on a file.
FileMakePath Creates a file path string from individual components.
FileOpen Opens or creates an ASCII file.
FilePrint Prints a file on a device.
FileRead Reads characters from a file.
FileReadBlock Reads a block of characters from a file.
FileReadLn Reads a line from a file.
FileRename Renames a file.
FileRichTextPrint Prints a rich text file.
FileSeek Seeks a position in a file.
FileSetTime Sets the time on a file.
FileSize Gets the size of a file.
FileSplitPath Splits a file path into individual string components.
FileWrite Writes characters to a file.
FileWriteBlock Writes a block of characters to a file.
FileWriteLn Writes a line to a file.
See Also Cicode Function Categories
Form Functions
Form functions create and display data entry forms. Use them to display large
amounts of data or request data from the operator; for example, to display, load,
and/or edit a database of recipes.
FormActive Checks if a form is currently active.
FormAddList Adds a text string to a list box or combo box.
FormButton Adds a button to a form.
FormCheckBox Adds a check box to the current form.
FormComboBox Adds a combo box to the current form.
FormCurr Gets the current form and field handles.
FormDestroy Removes a form from the screen.
129
Format Functions
Format functions convert data into formatted strings. You can convert many
different items of data into single, formatted strings that can then be displayed,
printed, or written to a file. The format functions also convert (formatted) data
back into individual elements; e.g., strings that are read from files or other
devices.
FmtClose Closes a format template.
FmtFieldHnd Gets the handle of a field in a format template.
FmtGetField Gets field data from a format template.
FmtGetFieldHnd Gets field data from a format template using a field handle.
FmtOpen Creates a new format template.
130
FTP Functions
FTP functions are used to manage your FTP communications and files (used
when running your project over the Internet). These functions can only be used
on the Internet Display Client.
FTPClose Closes an FTP session.
FTPFileCopy Copies a file from the FTP server to the Internet Display Client.
FTPFileFind Finds a file on the FTP server that matches a specified search criteria.
FTPFileFindClose Closes a find (started with FTPFileFind) that did not run to completion.
FTPOpen Connects to an FTP server
See Also Cicode Function Categories
FuzzyTech Functions
The CitectSCADA FuzzyTech functions support fuzzy logic control and provide an
interface to the FuzzyTech functions provided by INFORM Software
Corporation. To use these functions you must purchase the development
environment from INFORM - the makers of FuzzyTech.
FuzzyClose Closes specified fuzzy instance.
FuzzyGetCodeValue Gets a specified Code variable from the specified instance.
FuzzyGetShellValue Gets a specified Shell variable from the specified instance.
FuzzyOpen Creates a new fuzzy instance.
FuzzySetCodeValue Sets a specified Code variable in the specified instance.
FuzzySetShellValue Sets a specified Shell variable in the specified instance.
FuzzyTrace Controls the tracing.
See Also Cicode Function Categories
Group Functions
Group functions manipulate groups of areas, alarm categories, and any other
data that can be accessed as a group. Use these functions to create a group
dynamically to use for various purposes; for example, to allow operators to
change their areas, or to view alarms by category, and so on.
GrpClose Closes a group.
GrpDelete Deletes items from a group.
GrpFirst Gets the first item in a group.
131
Keyboard Functions
Keyboard functions control the processing of keyboard entries, including the
movement of the keyboard cursor and manipulation of keyboard commands.
KeyAllowCursor Allows the command cursor to move to any AN or only to ANs that have
commands defined.
KeyBs Deletes the last character from the key command line.
KeyDown Moves the command cursor down.
KeyGet Gets the raw key code from the key command line.
KeyGetCursor Gets the AN where the cursor is positioned.
KeyLeft Moves the command cursor left.
KeyMove Moves the command cursor in the required direction.
KeyPeek Gets a key from the key command line without removing the key.
KeyPut Puts a raw key code into the key command line.
KeyPutStr Puts a string into the key command line.
KeyReplay Replays the last key sequence.
KeyReplayAll Replays and executes the last key sequence.
132
Mail Functions
The mail facility enables you to send data (e.g. a report) between CitectSCADA
users (or any other computer). CitectSCADA can send mail automatically, triggered
by an event such as a report or an alarm. It can also read mail, so any user on the
system can send mail to CitectSCADA (for example, a batch recipe).
You can use the mail facility to send information from CitectSCADA to Managers,
Supervisors or anyone on a LAN or WAN whether they are running CitectSCADA
or not. You can use it to send mail directly to these people whenever an event
occurs (for example, you can mail reports directly to the QA department when
they are scheduled, or send mail to the maintenance department when
equipment is due for service).
The mail system uses the MAPI standard interface, so you can use any mail
system that supports this standard. The mail system allows data transfer across
different computer platforms and to remote sites (using a data gateway),
enabling you to send high-level data across a wide area network.
MailError Gets the last mail error code
MailLogoff Logoff from the mail system
MailLogon Logon to the mail system
MailRead Reads a standard mail message
MailSend Sends a standard mail message
See Also Cicode Function Categories
Math/Trigonometry Functions
The following functions allow you to perform mathematical calculations in your
Cicode files:
Abs Gets the absolute value of a number.
ArcCos Gets the arccosine of an angle.
ArcSin Gets the arcsine of an angle.
ArcTan Gets the arctangent of an angle.
Cos Gets the cosine of an angle.
DegToRad Converts an angle from degrees to radians.
Exp Raises e to the power of a number.
133
Miscellaneous Functions
The following are miscellaneous functions.
AreaCheck Determines whether the current user has access to a specified area.
Assert Verifies a particular condition is true, or halts the task.
Beep Beeps the speaker or sound card in the computer.
CitectInfo Gets information about a CitectSCADA variable.
CodeTrace Traces Cicode into the Kernel and the SYSLOG.DAT file.
DebugBreak Causes a breakpoint error to start the Cicode Debugger.
DebugMsg In-line debug messages of user Cicode.
DebugMsgSet Enables/disables the DebugMsg function.
DelayShutdown Causes CitectSCADA to shut down after a specified period
DisplayRuntimeManager Starts and displays CitectSCADA Runtime Manager.
DumpKernel Dumps Kernel data to the Kernel.dat file.
EngToGeneric Converts a variable into generic scale format.
Exec Executes an application or PIF file.
GetArea Gets the current viewable areas.
GetEnv Gets an environment variable.
InfoForm Displays graphics object help information for the AN closest to the cursor.
InfoFormAn Displays graphics object help information for an AN.
Input Gets text input from the operator.
134
Page Functions
Page functions display graphics pages, files, and the standard alarm, trend, and
menu pages.
PageAlarm Displays a category of active alarms on the predefined alarms page.
135
Plot Functions
With the plot functions, you can plot system data on the screen or on your
system printer(s).
PlotClose Displays and/or prints the plot, then closes the plot.
PlotDraw Draws a point, line, box, or circle on a plot.
PlotFile This function is now obsolete.
PlotGetMarker Gets the marker number of a symbol that is registered as a marker.
PlotGrid Draws gridlines to be used for plotted lines.
PlotInfo Gets information about a plot.
PlotLine Plots a line through a set of data points.
PlotMarker Draws markers on a plotted line or at a specified point.
PlotOpen Opens a new plot, sets its output device, and returns a plot handle for use by
the other plot functions.
136
PlotScaleMarker Draws scale lines (with markers) beside the grid on your plot (if there is one).
PlotSetMarker Sets (registers) a symbol as a marker.
PlotText Draws text on a plot.
PlotXYLine Draws an XY line through a set of data points.
See Also Cicode Function Categories
Report Functions
With the report functions, you can run reports on the report server, change their
scheduling, or get their status.
RepGetCluster Retrieves the name of the cluster the report is running on.
RepGetControl Gets report control information.
Report Runs a report.
RepSetControl Sets report control information.
See Also Cicode Function Categories
Security Functions
The security functions allow you to control logins, logouts, and general security,
and to add, delete, and modify user records during run time. By giving selected
users access to these functions, you can provide them with supervisory control
of the system.
FullName Gets the full name of the current operator.
GetPriv Checks the privilege and area of the current operator.
Login Logs an operator into the CitectSCADA system.
LoginForm Displays a form that allows an operator to log in to the CitectSCADA system.
Logout Logs an operator out of the CitectSCADA system.
LogoutIdle Sets an idle time logout for the current operator.
Name Gets the user name of the current operator.
UserCreate Creates a new user record during run time.
UserCreateForm Displays a form to create a record for a new user.
UserDelete Deletes a new user record during run time.
UserEditForm Displays a form for a selected user to create or delete user records during
run time.
UserPassword Changes a user's password during run time.
UserPasswordExpiryDays Returns the number of days left before the user's password is due to expire.
UserPasswordForm Displays a form for the operator to change their own password during run
time.
UserInfo Gets information about the operator who is currently logged-in to the system.
WhoAmI Displays the name of the operator who is currently logged-in to the system.
See Also Cicode Function Categories
137
SPC Functions
SPC (Statistical Process Control) functions allow you to alter the properties and
parameters that affect the SPC calculations. By using the SPC functions you can
also gain direct access to the SPC data and alarms.
SPCAlarms Returns the status of the specified SPC alarm.
SPCClientInfo Returns SPC data for the given SPC tag.
SPCGetHistogramTable Returns an array containing the frequency of particular ranges for the given
SPC tag.
SPCGetSubgroupTable Returns an array containing the specified subgroup's elements with the
mean, range and standard deviation.
SPCPlot Generates a single page print showing three separate trends of the SPC
Mean, Range, and Standard Deviation.
SPCProcessXRSGet Gets the process mean, range and standard deviation overrides.
SPCProcessXRSSet Sets the process mean, range and standard deviation overrides.
SPCSetLimit Sets the upper or lower control limits of X-bar, range, or standard deviation
charts.
SPCSpecLimitGet Gets the specification limits (USL and LSL) for the specified tag.
SPCSpecLimitSet Sets the specification limits (USL and LSL) for the specified tag.
SPCSubgroupSizeGet Gets the size of a subgroup for the specified SPC tag.
SPCSubgroupSizeSet Sets the subgroup size for the specified SPC tag.
See Also Cicode Function Categories
SQL Functions
SQL functions allow you to define, manipulate, and control data in SQL
databases and other relational databases. By using the SQL functions (or the
device functions with an SQL device), you can directly access data on database
servers, mini-computers, and mainframe computers.
ExecuteDTSPkg Loads and executes a DTS package which initiates data transfer between
OLE DB data sources.
SQLAppend Appends a text string to the SQL buffer.
SQLBeginTran Starts a database transaction.
SQLCommit Commits a transaction to the database.
SQLConnect Makes a connection to a database system for execution of SQL statements.
SQLDisconnect Closes a database connection.
SQLEnd Terminates an SQL query.
SQLErrMsg Returns an error message from the SQL system.
SQLExec Executes an SQL query on a database.
SQLFieldInfo Gets information about the fields or columns selected in an SQL query.
SQLGetField Gets field or column data from a database record.
SQLInfo Gets information about a database connection.
138
String Functions
String functions allow you to manipulate strings in various ways. You can
extract characters or substrings from a string, convert strings into other data
types, format strings, search for strings, and perform other operations.
CharToStr Converts an ASCII code into a string.
HexToStr Converts a number into a hexadecimal string.
IntToStr Converts an integer variable into a string.
PathToStr Converts a CitectSCADA path into a string.
RealToStr Converts a floating-point variable into a string.
StrClean Removes control characters from a string.
StrFill Fills a string with characters.
StrFormat Formats a variable into a string.
StrGetChar Gets a single character from a string or buffer.
StrLeft Gets the left-most characters from a string.
StrLength Gets the length of a string.
StrLower Converts a string to lower-case.
StrMid Gets characters from the middle of a string.
StrPad Pads a string to the required length.
StrRight Gets the right-most characters from a string.
StrSearch Searches for a string within a string.
StrSetChar Sets a single character into string or buffer.
StrToChar Converts a string to an ASCII code.
StrToDate Converts a string into a date variable.
StrToFmt Converts a string into format fields.
StrToGrp Converts a string into a group.
StrToHex Converts a hexadecimal string into an integer.
StrToInt Converts a string into an integer variable.
StrToLines Converts a string into lines of limited length.
StrToLocalText Converts a string from Native language to Local language.
139
AssTitle Sets the runtime window title to the tag name of the first variable substituted
into the Super Genie.
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). You can use this function repeatedly to associate more
than 8 variable tags to a Super Genie.
AssWin Associates up to eight variable tags with a Super Genie, and displays the
Super Genie in a new window.
See Also Cicode Function Categories
Tag Functions
The Tag functions allow you to read the values of variables in I/O devices such
as PLCs, and to write data into these I/O device variables. These functions also
allow you to control I/O devices and to display information about I/O devices.
TagDebug Displays a dialog which allows you to select any configured tag to read or
change (write) its value.
TagGetProperty Gets a property for a variable tag from the datasource.
TagGetScale Gets the value of a tag at a specified scale from the datasource
TagInfo Gets information about a variable tag.
TagInfoEx Gets information about a variable tag. Replacement for TagInfo supporting
online changes.
TagRamp Increments a tag by a percentage amount.
TagRead Reads a variable from an I/O Device.
TagScaleStr Gets the value of a tag at a specified scale.
TagSubscribe Subscribes a tag for periodic monitoring and event handling.
TagUnsubscribe Unsubscribes a tag for periodic monitoring and event handling.
TagWrite Writes to an I/O Device variable
TagWriteEventQue Opens the tag write event queue.
See Also Cicode Function Categories
141
Task Functions
Task functions support advanced multi-tasking operations in Cicode, handling
queues, semaphores, messages, and other process functions. The task functions
control the transfer of data between different Cicode tasks and across the
network to different computers (by remote procedure calls).
ClusterGetName Sets the execution mode of a Cicode task.
EnterCriticalSection Requests permission for the current thread to have access to a critical
shared resource (critical section). If the critical section is already being
accessed, the thread will be granted access when it is free.
Halt Halts the current Cicode task.
LeaveCriticalSection Relinquishes the current thread's ownership of a critical shared resource
(critical section).
MsgBrdcst Broadcasts a message.
MsgClose Closes a message.
MsgGetCurr Gets the handle of the message that called the current report or remote
procedure.
MsgOpen Opens a message session with a CitectSCADA server or client.
MsgRead Reads a message from a session.
MsgRPC Calls a remote procedure on another CitectSCADA computer.
MsgState Verifies the status of a message session.
MsgWrite Writes a message to a session.
QueClose Closes a queue.
QueLength Gets the current length of a queue.
QueOpen Creates or opens a queue.
QuePeek Searches a queue for a queue element.
QueRead Reads elements from a queue.
QueWrite Writes elements to a queue.
ReRead ReRead is deprecated in this version.
SemClose Closes a semaphore.
SemOpen Creates or opens a semaphore.
SemSignal Signals a semaphore.
SemWait Waits on a semaphore.
Sleep Suspends the current Cicode task for a specified time.
SleepMS Suspends the current Cicode task for a specified time (in milliseconds).
TaskCluster Gets the name of the cluster context in which the current task is executing.
TaskGetSignal Retrieves a value that indicates the stop signal for a specific task.
TaskHnd Gets the handle of a particular task.
TaskKill Kills a running task.
TaskNew Creates a new task.
TaskNewEx Creates a new task with a subscription rate.
TaskResume Resumes a task.
142
Time/Date Functions
Time/date functions manipulate time and date variables. CitectSCADA stores time/
date-related variables as a single integer. This integer represents the number of
seconds since 01/01/1970. It is in GMT, but it has an offset that updates it to local
time (determined by the timezone the application is in). The Time/date
functions convert this integer into time and date variables.
Note: The Time/date functions can only be used with dates between 1980 and
2035.
Date Gets the current system date in string format.
DateAdd Adds time to a date.
DateDay Gets the day from a date.
DateInfo Returns the date format currently in effect on the CitectSCADA Server.
DateMonth Gets the month from a date.
DateSub Subtracts two dates.
DateWeekDay Gets the day of week from a date.
DateYear Gets the year from a date.
OLEDateToTime Converts an OLE DATE value to a CitectSCADA time/date value.
SysTime Marks the start of an event.
SysTimeDelta Calculates the time-span of an event.
Time Gets the current system time in string format.
TimeCurrent Gets the current time/date value.
TimeHour Gets hours from a time.
TimeInfo Returns the time format currently in effect on the CitectSCADA Server.
TimeMidNight Converts a time variable into the time at midnight.
TimeMin Gets minutes from a time.
TimeSec Gets seconds from a time.
TimeSet Sets the new system time on the computer.
TimeToStr Converts a time/date variable into a string.
TimeUTCOffset Determines the local time bias from UTC at a specified time.
See Also Cicode Function Categories
Trend Functions
You can control a trend's operation by using the trend functions. CitectSCADA has
standard trend pages, so you would not normally use these low-level functions
unless you want to define your own trend displays. You can control the
143
movement of the trend cursor, trend scaling, and the definition of trend
attributes (such as the trend starting time and sampling period). You can also
create, and subsequently delete trends.
TrnAddHistory Restores an old history file to the trend system.
TrnBrowseClose Closes a trend browse session.
TrnBrowseFirst Gets the oldest trend entry.
TrnBrowseGetField Gets the field indicated by the cursor position in the browse session.
TrnBrowseNext Gets the next trend entry in the browse session.
TrnBrowseNumRecords Returns the number of records in the current browse session.
TrnBrowseOpen Opens a trend browse session.
TrnBrowsePrev Gets the previous trend entry in the browse session.
TrnClientInfo Gets information about the trend that is being displayed at the AN point.
TrnComparePlot Prints two trends (one overlaid on the other), each with up to four trend tags.
TrnDelete Deletes a trend created by the TrnNew() function.
TrnDelHistory Deletes an old history file from the trend system.
TrnEcho Enables and disables the echo on the trend display.
TrnEventGetTable Stores event trend data and the associated time stamp in an event table and
time table, for a specified trend tag.
TrnEventGetTableMS Stores event trend data and time data (including milliseconds) for a specified
trend tag.
TrnEventSetTable Sets trend data from a table, for a specified trend tag.
TrnEventSetTableMS Sets event trend data and time data (including milliseconds) for a specified
trend tag.
TrnExportClip Exports trend data to the clipboard.
TrnExportCSV Exports trend data to a file in CSV (comma separated values) format.
TrnExportDBF Exports trend data to a file in dBASE III format.
TrnExportDDE Exports trend data to applications via DDE.
TrnFlush Flushes the trend to disk.
TrnGetBufEvent Gets the event number of a trend at an offset for a pen.
TrnGetBufTime Gets the trend time at an offset for a pen.
TrnGetBufValue Gets the trend value at an offset for a pen.
TrnGetCluster Gets the name of the cluster the trend graph is associated with.
TrnGetCursorEvent Gets the event number of a trend at the trend cursor.
TrnGetCursorMSTime Gets the time (in milliseconds from the previous midnight) at a trend cursor
for a specified pen.
TrnGetCursorPos Gets the position of the trend cursor.
TrnGetCursorTime Gets the time/date at the trend cursor.
TrnGetCursorValue Gets the current trend cursor value of a pen.
TrnGetCursorValueStr Gets the current trend cursor value of a pen as a formatted string.
TrnGetDefScale Gets the default engineering zero and full scales of a trend tag.
TrnGetDisplayMode Gets the display mode of a trend.
TrnGetEvent Gets the event number of a trend at a percentage along the trend.
144
The following trend functions are used on all 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.)
TrendDspCursorScale Displays a scale value for the current pen.
TrendDspCursorTag Displays the tag name of the current pen.
TrendDspCursorTime Displays the cursor time of the current pen.
TrendDspCursorValue Displays the cursor value of the current pen.
TrendGetAn Gets the AN number of the trend under the mouse position.
TrendPopUp Displays a pop-up trend with the specified trend pens.
TrendRun Initialises the cursor and rubber-band features on a trend page.
TrendSetDate Sets the starting date for all the pens on a trend.
TrendSetScale Sets the scale of one or more pens on a trend.
TrendSetSpan Sets the span time of a trend.
TrendSetTime Sets the starting time for all the pens on a trend.
TrendSetTimebase Sets a new sampling period for a trend.
TrendWin Displays a trend page (in a new window) with the specified trend pens.
TrendZoom Zooms a trend in either one or both axes.
See Also Cicode Function Categories
Window Functions
Window functions control the display of windows. You can open, move, size,
activate, and de-activate windows. You can also specify titles for your windows.
GetWinTitle Returns the name of the active window as a string.
HtmlHelp Invokes the Microsoft HTML Help application
WinCopy Copies the active window to the Windows clipboard.
WinFile Writes the active window to a file.
WinFree Removes a display window.
WinGetFocus Gets the number of the CitectSCADAwindow that has the keyboard focus.
WinGetWndHnd Gets the window handle for the current window.
WinGoto Changes the active window.
WinMode Sets the display mode of the active window.
WinMove Moves the active window.
WinNew Opens a display window.
WinNewAt Opens a display window at specified coordinates.
WinNext Makes the next window active.
WinNumber Gets the window number of the active CitectSCADAwindow.
WinPos Positions a window on the screen.
WinPrev Makes the previous window active.
WinPrint Prints the active window.
WinPrintFile Prints a file to the printer.
146
This section describes Cicode functions, and provides syntax and use examples.
Note: In some examples, lines of code might wrap due to page size limitation.
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.
_ObjectCallMethod
Description 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
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);
Return Value The return value from the method - if successful, otherwise an error is returned.
_ObjectGetProperty
Return Value The value of the property - if successful, otherwise an error is returned.
_ObjectSetProperty
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.
Abs
Description 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.
Example Variable=Abs(-67);
! Sets Variable to 67.
Variable=Abs(67);
! Sets Variable to 67.
See Also Math/Trigonometry Functions
AccControl
Description Controls accumulators, e.g. 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.
AccumBrowseClose
Description 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 0 (zero) if the accumulator browse session exists, otherwise an error is returned.
AccumBrowseFirst
Description 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 is returned.
AccumBrowseGetField
Description 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.
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 occurred. The last error should be checked in this
instance to determine if an error has actually occurred.
AccumBrowseNext
Description The AccumBrowseNext function moves the data browse cursor forward one
record.
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.
Return Value 0 (zero) if the accumulator browse session exists, otherwise an error is returned.
AccumBrowseNumRec
ords
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.
AccumBrowseOpen
Description 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.
Return Value Returns an integer handle to the browse session. Returns -1 on error.
AccumBrowsePrev
Description The AccumBrowsePrev function moves the data browse cursor back one record.
157
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 is returned.
AlarmAck
Description 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.
You would normally call this function from a keyboard command. No action is
taken if the specified alarms have already been acknowledged.
Example
System Keyboard
Key Sequence LeftButton
Command AlarmAck(0, 0)
Comment Acknowledge the alarm where the cursor is positioned
System Keyboard
Key Sequence ShiftLeftButton
Command AlarmAck(1, -1)
Comment Acknowledge a page of alarms
System Keyboard
Key Sequence AlarmAck ### Enter
Command AlarmAck(2, Arg1, "clusterXYZ")
159
hGrp=GrpOpen("CatGroup",1);
StrToGrp(hGrp,CategoryGroup);
AlarmAck(2,hGrp, "clusterXYZ");
GrpClose(hGrp);
END
See Also Alarm Functions
AlarmAckRec
Description Acknowledges alarms by record number on both the Primary and Standby
Alarm Servers. You can call this function only on an Alarm Server. However, a
client can call this function remotely by using the MsgRPC() function.
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 "".
AlarmActive
Description 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.
Example
Strings
AN 9
Expression AlarmActive(5)
True Text "Hardware Alarms Active"
False Text "No Active Hardware Alarms"
Comment Display the alarm status at AN 9
See Also Alarm Functions
AlarmClear
Description 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.
Example
System Keyboard
Key Sequence Clear
Command AlarmClear(0, 0)
Comment Clear the alarm where the cursor is positioned
System Keyboard
Key Sequence ClearAll
Command AlarmClear(1, -1)
Comment Clear a page of alarms
System Keyboard
163
AlarmClearRec
Description Clears an alarm by its record number on both the Primary and Standby Alarms
Servers. You can call this function only on an Alarms Server. However, a client
can call this function remotely by using the MsgRPC() function.
resolving the alarm server via the current cluster context. The
argument is enclosed in quotation marks "".
AlarmComment
Description Allows an operator to add a comment to a selected alarm summary entry during
runtime. You would normally call this function from a keyboard command.
Comments can only be added to alarm summary (Alarm Type 10) alarms.
Syntax AlarmComment(sComment)
sComment: . . . . . . . The comment to add to the alarm summary entry. Comments
have a maximum of 128 characters.
Example
System Keyboard
Key Sequence Com ################## Enter
Command AlarmComment(Arg1)
Comment Add an alarm comment to the alarm where the
cursor is positioned
See Also Alarm Functions
AlarmDelete
Description Deletes alarm summary entries that are currently displayed. You can delete 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.
165
Example
System Keyboard
Key Sequence DelSum
Command AlarmDelete(0, 0)
Comment Delete the alarm summary entry where the cursor is positioned
System Keyboard
Key Sequence ShiftDelSum
Command AlarmDelete(1, -1)
Comment Delete a page of alarm summary entries
System Keyboard
Key Sequence SumDelete ### Enter
Command AlarmDelete(2, Arg1, "clusterXYZ")
Comment Delete all alarm summary entries of a specified category in cluster XYZ
System Keyboard
Key Sequence DelSum ############# Enter
Command AlarmDelete(3,Arg1, "clusterXYZ")
Comment Delete all alarm summary entries of a specified priority in cluster XYZ
See Also Alarm Functions
AlarmDisable
Description 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.
Example
System Keyboard
Key Sequence Disable
Command AlarmDisable(0, 0)
Comment Disable the alarm where the cursor is positioned
System Keyboard
Key Sequence ShiftDisable
Command AlarmDisable(1, -1)
Comment Disable a page of alarms
System Keyboard
Key Sequence AlarmDisable ### Enter
Command AlarmDisable(2, Arg1, "clusterXYZ")
Comment Disable all alarms of a specified category in cluster
XYZ
System Keyboard
Key Sequence DisPri ############# Enter
Command AlarmDisable(3,Arg1,"clusterXYZ")
Comment Disable all alarms of a specific priority in cluster XYZ
See Also Alarm Functions
AlarmDisableRec
Description Disables alarms by record number on both the Primary and Standby Alarms
Servers. You can call this function only on an Alarms Server. However, a client
can call this function remotely by using the MsgRPC() function.
AlarmDsp
Description 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 must
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
170
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).
Example
Advanced Animation
Command AlarmDsp(20,15,3)
Comment Display 15 disabled alarms at AN 20
See Also Alarm Functions
AlarmDspLast
Description Displays the most recent unacknowledged alarms, at a specified AN with the
cluster named. Use this function to display the last alarms on all (or selected)
pages. You can specify the number of alarms to display of a specified type, for
example, active hardware alarms or disabled non-hardware alarms.
Hardware alarms
5 - All active alarms, i.e. Types 6 and 7
6 - All unacknowledged alarms, ON and OFF
7 - All acknowledged ON alarms
8 - All disabled alarms
9 - All configured alarms, i.e. Types 5 to 8
Alarm Summary
10 - All summary alarms
Alarm General
11 - All ON alarms
12 - All OFF alarms
13 - All ON hardware alarms
14 - All OFF hardware alarms
If you do not specify a Type, the default is 1.
ClusterName: . . . . . The cluster name to which the alarms belong. This is optional
if you have one cluster or are resolving the alarm server via
the current cluster context. The argument is enclosed in
quotation marks "".
If a cluster name is not specified, alarms are returned for all
clusters.
Example
Advanced Animation
Command AlarmDspLast(11, 'ClusterXYZ')
Comment Display the last alarm at AN 11
Advanced Animation
Command AlarmDspLast(21,3, 'ClusterXYZ')
Comment Display the last 3 alarms at AN 21
See Also Alarm Functions
173
AlarmDspNext
Description 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 AlarmDspNext(AN)
AN. . . . . . . . . . . . . . The AN where the alarm list is displayed, or:
-1 - Scroll all alarm lists 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.
Example
System Keyboard
Key Sequence NextAlarm
Command AlarmDspNext(20)
Comment Display the next page of alarms (from the alarm list) at AN20
See Also Alarm Functions
AlarmDspPrev
Description 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 AlarmDspPrev(AN)
AN: . . . . . . . . . . . . . The AN where the alarm list is displayed, or:
-1 - Scroll all alarm lists 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.
Example
System Keyboard
Key Sequence PrevAlarm
Command AlarmDspPrev(20)
Comment Display the previous page of alarms (from the
alarm list) at AN20
See Also Alarm Functions
AlarmEnable
Description 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.
Example
System Keyboard
Key Sequence Enable
Command AlarmEnable(0, 0)
Comment Enable the alarm where the cursor is positioned
System Keyboard
Key Sequence ShiftEnable
Command AlarmEnable(1, -1)
Comment Enable a page of alarms
System Keyboard
Key Sequence AlarmEnable ### Enter
Command AlarmEnable(2, Arg1, "clusterXYZ")
Comment Enable all alarms of a specified category in cluster XYZ
System Keyboard
Key Sequence EnPri ############# Enter
Command AlarmEnable(3,Arg1, "clusterXYZ")
Comment Enable all alarms of a specific priority in cluster XYZ
176
AlarmEnableRec
Description Enables alarms by record number on both the Primary and Standby Alarms
Servers. You can call this function only on an Alarms Server. However, a client
can call this function remotely by using the MsgRPC() function.
AlarmEventQue
Description Opens the alarm event queue. The Alarms Server writes events into this queue
as they are processed. These events include all 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 all state changes into the queue and CitectSCADA does not
use this queue for anything.
To use this function, you must 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 to prevent the Alarms Server from
placing a formatted string into the queue. Enabling this feature can cause
increase CPU loading and reduce performance of the Alarms Server; only use
this feature if really necessary.
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.)
Syntax AlarmEventQue()
Return Value The handle of the alarm event queue, or -1 if the queue cannot be opened.
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. To get the alarm record identifier for an alarm on a
Display Client, use the AlarmDspGet() function.
178
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. To get the alarm record identifier for an alarm on a
Display Client, use the AlarmDspGet() function.
179
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.
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.
iCurrent=AlarmFirstPriRec(iPriority,1,-1);
WHILE iCurrent <>-1 DO
iNext=AlarmNextPriRec(iCurrent,iPriority,1,-1);
180
AlarmAckRec(iCurrent);
iCurrent=iNext;
END
END
See Also Alarm Functions
AlarmFirstTagRec
Description Searches for the first occurrence of an alarm tag, name, and description.
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.
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.
AlarmGetDelay
Description Gets the delay setting for the alarm the cursor is currently positioned over.
Syntax AlarmGetDelay(Type)
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)
Return Value The alarm delay if successful, otherwise -1 is returned. Use IsError() to retrieve
extended error information.
AlarmGetDelayRec
Description Gets the delay setting for an alarm via the alarm record number.
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.
Return Value The alarm delay if successful, otherwise -1 is returned. Use IsError() to retrieve
extended error information.
AlarmGetDsp
Description 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 must be displayed before this function can be used).
You can call this function on an Alarms Server or a Display 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.
sField: . . . . . . . . . . . The name of the field from which the data is retrieved. The
contents of the following fields can be retrieved when either
the Alarm Summary or the Alarm Page is displayed:
Category Alarm category
Cluster Alarm Cluster the alarm originated on
Comment Operator comments attached to the Alarm Log entry (if any)
Desc Alarm description
Help Alarm help page
Name Alarm name
RecNo The alarm record number
Tag Alarm tag
Time The time that the alarm changed state (hh:mm:ss)
Return Value Field data from the alarm entry (as a string).
Example ! Display the tag and category for the alarm at the specified AN.
FUNCTION
AlarmData(INT AN)
STRING Category;
STRING Tag;
184
Category=AlarmGetDsp(AN,"Category");
Tag=AlarmGetDsp(AN,"Tag");
Prompt("Alarm "+Tag+" is Category "+Category);
END
See Also Alarm Functions
AlarmGetFieldRec
Description Gets the contents of the specified field in the specified alarm record.
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.
Example FUNCTION
GetNameFromTag(STRING sTag)
INT record;
STRING sName
record = AlarmFirstTagRec(sTag, "", "");
IF record <> -1 THEN
sName = AlarmGetFieldRec(record,"NAME");
ELSE
sName = "";
186
END
RETURN sName;
END
See Also Alarm Functions
AlarmGetInfo
Description 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 that you can not 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
AlarmGetOrderbyKey
Description 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(AN)
AN: . . . . . . . . . . . . . The AN where the alarm list (with the required information)
is displayed.
AlarmGetThreshold
Description Gets the threshold of the analog alarm where the cursor is positioned.
Syntax AlarmGetThreshold(Type)
Type: . . . . . . . . . . . . The type of threshold:
188
0 - High high
1 - High
2 - Low
3 - Low low
4 - Deadband
5 - Deviation
6 - Rate of change
AlarmGetThresholdRec
Description Gets the threshold of analog alarms by the alarm record number.
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.
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 "".
AlarmHelp
Description 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 must also define the help page in the Pages database.
Syntax AlarmHelp()
Example
System Keyboard
Key Sequence AlmHelp
190
Command AlarmHelp()
Comment Display the alarm help page
See Also Alarm Functions
AlarmNextCatRec Searches for the next occurrence of an alarm category and type, commencing
with the specified alarm record identifier (returned from the previous search
through the AlarmFirstCatRec function). You can search all areas, the current
area only, or specify an area to limit the search.
This function returns an alarm record identifier that you can use in other alarm
functions, for example, to acknowledge, disable, or enable the alarm, or to get
field data on that alarm. To get the alarm record identifier for an alarm on a
Display Client, use the AlarmDspGet() function.
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. To get the alarm record identifier for an alarm on a
Display Client, use the AlarmDspGet() function.
AlarmNextTagRec
Description 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).
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.
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.
AlarmNotifyVarChange
Description 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.
Return Value The error that occurred when the function was called.
AlarmQueryFirstRec
Description Searches for the first occurrence of an alarm category (or priority) and type. This
is a wrapper function of AlarmFirstCatRec and AlarmFirstPriRec.
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.
0 - Search by category.
1 - Search by priority.
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 "".
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).
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.
This is wrapper function of AlarmNextCatRec and AlarmNextPriRec.
0 - Search by category.
1 - Search by priority.
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 "".
AlarmSetDelay
Description Changes the delay setting for an alarm (i.e. 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 permanent
(i.e. they are saved to the project).
AlarmSetDelayRec
Description Changes the delay setting for an alarm (i.e. 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. However, a client can call this function remotely by using the
MsgPRC() function.
AlarmSetInfo
Description Changes the display parameters for the alarm list displayed at a specified AN.
AlarmSetInfo(21,9,1);
/* In the following examples, the display parameters of the alarm
list where the cursor is positioned are changed. */
! Change the vertical offset (pages) to 2.
AlarmSetInfo(0,0,2);
! Change the vertical offset (lines) to 15.
AlarmSetInfo(0,1,15);
! Change the alarm category to 10.
AlarmSetInfo(0,2,10);
! Change the type of alarms displayed to type 5 (all hardware
alarms).
AlarmSetInfo(0,3,5);
/* In the following examples, the display parameters of the alarm
list at AN 20 are changed. */
! Display all alarms with category 120 format and fonts
AlarmSetInfo(20, 4, 120);
! Display all alarms with a new format
hFmt=FmtOpen("MyFormat","{Name}{Desc,20}",0);
AlarmSetInfo(20, 5, hFmt);
! Display all alarms with a new font
hFont = DspFont("Times",-60,black,gray);
AlarmSetInfo(20, 6, hFont);
The following example displays all 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");
Note that hGrp is defined in the variables database. The page exit command for
the alarm display page is configured as follows:
On page exit command GrpClose(hGrp)
AlarmSetInfo(20, 2, hGrp);
See Also Alarm Functions
AlarmSetQuery
Description Allows you to choose which alarms display on a page, by calling a user-defined
query function to filter the alarms on specific criteria. The query function is
called for each alarm, and only alarms matching the criteria are displayed on the
page.
There are two steps involved in using a query to display alarms:
1 Write the Cicode function that will be used as the query function.
2 Specify the query function and its arguments in a call to AlarmSetQuery().
203
Note: You can also use AlarmSetQuery() to remove filtering from an alarm list.
AlarmSetQuery( -1, "", "" ) stops the query function filtering the display of
alarms.
AlarmSetThreshold
Description Changes the thresholds (i.e. 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
205
Analog Alarms database. Threshold changes made using this function are
permanent (i.e. 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.
Example
System Keyboard
Key Sequence SetHighHigh ### Enter
Command AlarmSetThreshold(0, Arg1)
Comment Change the threshold of a high high alarm
System Keyboard
Key Sequence SetHigh ### Enter
Command AlarmSetThreshold(1, Arg1)
Comment Change the threshold of a high alarm
System Keyboard
Key Sequence SetLow ### Enter
Command AlarmSetThreshold(2, Arg1)
Comment Change the threshold of a low alarm
System Keyboard
Key Sequence SetlowLow ### Enter
Command AlarmSetThreshold(3, Arg1)
206
AlarmSetThresholdRec
Description Changes the threshold (i.e. 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).
However, a client can call this function remotely by using the MsgRPC()
function.
Threshold changes made using this function are permanent (i.e. 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.
5 - Deviation
6 - Rate of change
Value: . . . . . . . . . . . The new value of the threshold. Enter a blank value "" to
remove the threshold.
AlarmSplit
Description Duplicates an entry (where the cursor is positioned) in the alarm summary
display. You can use this function to add another comment to an alarm
summary entry. You would normally call this function from a keyboard
command.
Syntax AlarmSplit()
Example
System Keyboard
Key Sequence Split
Command AlarmSplit()
Comment Duplicates an alarm summary entry
See Also Alarm Functions
AlarmSumAppend
Description Appends a new blank record to the alarm summary. Use this function to add
new alarm summary entries, either for actual alarms or as special user summary
entries.
If you specify a valid alarm tag in the sTag field, the summary entry is linked to
the actual alarm. If you specify an asterisk '*' as the first letter of the tag, the
summary entry becomes a user event.
208
User events are not attached to alarm records, so their status will never change.
You must manually change the status of the user event, by calling the
AlarmSumSet() function with the index returned by AlarmSumAppend(). As
user events are not attached to alarms, they don't have the alarm fields - so the
AlarmSumGet() function will not return any field data.
You can use user events to keep a record of logins, or control operations that you
need to display in the alarm summary etc. To set the {ONTIME} {OFFTIME} etc.
data, use the AlarmSumSet() function.
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.
Return Value The index of the alarm summary entry, or -1 if the record could not be
appended.
AlarmSumCommit
Description Commits the alarm summary record to the alarm summary device. Alarm
summaries are normally written to the alarm summary device just before they
209
are deleted from the summary queue. The length of time that alarm summary
entries remain in the alarm summary queue is controlled by
[Alarm]SummaryTimeout parameter
This function allows you to commit the alarm summary records now, rather
than when they are deleted from the queue.
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.
Example /* This function commits all alarm summary entries that match the
specified tag. */
FUNCTION
SumCommitTag(STRING sTag)
INT Next;
INT Index;
STRING Name;
Index=AlarmSumFirst();
WHILE Index<>-1 DO
Name=AlarmSumGet(Index,"Tag");
Next=AlarmSumNext(Index);
IF Name=sTag THEN
AlarmSumCommit(Index);
END
Index=Next;
END
END
See Also Alarm Functions
210
AlarmSumDelete
Description Deletes an alarm summary entry. You identify the alarm summary entry by the
Index, returned by one of the alarm summary search functions.
By embedding this function in a loop, you can delete a series of alarm summary
entries. To start deleting from the oldest entry, call the AlarmSumFirst() function
to get the index, and then call AlarmSumNext() in a loop. To delete back from
the most recent entry, call AlarmSumLast() and then AlarmSumPrev() in a loop.
You can also get the Index from the AlarmSumFind() function, which finds an
alarm summary entry by its alarm record identifier and time of activation.
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.
Return Value 0 (zero) if the specified alarm entry exists, otherwise an error is returned.
Example /* This function deletes all alarm summary entries that match the
specified tag. */
FUNCTION
SumDelTag(STRING sTag)
INT Next;
INT Index;
STRING Name;
Index=AlarmSumFirst();
WHILE Index<>-1 DO
Name=AlarmSumGet(Index,"Tag");
Next=AlarmSumNext(Index);
IF Name=sTag THEN
AlarmSumDelete(Index);
END
211
Index=Next;
END
END
See Also Alarm Functions
AlarmSumFind
OnTime: . . . . . . . . . The ON time of the alarm associated with the Record, that is,
the time that the alarm was activated.
AlarmSumFind() requires that the OnTime argument
contains the number of seconds from Midnight, so the
formulation:
iOnTime = StrToTime(AlarmSumGet(iIndex,
"OnTime"));
will NOT yield the correct result. The correct formulation for
this calculation is:
OnTime = StrToTime(AlarmSumGet(iIndex, "OnTime"))
+ TimeMidnight(TimeCurrent());
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 index of the alarm summary entry, or -1 if no alarm summary entry is
found.
Example /* This function sets the summary comment from the alarm record
number and the ontime of the summary event. */
FUNCTION
SumSetComment(INT AN, STRING sComment)
INT nRecord;
INT iOnTime;
INT Index;
iOnTime=StrToDate(AlarmGetDsp(AN,"OnDate"))+StrToTime(AlarmGetDsp
(AN,"OnTime"));
nrecord=StrToInt(AlarmGetDsp(AN,"RecNo"));
Index = AlarmSumFind(nRecord, iOnTime);
IF Index<>-1 THEN
AlarmSumSet(Index,"Comment", sComment);
END
END
See Also Alarm Functions
213
AlarmSumFirst
Return Value The index of the oldest alarm summary entry, or -1 if no alarm summary entry is
found.
Example /* This function finds all alarm summary entries that match the
specified tag and sets the "OffTime" to the time specified. The
alarm entry is not acknowledged or set to the off state, the alarm
summary "OffTime" field is all that is affected. */
FUNCTION
SumSetTime(STRING sTag, INT Time)
INT Index;
STRING Name;
Index=AlarmSumFirst();
WHILE Index<>-1 DO
Name=AlarmSumGet(Index,"Tag");
IF Name=sTag THEN
AlarmSumSet(Index,"OffTime",Time);
END
214
Index=AlarmSumNext(Index);
END
END
See Also Alarm Functions
AlarmSumGet
Return Value Field data from the alarm summary entry (as a string).
AlarmSumLast
Return Value The index of the most recent alarm summary entry, or -1 if no alarm summary
entry is found.
Example /* This function finds all alarm summary entries that match the
specified tag and sets the "OffTime" to the time specified. The
alarm entry is not acknowledged or set to the off state, the alarm
summary "OffTime" field is all that is affected. */
FUNCTION
SumSetTime(STRING sTag, INT Time)
INT Index;
STRING Name;
Index=AlarmSumLast();
WHILE Index<>-1 DO
Name=AlarmSumGet(Index,"Tag");
IF Name=sTag THEN
AlarmSumSet(Index,"OffTime",Time);
END
Index=AlarmSumPrev(Index);
END
END
See Also Alarm Functions
AlarmSumNext
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.
Return Value The index of the next alarm summary entry or -1 if no more alarm summary
entries are found.
AlarmSumPrev
Return Value 0 (zero) if the alarm summary entry exists, otherwise an error is returned.
AlarmSumSet
Description Sets field information in an alarm summary entry. You identify the alarm
summary entry by the Index, returned by one of the alarm summary search
functions.
By embedding this function in a loop, you can change field data in a series of
alarm summary entries. To start from the oldest entry, call the AlarmSumFirst()
function to get the index, and then call AlarmSumNext() in a loop. To work back
from the most recent entry, call AlarmSumLast() and then AlarmSumPrev() in a
loop.
You can also get the Index from the AlarmSumFind() function, which finds an
alarm summary entry by its alarm record identifier and time of activation.
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.
Return Value 0 (zero) if the alarm summary entry exists, otherwise an error is returned.
AlarmSumSplit
Description Duplicates the alarm summary entry identified by Index. You can use this
function to add another comment to an alarm summary entry.
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.
To duplicate an alarm summary entry on a Display Client, use the AlarmSplit()
function - the entry at the cursor position is duplicated.
resolving the alarm server via the current cluster context. The
argument is enclosed in quotation marks "".
Return Value 0 (zero) if the alarm summary entry exists, otherwise an error is returned.
Example /* This function finds the first alarm summary entry that matches
the specified tag, splits that entry and then adds the specified
comment to the new entry. */
FUNCTION
AlarmSplitAdd(STRING Tag, STRING Comment)
INT Index;
STRING Name;
Index=AlarmSumFirst();
WHILE Index<>-1 DO
Name=AlarmSumGet(Index,"Tag");
IF Name=sTag THEN
AlarmSumSplit(Index);
Index=AlarmSumFirst();
AlarmSumSet(Index,"Comment",Comment);
Index=-1;
ELSE
Index=AlarmSumNext(Index);
END
END
END
See Also Alarm Functions
AlarmSumType
Return Value A number that represents one of the following alarm types:
0 = digital alarm
1 = analog alarm
2 = advanced alarm
3 = Multi-Digital alarm
4 = Argyle analog alarm
5 = user-generated event
6 = high resolution alarm
8 = time-stamped digital alarm
9 = time-stamped analog alarm
-1 indicates an invalid response to the request.
AlmSummaryAck
Description The AlmSummaryAck function acknowledges 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 AlmSummaryAck(iSession)
iSession . . . . . . . . . . The handle to a browse session previously returned by a
AlmSummaryOpen call.
222
Return Value 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmSummaryClear
Description 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 AlmSummaryClear(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 is returned.
AlmSummaryClose
Description 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.
223
Return Value 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmSummaryCommit
Description The AlmSummaryCommit function triggers the actual write of the value for the
field previously specified by AlmSummarySetFieldValue.
This function is a blocking function. It blocks the calling Cicode task until the
operation is complete.
Syntax AlmSummaryCommit(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 is returned.
AlmSummaryDelete
Description The AlmSummaryDelete function deletes the record that the browse 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 browse session previously returned by a
AlmSummaryOpen call.
Return Value 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmSummaryDeleteAll
Description The AlmSummaryDeleteAll function deletes all of the records from the data
browse 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 browse session previously returned by a
AlmSummaryOpen call.
225
Return Value 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmSummaryDisable
Description 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 is returned.
AlmSummaryEnable
Description 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 AlmSummaryEnable(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 is returned.
AlmSummaryFirst
Description 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 is returned.
AlmSummaryGetField
Description 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.
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 occurred. The last error should be checked in this
instance to determine if an error has actually occurred.
AlmSummaryNext
Description The AlmSummaryNext function moves the data browse cursor forward one
record.
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.
Return Value 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmSummaryOpen
Description 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.
229
This function is a blocking function. It blocks the calling Cicode task until the
operation is complete.
Return Value Returns an integer handle to the browse session. Returns -1 on error.
AlmSummaryPrev
Description The AlmSummaryPrev function moves the data browse cursor back one record.
This function is a blocking function. It blocks the calling Cicode task until the
operation is complete.
Syntax AlmSummaryPrev(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 is returned.
AlmSummarySetFieldV
alue
Description The AlmSummarySetFieldValue function sets a new value for the specified field
for the record the data browse cursor is currently referencing. The value is not
committed until a call to AlmSummaryCommit is made.
231
This function is a blocking function. It blocks the calling Cicode task until the
operation is complete.
Return Value 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmTagsAck
Description 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 is returned.
AlmTagsClear
Description 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 is returned.
233
AlmTagsClose
Description 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 is returned.
AlmTagsDisable
Description 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 is returned.
AlmTagsEnable
Description 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 0 (zero) if the alarm browse session exists, otherwise an error is returned.
AlmTagsFirst
Description 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 is returned.
AlmTagsGetField
Description 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.
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 occurred. The last error should be checked in this
instance to determine if an error has actually occurred.
AlmTagsNext
Description The AlmTagsNext function moves the data browse cursor forward one record.
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 is returned.
AlmTagsNumRecords
Description 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)
237
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.
AlmTagsOpen
Description 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.
Return Value Returns an integer handle to the browse session. Returns -1 on error.
AlmTagsPrev
Description The AlmTagsPrev function moves the data browse cursor back one record.
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 is returned.
AnByName
Syntax AnByName(sName)
sName: . . . . . . . . . . The name for the object in the form of "AN" followed by its
AN number, eg. "AN35". This name is used to access the
object.
Return Value The animation point number of the object - if successful, otherwise an error is
returned.
ArcCos
Syntax ArcCos(Number)
Number . . . . . . . . . . The cosine of the angle.
240
Example Variable=ArcCos(0.4);
! Sets Variable to 1.1592...
See Also Math/Trigonometry Functions
ArcSin
Syntax ArcSin(Number)
Number: . . . . . . . . . The sine of the angle.
Example Variable=ArcSin(1);
! Sets Variable to 1.5707...
See Also Math/Trigonometry Functions
ArcTan
Syntax ArcTan(Number)
Number: . . . . . . . . . The tangent of the angle.
Example Variable=ArcTan(0.4);
! Sets Variable to 0.3805...
See Also Math/Trigonometry Functions
241
AreaCheck
Description Determines whether the current user has access to a specified area.
Syntax 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.
Ass
Description 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 must call this function once for every Super Genie substitution
string in the Super Genie.
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.
Example // Associate variable tag PV123 with the next Genie to display in
the current window
Ass(-3, 5, "PV123", 0);
See Also Super Genie Functions
AssChain
Description 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 all 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.
Example // Copy all associations from the current Super Genie to !NewGenie
AssChain(WinNumber(), WinNumber(), 0);
PageDisplay("!NewGenie");
See Also Super Genie Functions
AssChainPage
Description 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 all 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.
AssChainPopUp
Description 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 all the associations of the
first.
Note: This function prevents 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.
Example // Display new Super Genie in new popup using current associations
AssChainPopUp("!NewGenie");
See Also Super Genie Functions
AssChainWin
Description 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 all the associations of the first.
Example // Displays a new super genie in a new window using the current
associations
AssChainWin("!NewGenie", 100, 200, 1 + 8);
See Also Super Genie Functions
AssChainWinFree
Description Saves the first 8 tag associations on an existing Super Genie, closes it, then
assigns the 8 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.
Example // Close the current genie window and display a new genie using
the current associations
AssChainWinFree("!GeniePopup", 200, 300, 1 + 8);
248
Assert
Description Verifies that the specified expression is TRUE. If then expression is FALSE, the
current task will be halted. This is useful for ensuring that sensitive code is not
executed in the event of an error.
This function can be used in a debug mode, where the failed 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 must '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 must evaluate to
TRUE (1) or FALSE (0).
Return Value None. However, if the assertion fails (the condition is FALSE), error 347 is
generated.
Example INT
FUNCTION
FileDisplayEx(STRING sFileName);
INT hFile;
hFile = FileOpen(sFileName, "r");
Assert(hFile <> -1);
.
.
.
FileClose(hFile);
RETURN 0;
END
See Also Miscellaneous Functions
249
AssGetProperty
Description This function gets association information about the current Super Genie from
the datasource (i.e. information about a variable tag that has been substituted
into the Super Genie). You can only call this function on a Super Genie after all
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. All other properties are not valid.
This function replaces AssInfo.
Bit 17 - left-justified
Bit 18 - display engineering units
Bit 20 - exponential (scientific) notation
FormatDecPlaces - Number of decimal places for default
format
FormatWidth - Number of characters used in default format
FullName - The full name of the association tag in the form
cluster.tagname.
RangeHigh - Maximum unscaled value
RangeLow - Minimum unscaled value
TagName - Name of the tag for the specified association
Type - Raw type of associated tag
Units - Engineering Units e.g. %, mm, Volts
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. Ensures cicode is non-blocking
Default value is 1 (true).
Return Value String representation of the property of the association. On error, an empty
string and an error is set.
Example // 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);
See Also Super Genie Functions
251
AssGetScale
Description Gets scale information about the associations of the current Super Genie from
the datasource (i.e. 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 all 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.
Example // 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));
See Also Super Genie Functions
AssInfo
Description Gets association information about the current Super Genie (i.e. information
about a variable tag that has been substituted into the Super Genie). You can
only call this function on a Super Genie after all 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: This function is being deprecated and is replaced by the AssGetProperty
function. If the Tag properties are updated AssInfo does not get the updated
values whereas AssGetProperty does.
Note: This function is being deprecated and is replaced by the AssGetProperty
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 most cases AssInfo can be replaced with AssInfoEx using Find and
Replace (see Using Find and Replace in a project). Note 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 ensure you are using the
correct value for the Tag in your logic.
?INT 3?
set nArg to 3.
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:
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
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.
254
AssInfoEx
Description Gets association information about the current Super Genie (i.e. information
about a variable tag that has been substituted into the Super Genie). You can
only call this function on a Super Genie after all 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 ensure you are
using the correct value for the Tag in your logic.
Return Value The value of the information as a string. In case of error an empty string is
returned. The error code can be obtained by calling the IsError Cicode function.
256
AssPage
Description Associates up to eight variable tags 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, you must
call the AssVarTags(), AssTag(), or Ass() function to create the associations
before you call this function.
sTag8 8
Because there is a strict correlation between the variable tag
numbers and the substitution string numbers, it is important
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 must enter a
blank ("") for sTag2.
The variable tags that you specify here must 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 (eg. ?5?), you can
use any type except STRING.
The name of the tag can be prefixed by the name of the
cluster i.e. "ClusterName.Tag".
Example // Associate 3 tags with the Super Genie then display the Super
Genie
AssPage("!MyGenie", "PV123", "OP123", "SP123");
See Also Super Genie Functions
AssPopUp
Description Associates up to eight variable tags 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.
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 must
call the AssVarTags(), AssTag(), or Ass() function to create the associations
before you call this function.
258
Note: This function prevents the Super Genie from being opened more than
once (at the same time). However, the same Super Genie with different
associations can be opened.
AssScaleStr
Description Gets scale information about the associations of the current Super Genie (i.e.
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 all 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 whereas AssGetScale does.
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));
See Also Super Genie Functions
AssTag
Description Associates a variable tag with the 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 must call this
function once for every substitution string in the current Super Genie. You
cannot use this function to create associations for variables that will display in
new windows.
AssTitle
Description Sets the runtime window title to the tag name of the first variable substituted
into the Super Genie.
AssVarTags
Description 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 all the
necessary variable tags.
262
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.
AssWin
Description Associates up to eight variable tags 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 must call
the AssVarTags(), AssTag(), or Ass() function to create the associations before
you call this function.
Beep
Description 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
266
2 - Question waveform
3 - Exclamation waveform
4 - Asterisk waveform
Return Value 0 (zero) if successful, otherwise an error is returned.
CallEvent
Description 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.
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.
267
Return Value 0 (zero) if successful, otherwise an error is set. To view the error, use the
IsError() function.
Example ! Call Event Type 1 - key has been pressed in the current window.
Number=WinNumber();
CallEvent(Number,1);
See Also Event Functions
ChainEvent
Description 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.
CharToStr
Syntax CharToStr(ASCIICode)
ASCIICode: . . . . . . The ASCII code to convert.
CitectColourToPackedR
GB
Description Converts a CitectSCADA color value into a packed RGB color value that can be
understood by an ActiveX object.
Syntax CitectColourToPackedRGB(nCitectColour)
nCitectColour: . . . . The CitectSCADA color value to be converted into a packed
RGB color. CitectSCADA colors are defined in the labels
database, or calculated by the function MakeCitectColour
Return Value The packed RGB color value - if successful, otherwise an error is returned.
CitectInfo
Description Gets information about a CitectSCADA variable. This function returns internal
statistics and other information about the CitectSCADA runtime 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.
ClipCopy
Description 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.
ClipPaste
Syntax ClipPaste()
Return Value The contents of the clipboard (as a string). If the clipboard is empty, an empty
string is returned.
ClipReadLn
Description 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.
ClipSetMode
Syntax ClipSetMode(nMode)
nMode: . . . . . . . . . . The mode of the data:
1 - ASCII Text
2 - CSV (Comma separated values) format
You can select multiple modes by adding modes together.
Example /* Set the clipboard to CSV mode, write two values, and reset the
clipboard to the original mode. */
nOldMode = ClipSetMode(2);
ClipCopy("100,200");
ClipSetMode(nOldMode);
See Also Clipboard Functions
ClipWriteLn
Description 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.
ClusterActivate
Description 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)
ClusterName: . . . . . The name of the cluster to activate enclosed in quotation
marks "".
ClusterDeactivate
Description 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)
ClusterName: . . . . . The name of the cluster to deactivate enclosed in quotation
marks "".
ClusterFirst
Description This function allows the user to retrieve the first configured cluster in the
project.
Syntax ClusterFirst()
ClusterGetName
Description Returns the names of the primary and standby cluster servers to which
CitectSCADA is currently connected (sPrimary and sStandby, as set using the
ClusterSetName function).
ClusterIsActive
Syntax ClusterIsActive(ClusterName)
ClusterName: . . . . . The name of the cluster to query enclosed in quotation marks
"".
281
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.
ClusterNext
Description This function allows the user to retrieve the next configured cluster in the
project.
Syntax ClusterNext(ClusterName)
ClusterName: . . . . . 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.
ClusterServerTypes
Description This function allows the user to determine which servers are defined for a given
cluster.
Syntax ClusterServerTypes(ClusterName)
ClusterName: . . . . . The name of the cluster to query enclosed in quotation marks
"".
ClusterSetName
Description Connects to a specific cluster server (Reports Server, Alarms Server etc.).
CitectSCADA will disconnect from the current cluster before connecting to the
server you specify here.
This function would be used for switching the information displayed on the
Global Client. For example, if your system consists of plants A, B, and C, you
could include this function in a button command to connect to the Reports
Server for Plant B. Once connected, you could then display any information
from that server.
ClusterStatus
Description This function allows the user to determine the connection status from the client
to a server on a cluster.
ClusterSwapActive
Description 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 must be active and the other must be inactive.
CodeSetMode
Description Sets various execution modes for Cicode tasks in the current thread. Using this
function, you can specify whether to:
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.
Return Value -1 if there is an error, otherwise the last value of the mode.
CodeTrace
Description Traces Cicode into the Kernel and the SYSLOG.DAT file. Use this function for
finding bugs in your Cicode. It will trace all 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.
-4 - All tasks.
nMode: . . . . . . . . . . The mode of the trace:
0 - Tracing off
1 - Trace user Cicode functions calls
2 - Trace in-built function calls
4 - Trace errors
8 - Trace writes to the I/O devices
16 - Trace task state changes
-1 - All modes (except 0)
ComClose
Description 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.
288
ComOpen
Description Opens a communication port for access. The board and port must 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 fail and return -1. 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.
Example INT
FUNCTION
StartSerial(STRING sPort)
INThPort;
hPort = ComOpen(sPort, 0);
IF hPort < 0 THEN
Prompt("Cannot open port " + sPort);
RETURN -1;
END
TaskNew("SerialRead", hPort, 0);
TaskNew("SerialWrite", hPort, 0);
ComClose(hPort);
RETURN 0;
END
INT
FUNCTION
SerialWrite(INT hPort)
STRING buffer;
INT error;
INT length;
WHILE 1 DO
! put data into buffer and set length
.
.
error = ComWrite(hPort, buffer, length, 2);
IF error THEN
Prompt("Error Writing port");
ComReset(hPort);
END
END
RETURN 0;
END
INT
FUNCTION
SerialRead(INT hPort)
STRINGbuffer;
INTlength;
INTtotal;
INTerror;
total = 0;
WHILE 1 DO
length = 128; ! must set length as read modifies
error = ComRead(hPort, buffer, length, 2);
IF error THEN
Prompt("Error from port " + error : ####);
ComReset(hPort);
ELSE
! get data from buffer, length is set to number read
.
290
.
END
END
RETURN 0;
END
See Also Communication Functions
ComRead
Description 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 must 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.
Do not call ComRead() while another ComRead() is still pending on the same
port, because it can produce unexpected results.
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.
ComReset
Description 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.
ComWrite
Description 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
292
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.
Cos
Syntax Cos(Angle)
293
Example Variable=Cos(0.7854);
! Sets Variable to 0.7071...
See Also Math/Trigonometry Functions
CreateControlObject
sEventClass: . . . . . . The string you would like to use as the event class for the
object.
Return Value The newly created object, if successful, otherwise an error is generated.
END
// This function shows you how to write a mouse click event
handler for the calendar//
FUNCTION
CalendarEvent_Click(OBJECT This)
INT nDay;
INT nMonth;
INT nYear;
nDay = _ObjectGetProperty(This, "Day");
nMonth = _ObjectGetProperty(This, "Month");
nYear = _ObjectGetProperty(This, "Year");
.
.
.
Your code goes here...
.
.
.
END
See Also ActiveX Functions
CreateObject
Description 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.
Syntax CreateObject(sClass)
296
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 fail.
For example:
"Calendar Control 8.0" - human readable name
"MSCAL.Calendar.7" - Program ID
"{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID
Return Value The newly created object, if successful, otherwise an error is generated.
Example The following examples show correct techniques for calling CreateObject()
within a loop.
/* In the example below, the variable objTest is local. Resources
associated with calls to ProcessObject() will be released each
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 is global. Resources
associated with calls to ProcessObject() will be released when
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
See Also ActiveX Functions
297
Date
IF StrToDate(Arg1)>0 THEN
.
.
ELSE
.
.
END
Example /* If the current system date is 3rd November 1991 and the Windows
date format is dd/mm/yy; */
str = Date();
! Sets str to "3/11/91".
str = Date(2);
! Sets str to "3/11/91".
str = Date(3);
! Sets str to "3rd November 1991".
See Also Time/Date Functions
298
DateAdd
Description 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.
Example DateVariable=DateAdd(StrToDate("3/11/91"),86400);
! Adds 24 hours to 3/11/91.
NewDate=TimeToStr(DateVariable);
! Sets NewDate to 4/11/91.
See Also Time/Date Functions
DateDay
Syntax DateDay(Time)
Time: . . . . . . . . . . . . The time/date variable.
DateInfo
Description Returns the date format currently used on the CitectSCADA Server.
DateMonth
IF StrToDate(Arg1)>0 THEN
.
.
ELSE
.
.
END
301
Syntax DateMonth(Time)
Time: . . . . . . . . . . . . The time/date variable.
DateSub
Description 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.
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".
See Also Time/Date Functions
DateWeekDay
ELSE
.
.
END
Syntax DateWeekDay(Time)
Time: . . . . . . . . . . . . The time/date variable.
DateYear
DDEExec
DDEhExecute
Description Executes a command in an external Windows application. You must 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.
DDEhGetLastError
Description 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.
305
Return Value The error code last issued from Windows DDEML (for that conversation):
DMLERR_ADVACKTIMEOUT 0x4000
DMLERR_BUSY 0x4001
DMLERR_DATAACKTIMEOUT 0x4002
DMLERR_DLL_NOT_INITIALIZED 0x4003
DMLERR_DLL_USAGE 0x4004
DMLERR_EXECACKTIMEOUT 0x4005
DMLERR_INVALIDPARAMETER 0x4006
DMLERR_LOW_MEMORY 0x4007
DMLERR_MEMORY_ERROR 0x4008
DMLERR_NOTPROCESSED 0x4009
DMLERR_NO_CONV_ESTABLISHED 0x400a
DMLERR_POKEACKTIMEOUT 0x400b
DMLERR_POSTMSG_FAILED 0x400c
DMLERR_REENTRANCY 0x400d
DMLERR_SERVER_DIED 0x400e
DMLERR_SYS_ERROR 0x400f
DMLERR_UNADVACKTIMEOUT 0x4010
DMLERR_UNFOUND_QUEUE_ID 0x4011
DDEhInitiate
Description Starts a conversation with an external Windows application. When the data
exchange is complete, you should terminate the conversation to free system
resources.
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.
306
DDEhPoke
This function is a blocking function. It will block the calling Cicode task until the
operation is complete.
DDEhReadLn
Description Reads a line of text from a DDE Conversion, e.g. from an Excel spreadsheet. You
must 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. You should keep calling the
function until an empty string is returned.
This function is a blocking function. It will block the calling Cicode task until the
operation is complete.
Return Value A line of data, or an empty string when all data has been read.
DDEhSetMode, DDEhWriteLn, DDEhInitiate, DDEhExecute,
DDEhRequest, DDEhTerminate, DDEhGetLastError
DDEhRequest
Description Reads a value from an external Windows application, e.g. from an Excel
spreadsheet. You must 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.
DDEhSetMode
Description 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.
2 - CSV
DDEhTerminate
Description 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 and must not be used.
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.
DDEhWriteLn
Description 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.
DDEPost
Description Makes a CitectSCADA variable value available for DDE linking (i.e. 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.
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.
311
To link to this value from any DDE Client applications running on the same
computer, they must appropriately use the DDE Client syntax with:
"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.
Return Value The value that is posted, or 0 (zero) if the function fails.
DDERead
Description Reads values from an external DDE compliant Windows application running on
the same computer, (e.g. 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, you must 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.
312
Return Value The value (from the external application) as a string, or an empty string if the
function fails.
DDEWrite
Return Value The value that is sent to the other application, or an empty string if the function
fails.
DebugBreak
Description 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()
Example !Check to see that rSpan is greater than zero else cause a break.
If rSpan equals 0 it would cause a Divide by Zero hardware error
anyway.
IF rSpan > 0 THEN
rCalcRate = iAmount/rSpan;
ELSE
DebugBreak();
END
See Also Miscellaneous Functions
DebugMsg
Description 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.
Syntax DebugMsg(sMessage)
314
Example INT
FUNCTION
FileDisplayEx(STRING sFileName);
INT hFile;
hFile = FileOpen(sFileName, "r");
DebugMsg("When opening file " + sFileName + ", the handle was: "
+ IntToStr(hFile));
.
.
.
FileClose(hFile);
RETURN 0;
END
See Also Miscellaneous Functions
DebugMsgSet
Syntax DebugMsgSet(nMode)
nMode: . . . . . . . . . . The logging mode:
0 - Disable logging.
1 - Enable logging.
Example
Buttons
Text Debug Enable
Command DebugMsgSet(1)
315
DegToRad
Syntax DegToRad(Angle)
Angle: . . . . . . . . . . . Any angle (in degrees).
Example Variable=DegToRad(180);
! Sets Variable to 3.1415... (pi).
See Also Math/Trigonometry Functions
DelayShutdown
Description 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 which CitectSCADA will
shut down.
DevAppend
Description 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.
You must first call the DevOpen() function to get the device handle (hDev).
Syntax DevAppend(hDev)
hDev: . . . . . . . . . . . The device handle, returned from the DevOpen() function.
The device handle identifies the table where all data on the
associated device is stored.
Return Value 0 (zero) if the record is successfully appended, otherwise an error is returned.
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
See Also Device Functions
DevClose
Description 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.
Example DevClose(hDev);
See Also Device Functions
DevControl
Description 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.
DevCurr
Description 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 (e.g. DevPrint()) to access that logging device. (To get the
318
handle of a device other than a logging device, you must 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, e.g. you
cannot read from a group of devices.
Syntax DevCurr()
Return Value The current device handle or group handle. If no device is configured, -1 is
returned.
DevDelete
Description Deletes the current record in a dBASE database device. The record is not
physically deleted, but is marked for deletion. You can physically delete the
record by packing the database with the DevControl() function.
Syntax DevDelete(hDev)
hDev: . . . . . . . . . . . The device handle, returned from the DevOpen() function.
The device handle identifies the table where all data on the
associated device is stored.
Return Value 0 (zero) if the record is successfully deleted, otherwise an error is returned.
DevDisable
Description 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
319
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.
DevEOF
Description Gets the status of the end of file (EOF) flag for a device. When you use the
DevPrev(), DevNext(), or DevSeek() function, the start or end of the device will
eventually be reached, and the EOF flag will be set. Use this function to test the
EOF flag.
Syntax DevEOF(hDev)
hDev: . . . . . . . . . . . The device handle, returned from the DevOpen() function.
The device handle identifies the table where all data on the
associated device is stored.
Return Value 1 if the EOF flag has been set, otherwise 0 (zero).
DevNext(hDev);
END
DevClose(hDev);
See Also Device Functions
DevFind
Description 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.
DevFirst
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.
DevFlush
Description Flushes all 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)
hDev: . . . . . . . . . . . The device handle, returned from the DevOpen() function.
The device handle identifies the table where all data on the
associated device is stored.
DevGetField
Return Value The field data (as a string). If the field is not found an empty string is returned.
Example INT
FUNCTION
GetRecipe(STRING sName)
INT hDev;
hDev = DevOpen("Recipe", 0);
IF hDev >= 0 THEN
DevSeek(hDev, 1);
IF DevFind(hDev, sName, "NAME") = 0 THEN
PLC_FLOUR = DevGetField(hDev, "FLOUR");
PLC_WATER = DevGetField(hDev, "WATER");
PLC_SALT = DevGetField(hDev, "SALT");
PLC_MILK = DevGetField(hDev, "MILK");
ELSE
DspError("Cannot Find Recipe " + sName);
END
DevClose(hDev);
ELSE
DspError("Cannot open recipe database");
END
END
See Also Device Functions
DevHistory
Description 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
323
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 that if the device file has not been created (i.e. 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.
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.
DevInfo
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
11: Type of history schedule:
0: Event triggered
1: Daily
2: Weekly
3: Monthly
4: Yearly
12: The history period, in seconds, or week day, month or
year, e.g. if history is weekly then this is the day of the
week, i.e. 1 to 7
13: Synchronisation time of day of the history in seconds, e.g.
36000 (i.e., 10:00:00)
14: The time the next history file will be created in seconds
Return Value The device information as a string if successful, otherwise an empty string is
returned.
DevModify
Description Modifies the attributes of a device. The device must 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.)
When using this function, you should be careful that no other Cicode function is
already using the same device. Always 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. Use a semaphore to protect your Cicode.
DevNext
Description 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.
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);
See Also Device Functions
DevOpen
Description Opens a device and returns the device handle. The device must 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
327
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 must
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 (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 leak memory on each
connection and may crash your computer 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
exsist. 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.
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.
328
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
See Also Device Functions
DevOpenGrp
Return Value Returns 0 if successful or -1 if the function is provided with a bad handle and
fails.
DevPrev
Description 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 if the start of the database is
reached.
Example Status=0;
I = 0;
hDev = DevOpen("Log", 0);
iError = DevSeek(hDev, DevSize(hDev)); ! seek to end
WHILE iError = 0 DO
DspText(20 + I, 0, DevGetField(hDev,"Tag"));
330
I = I + 1;
iError = DevPrev(hDev);
END
DevClose(hDev);
See Also Device Functions
DevPrint
Description 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.
Example ! Get the report device number or group number (for a group of
devices).
hGrp=DevCurr();
! Print PV123 to a group of devices.
DevPrint(hGrp,"PV123="+PV123:###,1);
See Also Device Functions
DevRead
Description 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.
Return Value The data (in string format). If the end of the device is found, an empty string is
returned.
DevReadLn
Description 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.
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.
Example Str=DevReadLn(hDev);
See Also Device Functions
DevRecNo
Description 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.
Syntax DevRecNo(hDev)
332
Return Value The record number. If an error occurs getting the record number, -1 is returned.
DevSeek
Description 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.
Return Value 0 (zero) if the seek was successful, otherwise an error code is returned.
DevSetField
Return Value 0 (zero) if the data is successfully set, otherwise an error is returned.
DevSize
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 occurs, -
1 is returned.
334
DevWrite
Description 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.
DevWrite(hDev, sData)
hDev: . . . . . . . . . . . The device handle, returned from the DevOpen() function.
The device handle identifies the table where all data on the
associated device is stored.
sData: . . . . . . . . . . . The data to write, as a string.
DevWriteLn
Description 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.
DevZap
Description 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.
DisplayRuntimeManage
r
Description 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()
DLLCall
Description 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 must first open the DLL with the DLLOpen() function.
Only one call to the DLLCall() function can be made at a time, so care must be
taken to ensure 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.
DLLCallEx
Description Calls a DLL function, and passes the specified arguments to that function.
You must first open the DLL with the DLLOpen function.
Only one call to the DLLCallEx() function can be made at a time, so care must be
taken to ensure 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 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.
INT
FUNCTION
GlobalAlloc(INT Mode, INT Length)
INT hMem;
hMem = DLLCallEx(hGlobalAlloc, Mode, Length);
RETURN hMem;
END
See Also DLL Functions
DLLClose
Description 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().
DLLOpen
Description 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.
The best method of 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.
Note that DLL's must be on the path. The file extension is not required.
339
Note: You must 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 will crash. You
should test your interface thoroughly before using it on a live system.
Return Value The DLL function handle, or -1 if the library or function could not be found or
loaded.
STRING
FUNCTION
AnsiUpper(STRING sString)
STRING sResult;
sResult = DLLCall(hAnsiUpper, "^"" + sString + "^"");
RETURN sResult;
END
/* Allocate memory and return memory handle */
INT
FUNCTION
GlobalAlloc(INT Mode, INT Length)
STRING sResult;
INT hMem;
sResult = DLLCall(hGlobalAlloc, Mode : #### + "," + Length :
####);
hMem = StrToInt(sResult);
RETURN hMem;
END
See Also DLL Functions
DriverInfo
Description 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.
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".
ClusterName: . . . . . 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 "".
Return Value The driver information as a string. It is important to note that this function does
not currently return an error if it is used incorrectly.
DspAnCreateControlOb
ject
Description 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, i.e. 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.
"MSCAL.Calendar.7" - Program ID
"{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID
Width: . . . . . . . . . . . The width of the ActiveX object.
Height: . . . . . . . . . . The height of the ActiveX object.
sEventClass: . . . . . . The string you would like to use as the event class for the
object.
Return Value The newly created object, if successful, otherwise an error is generated.
DspAnFree
Description 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. Note that the ANs
are only freed in memory - the change is not permanent.
Syntax DspAnFree(AN)
AN: . . . . . . . . . . . . . The animation-point number.
DspAnGetArea
Note: This function does not return the areas of keyboard commands associated
with the object.
Syntax DspAnGetArea(AN)
AN: . . . . . . . . . . . . . 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.
DspAnGetPos
Description Gets the x and y coordinates of an AN, in pixels, relative to the top-left corner of
the window.
Syntax DspAnGetPos(AN, X, Y)
AN: . . . . . . . . . . . . . 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 occurred.
DspAnGetPrivilege
Note: This function does not return the privileges of keyboard commands
associated with the object.
Syntax DspAnGetPrivilege(AN)
AN: . . . . . . . . . . . . . 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.
DspAnInfo
Description Note: This function is only used for V3.xx and V4.xx animations, and has been
superseded by future releases.
Gets information on an AN - the type or state of the animation that is currently
displayed.
DspAnInRgn
Example DspGetMouse(X,Y);
DspAnMove(250,X,Y);
IF DspAnInRgn(250,20,30) THEN
Prompt("Mouse in region bounded by AN20 and AN30");
ELSE
Prompt("Mouse not in region");
END
See Also Display Functions
346
DspAnMove
Description 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 DspAnMove(AN, X, Y)
AN: . . . . . . . . . . . . . The animation-point number.
X: . . . . . . . . . . . . . . The x pixel coordinates of the new position.
Y: . . . . . . . . . . . . . . The y pixel coordinates of the new position.
Example DspAnMove(25,100,200);
! Moves AN25 to pixel location 100,200.
See Also Display Functions
DspAnMoveRel
Description 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(AN, X, Y)
AN: . . . . . . . . . . . . . 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.
Example DspAnMoveRel(25,10,20);
/* Moves AN25 by 10 pixels to the right and 20 pixels downward,
relative to its current position. */
See Also Display Functions
347
DspAnNew
Description 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.
Example AN=DspAnNew(100,200);
DspSym(AN,20);
/* Displays symbol 20 at pixel location 100,200 */
See Also Display Functions
DspAnNewRel
Description 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(AN, X, Y)
AN: . . . . . . . . . . . . . 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.
Example AN=DspAnNewRel(20,100,200);
/* Creates an AN at 100x and 200y pixels from AN20 */
See Also Display Functions
DspBar
Description 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.
Example DspBar(25,"Bars.Loops",320);
/* Displays a value of 320 (i.e. 10%) on the loops bar (from the
bars library) at AN25. */
DspBar(25,3,320);
/* Displays a value of 320 (i.e. 10%) on bar definition 3
(CitectSCADA Version 1.xx) at AN25. */
DspBar(26,"Loops_Bar",EngToGeneric(Tag1,0,100));
/* Displays Tag1 on the loops_bar (from the global library) at
AN26. Tag1 has an engineering scale of 0 to 100. */
See Also Display Functions
349
DspBmp
Description 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.
DspButton
Description 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 Name.
350
Note: This function is only used for V3.xx and V4.xx animations, and was
superseded in later releases.
DspButtonFn
Description 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 Name.
Note: This function is only used for V3.xx and V4.xx animations, and was
superseded in later releases.
Example DspButtonFn(20,MyFunc,"Help",0,50,10);
! Call this function when the button is selected.
INT
FUNCTION
MyFunc()
PageDisplay("Help");
RETURN 0;
END
See Also Display Functions
DspChart
Description Displays a chart at an AN. Charts are trend lines with markers on them. Values
are plotted on the chart pens. You must 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.
You should use this function only if you want to control the display of charts
directly.
Value2 ... 8: . . . . . . . The values to display on Pen 2...Pen 8 of the chart. These
values are optional.
DspCol
Example DspCol(25,RED);
/* Displays the color red at AN25. */
See Also Display Functions
DspDel
Syntax DspDel(AN)
AN: . . . . . . . . . . . . . The animation-point number.
354
Example DspDel(25);
! Deletes all animation at AN25.
See Also Display Functions
DspDelayRenderBegin
Syntax 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"
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"
at AN 200
355
DspDelayRenderEnd
Description 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 freeze 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()
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"
at AN 200
DspBMP(250, "Image5.bmp", 0) ! Display the bitmap "Image5.bmp"
356
at AN 250
/* End delay so the images can be re-drawn. */
DspDelayRenderEnd();
See Also Display Functions
DspDirty
Syntax DspDirty(AN)
AN: . . . . . . . . . . . . . The animation-point number.
Example DspDirty(20);
! Forces an update of AN20.
See Also Display Functions
DspError
Description 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.
DspFile
Description 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 must 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.
Example DspFile(20,0,20,80);
/* Defines the attributes of a screen display to start at AN20,
using the default font, with a window size of 20 lines x 80
columns. */
See Also Display Functions
DspFileGetInfo
Description Gets the attributes of a file-to-screen display (used for displaying text files).
DspFileGetName
Description 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(AN)
359
Return Value The name of the file (as a string). If an incorrect AN is specified, an error is
returned.
Example DspText(11,0,DspFileGetName(20));
! Displays the name of the file displayed at AN20.
See Also Display Functions
DspFileScroll
Example
Page Keyboard
Key Sequence PgUp
Command DspFileScroll(20,3,10)
Comment Scroll up 10 lines
See Also Display Functions
360
DspFileSetName
Description 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.
Example
Pages
Page Name FilePage
Entry Command DspFile(20,0,20,80)
Comment Defines a file to screen display to commence at
AN20
Page Keyboard
Key Sequence ######## Enter
Command DspFileSetName(20, Arg1)
Comment Displays a specified file on the page
DspFile(20,0,20,80);
/* Defines the file-to-screen display to commence at AN20 using
the default font, with a window size of 20 lines x 80 columns. */
DspFileSetName(20,"C:\AUTOEXEC.BAT");
! Displays file C:\AUTOEXEC.BAT.
See Also Display Functions
DspFont
Description 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.
361
Note: This function is only used for V3.xx and V4.xx animations, and was
superseded in later releases.
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.
Example Font=DspFont("Helv",-12,"White","Red");
DspText(20,Font,"Text in Helv Font");
/* Displays "Text in Helv Font" in 12-point Helvetica font in
white on red at AN20. */
Font=DspFont("Helv",24,"White","Red","White");
DspText(20,Font,"Text in Helv Font");
/* Displays "Text in Helv Font" in 24 pixel Helvetica font in
flashing black and white on red at AN20. */
362
DspFontHnd
Description 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.
Note: This function is only used for V3.xx and V4.xx animations, and was
superseded in later releases.
Syntax DspFontHnd(Name)
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 all data on the associated font is stored.
Example
Fonts
Font Name BigFont
hBigFont=DspFontHnd("BigFont");
DspText(20,hBigFont,"Text in Big Font");
/* Displays "Text in Big Font" in 24-point Helvetica font in blue
on an unchanged background at AN20. */
See Also Display Functions
DspFullScreen
Description Disables or enables the full screen 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.
363
Syntax DspFullScreen(Mode)
Mode: . . . . . . . . . . . Full screen mode:
0 - Disable full screen mode.
1 - Enable full screen mode.
Example /*Minimize the Window, Enable full screen mode and then maximize
the window.*/
WinMode(6);
DspFullScreen(1);
WinMode(3);
See Also Display Functions
DspGetAnBottom
Description Gets the bottom extent of the object at the specified AN.
Syntax DspGetAnBottom(AN)
AN: . . . . . . . . . . . . . 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.
364
DspGetAnCur
Description Gets the number of the current graphics AN. You should only call this function
from the database, by using one of the Page forms (for example, the Page
Number, Page String, and Page Trend forms). This function is useful for writing
general functions and macros that apply to graphics pages.
You cannot call this function from the Button or Keyboard forms.
Syntax DspGetAnCur()
Return Value The AN associated with the current record in the associated Page database. If
this function is called outside the page animation system then -1 will be
returned.
Example
Numbers
AN 20
Expression MyFunc(PV_10)
Comment Display the value of PV_10 at AN20
DspGetAnExtent
Description Gets the extent of the object (the enclosing boundary) at the specified AN.
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.
DspGetAnFirst
Description Gets the first AN on the current page, based on the order in which the ANs were
stored by Graphics Builder.
Syntax DspGetAnFirst()
Return Value The value for the first AN, otherwise an error is returned.
DspGetAnFromPoint
Description Gets the AN of the object at a specified set of screen coordinates. If the X and Y
co-ordinates given are within the extents of an object, then the AN number of the
object will be returned.
366
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.
Example DspGetMouse(X,Y);
// GetMouse position
AN = DspGetAnFromPoint(X,Y);
// Gets AN if mouse is over the object
Prompt("AN of object ="+AN:###);
!Displays the object's AN at the prompt line
If several objects overlap each other at the specified point, the PrevAN argument
can be used to produce a list of the associated ANs. This is achieved by using
PrevAN to pass the previous result into another call of the function until a zero
return is given.
INT nAn;
nAn = DspGetAnFromPoint(100,100)
WHILE nAn <> 0 DO
//Do Something
nAn = DspGetAnFromPoint(100,100,nAn);
END
See Also Display Functions
367
DspGetAnHeight
Syntax DspGetAnHeight(AN)
AN: . . . . . . . . . . . . . The animation-point number.
Return Value The height of the object (in pixels). If no object exists at the AN, -1 is returned.
DspGetAnLeft
Description Gets the left extent of the object at the specified AN.
Syntax DspGetAnLeft(AN)
AN: . . . . . . . . . . . . . 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.
DspGetAnNext
Description 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(AN)
AN: . . . . . . . . . . . . . The animation-point number.
368
Return Value 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.
DspGetAnRight
Description Gets the right extent of the object at the specified AN.
Syntax DspGetAnRight(AN)
AN: . . . . . . . . . . . . . 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.
DspGetAnTop
Description Gets the top extent of the object at the specified AN.
Syntax DspGetAnTop(AN)
AN: . . . . . . . . . . . . . The animation-point number.
Return Value The y coordinate of the top extent of the object at the AN. If no object exists at the
AN, -1 is returned.
DspGetAnWidth
Syntax DspGetAnWidth(AN)
AN: . . . . . . . . . . . . . The animation-point number.
Return Value The width of the object (in pixels). If no object exists at the AN, -1 is returned.
DspGetEnv
Syntax DspGetEnv(sName)
sName: . . . . . . . . . . The name of the variable (set using the page environment
dialog)
Example FUNCTION
PageGroup()
PageDisplay(DspGetEnv("GroupMenu"));
END
See Also Display Functions
DspGetMouse
Description Gets the x and y coordinates of the mouse position, relative to the top left corner
of the window.
Syntax DspGetMouse(X, Y)
X: . . . . . . . . . . . . . . The variables used to store the x pixel coordinate of the
mouse position, returned from this function.
370
Return Value 0 (zero) if successful, otherwise an error is returned. The X and Y variables are
set to the mouse position.
DspGetMouseOver
Syntax DspGetMouseOver(AN)
AN. . . . . . . . . . . . . . The AN of the animation you wish to check, or -1 for the
current AN. Defaults to -1.
DspGetNearestAn
Syntax DspGetNearestAn(X, Y)
X: . . . . . . . . . . . . . . The x coordinate (in pixels).
Y: . . . . . . . . . . . . . . The y coordinate (in pixels).
Return Value The animation point number (AN). A value of -1 is returned if no AN is found.
Example DspGetMouse(X,Y);
! Gets mouse position.
AN=DspGetNearestAn(X,Y);
! Gets AN nearest to the mouse.
Prompt("Mouse At AN"+AN:###);
! Displays AN nearest to the mouse.
See Also Display Functions
DspGetParentAn
Description 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(AN)
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.
Example // Get the parent animation for object 89 (part of a symbol set)
AN = DspGetParentAn(89);
See Also Display Functions
DspGetSlider
Description 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(AN)
AN: . . . . . . . . . . . . . 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.
DspGetTip
Return Value The tool tip text (as a string). If no user tip is available, an empty string is
returned.
DspGrayButton
Description 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 always 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.
DspInfo
Description 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: You must first create a handle to the information block using
DspInfoNew().
Return Value The object information (as a string). A blank string is returned if you specify a
non-existant expression or variable.
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);
iRawValue = StrToInt(DspInfo(hInfo, 4, iTagIndex));
iEngineeringValue = StrToInt(DspInfo(hInfo, 5, iTagIndex));
..
END
..
END
See Also Display Functions
DspInfoDestroy
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.
Example hInfo=DspInfoNew(20);
! Do animation operation
DspInfoDestroy(hInfo);
See Also Display Functions
376
DspInfoField
Description 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 must first call the
DspInfoNew() function to get the information block handle hInfo.
Example ! Get the I/O device that Variable Tag "PV123" belongs to.
IODev=DspInfoField(0,"PV123","Unit");
! Get the real-time engineering value of a tag.
hInfo=DspInfoNew(20);
sTag=DspInfo(hInfo,3,0);
EngValue=DspInfoField(hInfo,sTag,"Eng_Value");
See Also Display Functions
DspInfoNew
Description 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 must
destroy it with the DspInfoDestroy() function, or a fatal error could occur.
If you need simple animation help, use the InfoForm() or the InfoFormAn()
functions.
Syntax DspInfoNew(AN)
AN: . . . . . . . . . . . . . The AN for which object information is provided.
Return Value The object information block handle. If no object data is available, then -1 is
returned.
Example /*This example creates a form, with the title "Tag Info" and a
size of 25 x 5 characters. It creates an information block for the
AN closest to the mouse cursor and then extracts the name, I/O
device, and engineering value for the first tag in the object
expression.*/
INT hInfo;
STRING sTag;
hInfo=DspInfoNew(DspGetNearestAN());
IF hInfo>-1 THEN
FormNew("Tag Info",25,5,2);
sTag=DspInfo(hInfo,3,0);
FormPrompt(0,0,sTag);
FormPrompt(0,16,DspInfoField(hInfo,sTag,"Unit"));
FormPrompt(0,32,DspInfoField(hInfo,sTag,"Eng_Value"));
378
FormRead(0);
DspInfoDestroy(hInfo);
END
See Also Display Functions
DspInfoValid
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.
DspIsButtonGray
Syntax DspIsButtonGray(AN)
AN: . . . . . . . . . . . . . The AN for which object information is provided.
DspKernel
Description Displays the Kernel window. You should restrict the use of this function because
once you are in the Kernel, you can execute any Cicode function with no
privilege restrictions. You therefore have total control of CitectSCADA (and
subsequently your plant and equipment). Note 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.
You should restrict access to the Kernel, because once you are in the Kernel, you
can execute any Cicode function with no privilege restrictions. You therefore
have total control of CitectSCADA (and subsequently your plant and
equipment).
Syntax DspKernel(iMode)
iMode: . . . . . . . . . . . The display mode of Kernel:
1 - Display the Kernel. If the Kernel is already displayed and
iMode=1, the keyboard focus is changed to the Kernel.
0 - Hide the Kernel
Example DspKernel(1);
!Display the Citect Kernel window
380
DspMarkerMove
DspMarkerNew
Description 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 must
repaint them using the trend paint event (OnEvent(Window,22)). (Otherwise
CitectSCADA will delete any markers displayed when the trend is updated.)
Colour: . . . . . . . . . . The color of the marker (flashing color not supported). Select
a color from the list of Predefined Color Names and Codes or
create an RGB color using the function MakeCitectColour.
Return Value The marker handle, or -1 if the function is unsuccessful. The marker handle
identifies the table where all data on the associated marker is stored.
DspMCI
Description 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 (e.g. 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.
382
Return Value A string message with the status of the MCI command.
DspPlaySound
Description 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.
If you have a sound card, this function will return immediately and the sound
will play in the background. If you do not have a sound card, this function will
not return until the sound has finished playing - CitectSCADA will stop
running, so you should not use this function unless you have a sound card.
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 must include the
full path to the sound file.
Example DspPlaySound("C:\WINNT\MEDIA\Notify.wav",0);
DspPlaySound("SystemStart",0);
See Also Display Functions
DspPopupMenu
Description 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.
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.
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.
385
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
! If 'Item B2' is selected, iSelection will equal 102
! If 'Item B3' is selected, iSelection will equal 103
END
See Also Display Functions
DspRichText
Description Creates a Rich Text object of the given dimensions at the animation point AN.
This object can then be used to display an RTF file (like an RTF report) called
using the DspRichTextLoad function.
iMode: . . . . . . . . . . . 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 must 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.
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 (i.e. read only)//
DspRichText(57,200,200,0);
See Also Display Functions
DspRichTextEdit
Description Enables editing of the contents of the rich text object at AN if nEdit = TRUE, and
disables editing if nEdit = FALSE.
Changes made to the contents of the object will not be saved until the
DspRichTextSave function is used.
DspRichTextEnable
Description Enables the rich text object at AN if nEnable = TRUE, and disables the object if
nEnable = FALSE. When the object is disabled, it’s contents cannot be selected or
copied etc.
DspRichTextGetInfo
Description Retrieves size information about the rich text object at animation point AN.
Example ! Gets the height of the rich text object at AN 25 - if one exists.
iHeight = DspRichTextGetInfo(25,0);
! Gets the width of the rich text object at AN 423.
iWidth = DspRichTextGetInfo(423,1);
See Also Display Functions
DspRichTextLoad
Description Loads a copy of the file Filename into the rich text object) at animation point AN.
(The rich text object may have been created using either the DspRichTextLoad
function or the PageRichTextFile function.)
If you are keeping a number of history files for the report, instead of using the
extension rtf, you must change it to reflect the number of the desired history file,
e.g. 001.
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:\citect\data\DayRep.006, into the rich text object at animation
point 908. //
DspRichTextLoad(908, "f:\citect\data\DayRep.006");
See Also Display Functions
DspRichTextPgScroll
Description Scrolls the contents of the rich text object displayed at AN, by one page length in
the direction given in direction.
Example // This line scrolls the contents of the rich text object at AN 25
down one page. Otherwise an error will be returned to iResult //
iResult = DspRichTextPgScroll(25,4);
// This line scrolls the contents of the rich text object at AN 423
right one page. Otherwise an error will be returned to iResult //
iResult = DspRichTextPgScroll(423,2);
See Also Display Functions
DspRichTextPrint
Description Prints the contents of the rich text object at animation point AN, to the port
PortName.
DspRichTextSave
Description Saves the contents of the rich text object at animation point AN, to the file
Filename.
marks "", and must include the destination path. For example
"[Data]\saved.rtf".
Example // These lines show two different ways of saving the contents of
the rich text object (at AN 25) to file DayRep.rtf//
DspRichTextSave(25,"[Data]\DayRep.rtf");
DspRichTextSave(25,"c:\citect\data\DayRep.rtf");
See Also Display Functions
DspRichTextScroll
Description Scrolls the contents of the rich text object displayed at AN, 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.
Example DspRichTextScroll(25,4,8);
DspRichTextScroll(423,2,1);
See Also Display Functions
DspRubEnd
Description 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.
DspRubMove
Description Moves the rubber band selection to the new position. You must first call the
DspRubStart() function to start the rubber band selection, and DspRubEnd()
function to form the rubber band selection.
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.
DspRubSetClip
Description 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 must call this function (to enable the clipping region) before you can start
the rubber band selection (with the DspRubStart() function).
DspRubStart
Description 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
394
Example See also the ZOOM.CI file in the Include project for details.
INT xRub,yRub,cxRub,cyRub;
/* Call this function on left mouse button down. */
FUNCTION
StartSelection()
INT x,y;
DspGetMouse(x,y); ! Get the current mouse position
DspRubStart(x,y,0); ! Start the rubber banding
OnEvent(0,MouseEvent); ! Attach mouse move event
END
/* Call this function on left mouse button up. */
FUNCTION
EndSelection()
! Stop the rubber banding and get sizes into the ..Rub variables
DspRubEnd(xRub,yRub,cxRub,cyRub);
OnEvent(0,0); ! Stop mouse move event
END
INT
FUNCTION
MouseEvent()
INT x,y;
DspGetMouse(x,y); ! Get mouse position
DspRubMove(x,y); ! Move the rubber band
RETURN 0
END
See Also Display Functions
395
DspSetSlider
Description 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.
DspSetTip
Description Sets tool tip text associated with an AN. Any existing text associated with the
AN will be replaced with the new text.
DspSetTooltipFont
Example !Set the tool tip font to Bold, Italic, Times New Roman, with a
point size of 12
DspSetTooltipFont("Times New Roman", 12, "BI");
See Also Display Functions
DspStatus
Description Determines whether the object at the specified AN will be grayed (hatch pattern)
in the event of a communication failure.
Example DspStatus(67, 1)
// Disable the animation at AN 67
See Also Display Functions
DspStr
DspSym
Description Note: This function is only used for V3.xx and V4.xx animations, and was
superseded in later releases.
Displays a symbol at a specified AN. If the symbol number is 0, any existing
symbol (at the AN) is erased.
398
Example ! Erase the existing symbol and then display the centrifuge symbol
(from the pumps library) at AN25.
DspSym(25,"Pumps.Centrifuge");
! Erase the existing symbol and then display CitectSCADA Version
1.xx symbol 2 at AN25.
DspSym(25,2);
! Do not erase the existing symbol, just display the tank symbol
(from the global library) at AN26.
DspSym(26,"Centrifuge",1);
See Also Display Functions
399
DspSymAnm
Description 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, and has been
superseded.
Example DspSymAnm(25,"Pumps.Centrifuge","Pumps.Floatation");
! Alternately displays the centrifuge symbol and the flotation
symbol(from the pumps library) at AN25.
400
DspSymAnm(25,4,7);
! Alternately displays CitectSCADA Version1.xx symbols 4 and 7 at
AN25.
See Also Display Functions
DspSymAnmEx
Description 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, and has been
superseded.
Example DspSymAnmEx(25,0,"Pumps.Centrifuge","Pumps.Floatation");
! Alternately displays the centrifuge symbol and the flotation
symbol(from the pumps library) at AN25.
DspSymAnmEx(25,0,4,7);
! Alternately displays CitectSCADA Version1.xx symbols 4 and 7 at
AN25.
DspSymAnmEx(25,2,"Pumps.Centrifuge","Pumps.Floatation");
! Stop the cycle and display the current symbol.
See Also Display Functions
DspSymAtSize
Description 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.
402
You can only use this function at a blank AN, or an AN with a symbol defined
without symbols configured. The AN must 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.
DspText
Description Displays text at an AN. 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.
Example /* Displays "Display this text" at AN25 using the font defined as
BigFont. */
hBigFont=DspFontHnd("BigFont");
DspText(25,hBigFont,"Display this text");
See Also Display Functions
404
DspTipMode
Description Switches the display of tool tips on or off. This function overrides the setting in
the [Page]TipHelp parameter.
Syntax DspTipMode(nMode)
nMode: . . . . . . . . . . The display mode:
0 - Off
1 - On
2 - Toggle the tool tip mode
3 - Do not change the mode, just return the current value
DspTrend
Description Displays a trend at an AN. Values are plotted on the trend pens. You must
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.
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
406
DspTrendInfo
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.
Example ! get the number of samples for the main_loop trend (from the
trends library).
nSamples = DspTrendInfo("Trends.Main_Loop", 1);
! get the number of samples for trend 3 (CitectSCADA Version
1.xx).
nSamples = DspTrendInfo(3, 1);
See Also Display Functions
DumpKernel
EngToGeneric
Description 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
409
the project, however, you must call this function to display a trend by using
Cicode,.
EnterCriticalSection
Description Requests permission for the current thread to have access to a critical section. 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() must 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 EnterCriticalSection(sName)
sName: . . . . . . . . . . The name of the critical section. The name must be entered in
quotation marks.
ErrCom
Description 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 0 (zero) if all I/O device data associated with the task is valid, otherwise an error
is returned.
ErrDrv
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.
Example // Get the error message and number associated with error 108
nError = 108;
sError = ErrDrv("TIWAY", "MESSAGE", nError);
See Also Error Functions
ErrGetHw
Description 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, 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.
412
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 which type of device hardware alarm you want to work with.
Note: To use this function, you must set [Code]BackwardCompatibleErrHw to
1. You cannot use this function if you have more than 511 I/O devices in your
project.
This was for versions of CitectSCADA permitting a maximum limit of 4095 I/O
devices.
Versions of CitectSCADA prior to V5.20 masked the IODevNo with a value of
512. The backward compatibility flag for using this mask must be set in the
Citect.INI file (see code parameter BackwardCompatibleErrHw.).
Example Error=ErrGetHw(3,0);
! Sets Error to the current error status for the animation device.
IF Error=0 THEN
DspText(4,0,"");
ELSE
DspText(4,0,"Hardware error");
END
See Also Error Functions
ErrHelp
Syntax ErrHelp(Error)
Error: . . . . . . . . . . . The Cicode hardware error string (as returned by ErrMsg()).
Example ! Invokes the CitectSCADA Help with help on the hardware alarm.
iResult = ErrHelp(ErrMsg(IsError()));
See Also Error Functions
ErrInfo
Description Gets extended error information on the last error that occurred.
Syntax ErrInfo(Type)
414
Example ! Get the animation number where the last error occurred
AN = ErrInfo(0);
See Also Error Functions
ErrLog
Syntax ErrLog(Message)
Message: . . . . . . . . . The message to log. This field can also contain control (such
as /n) and formatting characters.
Example FUNCTION
MyFunc(INT Arg)
IF Arg<0 THEN
ErrLog("Invalid arg in Myfunc");
Halt();
END
END
See Also Error Functions
ErrMsg
Syntax ErrMsg(nError)
nError: . . . . . . . . . . The hardware error number returned from the IsError()
function.
415
Return Value The error message (as a string). A null value is returned if nError is not in the
range of Cicode errors.
ErrSet
Description Sets the error-checking mode. When Mode is set to 0 and a fatal error occurs,
CitectSCADA halts the execution of the Cicode task that caused the error, and
generate 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 effect all Cicode tasks.
Syntax ErrSet(Mode)
Mode: . . . . . . . . . . . Error-checking mode:
0 - default - CitectSCADA will check for errors.
1 - The user must check for errors.
Example ErrSet(1);
Test=Var/0;
Error=IsError();
! Sets Error to 273 (divide by zero).
See Also Error Functions
416
ErrSetHw
Description 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 must set [Code]BackwardCompatibleErrHw to
1. You cannot use this function if you have more than 511 I/O devices in your
project.
Example ErrSetHw(4,273,0);
! Generates a divide by zero error (273) on the report device.
ErrSetHw(3,0,0)
! Resets any error on the animation device.
See Also Error Functions
ErrSetLevel
Description 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.
ErrTrap
Description 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.
Exec
Description 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.
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 must quote paths and applications passed to the exec function (using ^" to
embed quotes) to ensure that the function executed correctly when long file
names are used. For example:
420
ExecuteDTSPkg
Description 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.
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");
See Also SQL Functions
422
Exp
Syntax Exp(Number)
Number: . . . . . . . . . Any number.
Example Variable=Exp(1);
! Sets Variable to 2.7182...
See Also Math/Trigonometry Functions
Fact
Syntax Fact(Number)
Number: . . . . . . . . . Any number.
Example Variable=Fact(6);
! Sets Variable to 720 (i.e. 720=1x2x3x4x5x6).
See Also Math/Trigonometry Functions
FileClose
Description 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.
Example File=FileOpen("C:\Data\Report.Txt","r");
:
! Do file operations.
:
! Close the file.
FileClose(File);
See Also File Functions
FileCopy
Description 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.
Return Value 0 (zero) if successful, otherwise an error is returned. However, if you copy in
asynchronous mode, the return value does not reflect the success or failure of
the copy, because the function returns before the actual copy is complete.
FileDelete
Syntax FileDelete(Name)
Name: . . . . . . . . . . . The name of the file to delete.
FileEOF
Syntax FileEOF(File)
File: . . . . . . . . . . . . . The file number.
Return Value 1 if the end of file has been reached, otherwise 0 (zero).
FileExist
Description Checks if a file exists. If the return value is 1, the file exists.
Syntax FileExist(Name)
Name: . . . . . . . . . . . The name of the file to check.
Return Value TRUE (1) if the file exists, otherwise FALSE (0).
425
FileFind
Description Finds a file that matches a specified search criteria. To find a list of files, you
must 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 must be called if the search does
not run to completion (for example, you do not run until an empty string is
returned).
Return Value The full path and filename. If no files are found, an empty string is returned.
Example ! Search for all dBase files in the run directory and make a backup
sPath = FileFind("[run]:\*.dbf", 0);
WHILE StrLength(sPath) > 0 DO
FileSplitPath(sPath, sDrive, sDir, sFile, sExt);
sBak = FileMakePath(sDrive, sDir, sFile, "BAK");
FileCopy(sPath, sBak, 0);
! Find the next file
sPath = FileFind("", 0);
END
See Also File Functions
FileFindClose Closes a find (started with FileFind) that did not run to completion.
Syntax FileFindClose()
FileGetTime
Syntax FileGetTime(File)
File: . . . . . . . . . . . . . The file number.
Return Value The file time of the file (in the CitectSCADA time/date variable format).
FileMakePath
FileOpen
Description Opens a file and returns a file number that can be used by other file functions.
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.
Return Value The file number. If the file cannot be opened, -1 is returned and the code is
halted.
FilePrint
FileRead
Description 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.
FileReadBlock
Description 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.
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.
FileReadLn
Description 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.
FileRename
FileRichTextPrint
Description Prints the rich text file sFilename to the printer given by sPortname.
FileSeek
FileSetTime
FileSize
Syntax FileSize(File)
File: . . . . . . . . . . . . . The file number.
FileSplitPath
Description 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.
FileWrite
Description Writes a string to a file. The string is written at the current file position.
FileWriteBlock
Description 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.
Return Value The number of characters written to the file. If an error occurs -1 will be returned
and IsError() will return the error code.
FileWriteLn
Description Writes a string to a file, followed by a newline character. The string is written at
the current file position.
Return Value The number of characters written (including the carriage return and newline
characters).
FmtClose
Description 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.
Example FmtClose(hFmt);
See Also Format Functions
FmtFieldHnd
Description 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.)
Return Value The handle of the format template field, or -1 if the field cannot be found.
FmtGetField
Description Gets field data from a format template. Use this function to extract data after a
call to StrToFmt().
Return Value The data (as a string). If the field does not contain any data, an empty string will
be returned.
FmtGetFieldHnd
Description 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.
Return Value The data (as a string). If the field does not contain any data, an empty string will
be returned.
FmtOpen
Description 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, i.e.
{<name>[,width[,justification]]}.
Return Value The format template handle, or -1 if the format cannot be created.
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".
See Also Format Functions
FmtSetField
Description 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.
FmtSetFieldHnd
Description 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.
Example hField=FmtFieldHnd(hFmt,"Name");
FmtSetFieldHnd(hFmt,hField,"CV101");
See Also Format Functions
440
FmtToStr
Description 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.
FormActive
Description 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 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 TRUE (1) if the form is active or FALSE (0) if it is not.
FormAddList
Description 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
441
Syntax FormAddList(sText)
sText: . . . . . . . . . . . The text string to add to the list box or combo box.
FormButton
Description 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.
Return Value The field handle if the button is successfully added, otherwise -1 is returned.
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
See Also Form Functions
FormCheckBox
Description 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.
Col: . . . . . . . . . . . . . The number of the column in which the check box will be
placed. Enter a number from 0 (column 1) to the form width -
1. For example, to place the check box in column 8, enter 7.
Row: . . . . . . . . . . . . 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.
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
See Also Form Functions
444
FormComboBox
Description 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.
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.
Return Value The field handle if the combo box is successfully added, otherwise -1 is returned.
445
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
See Also Form Functions
FormCurr
Description 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.
FormDestroy
Description Destroys a form, i.e. 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.
FormEdit
Description 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.
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.
Return Value The field handle if the string is successfully added, otherwise -1 is returned.
FormField
Description 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.
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".
Text: . . . . . . . . . . . . The display prompt text for a button, or the default text for
an edit field (which is then passed back with the operator's
input).
Fn . . . . . . . . . . . . . . The callback function to call when the button is selected. Set
to 0 to call no function. Note that the Fn parameter must 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.
Return Value The field handle if the field is successfully added, otherwise it will return -1.
FormGetCurrInst
Description 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.
Example INT
FUNCTION
GetNextRec()
INT hDev;
STRING Str;
FormGetCurrInst(hDev,Str);
DevNext(hDev);
RETURN 0;
END
See Also Form Functions
450
FormGetData
Description 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, e.g. 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.
FormGetInst
Description 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.
Example INT
FUNCTION
GetNextRec()
INT hDev,hForm,hField;
STRING Str;
! Get field data, e.g. the hDev value.
.
.
FormCurr(hForm,hField);
FormGetInst(hForm,hField,hDev,Str);
DevNext(hDev);
! Display new record in form.
.
.
RETURN 0;
END
See Also Form Functions
FormGetText
Description Gets the current text from a form field. You should call this function only while
the form is displayed; e.g., from a field callback function.
Example FUNCTION
Search()
INT hForm,hField;
STRING Recipe;
FormCurr(hForm,hField);
452
Recipe=FormGetText(hForm,hField);
! Go and find recipe.
.
.
END
See Also Form Functions
FormGoto
Description 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.
Example FormGoto(hForm);
See Also Form Functions
FormGroupBox
Description 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.
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.
Example ! Create a form, add to radio buttons groups and then display the
form
! The operator may select one of the radio buttons from each group
FUNCTION
FnMenu()
STRING sFast, sSlow, sMedium;
STRING sNorth, sSouth, sEast, sWest;
FormNew("Select Item",40,7,1);
FormGroupBox(1 ,1, 15, 5, "Speed");
FormRadioButton(2 ,2,"Fast", sFast);
FormRadioButton(2, 3,"Medium", sMedium);
FormRadioButton(2 ,4,"Slow", sSlow);
FormGroupBox(19 ,2, 15, 6, "Direction");
FormRadioButton(20 ,2,"North", sNorth);
FormRadioButton(20, 3,"South", sSouth);
FormRadioButton(20 ,4,"East", sEast);
FormRadioButton(20 ,5,"West", sWest);
FormRead(0);
END
See Also Form Functions
FormInput
Description 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 FormInput(Col,Row,Prompt,Text,Width)
454
Example FormInput(1,2,"Recipe",Recipe,20);
See Also Form Functions
FormListAddText
Description 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, e.g. from a field callback function.
FormAddList("Salt");
FormAddList("Sugar");
/* Display the form */
FormRead(1);
:
:
/*Add Milk to list */
FormListAddText(hForm, hField, "Milk");
:
:
See Also Form Functions
FormListBox
Description 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.
Return Value The field handle if the list box is successfully added, otherwise -1 is returned.
Example ! Create a form, add list box and then display the form.
! The operator may select one of the items from the list.
STRING sBuf;
FUNCTION
FnMenu()
FormNew("Select Item",20,6,1);
FormListBox(2 ,2, 15, 5, sBuf, 1);
FormAddList("Item One");
FormAddList("Item two");
FormAddList("Item three");
FormButton(0,0," OK ",0,1);
FormButton(5,0," CANCEL ",0,2);
FormRead(0);
SELECTION= sBuf;
END
See Also Form Functions
FormListDeleteText
Description 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, e.g. from a field callback
function.
FormListSelectText
Description Selects (highlights) a text entry in a Combo box or a List box while the form is
displayed. The text to be selected must 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, e.g. from a field callback function.
FormAddList("Salt");
FormAddList("Sugar");
/* Display the form */
FormRead(1);
:
:
/*Select Flour */
FormListSelectText(hForm, hField, "Flour");
See Also Form Functions
FormNew
Description 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 must 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.
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
behaviour.
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.
Example FormNew("Recipe",30,5,0);
FormInput(1,1,"Recipe No",Recipe,20);
FormInput(1,2,"Amount",Amount,10);
FormRead(0);
See Also Form Functions
FormNumPad
Description 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.
16 - With . button
32 - With : button
64 - With AM, PM buttons
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);
See Also Form Functions
FormOpenFile
Return Value The name and full path of the selected file (as a string) or an empty string ("") if
the Cancel button is selected.
Example // Display the Open File dialog with the following filter list:
// All Files (*.*)
// Exe Files (*.EXE)
461
FormPassword
Description 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.
FormPosition
Description 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.
462
FormPrompt
Description Adds a prompt field to the current form. You should call this function only after
the FormNew() function and before the FormRead() function.
FormRadioButton
Description 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.
463
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.
Return Value The field handle if the radio button is successfully added, otherwise -1 is
returned.
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()
STRINGsFast, 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
464
FormRead
Description 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:
0 - Wait for the user.
1 - Do not wait for the user.
FormSaveAsFile
Return Value The name and full path of the selected file (as a string) or an empty string ("") if
the Cancel button is selected.
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");
See Also Form Functions
FormSelectPrinter
Syntax FormSelectPrinter()
466
Return Value The name of the selected printer (as a string) or an empty string ("") if the Cancel
button is selected.
FormSetData
Description 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.
Example INT
FUNCTION
MyNextRec()
INT hForm,hField;
FormCurr(hForm,hField);
FormSetData(hForm);
RETURN 0;
END
See Also Form Functions
FormSetInst
Description 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.
FormSetText
Description 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, e.g.
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.
FormWndHnd
Description Gets the window handle for the given form. The window handle may be used by
'C' programs and CitectSCADA Wnd... functions. You should call this function
only after the FormNew() function and before 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 all data on the
associated form is stored.
FTPClose
Syntax FTPClose(hndFTP)
hndFTP: . . . . . . . . . The handle of a valid FTP session, as returned by FTPOpen().
FTPFileCopy
Description Copies a file from the FTP server to the Internet Display Client. Before calling
this function, you must call FtpOpen().
FTPFileFind
Description Finds a file on the FTP server that matches a specified search criteria. Before you
can call this function, you must call FTPOpen().
To find a list of files, you must 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.
If the search is for multiple files, FTPFileFindClose must be called if the search
does not run to completion (for example, you do not run until an empty string is
returned).
Return Value The full path and filename. If no files are found, an empty string is returned.
FTPFileFindClose Closes a find (started with FTPFileFind) that did not run to completion.
Syntax FTPFileFindClose(hndFTP)
hndFTP . . . . . . . . . . The handle of a valid FTP session, as returned by FTPOpen().
FTPOpen
Return Value A handle to the FTP server otherwise -1 if an error occurs (e.g. the server cannot
be found).
472
FullName
Description Gets the full name of the user who is currently logged-in to the system.
Syntax FullName()
FuzzyClose
Description 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).
FuzzyGetCodeValue
Description Gets a value for the specified input of the specified instance.
Return Value The code value if the function was successful. Use IsError() to find the error
number if the function fails.
FuzzyGetShellValue
Description Gets a value for the specified input of the specified instance. The variables in the
instance must have the data type REAL (floating point values).
Return Value The shell value if the function was successful. Use IsError() to find the error
number if the function fails.
FuzzyOpen
Description This function loads a *.FTR file, allocates memory and creates a handle for this
fuzzy instance. To use the FuzzyTech functions you must 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
must only use fuzzyTECH to generate the *.FTR file for FTRUN.
The application must 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 The handle to the fuzzy instance, or -1 if the function fails. Use IsError() to find
the error number.
END
FuzzyClose(hFuzzy);
END
See Also FuzzyTech Functions
FuzzySetCodeValue
Description Sets a value for the specified input of the specified instance.
FuzzySetShellValue
Description Sets a value for the specified input of the specified instance.
FuzzyTrace
Description Controls the trace process (starting and stopping) of the specified instance.
GetArea
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.
GetBlueValue
Syntax GetBlueValue(nPackedRGB)
nPackedRGB: . . . . . The packed RGB color.
Return Value The red value (0-255) - if successful, otherwise an error is returned.
GetEnv
Syntax GetEnv(sName)
sName: . . . . . . . . . . The name of the environment variable.
GetEvent
Description 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(Type)
Type: . . . . . . . . . . . . The type of event:
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.
Return Value The function handle of the existing callback event handler, or -1 if there are no
event handlers.
GetGreenValue
Syntax GetGreenValue(nPackedRGB)
nPackedRGB: . . . . . The packed RGB color.
Return Value The red value (0-255) - if successful, otherwise an error is returned.
GetPriv
Description 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.
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.
GetRedValue
Syntax GetRedValue(nPackedRGB)
nPackedRGB: . . . . . The packed RGB color.
Return Value The red value (0-255) - if successful, otherwise an error is returned.
Syntax GetWinTitle()
Return Value The title of the active window as a string if successful; otherwise, an error is
returned.
GrpClose
Description 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.
Example hGrp=GrpOpen("MyGrp",1);
.
.
GrpClose(hGrp);
See Also Group Functions
GrpDelete
Description Deletes a single element or all elements from a group. You can also delete
another group from within the group.
GrpFirst
Description 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 The value of the first element in a group or -1 if the group is empty.
Example Value=GrpFirst(hGrp);
IF Value<>-1 THEN
Prompt("First value is "+Value:###);
END
See Also Group Functions
GrpIn
GrpInsert
GrpMath
Description 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.
Example hOne=GrpOpen("Plantwide",0);
hTwo=GrpOpen("Section1",0);
hResult=GrpOpen("Result",0);
! Subtract Section1 from Plantwide and place in Result.
GrpMath(hResult,hOne,hTwo,1);
See Also Group Functions
GrpName
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.
486
GrpNext
Description 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.
Return Value The value of the next element in a group, or -1 if the end of the group has been
found.
GrpOpen
Description 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, e.g. SetArea() and AlarmSetInfo(). You can open a
487
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.
Return Value The group handle , or -1 if the group cannot be created or opened. The group
handle identifies the table where all data on the associated group is stored.
GrpToStr
Description 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.
488
Halt
Description 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()
Example INT
FUNCTION
MyFunc(INT Arg)
IF Arg<0 THEN
Prompt("Invalid Arg");
Halt();
END
.
.
END
See Also Task Functions
HexToStr
Description Converts a number into a hexadecimal string. The string is the width specified
(padded with zeros).
HighByte
Syntax HighByte(TwoByteInteger)
TwoByteInteger: . . . A two-byte integer.
Example Variable=HighByte(0x5678);
! Sets Variable to 0x56.
See Also Math/Trigonometry Functions
HighWord
Syntax HighWord(FourByteInteger)
FourByteInteger: . . A four-byte integer.
Example Variable=HighWord(0x12345678);
! Sets Variable to 0x1234.
See Also Math/Trigonometry Functions
HtmlHelp Invokes the Microsoft HTML Help application (hh.exe) to display a specific
topic from a specific HTML help file (.chm).
Example The following example displays the overview page of the CitectSCADA help:
HtmlHelp("C:\Program
Files\Citect\CitectSCADA\bin\CitectSCADA.chm", 0,
"CitectSCADA_Help_Overview.html");
See Also Window Functions
InfoForm
Description 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 all the details from the
491
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 do not enter a mode, the default mode is 0.
Example
System Keyboard
Key Sequence AnHelp
Command InfoForm();
Comment Display graphics object help for the AN closest to
the cursor
See Also Miscellaneous Functions
InfoFormAn
Description 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 all the details from the Variable Tags form. The
function also displays the Cicode expression, with any result that the expression
has generated.
Example
System Keyboard
Key Sequence ### AnHelp
Command InfoFormAn(Arg1);
Comment Display graphics object help for a specified AN
See Also Miscellaneous Functions
Input
Description 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.
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.
IF sStr="Yes" THEN
Shutdown();
END
See Also Miscellaneous Functions
IntToReal
Syntax IntToReal(Number)
Number: . . . . . . . . . The integer to convert.
IntToStr
Syntax IntToStr(Number)
Number: . . . . . . . . . The number to convert.
Example Variable=IntToStr(5);
! Sets Variable to "5".
See Also String Functions
494
IODeviceControl
Description 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.
IODeviceInfo
DIALCALLSTATE_DISCONNECTED_UNKNOWN 18
DIALCALLSTATE_DISCONNECTED_REJECT 19
DIALCALLSTATE_DISCONNECTED_PICKUP 20
DIALCALLSTATE_DISCONNECTED_FORWARDED 21
DIALCALLSTATE_DISCONNECTED_BUSY 22
DIALCALLSTATE_DISCONNECTED_NOANSWER 23
DIALCALLSTATE_DISCONNECTED_BADADDRESS 24
DIALCALLSTATE_DISCONNECTED_UNREACHABLE 25
DIALCALLSTATE_DISCONNECTED_CONGESTION 26
DIALCALLSTATE_DISCONNECTED_INCOMPATIBLE 27
DIALCALLSTATE_DISCONNECTED_UNAVAIL 28
DIALCALLSTATE_DISCONNECTED_NODIALTONE 29
DIALCALLSTATE_DISCONNECTED_NUMBERCHANGED 30
DIALCALLSTATE_DISCONNECTED_OUTOFORDER 31
DIALCALLSTATE_DISCONNECTED_TEMPFAILURE 32
DIALCALLSTATE_DISCONNECTED_QOSUNAVAIL 33
DIALCALLSTATE_DISCONNECTED_BLOCKED 34
DIALCALLSTATE_DISCONNECTED_DONOTDISTURB 35
DIALCALLSTATE_DISCONNECTED_CANCELLED 36
DIALCALLSTATE_UNKNOWN 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.)
ClusterName: . . . . . 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 "".
IODeviceStats
Description Gets statistical information for all I/O devices, and displays the information in a
dialog box.
Syntax IODeviceStats()
IsError
Description Gets the current error value. The error value is set when any error occurs, 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.
KerCmd
KeyAllowCursor
Description 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.
Example KeyAllowCursor(20,1);
! Allows the command cursor to move to AN20.
KeyAllowCursor(0,1);
! Allows the command cursor to move to any AN.
See Also Keyboard Functions
KeyBs
Description 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
504
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 KeyBs()
Example
System Keyboard
Key Sequence *Bs
Command KeyBs()
Comment Define a backspace Hot Key
KeyDown
Description 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()
KeyGet
Description 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.
KeyGetCursor
Description Gets the AN at the position of the command cursor. 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 The AN at the position of the command cursor. If no cursor is visible, -1 is
returned.
KeyLeft
Description 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()
KeyMove
Description 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:
0 - Do not move
1 - Left
2 - Right
3 - Up
4 - Down
Example KeyMove(1);
! Moves the cursor left.
See Also Keyboard Functions
KeyPeek
Description 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: . . . . . . . . . . . The offset from the end of the key command line
KeyPut
Description 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.
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
508
KeyPutStr
Description 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.
KeyReplay
Description 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: . . . . . . . . . . . . . Number of characters to subtract before replay. Default
value is 1.
KeyReplayAll
Description 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()
KeyRight
Description 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()
KeySetCursor
Description Displays the command cursor at a specified AN. A keyboard command must
exist, or you must 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(AN)
AN: . . . . . . . . . . . . . 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.
KeySetSeq
Description 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.
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
See Also Keyboard Functions
KeyUp
Description 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()
LanguageFileTranslate
Description Translates an ASCII file into a local language. Use this function to translate RTF
reports for viewing on Display Client screens.
The local language used by this function is specified by the
[Language]LocalLanguage parameter. You must set this parameter
accordingly.
LeaveCriticalSection
Syntax LeaveCriticalSection(sName)
sName: . . . . . . . . . . The name of the critical section. The name must be entered in
quotation marks.
Ln
Syntax Ln(Number)
Number: . . . . . . . . . Any number.
Example Variable=Ln(2);
! Sets Variable to 0.6931...
See Also Math/Trigonometry Functions
Log
Syntax Log(Number)
Number: . . . . . . . . . Any number.
Related Functions Ln
Example Variable=Log(100);
! Sets Variable to 2 (i.e. 100=10 to the power of 2).
See Also Math/Trigonometry Functions
514
Login
Description Logs a user into the CitectSCADA system, and gives users access to the areas
and privileges assigned to them in the Users database. 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.
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.
Example /* Log in a user whose user name is "FRED" and whose password is
"ABC". */
Login("FRED","ABC");
See Also Security Functions
LoginForm
Description Displays a form in which a user can log in to the CitectSCADA system by
entering their name and password. 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.
This function is a blocking function. It will block the calling Cicode task until the
operation is complete.
Syntax LoginForm()
Example
System Keyboard
515
Logout
Description 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.
Syntax Logout()
LogoutIdle
Description 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 all users 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.
Syntax LogoutIdle(Idle)
Idle: . . . . . . . . . . . . . The number of minutes the user must be idle before logout
will occur. Set Idle to -1 to disable the current logout timeout.
Example
Users
User Name Operator1
LoginForm LogoutIdle(5)
Comment Logs the user out after five minutes
See Also Security Functions
LowByte
Syntax LowByte(TwoByteInteger)
TwoByteInteger: . . . A two-byte integer.
Example Variable=LowByte(0x5678);
! Sets Variable to 0x78.
See Also Math/Trigonometry Functions
LowWord
Syntax LowWord(FourByteInteger)
FourByteInteger: . . A four-byte integer.
Example Variable=LowWord(0x12345678);
! Sets Variable to 0x5678
See Also Math/Trigonometry Functions
517
MailError
Description Gets the last mail error code. The error code is extracted from the MAPI mail
system, and explains what caused the MAPI function to fail.
Syntax MailError()
Return Value 0 (zero) if successful, otherwise an error is returned. Refer also to MAPI errors.
MailLogoff
Description 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()
MailLogon
Description Logs on to the mail system. You must call this function before any other mail
function.
518
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.
MailRead
Description Reads a standard mail message. The mail message can contain text, an attached
file, or both.
Before you can use this function, you must 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.
sNote: . . . . . . . . . . . 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 must 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.
MailSend
Description Sends a standard mail message. The mail message can contain text, an attached
file, or both.
Before you can use this function, you must 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 Display Client.
sName: . . . . . . . . . . The name of the mail user who will receive the message. This
name is the user's full name (not their mailbox name).
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.
MakeCitectColour
Description 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
521
Max
Example Variable=Max(24,12);
! Sets Variable to 24.
See Also Math/Trigonometry Functions
Message
Description 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.
0 - OK button
1 - OK and Cancel button
16 - Stop Icon
32 - Question Icon
48 - Exclamation Icon
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.
Min
Example Variable=Min(24,12);
! Sets Variable to 12.
See Also Math/Trigonometry Functions
523
MsgBrdcst
Description 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).
MsgClose
Description 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.
Example MsgClose("Alarm",hMsg);
See Also Task Functions
524
MsgGetCurr
Description 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()
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.
MsgOpen
Description 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.
Return Value The message handle, or -1 if the session cannot be opened. The message handle
identifies the table where all data on the associated message is stored.
MsgRead
Description 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 Type 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).
527
You must open the message session using the MsgOpen() function, to enable the
callback function.
Example /* This function will read a message from the session and if
Type=1, will display the string as a prompt. If Type=2 then the
speaker beeps and an acknowledgment is sent back to the caller. */
INT
FUNCTION
MsgPostClient()
INT Type;
STRING Str;
INT hMsg;
hMsg=MsgRead(Type,Str);
IF Type=1 THEN
Prompt("Message"+Str);
ELSE
IF Type=2 THEN
Beep();
MsgWrite(hMsg,2,"DONE");
END
END
See Also Task Functions
MsgRPC
Description Calls a remote procedure on another CitectSCADA computer. You can call any
of the in-built Cicode functions remotely, or your own functions. You pass the
Name 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.
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.
Example ! Call remote procedure, call MyRPC() on server. Wait for result
Str=MsgRPC(hMsg,"MyRPC","Data",0);
! Call remote procedure, pass two strings. Don't wait for call to
complete.
! be careful of your string delimiters as shown.
MsgRPC(hMsg,"MyStrFn","^"First string^",^"Second string^"",1);
! Call remote procedure, pass Cicode string. Don't wait for call
to complete.
STRING sMessage = "this is a message";
MsgRPC(hMsg,"MyStrFn","^"" + sMessage + "^"",1);
! These functions could be used to acknowledge an alarm by record
from any CitectSCADA Client on the network.
! The AlmAck() function is initialized by the Display Client
(Don't forget that servers are also Display 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
529
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 Display 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
See Also Task Functions
MsgState
Description 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 This function has the following possible return values:
-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.
MsgWrite
Description 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 must first open the message session using the MsgOpen() function, to
obtain the message handle.
Example MsgWrite(hMsg,10,"MyMsg");
See Also Task Functions
Name
Description Gets the name of the operator who is currently logged-in to the display system.
If this function is called on a server, it returns the name of the local operator.
Syntax Name()
ObjectAssociateEvents
Description 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
"MSCAL.Calendar.7" - Program ID
"{8E27C92B-1264-101C-8A2F-040224009C02}" - GUID
ObjectAssociatePropert
yWithTag
Description 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 fail if property change notification is not supported
and the OnChangeEvent argument is left blank. You must ensure 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.
ObjectByName
Description Retrieves an ActiveX object. This is useful when you know the object by name
only (this will often be the case for objects created during configuration, rather
than those created at runtime using a Cicode function).
Syntax ObjectByName(sName)
sName: . . . . . . . . . . The name for the object in the form of "AN" followed by its
AN number, eg. "AN35". This name is used to access the
object.
ObjectHasInterface
ObjectIsValid
Description 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).
ObjectToStr
Syntax ObjectToStr(hObject)
hObject: . . . . . . . . . The handle for the object (as returned by the
ObjectByName() function).
OLEDateToTime
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.
OnEvent
Description Sets an event callback function for an event type. The callback function is called
when the event occurs.
Using callback functions saves polling or checking for events. Callback functions
have no arguments and must return an integer.
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. 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.
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,
537
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 re-animates 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 occurred.
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 (i.e. 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 (e.g. 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.
539
Example OnEvent(1,KeyFn);
! Calls a function named KeyFn().
INT
FUNCTION
KeyFn()
INT Key;
Key=KeyPeek(0);
IF Key=27 THEN
Prompt("ESC pressed");
RETURN 1;
ELSE
RETURN 0;
END
END
OnEvent(0,MouseFn);
! Calls a function named MouseFn().
INT
FUNCTION
MouseFn()
INT X,Y;
DspGetMouse(X,Y);
RETURN 0;
END
See Also Event Functions
PackedRGB
Description Returns a packed RGB color based on specified red, green, and blue values.
540
Return Value The packed RGB color value - if successful, otherwise an error is returned.
PackedRGBToCitectCol
our
Description Converts a packed RGB color into a calculated CitectSCADA color value.
Syntax PackedRGBToCitectColour(nPackedRGB)
nPackedRGB: . . . . . The packed RGB color.
Return Value The CitectSCADA color value if successful; otherwise an error is returned.
PageAlarm
Description Displays a category of active alarms on the alarm page. To use this function, you
must use the Graphics Builder to create a page called "Alarm" (using the alarm
template).
Notes
The operation of this function has changed. In Version 2.xx this function
displayed the in-built 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.
Example
System Keyboard
Key Sequence AlarmPage
Command PageAlarm(0)
Comment Display all active alarms on the alarm page
System Keyboard
Key Sequence Alarm ### Enter
Command PageAlarm(Arg1)
Comment Display a specified category of active alarms on
the alarm page
See Also Page Functions
PageDisabled
Description Displays a category of disabled alarms on the alarm page. To use this function,
you must use the Graphics Builder to create a page called "Disabled" (using the
disabled template).
Notes
The operation of this function has changed. In Version 2.xx this function
displayed the in-built 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.
Example
System Keyboard
Key Sequence DisabledPage
Command PageDisabled(0)
Comment Display all disabled alarms on the alarm page
System Keyboard
Key Sequence Disabled ### Enter
Command PageDisabled(Arg1)
Comment Display a specified category of disabled alarms
on the alarm page
See Also Page Functions
PageDisplay
Description Displays a graphics page in the active window. The page must 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 always return zero (0).
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 arguement is used to resolve any tags that do not have a cluster
explicitly defined.
CitectSCADA saves 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)
Page: . . . . . . . . . . . . The name or page number of the page to display (in
quotation marks ""). Can be prefixed by the name of a host
543
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 always
return 0 (zero) as a CSV version of the function is excuted via TaskNew.
Example
Buttons
Text Mimic Page
Command PageDisplay("Mimic")
Comment Display the "Mimic" page
System Keyboard
Key Sequence Page ############## Enter
Command PageDisplay(Arg1)
Comment Display a specified page
PageDisplay("MIMIC1");
! Displays page "MIMIC1".
PageDisplay("MIMIC2");
/* Displays page "MIMIC2" and places page "MIMIC1" onto the
PageLast stack. */
PageDisplay("10");
/* Displays page "10" and places page "MIMIC2" onto the PageLast
stack. */
PageLast();
/* Displays the last page on the stack, i.e. 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
544
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
PageFile
Description 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 must use the Graphics Builder
to create a page called "File" (using the file template).
Notes
The operation of this function has changed. In Version 2.xx this function
displayed the in-built 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: . . . . . . . . . . The name of the file to display.
Return Value 0 (zero) if the file is successfully displayed, otherwise an error is returned.
Example
System Keyboard
Key Sequence File ######## Enter
Command PageFile(Arg1)
Comment Display the specified file on the page
See Also Page Functions
PageFileInfo
Return Value The height or width of the specified page in pixels, depending on the value set
for nMode.
See Also Page Functions
PageGetInt
Description Gets a local page-based integer. 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.
Notes
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 PageGetInt(Offset)
Offset: . . . . . . . . . . . The offset in the array of integers.
PageGetStr
Description Gets a local page-based string. Page-based variables are local to each display
page. If two or more windows are displayed, each window has a unique copy of
546
the variable. You can use these variables in Cicode to keep track of variables
unique to each window.
Specify the position of the variable in the array in the Offset argument. (The
length of the array is set by the [Page]MaxStr parameter.)
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 PageGetStr(Offset)
Offset: . . . . . . . . . . . The offset in the array of strings.
PageGoto
Description Displays a graphics page in the active window. The page must 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 arguement is used to resolve any tags that do not have a cluster
explicitly defined.
This function is similar to PageDisplay(), however PageGoto() does not put the
current page onto the PageLast 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 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, i.e. "ClusterName.Page". This will take precedence
over the use of the ClusterName parameter if the two differ.
547
ClusterName: . . . . . The name of the cluster that will accomodate the page at
runtime (in quotation marks ""). The specified cluster is used
to resolve any tags that do not have a cluster explicitly
defined. If the Page parameter is prefixed with the name of a
cluster, this parameter will not be used.
Return Value 0 (zero) if the page is successfully displayed, otherwise an error is returned.
Example PageDisplay("MIMIC1");
! Displays page "MIMIC1".
PageDisplay("MIMIC2");
/* Displays page "MIMIC2" and places page "MIMIC1" onto the
PageLast stack. */
PageGoto("10");
/* Displays page "10". Page "MIMIC2" is not placed onto the
PageLast 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
PageHardware
Description Displays the active hardware alarms on the alarms page. To use this function,
you must use the Graphics Builder to create a page called "Hardware" (using the
alarm template).
Notes
The operation of this function has changed. In Version 2.xx this function
displayed the in-built hardware alarm page from the Include project.
548
Syntax PageHardware()
Example
System Keyboard
Key Sequence Hardware
Command PageHardware()
Comment Display active hardware alarms on the hardware
alarms page
See Also Page Functions
PageInfo
Syntax PageInfo(Type)
Type: . . . . . . . . . . . . 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
549
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
PageLast
Description 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 0 (zero) if the page is successfully displayed, otherwise an error is returned.
Example
Buttons
Text Last Page
Command PageLast()
Comment Display the graphics page that was last
displayed
PageDisplay("MIMIC1");
! Displays page "MIMIC1".
PageDisplay("MIMIC2");
/* Displays page "MIMIC2" and places page "MIMIC1" onto the
PageLast stack. */
PageDisplay("10");
! Displays page "10" and places page "MIMIC2" onto the PageLast
stack.
PageLast();
/* Displays the last page on the stack, i.e. page "MIMIC2" and
removes it from the stack. */
PageLast();
/* Displays the last page on the stack, i.e. 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.*/
See Also Page Functions
PageMenu
Description 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 0 (zero) if the page is successfully displayed, otherwise an error is returned.
Example
Buttons
Text Menu
Command PageMenu()
Comment Display the menu page
552
System Keyboard
Key Sequence Menu
Command PageMenu()
Comment Display the menu page
See Also Page Functions
PageNext
Syntax PageNext()
Return Value 0 (zero) if the page is successfully displayed, otherwise an error is returned.
Example
Buttons
Text Page Next
Command PageNext()
Comment Display the next page in the browse sequence
System Keyboard
Key Sequence PageNext
Command PageNext()
Comment Display the next page in the browse sequence
PagePeekLast
Description Gets the Page Name at an offset in the PageLast stack (without removing the
page from the stack).
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 PagePeekLast(Offset)
Offset: . . . . . . . . . . . The offset from the end of the PageLast stack. Offset 0 is the
last page on the stack, Offset 1 is the second last page on the
stack, etc.
Return Value The Page Name or an empty string if there is no last page.
Example PageDisplay("MIMIC1");
! Displays page "MIMIC1".
PageDisplay("MIMIC2");
/* Displays page "MIMIC2" and places page "MIMIC1" onto the
PageLast stack. */
PageDisplay("10");
! Displays page "10" and places page "MIMIC2" onto the PageLast
stack.
PageGoto(PagePeekLast(0));
! Displays page "MIMIC2".
PageGoto(PagePeekLast(1));
! Displays page "MIMIC1".
See Also Page Functions
PagePopLast
Description Gets the Page Name of the last item on the PageLast stack and removes the page
from the stack.
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 The page name or an empty string if there is no last page.
554
Example PageDisplay("MIMIC1");
! Displays page "MIMIC1".
PageDisplay("MIMIC2");
/* Displays page "MIMIC2" and places page "MIMIC1" onto the
PageLast stack. */
PageDisplay("10");
! Displays page "10" and places page "MIMIC2" onto the PageLast
stack.
Variable=PagePopLast();
/* Sets Variable to "MIMIC2" and removes "MIMIC2" from the
PageLast stack. */
PageLast();
! Displays page "MIMIC1".
See Also Page Functions
PagePopUp
Description 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 PagePopUp(sPage)
sPage: . . . . . . . . . . . The name of the page (drawn with the Graphics Builder).
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.
PagePrev
Syntax PagePrev()
Return Value 0 (zero) if the page is successfully displayed, otherwise an error is returned.
Example
Buttons
Text Page Previous
Command PagePrev()
Comment Display the previous page in the browse
sequence
System Keyboard
Key Sequence PagePrev
Command PagePrev()
Comment Display the previous page in the browse
sequence
PagePushLast
Syntax PagePushLast(Page)
Page: . . . . . . . . . . . . The Page Name or Page Number (of the page) to place at the
end of the PageLast stack.
Example PageDisplay("MIMIC1");
! Displays page "MIMIC1".
PageDisplay("MIMIC2");
/* Displays page "MIMIC2" and places page "MIMIC1" onto the
PageLast stack. */
PageDisplay("10");
! Displays page "10" and places page "MIMIC2" onto the PageLast
stack.
PagePushLast("TREND1");
! Places page "TREND1" onto the PageLast stack.
PageLast();
/* Displays the last page on the stack, i.e. page "TREND1" and
removes it from the stack. */
PageLast();
/* Displays the last page on the stack, i.e. page "MIMIC2" and
removes it from the stack. */
See Also Page Functions
PageRichTextFile
Description 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, AN 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.
Remember that the filename for the saved report comes from
the File Name field in the Devices form. The location of the
saved file must 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, e.g. "c:\citect\data\repdev.rtf".
If you are keeping a number of history files for the
report, instead of using the rtf extension, you must
change it to reflect the number of the desired history file,
e.g. 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.
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 must 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 AN 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 AN and AN+1.
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
contents of the object, but not make changes. //
See Also Page Functions
PageSelect
Description Displays a dialog box with a list of all graphics pages defined in the project. AN
operator can select a page name for display.
Syntax PageSelect()
Example
Buttons
Text Page Select
Command PageSelect()
Comment Display the page selection dialog box
PageSelect();
! Displays the page selection dialog box.
See Also Page Functions
559
PageSetInt
Description Stores a local page-based integer. 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
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.
PageSetStr
Description Stores a local page-based string. Page-based variables are stored in an array,
local to each display page. This function allows you to save string variables in
temporary storage.
Specify the position of the variable in the array in the Offset argument. (The
length of the array is set by the [Page]MaxStr parameter.)
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.
PageSummary
Description Displays a category of alarm summary entries on the alarm page. To use this
function, you must use the Graphics Builder to create a page called "Summary"
(using the alarm template).
Notes
The operation of this function has changed. In Version 2.xx this function
displayed the in-built 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.
Example
System Keyboard
Key Sequence SummaryPage
Command PageSummary(0)
Comment Display all alarm summary entries on the alarm
page
System Keyboard
Key Sequence Summary ### Enter
Command PageSummary(Arg1)
Comment Display a specified category of alarm summary
entries on the alarm page
See Also Page Functions
561
PageTrend
Description 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 must create the
trend page with the Graphics Builder and set all 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.
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.
Example
Buttons
Text Process Trend
Command PageTrend("MyTrend", "PV1", "PV2", "PV3")
Comment Display the trend page with three trend pens
PageTrendEx
Description 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 must create the trend page with the Graphics
Builder and set all 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, “SingleTrend”), the page displays, but no trend tag is added. This
also applies for the CSV_Trend_Page function.
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.
Example
Buttons
Text Process Trend
Command PageTrendEx("MyTrend", "MyCluster", "PV1",
"PV2", "PV3")
Comment Display the trend page on the specified cluster
with three trend pens
ParameterGet
Description 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.
Example Variable=ParameterGet("Page","Windows","4");
See Also Miscellaneous Functions
ParameterPut
Description Updates a system parameter in the CITECT.INI file. If the system parameter
does not exist, it is added to the CITECT.INI file.
PathToStr
Description Converts a CitectSCADA path into a string. The path string can contain one of
the standard CitectSCADA path operators, BIN, DATA, RUN, 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.
Example Variable=PathToStr("[data]:test.txt");
! Sets Variable to "c:\citect\data\test.txt".
! assuming that DATA=C:\CITECT\DATA
565
Pi
Description Gets the value of pi (the ratio of the circumference of a circle to its diameter).
Syntax Pi()
Example Variable=Pi();
! Sets Variable to 3.1415...
See Also Math/Trigonometry Functions
PlotClose
Description 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.
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.
PlotDraw
Description 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.
566
You must 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 all data on the plot is
stored.
Type: . . . . . . . . . . . . The type of drawing:
1 - Rectangle or square
2 - Circle or ellipse
3 - Line
4 - Point
PenStyle: . . . . . . . . The style of the pen used to draw:
0 - Solid
1 - Dash ( - - - - -)
2 - Dot (...............................)
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, all coordinates are relative to the AN
specified in the PlotOpen() function. If the output device is a printer, all
coordinates are relative to the point (0,0).
PlotGetMarker
Description Gets the marker number of a symbol. The symbol must 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.
PlotGrid
Description 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 must 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).
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 must 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 all data on the plot is
stored.
nSamples: . . . . . . . . The maximum number of samples that can be plotted for a
single line in this grid. 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 you do not need grid lines, set
nHorGrid to 0 (zero) and HorGridCol to 0.
569
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: . . . . . . . . The number of columns (formed by the vertical grid lines) to
draw within the frame. If you do not need grid lines, set
nVerGrid to 0 (zero) and VerGridCol to 0.
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).
PlotInfo
Description 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().)
570
You must first call the PlotOpen() function to get the handle for the plot (hPlot)
and specify the output device.
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);
See Also Plot Functions
PlotLine
Description 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 must 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.
2 - 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 must 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 you do not know
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, i.e., the number of points in the table
pTable for PlotLine(), or in tables xTable and yTable for
PlotXYLine().
For every line you draw with the PlotLine() and
PlotXYLine() functions within a plot, you must add the
Length arguments for each call, and pass the total to the
PlotGrid() function (in the nSamples argument).
573
PlotMarker
Description 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 must first register
your symbol as a marker, by using the PlotSetMarker() function.)
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, i.e. within the
PlotLine() or PlotXYLine() function. You would use the PlotMarker() function
574
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 must first call the PlotOpen() function to get the handle for the plot (hPlot)
and specify the output device.
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);
See Also Plot Functions
PlotOpen
Description 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 must call this function before you can call the other plot functions.
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.
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
The above example prints the following (on the printer):
578
PlotScaleMarker
Description 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 must 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.
PlotSetMarker
Description 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.
Example 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);
See Also Plot Functions
580
PlotText
Description 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 must check that
the font (and the printer) supports the orientation.
You must first call the PlotOpen() function to get the handle for the plot (hPlot)
and specify the output device. You also must call the DspFont() function to get a
handle for the font (hFont).
PlotXYLine
Description 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 must 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.
2 - Dot (...............................)
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 you do not know
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, i.e. the number of points in the table
pTable for PlotLine(), or in tables xTable and yTable for
PlotXYLine().
For every line you draw with the PlotLine() and PlotXYLine()
functions within a plot, you must 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 (i.e.
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. e.g. If LoXScale = 0 (zero) and
HiXScale = 100, a value of 50 will be plotted half way along
the X-axis of your grid.
LoXScale must 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. e.g. If LoXScale =
583
Pow
Syntax Pow(X, Y)
X: . . . . . . . . . . . . . . The base number.
Y: . . . . . . . . . . . . . . The exponent.
Example Variable=Pow(5,3);
! Sets Variable to 125.
See Also Math/Trigonometry Functions
Description 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.
PrintFont
Description 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).
{! example.rpt }
-------------------------------------
AN example Report
-------------------------------------
{CICODE}
PrintFont("HeadingFont");
{END}
Plant Area 1
{CICODE}
PrintFont("ReportFont");
{END}
{Time(1) } {Date(2) }
PV_1 {PV_1:#####.##}
PV_2 {PV_2:#####.##}
----------End of Report---------------
...will print as...
-------------------------------------
AN example Report
-------------------------------------
Plant Area 1
04:41:56 19-10-93
PV_1 49.00
PV_2 65.00
----------End of Report---------------
See Also Device Functions
PrintLn
Description 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.
ProcessIsClient
Syntax ProcessIsClient()
Return Value TRUE (1) if the process contains a Client component, otherwise FALSE (0).
ProcessIsServer
Return Value TRUE (1) if the process contains the specified component, otherwise FALSE (0).
Example To execute disk PLC tag simulation code only on the I/O server in Cluster1 with
the name IOServer3:
587
ProjectRestartGet
Description Gets the path to the project to be run the next time CitectSCADA is restarted.
(You must 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.
ProjectRestartSet
Description 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 must use the full path, for
example to specify the path to the project "Demo", use:
"C:\CITECT\USER\DEMO".
ProjectSet
Description 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.
588
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 must
use the full path, for example to specify the path to the
project "Demo", use:
"c:ProgramFilesCitectCitectSCADA6.10\USER\DEMO". If
you do not specify a project, the current project will be used.
Prompt
Description Displays a message in the prompt line (AN=2) on the operator's computer.
Syntax Prompt(String)
String: . . . . . . . . . . The message to be displayed.
Pulse
Description 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.
589
The code in the I/O device should not rely on a pulse time of exactly 2 seconds.
Use the pulse as a trigger only.
Syntax Pulse(sTag)
sTag: . . . . . . . . . . . . The digital tag to pulse.
Example
Buttons
Text Jog 145
Command Pulse(M145)
Comment Pulse the variable tag M145 every two seconds
See Also Miscellaneous Functions
QueClose
Description 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.
Example hQue=QueOpen("MyQue",1);
.
.
QueClose(hQue);
See Also Task Functions
590
QueLength
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.
Example Length=QueLength(hQue);
See Also Task Functions
QueOpen
Description 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.
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.
QueWrite(hQue,1,"Moretext");
! Read back data from the queue.
QueRead(hQue,Type,Str,0);
See Also Task Functions
QuePeek
Description 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 must be variables. You should be careful to
not assume that they have not been changed when calling the function.
QueRead
Description 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.
0 - Non-blocking.
1 - Wait for element.
Example Status=QueRead(hQue,Type,Str,0);
IF Status = 0 THEN
! Now use Type and Str.
.
.
END
See Also Task Functions
QueryFunction
Description The user-defined query function set in AlarmSetQuery. Called for each active
alarm, the query function can be written to display an alarm based on specific
information (for example, OnDate). To examine the information in an alarm
field, call the function AlarmGetFieldRec from within your query function.
Note: The function name "QueryFunction" can be any valid Cicode function
name specified by the user.
Return Value The return value must be defined as an INT with a value of either TRUE or
FALSE. If the function returns a value of TRUE, the alarm being filtered is
displayed, otherwise it is excluded from the alarms list.
QueWrite
Description 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.
RadToDeg
Syntax RadToDeg(Angle)
Angle: . . . . . . . . . . . Any angle (in degrees).
Example Variable=RadToDeg(Pi());
! Sets Variable to 180.
See Also Math/Trigonometry Functions
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 must be between 2 and
32767 (inclusive).
Example Variable=Rand(101);
! Sets Variable to a random number from 0 to 100.
// To create a random number between 0 and 1 with 2 decimal places,
divide the above variable by 100, as shown here: //
Variable = Variable/100;
See Also Math/Trigonometry Functions
RealToStr
Example Variable=RealToStr(12.345,10,1);
! Sets Variable to " 12.3" (10 characters long).
See Also String Functions
RepGetCluster
Description 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
Description 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.
597
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
See Also Report Functions
Report
Description 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.
Example
Buttons
Text Shift Report
Command Report("Shift", “ClusterXYZ”)
Comment Runs the Shift Report
System Keyboard
Key Sequence Report ############ Enter
599
Command Report(Arg1)
Comment Runs a specified Report
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. */
See Also Report Functions
RepSetControl
Description 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-off 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.
Example RepSetControl("Shift",1,TimeCurrent()+60,"ClusterXYZ");
! Runs the "Shift" report in 1 minute.
! change weekly report to 8 hour shift starting at 7 am
RepSetControl("Weekly", 5, 1,"ClusterXYZ");! disable report
RepSetControl("Weekly", 4, 1,"ClusterXYZ");! change mode to daily
RepSetControl("Weekly", 3, 7 * 60 * 60,"ClusterXYZ"); ! sync at
7:00:00 am
RepSetControl("Weekly", 2, 8 * 60 * 60,"ClusterXYZ"); ! run every
8 hours
601
ReRead
Syntax ReRead(Mode)
Mode: . . . . . . . . . . . The mode of the read:
0 - Read only if data is stale.
1 - Read anyway.
Round
Example Variable=Round(0.7843,2);
! Sets Variable to 0.78 (result is rounded to 2 decimal places).
Variable=Round(123.45,-1);
! Sets Variable to 120.0 (rounded to -1 decimal place).
See Also Math/Trigonometry Functions
SemClose
Description 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 a critical section within a single process. This function only
works between Cicode tasks within the same process.
Syntax SemClose(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.
Example SemClose(hSem);
See Also Task Functions
603
SemOpen
Description 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,
e.g. 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.
Return Value 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.
Example hSem=SemOpen("MySem",1);
See Also Task Functions
SemSignal
Description 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)
604
Example SemSignal(hSem);
See Also Task Functions
SemWait
Return Value 0 (zero) if the semaphore has been gained, otherwise an error is returned.
Example Status=SemWait(hSem,10);
IF Status=0 THEN
.
.
ELSE
Prompt("Could not get semaphore");
END
605
SendKeys
Description 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.
Page Up {pgup}
Print Screen {prtsc}
Scroll Lock {scrolllock}
Tab {tab}
Up Arrow {up}
Down Arrow {down}
Right Arrow {right}
Left Arrow {left}
F1 {f1}
F2 {f2}
F3 {f3}
F4 {f4}
F5 {f5}
F6 {f6}
F7 {f7}
F8 {f8}
F9 {f9}
F10 {f10}
F11 {f11}
F12 {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 Code
Shift +
Ctrl ^
Alt %
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. Note that you must leave a space between the key and number.
SerialKey
Description 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 must be defined in the Ports database.
If the port is not on an I/O server, you must create a dummy I/O server record
(e.g. 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 (e.g. 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.
ServerInfo
Example sSrvInfo=ServerInfo("Report",0);
IF sSrvInfo THEN
! This is a primary report server.
ELSE
! This is a stand-by report server.
END
/* Get and store the names of all clients attached to this server
*/
iCount = 1;
iClients = ServerInfo("Server", 1);
WHILE iCount <= iClients DO
sName[iCount] = ServerInfo(IntToStr(iCount), 2);
iCount = iCount + 1;
END
See Also Miscellaneous Functions
ServerInfoEx
610
ServerInfoEx
Description 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 all the connected local processes, a
hardware alarm is raised.
Note: When sName is "Server" and nType is "0", the only values supported for
sComponent are "Alarm", "Trend", "Report" or "IOServer". All other values for
sComponent will result in an invalid argument error.
ClusterName: . . . . . The name of the cluster that the server belongs to. This is
only relevant if:
The Name is "alarm", "report", or "trend"; AND
The type of information required, nType, is 2 or 3.
Example 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 all 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
See Also Miscellaneous Functions
ServiceGetList
Description 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.
If you call this function from a component that is running purely as a display/
manager client, the function will return "Client".
If you call this function from a single-process component that includes:
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
613
Client
The function will return a string similar to:
"IOServer.ClustA.IOServ1,Trend.ClustB.Trend1,Alarm.ClustA.Alarm1,Report.C
lustB.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()
SetArea
Description 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 (defined in the Users database).
Syntax SetArea(Area)
Area: . . . . . . . . . . . . The area to set (1 to 255).
SetEvent
Description 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.
614
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.
SetLanguage
Description Sets the language database from which the local translations of all native strings
in the project will be drawn, and specifies the character set to be used. Native
strings are those that are preceded by a @, and enclosed in brackets (e.g.
@(Motor Overload)).
This function will dynamically change the language of display items such as
alarm descriptions, button text, keyboard/alarm logs, graphic text, Cicode
strings etc. The language will only be changed on the display client that calls the
function. This means that you can display different languages at different
display clients, even though they are running the same project.
If the local language character set differs from the default character set of the
Windows installation, the runtime text may be garbled. You can set the local
language and character set by using this function, or through the
[Language]LocalLanguage and [Language]CharSet Parameters.
617
Return Value 0 (zero) if successful, otherwise 262 (the file could not be opened).
Example SetLanguage("French",1);
! Changes the current language to French, using the Windows
default character set.
See Also Miscellaneous Functions
Shutdown
Description Terminates CitectSCADA's operation. You should always use this function to
shut down the CitectSCADA system, otherwise buffered data could be lost.
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 (Display Clients and servers) to be shut down in sDest, and the extent
of the shutdown in Mode.
618
You can allow selected computers to override the shutdown with the
[Shutdown]NetworkIgnore parameter. (You might set this parameter for critical
servers, e.g. 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.
ClusterName: . . . . . The name of the cluster that the machine(s) named in Dest
belongs to. This is not required if:
the function is called with Dest empty (the default); OR
the client is connected to only one cluster containing an
Alarm Server.
ShutdownForm
Description 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()
Example
System Keyboard
Key Sequence Shutdown
Command ShutdownForm();
Comment Display the shutdown form
Buttons
Text Shutdown
Command ShutdownForm();
Comment Display the shutdown form
620
ShutdownMode
Description 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 The shutdown mode set when shutdown was called.
Sign
Syntax Sign(Number)
Number: . . . . . . . . . Any number.
Example Variable=Sign(100);
! Sets Variable to 1.
Variable=Sign(-300);
! Sets Variable to -1.
Variable=Sign(0);
! Sets Variable to 0.
See Also Math/Trigonometry Functions
621
Sin
Syntax Sin(Angle)
Angle: . . . . . . . . . . . Any angle (in radians).
Example Variable=Sin(0.7854);
! Sets Variable to 0.7071...
See Also Math/Trigonometry Functions
Sleep
Description 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.
Example
Buttons
Text Step
Command PLCBit=1;Sleep(2);PLCBit=0;
Comment Switch Bit ON and then OFF 2 seconds later
622
SleepMS
Description 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.
0 (zero) if successful, otherwise an error is returned.
Example
Buttons
623
Text Step
Command PLCBit=1;SleepMS(500);PLCBit=0;
Comment 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
See Also Task Functions
SPCAlarms
Description 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.
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.
Example
Advanced Alarms
Alarm Tag Feed_SPC_XBLCL
Alarm Desc Process mean below LCL
Expression SPCAlarms("Feed_SPC", XBelowLCL)
Comment Trigger an alarm when XBelowLCL condition becomes
true.
Advanced Alarms
Alarm Tag Temp_SPC_GRADUP
Alarm Desc Mean is drifting up
Expression SPCAlarms("Temp_SPC", XGradualUp)
Comment Trigger an alarm if mean drifts up.
See Also SPC Functions
SPCClientInfo
Description Returns SPC data for the given SPC tag. The information retrieved through this
function is from the cache maintained by the display 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 on an SPC page.
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
625
SPCGetHistogramTable
Description 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 on an SPC page.
Return Value 0 (zero) if successful, otherwise an error number is returned. The histogram table
is written to TableVariable.
Example /* This function will get the maximum frequency present in the
histogram of a particular SPC tag.*/
INT iFrequency[7];
! This variable must 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
See Also SPC Functions
SPCGetSubgroupTable
Description 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 on an SPC page.
TableVariable: . . . . . The first element of the Cicode array that will store the
sample data. This variable must be defined as a global array
of type REAL. The number of elements in the array must 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.
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 must 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. Note that the range of data is 5
iMin = TableMath(rSubgroup,5,0,0);
END
Return iMin;
END
See Also SPC Functions
SPCPlot
Example /* This function will print the Mean trend (currently displayed at
animation point 40), the Range trend (currently at animation point
41), and the Standard Deviation trend (currently at animation
point 42). The result is a one page, black and white combination
of all three trends, printed to LPT1. */
SPCPlot("LPT1:",40, "CitectSCADA SPC Chart","Gradually increasing
trend",0);
See Also SPC Functions
SPCProcessXRSGet
Description 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 on an SPC page.
XVariable: . . . . . . . . The Cicode variable that stores the process mean (X double
bar). This variable must be defined as a global of type REAL.
Do not specify a constant in this field.
RVariable: . . . . . . . . The Cicode variable that stores the range (R). This variable
must be defined as a global of type REAL. Do not specify a
constant in this field.
SVariable: . . . . . . . . The Cicode variable that stores the standard deviation (S).
This variable must be defined as a global of type REAL. Do
not specify a constant in this field.
ClusterName: . . . . . 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.
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;
! These variables must 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
See Also SPC Functions
630
SPCProcessXRSSet
Description 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 on an SPC page.
SPCSetLimit
Description 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.
Example SPCSetLimit(40,1,250,1);
! Sets X-bar upper control limit to 250 at AN40.
See Also SPC Functions
SPCSpecLimitGet
Description 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.
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.
Example /* This function will increase the current USL and LSL of the
specified Tag by 10 percent.*/
REAL rLSL;
REAL rUSL;
! These variables must 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 * rIntPercent;
IF iError = 0 THEN
iError = SPCSpecLimitSet(sTAG, rLSL, rUSL);
END
Return iError;
END
! The function would be called as follows;
Page Button
Button Text Expand Temperature Limits
Expression ExpSLby10Percent("TANK_1_TEMP");
See Also SPC Functions
SPCSpecLimitSet
Description 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.
SPCSubgroupSizeGet
Description 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 on an SPC page.
Return Value 0 (zero) if successful, otherwise an error number is returned. The subgroup size
is written to SizeVariable.
SPCSubgroupSizeSet
Description 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 all display 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 on an SPC page.
SQLAppend
Description Appends a statement string to the SQL buffer. Cicode cannot send an SQL
statement that is longer than 255 characters. If you have an SQL statement that is
longer than the 255 character limit, you can split the statement into smaller
strings, and use this function to append the statements in 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).
SQLBeginTran
Description 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 must call either SQLCommit() to save the
changes or SQLRollBack() to discard the changesæthese functions complete the
transaction and release all database locks. Unless you complete the transaction,
you cannot successfully disconnect the SQL connection.
A single database connection can only handle one transaction at a time. After
you call SQLBeginTran(), you must complete that transaction before you can call
SQLBeginTran() again.
If you disconnect from a database while a transaction is active (not completed),
CitectSCADA automatically "rolls back" the transaction; any changes you made
to the database in that transaction are discarded.
636
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 you have
difficulty using the function, check that both your database and ODBC driver
support transactions. Refer to the documentation for your database for more
information on transactions.
Syntax SQLBeginTran(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
identifies the table 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).
SQLCommit
Description Commits (to the database) all changes made within a transaction. If you call the
SQLBeginTrans() function to begin a transaction, you must 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, CitectSCADA automatically rolls back the transaction; any changes
you made to the database in that transaction are discarded.
The SQLCommit() function could affect different databases in different ways. If
you have difficulty using the function, check that your database is ODBC
compatible. Refer to the documentation for your database for information on
committing transactions.
Syntax SQLCommit(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
identifies the table 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).
SQLConnect
Description Makes a connection to a database system, and returns a handle to the connection
for use by the other SQL functions. Through this connection, you can execute
638
SQL statements in the specified database. You must call this function before any
other SQL function.
You only require one connection for each database system to be accessed (e.g.
Oracle, dBASE, Excel, etc.).
Do not 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 critical (for
example, recipes or reports). If you try to use SQL to store real time data,
CitectSCADA's performance could be greatly degraded.
Syntax SQLConnect(sConnect)
sConnect: . . . . . . . . The connection string, in the format:
<attribute>=<value>[;<attribute>=<value>. . .]
The following attributes can be used in a connection string:
DSN Data Source Name. The name of the data source defined with the
ODBC utility in the Windows Control Panel. You must use the DSN
attribute, unless you are using CitectSCADA v2.01 or earlier.
DLG Dialog box. Set DLG to 1 to display a dialog box that allows the
user to input their user ID, password, and connection string. DLG
is an optional attribute.
UID User name or Authorisation/Login ID. Check the documentation
for your ODBC driver and database to see if you need to use the
UID attribute.
PWD Password. Check the documentation for your ODBC driver and
database to see if you need to use the PWD attribute.
MODIFY The ability of CitectSCADA to understand and accept native SQL
SQL depends on the database driver being used. Set MODIFYSQL to 1
(the default) for an ODBC-compliant SQL. Set MODIFYSQL to 0 to
use the native SQL syntax of the database system, as well as for
any CitectSCADA databases you created with versions 2.01 or
earlier, that employ database-specific SQL statements. The Q+E
ODBC database drivers are backward compatible with those
supplied with earlier versions of CitectSCADA.
REREAD Set to 1 to reread records from the database after updating them.
AFTER Use this attribute to get the correct value of automatically updated
UPDATE columns, such as time and date stamps.
REREAD Set to 1 to reread records from the database after inserting into it.
AFTER Use this attribute to get the correct value of automatically-updated
INSERT columns, such as time and date stamps.
DRV Use the DRV attribute for compatibility with CitectSCADA v2.01
and earlier. Use the DRV instead of the data source name (DSN)
in the connection string. Do not use DRV in new CitectSCADA
applications.
639
Return Value The SQL connection handle if the connection is successful, otherwise -1 is
returned. (For details of the 307 error code, call the SQLErrMsg() function). The
SQL connection handle identifies the table where details of the associated SQL
connection are stored.
Example /* 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;
hSQL = SQLConnect("DSN=MyDatabase;UID=billw;SRVR=CI1");
IF hSQL <> -1 THEN
Status = SQLExec(hSQL, "SELECT NAME FROM EMPLOYEE");
IF Status = 0 THEN
WHILE SQLNext(hSQL) = 0 DO
sName = SQLGetField(hSQL, "NAME");
. . .
END
SQLEnd(hSQL);
ELSE
Message("Error", SQLErrMsg(), 48);
END
SQLDisconnect(hSQL);
ELSE
Message("Error", SQLErrMsg(), 48);
END
END
See Also SQL Functions
SQLDisconnect
Description Closes a database connection. You should close all connections to databases
before you shut down CitectSCADA, to release system resources.
For each active transaction (that is, for each SQLBeginTran() call), you should
complete the transaction before you disconnect from the database; call
SQLCommit() to save your changes, or SQLRollBack() function to discard
changes. If you call SQLDisconnect() while a transaction is still active,
CitectSCADA automatically "rolls back" the transaction; any changes you made
to the database in that transaction are discarded.
CitectSCADA also automatically ends any queries that are active when the
database is disconnected. If you have called SQLExec() during a database
connection, you must call SQLEnd() before you disconnect from the database or
the disconnection could fail.
Syntax SQLDisconnect(hSQL)
641
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg function).
You should not call SQLErrMsg() if SQLDisconnect() returns zero (that is, if the
disconnection is successful). SQLErrMsg() would provide information about a
connection that does not exist; the information could be meaningless.
SQLEnd
Description Ends the execution of an SQL query (from the latest SQLExec() call). If you have
called the SQLExec() function from within a database connection, you should
call SQLEnd() before you disconnect from that database. When the SQLEnd()
function ends the execution of the current SQL query, it frees the memory that
was allocated for that query.
Only one query can be active at a time, so you do not 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. Similarly,
CitectSCADA automatically ends the latest query when it disconnects the
database, even if you have not called SQLEnd(). However, the SQLEnd()
function ensures efficiency⎯SQLEnd() releases the memory that was allocated
when the latest query was executed.
Syntax SQLEnd(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
identifies the table where details of the associated SQL
connection are stored.
642
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg() function).
SQLErrMsg
Description Returns an error message from the SQL 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.
Syntax SQLErrMsg()
SQLExec
Description Executes an SQL query on a database. With this function, you can execute any
SQL query or command supported by the SQL database. Only "CHAR" type
fields are supported in database tables.
Keywords such as "DATE", "TIME", and "DESC" cannot be used as field names
by some database systems. To use fields with these names, you must append
underscores to the names (e.g. "TIME_", "DATE_", "DESC_").
The SQLNext() function must be called after the SQLExec() function before you
can access data in the first record.
643
Only one query can be active at a time, so you do not 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. Similarly,
CitectSCADA automatically ends the latest query when it disconnects the
database, even if you have not called SQLEnd(). However, the SQLEnd()
function ensures efficiency⎯SQLEnd() releases the memory that was allocated
when the latest query was executed.
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg() function).
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 FIRSTNAME OCCUPATION DEPARTMENT
MARTIAN MARVIN ENGINEER MANAGEMENT
CASE CARRIE SUPPORT CITECT
LIGHT LARRY PROGRAMMER CITECT
BOLT BETTY ENGINEER SYSTEMS
PHONE
SURNAME NUMBER
MARTIAN 5551000
CASE 5551010
BOLT 5551020
LIGHT 5551030
Each SQL string (sSQL) should be encased within the SQLExec function, for
example:
644
SQLExec(hSQL, sSQL);
To add a record to a table:
sSQL = "INSERT INTO PEOPLE (SURNAME, FIRSTNAME, OCCUPATION,
DEPARTMENT) VALUES('ALLEN','MATTHEW','PROGRAMMER','CITECT')";
This SQL command changes the PEOPLE table to:
PEOPLE
SURNAME FIRSTNAME OCCUPATION DEPARTMENT
MARTIAN MARVIN ENGINEER MANAGEMENT
CASE CARRIE SUPPORT CITECT
LIGHT LARRY PROGRAMMER CITECT
BOLT BETTY ENGINEER SYSTEMS
ALLEN MATTHEW PROGRAMMER CITECT
PHONE
SURNAME NUMBER
CASE 5551010
BOLT 5551020
LIGHT 5551030
To change a record:
sSQL = "UPDATE PEOPLE SET OCCUPATION='SUPPORT' WHERE
FIRSTNAME='LARRY'";
This SQL command changes the PEOPLE table to:
645
PEOPLE
SURNAME FIRSTNAME OCCUPATION DEPARTMENT
MARTIAN MARVIN ENGINEER MANAGEMENT
CASE CARRIE SUPPORT CITECT
LIGHT LARRY SUPPORT CITECT
BOLT BETTY ENGINEER SYSTEMS
You can also select data using a much more complete SQL string, for example:
sSQL = "SELECT (SURNAME, OCCUPATION, NUMBER) FROM (PEOPLE, PHONE)
WHERE DEPARTMENT='CITECT' AND PEOPLE.SURNAME = PHONE.SURNAME";
This SQL command retrieves the following table:
SURNAME OCCUPATION NUMBER
CASE SUPPORT 5551010
LIGHT PROGRAMMER 5551030
2
3
4
...
See Also SQL Functions
SQLFieldInfo
Description 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.
Keywords such as "DATE", "TIME", and "DESC" cannot be used as field names
by some database systems. To use fields with these names, you must append
underscores to the names (e.g. "TIME_", "DATE_", "DESC_").
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg function).
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
See Also SQL Functions
SQLGetField
Description Gets field or column data from a database record. To get the database record,
use the SQLExec() and SQLNext() functions.
Keywords such as "DATE", "TIME", and "DESC" cannot be used as field names
by some database systems. To use fields with these names, you must append
underscores to the names (e.g. "TIME_", "DATE_", "DESC_").
Return Value The field or column data (as a string). A null string is returned if the field or
column does not contain data.
The maximum length of the return data is 255 characters. If the returned data is
longer than this, the function will return error 306.
SQLInfo
Example SQLInfo(1,2);
See Also SQL Functions
SQLNext
Description Gets the next database record from an SQL query. Use the SQLExec() 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.
649
Syntax SQLNext(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
identifies the table 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).
SQLNoFields
Description Gets the number of fields or columns that were returned by the last SQL
statement.
Syntax SQLNoFields(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
identifies the table where details of the associated SQL
connection are stored.
Return Value The number of fields. A value of 0 is returned if no fields were returned or if an
error has occurred. (For details of an error, call the SQLErrMsg function).
SQLNumChange
Description Gets the number of records that were modified in the last SQL Insert, Update, or
Delete statement.
Syntax SQLNumChange(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
identifies the table 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, call the
SQLErrMsg function).
SQLRollBack
Description 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
you have difficulty using the function, check that your database is ODBC-
compatible. Refer to the documentation for your database for more information
on rolling back transactions.
Syntax SQLRollBack(hSQL)
hSQL: . . . . . . . . . . . The handle to the SQL connection, returned from the
SQLConnect() function. The SQL connection handle
651
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg function).
SQLSet
Description Sets a statement string in the SQL buffer. Cicode cannot send an SQL statement
that is longer than 255 characters. If you have an SQL statement that is longer
than the 255 character limit, you can split the statement into smaller strings, and
use this function and the SQLAppend() function to append the statements in 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).
SQLTraceOff
Description Turns off the debug trace. Use this function to stop tracing function calls that are
made to the database.
Syntax SQLTraceOff()
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg function).
SQLTraceOn
Description Turns on a debug trace. Use this function to begin tracing function calls that are
made to the database. The information is written to a log file.
Syntax SQLTraceOn(sFile)
sFile: . . . . . . . . . . . . The output file name for the debug trace.
Return Value 0 (zero) if successful, otherwise an error number is returned. (For details of the
307 error code, call the SQLErrMsg function).
Sqrt
Syntax Sqrt(Number)
Number: . . . . . . . . . Any positive number.
Example Variable=Sqrt(4);
! Sets Variable to 2.
See Also Math/Trigonometry Functions
StrClean
Description 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.
Example Variable=StrClean("*****Text*****");
/* Sets Variable to "Text" (the "*" character in this example
represents an unprintable character). */
See Also String Functions
StrFill
Example Variable=StrFill("abc",10);
! Sets Variable to "abcabcabca".
Variable=StrFill("x",10);
! Sets Variable to "xxxxxxxxxx".
See Also String Functions
StrFormat
Description Converts a variable into a formatted string. This function is the equivalent of the
Cicode " :#### " operator.
Example Variable=StrFormat(10.345,5,2,"%");
! Sets Variable to "10.35%".
See Also String Functions
StrGetChar
Description Gets a single character from a string or buffer. Use this function to read a string,
character by character.
StrLeft
Syntax StrLeft(String, N)
String: . . . . . . . . . . The source string.
N: . . . . . . . . . . . . . . The number of characters to get from the source string.
Example Variable=StrLeft("ABCDEF",2);
! Sets Variable to "AB".
See Also String Functions
StrLength
Syntax StrLength(String)
String: . . . . . . . . . . The source string.
Example Variable=StrLength("ABCDEF");
! Sets Variable to 6.
See Also String Functions
656
StrLower
Syntax StrLower(String)
String: . . . . . . . . . . The source string.
Example Variable=StrLower("ABCDEF");
! Sets Variable to "abcdef".
Variable=StrLower("AbCdEf");
! Sets Variable to "abcdef".
See Also String Functions
StrMid
Return Value A string containing the number of characters from the offset.
Example Variable=StrMid("ABCDEF",1,3);
! Sets Variable to "BCD".
Variable=StrMid("ABCDEF",4,1);
! Sets Variable to "E".
See Also String Functions
657
StrPad
Description 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.
StrRight
Syntax StrRight(String, N)
String: . . . . . . . . . . The source string.
N: . . . . . . . . . . . . . . The number of characters to get from the source string.
Example Variable=StrRight("ABCDEF",2);
! Sets Variable to "EF".
See Also String Functions
658
StrSearch
Description 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.
Return Value The index in the search string, or -1 if the sub-string does not exist in the string.
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
StrSetChar
Description 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).
StrToChar
Syntax StrToChar(String)
String: . . . . . . . . . . The source string.
Example Variable=StrToChar("ABC");
! Sets Variable to 65 (ASCII "A").
See Also String Functions
StrToDate
Description 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)
660
StrToFmt
Description Converts a string into field data for a format template. This function is useful for
breaking 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.
StrToGrp
Description 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.
661
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
StrToHex
Description 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):
(0-9, a-f, A-F);
A space;
A"+" (plus) or a "-" (minus) sign.
Syntax StrToHex(String)
String: . . . . . . . . . . The string to convert.
Example Variable=StrToHex("123");
! Sets Variable to hex 123, decimal 291
Variable=StrToHex("F2");
! Sets Variable to hex F2, decimal 242
Variable=StrToHex("G45");
! Sets Variable to 0.
Variable=StrToHex("-FG");
! Sets Variable to hex, -F decimal -15.
662
StrToInt
Description Converts a 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-numeric 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.
Example Variable=StrToInt("45");
! Sets Variable to 45.
Variable=StrToInt("45.23");
! Sets Variable to 45.
Variable=StrToInt("A45");
! Sets Variable to 0.
See Also String Functions
StrToLines
Description Converts a string into separate lines that contain no more than the number of
characters specified in the MaxChars argument.
The function breaks the string by inserting newline characters into the text
string, thus dividing it into separate lines. The string will be broken 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.
Return Value An integer (nLines) containing the number of lines produced by the StrToLines()
function from the input string.
StrToLocalText
Description Converts a native string into the local version of that string. (The string must 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 must 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.
664
StrToPeriod
Description Converts a string into a time period. You would normally use this function to
convert operator input, e.g. 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 delimeter for these fields, which will be the current system
time delimeter as set in the Windows Control Panel.
If minutes are specified, seconds must be in the range 0-59. If hours are specified,
minutes must be in the range 0-59.
Syntax StrToPeriod(String)
String: . . . . . . . . . . The string to convert.
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
StrToReal
Description 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 (0-9), a space, a decimal point, a " + " or a " - " sign, the
return value is 0 (zero).
665
Syntax StrToReal(String)
String: . . . . . . . . . . The string to convert.
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
StrToTime
Description 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; e.g., am or pm. The colon character
':' represents the time delimeter for these fields, which will be the current system
time delimeter 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.
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
666
StrToValue
Description 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 empty or
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 (e.g., it prevents a setpoint from being set to 0 if the operator presses
ENTER or enters invalid data by mistake).
Syntax StrToValue(String)
String: . . . . . . . . . . The string to convert.
Example
System Keyboard
Key Sequence F3 ######## Enter
Command SP123 = StrToValue(Arg1);
Comment Set setpoint 123 to value unless value is invalid
Note that the Cicode is halted. Any other Cicode after the StrToValue() function
will not execute.
See Also String Functions
StrTrim
Description Removes leading and trailing spaces from a string. Internal spaces are not
removed from the string.
Syntax StrTrim(String)
String: . . . . . . . . . . The source string.
StrUpper
Syntax StrUpper(String)
String: . . . . . . . . . . The source string.
Example Variable=StrUpper("abcdef");
! Sets Variable to "ABCDEF".
Variable=StrUpper("AbCdEf");
! Sets Variable to "ABCDEF".
See Also String Functions
StrWord
Description 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.
SubscriptionAddCallba
ck
Description 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.
To remove a callback from a subscription use the SubscriptionRemoveCallback
function.
SubscriptionGetAttribut
e
Description Reads the specified attribute value of a subscribed tag. Similar to TagRead.
Return Value String representation of the cached value for a subscribed tag. On error, an
empty string and an error is set.
SubscriptionRemoveCa
llback
Description Removes a function callback from a tag subscription. The subscription handle
and callback function must match those used when adding the callback.
SwitchConfig
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)
SysTime
Description 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.
671
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 The CitectSCADA internal system millisecond counter (as an integer).
Example Start=SysTime();
! Gets the current time.
.
.
Delay=SysTime()-Start;
! Sets Delay to the time difference, in milliseconds.
See Also Time/Date Functions
SysTimeDelta
Description 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.
672
Return Value The time difference from a start time and the current time.
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.
See Also Time/Date Functions
TableLookup
Description Searches for a value in a table, and returns the position (offset) of the value in the
table. Note that the first item in a table is offset 0 (zero), the next item is offset 1,
etc.
Return Value The offset to the table value, or -1 if the value does not exist.
TableMath
TableShift
Description 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.
TagDebug
Description Displays a dialog which allows you to select from a list of all 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 is useful for debugging or
commissioning.
675
Syntax TagDebug()
TagGetProperty
Description This function reads a property of a variable tag from the datasource. This
function replaces TagInfo.
Return Value String representation of the property of the tag. On error, an empty string and an
error is set.
Example // Get the engineering full scale value for the variable "PV131"
EngFullScale = TagGetProperty("PV131", "EngUnitsHigh", 0);
// Get the cached array size for the array variable "PLC_Array"
ArrayLength = TagGetProperty("PLC_Array", "ArraySize", 1);
See Also Tag Functions
TagGetScale
Description 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.
Example // Display the zero, 50% and full scale of the tag CV_123_PV
DspText(31,0,TagGetScale("CV_123_PV", 0, 1));
DspText(32,0,TagGetScale("CV_123_PV", 50, 1));
DspText(33,0,TagGetScale("CV_123_PV", 100, 1));
See Also Tag Functions
TagInfo
Description Gets information about a variable tag. This function allows you to develop
generic Cicode and Super Genies.
Note: This function is being deprecated and is replaced by the TagGetProperty
function. If the Tag properties are updated, TagInfo does not get the updated
values whereas TagGetProperty does. In addition, the function TagInfoEx has
been introduced to make it easier to make legacy Cicode compatible with online
changes. In most cases TagInfo can be replaced with TagInfoEx using Find and
Replace (see Using Find and Replace in a project). Note that if you are replacing
an instance of TagInfo with TagInfoEx in a loop, you may want to make
TagInfoEx blocking using the iCached argument to ensure you are using the
correct value for the Tag in your logic.
ClusterName . . . . . . Specifies the name of the cluster in which the Tag resides.
The argument is enclosed in quotation marks.
Example /* Get the engineering full scale value for the variable "PV131"
*/
EngFullScale = TagInfo("PV131", 5);
/* Get the engineering zero scale value for the array variable
"PLC_Array" */
EngZeroScale = TagInfo("PLC_Array", 4);
See Also Tag Functions
TagInfoEx
Description This function replaces TagInfo and 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 to ensure you are
using the correct value for the Tag in your logic.
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:
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
11 - Bit Width – Tag’s size in bits. For example, an INT is 16
bits
12-15 - Not supported
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.
If the tag is a local variable, modes 1, 6, 7, 8, 9 or 11 will
return an empty string.
ClusterName . . . . . . Specifies the name of the cluster in which the Tag resides.
The argument is enclosed in quotation marks.
682
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. Ensures cicode is non-blocking
Default value is 1 (true).
Return Value The value of the information as a string. In case of error an empty string is
returned. The error code can be obtained by calling the IsError Cicode function.
Example /* Get the engineering full scale value for the variable "PV131".
Obtain the value from Cluster1 in blocking mode */
EngFullScale = TagInfoEx("PV131", 5, "Cluster1", 0);
/* Get the engineering zero scale value for the array variable
"PLC_Array" in non-blocking mode*/
EngZeroScale = TagInfoEx("PLC_Array", 4);
See Also Tag Functions
TagRamp
Description 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.
Example
Buttons
Text Ramp Up
Repeat Command TagRamp("PLC_VAR_1",2);
Comment Continual increment by 2%
See Also Tag Functions
TagRead
Description Reads a variable from the I/O device. The variable tag must 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.
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.
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).
nOffset: . . . . . . . . . . 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 value of the I/O device variable, as a string. An error is returned if the tag
does not exist, or if the variable cannot be read from the I/O device.
TagScaleStr
Description 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.
Example // Display the zero, 50% and full scale of the tag CV_123_PV
DspText(31,0,TagScaleStr("CV_123_PV", 0, 1));
DspText(32,0,TagScaleStr("CV_123_PV", 50, 1));
DspText(33,0,TagScaleStr("CV_123_PV", 100, 1));
See Also Tag Functions
TagSubscribe
Description 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.
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.
Example The following example subscribes the tag "Conveyor1" in order to manually poll
for attributes of the tag:
...
INT subsHandle = TagSubscribe("Conveyor1");
...
// Get the last changed value, quality and timestamp for the tag
convValue = SubscriptionGetAttribute(subsHandle, "Value");
convQual = SubscriptionGetAttribute(subsHandle, "ValueQuality");
convTime = SubscriptionGetAttribute(subsHandle, "ValueTimestamp");
...
// Unsubscribe the tag
TagUnsubscribe(subsHandle);
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.
...
INT subsHandle = TagSubscribe("Conveyor1", 100, "Percent",
"OnValueChanged");
...
SubscriptionAddCallBack(subsHandle, "ValChanged2");
...
Function OnValueChanged(INT handle)
subsVal = SubscriptionGetAttribute(handle, "Value");
subsQual = SubscriptionGetAttribute(handle, "ValueQuality");
...
END
687
...
Function ValChanged2(INT handle)
subsVal = SubscriptionGetAttribute(handle, "Value");
subsTime = SubscriptionGetAttribute(handle, "ValueTimestamp");
...
END
...
// Remove all callbacks and unsubscribe
TagUnsubscribe(subsHandle);
See Also Tag Functions
TagUnsubscribe
Description 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 TagUnsubscribe(iHandle)
iHandle . . . . . . . . . . Integer handle of the subscription to unsubscribe.
TagWrite
Description Writes to an I/O device variable by specifying the variable tag. The variable tag
must be defined in the Variable Tags database.
This function completes asynchronously to the caller. An error occurs if the tag
does not exist or if a write request could not be sent. This function does not
guarantee that the write succeeded. In cases of write failure TagWrite does not
return a driver error code. For critical updates, perform a TagRead to confirm
that the write took place.
Note: When using this function, you cannot use the ClusterGetName function or
[Code]ScaleCheck parameter to write an out-of-range value to a device. This
function checks a value before writing it to a PLC. If the value is out of range, the
attempted write operation will fail, but no hardware alarm will be generated.
688
TagWriteEventQue
Description 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.
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:
nDateTime is the timestamp of the tag write.
sTagAndValue is the tagname and value written to the queue.
When the function is run, all 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
Tan
Syntax Tan(Angle)
Angle: . . . . . . . . . . . Any angle (in degrees).
Example Variable=Tan(1);
! Sets Variable to 1.5574...
See Also Math/Trigonometry Functions
691
TaskCluster
Description 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.
TaskGetSignal
Description 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).
TaskHnd
Description 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.
Return Value The task handle, identifying the table where all data on the task is stored.
Example ! Get the task handle of the current task and then kill it.
hTask=TaskHnd();
TaskKill(hTask);
! Get the task handle of MyTask and then kill it.
hTask=TaskHnd("MyTask");
TaskKill(hTask);
See Also Task Functions
TaskKill
Description 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.
Note: TaskKill is an abrupt way to stop a Cicode task and can cause system
errors; try to use TaskGetSignal and TaskSetSignal instead.
Example ! Create a task, run it for 10 seconds and then kill it.
hTask=TaskNew("MyFunc","",0);
Sleep(10);
TaskKill(hTask);
FUNCTION
MyFunc()
INT Count;
WHILE 1 DO
Prompt("Hello "+Count:###);
Count=Count+1;
END
END
See Also Task Functions
TaskNew
Description Creates a new Cicode task and returns the task handle. You pass the Name of the
function (that creates the task) as a string, not as the function tag, and pass all 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.
You can set the Mode to run the task forever or only until the current page is
changed or the current window is freed. If you do not add 4 to the Mode,
CitectSCADA starts the task immediately, without reading 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. If you add 4 to the Mode, CitectSCADA requests all 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. Use
Mode 4 when the I/O device data must be read, but do not use Mode 4 when the
task has to start immediately.
You can specify that if the task is already running, the function will fail, 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
694
specified, the task will use the cluster context of the caller, be it a page or Cicode
task. Note 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.
Return Value The task handle, or -1 if the task cannot be successfully created. The task handle
identifies the table where all data on the associated task is stored.
TaskNewEx
Description Creates a new Cicode task with an individual subscription rate and returns the
task handle. You pass the Name of the function (that creates the task) as a string,
not as the function tag, and pass all 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.
You can set the Mode to run the task forever or only until the current page is
changed or the current window is freed. If you do not add 4 to the Mode,
CitectSCADA starts the task immediately, without reading 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. If you add 4 to the Mode, CitectSCADA requests all 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. Use
Mode 4 when the I/O device data must be read, but do not use Mode 4 when the
task has to start immediately.
You can specify that if the task is already running, the function will fail, and an
error will display. This is useful when you want only a single instance of the
function running at any point in time.
696
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. Note 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.
Return Value The task handle, or -1 if the task cannot be successfully created. The task handle
identifies the table where all data on the associated task is stored.
TaskResume
Description 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.
Example TaskResume(hTask);
See Also Task Functions
TaskSetSignal
TaskSuspend
Description 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.
Example TaskSuspend(hTask);
.
.
TaskResume(hTask);
See Also Task Functions
TestRandomWave
Description 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.
TestSawWave
Description 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.
TestSinWave
Description 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.
TestSquareWave
Description 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.
TestTriangWave
Description 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.
Time
TimeCurrent
Description Gets the current system time/date in time/date variable format. Note 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.
703
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()
TimeHour
Syntax TimeHour(Time)
Time: . . . . . . . . . . . . The time/date variable.
TimeInfo
Description 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:
"0" - 12 hour
"1" - 24 hour
2 - The current time delimiter.
3 - The current morning time extension.
4 - The current evening time extension.
Return Value Depending on the nInfo argument passed to the function, a string containing:
Current time hour format ("0" for 12 hour, "1" for 24 hour)
Current time delimiter
Current morning time extension
Current evening time extension
TimeMidNight
Description 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.
TimeMin
.
.
END
Syntax TimeMin(Time)
Time: . . . . . . . . . . . . The time/date variable.
TimeSec
Syntax TimeSec(Time)
Time: . . . . . . . . . . . . The time/date variable.
TimeSet
Description Sets the new system time. You can set the time only on the computer where this
function is called, or on the time server (and therefore on all CitectSCADA
computers on the network).
When you change the time on the time server, the alarm, report, and trend
servers must adjust their databases records to the new time. Adjusting records
can be time-consuming and can cause some loss of data (if data logging is in
progress). Change the time only if necessary.
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
TimeToOLEDate
Description Converts a CitectSCADA time/date value to an OLE DATE value (this should be
stored in a REAL).
TimeToStr
Description 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:
709
IF StrToDate(Arg1)>0 THEN
.
.
ELSE
.
.
END
Return Value A string containing the converted time/date or period variable, or an empty
string if invalid.
String=TimeToStr(125 + TimeCurrent(),5);
! Sets String to "11:52:05" (the current time + 2 minutes and 5
seconds).
See Also Time/Date Functions
TimeUTCOffset
Description 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.
Toggle
Description 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.
Syntax Toggle(sTag)
sTag: . . . . . . . . . . . . The digital tag to toggle.
Example
Buttons
Text Motor 145
Command Toggle(M145)
Comment Toggle the variable tag M145 (Motor 145) on or off
See Also Miscellaneous Functions
711
TraceMsg
Syntax TraceMsg(String)
String: . . . . . . . . . . The message to display.
TrendDspCursorScale
Description Displays a scale value for the current pen in the current pen font.
TrendDspCursorTag
Description Displays the trend tag name of the current pen in the pen font.
712
TrendDspCursorTime
Description Displays the cursor time of the current pen in the current pen font.
TrendDspCursorValue
Description Display the cursor value of the current pen in the current pen font.
Syntax TrendDspCursorValue(AN)
AN: . . . . . . . . . . . . . The AN of the trend.
TrendGetAn
Description 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.
TrendPopUp
Description Displays a pop-up trend with the specified trend pens. You must create the
trend page with the graphic builder and set all the pen names to blank.
Example
Buttons
Text Popup Trend
Command TrendPopUp("MyPop", "PV1", "PV2", "PV3")
Comment Display a popup trend with three trend pens
See Also Trend Functions
TrendRun
Description 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: . . . . . . . The type of the page:
0 - Normal trend page template
1 - Compare trend page template
TrendSetDate
Description 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.
TrendSetScale
Description 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.
TrendSetSpan
Description 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.
TrendSetTime
Description 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.
717
TrendSetTimebase
Description 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.
TrendWin
Description Displays a trend page (in a new window) with the specified trend pens. You
must create the trend page with the graphic builder and set all the pen names to
blank. You then display that page by calling this function and pass the required
718
trend tags. The function will create a new window with the specified window
mode.
Example
Buttons
Text Trend Window
Command TrendWin("MyTrend", 0, 0, 4, "PV1", "PV2",
"PV3")
Comment Display a trend page in a new window with no
maximize and minimize icons
See Also Trend Functions
TrendZoom
Description "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.
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.
TrnAddHistory
Description 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. Note that only a reference to
the archived file, and not the file itself, is kept in the trend history. Therefore,
care must 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.
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.
resolving the trend server via the current cluster context. The
argument is enclosed in quotation marks "".
Example TrnAddHistory("C:\CITECT\DATA\TR1.MAY91");
! Adds the file TR1.MAY91 to the trend system.
See Also Trend Functions
TrnBrowseClose
Description 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 is returned.
TrnBrowseFirst
Description 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 is returned.
722
TrnBrowseGetField
Description 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.
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 occurred. The last error should be checked in this
instance to determine if an error has actually occurred.
// Function failed
END
...
See Also Trend Functions
TrnBrowseNext
Description The TrnBrowseNext function moves the data browse cursor forward one record.
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.
Return Value 0 (zero) if the trend browse session exists, otherwise an error is returned.
TrnBrowseNumRecords
Description 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.
TrnBrowseOpen
Description 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.
Return Value Returns an integer handle to the browse session. Returns -1 on error.
TrnBrowsePrev
Description The TrnBrowsePrev function moves the data browse cursor back one record.
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 is returned.
TrnClientInfo
Description Gets information about the trend that is being displayed at the AN point.
Return Value The requested information (as a string) if successful, otherwise a hardware
alarm is generated.
TrnComparePlot
Description 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.
sPort: . . . . . . . . . . . The name of the printer port to which the plot will be
printed. This name must 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.
AN: . . . . . . . . . . . . . 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.
0 - black and white (default)
1 - Color
nSamples: . . . . . . . . The number of data points on the plot.
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: . . . . . . . . . . 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 must be for the first
trend, and tags 5 to 8 must be for the second.
rLoScale1, HiScale1,....LoScale8, HiScale8
The minimum and maximum on the vertical scale for the
trend line of each of the tags (Tag1. . . Tag8)
Example /* Prints two black and white trends (one overlaid on the other)
to LPT1, comparing the trend lines of one trend tag (Feed_Flow) at
different times. The first trend line has a starting time of
12noon, on 11/12/96, and the second has a starting time of 9am, on
11/10/96. Both contain 200 sample points, and have a period of 2
728
TrnDelete
Description 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 TrnDelete(AN)
AN: . . . . . . . . . . . . . The AN where the trend is located.
Example TrnDelete(20);
! Deletes the trend at AN20.
See Also Trend Functions
TrnDelHistory
Description 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.
FileName: . . . . . . . . The trend history file to disconnect from the historical trend
system.
ClusterName: . . . . . 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 "".
Example TrnDelHistory("C:\CITECT\DATA\TR1_91.MAY");
! Disconnects the file from the trend system.
See Also Trend Functions
TrnEcho
Description 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.
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.
TrnSetScale(40,2,100,-1000);
! Enable echo to show changes to the display
TrnEcho(40,1);
See Also Trend Functions
TrnEventGetTable
Description 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.
Return Value The actual number of samples read. The return value is 0 if an error occurs. 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.
TrnEventGetTableMS
Description 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.
Return Value The actual number of samples read. The return value is 0 if an error occurs. You
can call the IsError() function to get the actual error code.
TrnEventSetTable
Description 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.
Return Value The actual number of samples read. The return value is 0 if an error occurs. You
can call the IsError() function to get the actual error code.
TrnEventSetTableMS
Description 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 must 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.
Return Value The actual number of samples read. The return value is 0 if an error occurs. You
can call the IsError() function to get the actual error code.
TrnExportClip
Description 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. (Note that not all packages support multiple
clipboard formats in this way.)
1. . . . .Text
2. . . . .CSV
You can add these modes for a combination of formats.
sTag1 ... sTag8: . . . . The trend tag names for the data being exported.
iDisplayMode1 ... iDisplayMode8:
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.
By default, this argument is set to 3 (see the details for
options 1 and 2 below).
Invalid/Gated trend options:
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 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.
739
TrnExportCSV
Description 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 must
specify a valid event number in the Time argument, rather than a time.
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 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.
Options listed in each group are mutually exclusive. The
default value for each Display Mode is 258 (0 + 2 + 256).
/* 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. */
See Also Trend Functions
742
TrnExportDBF
Description 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.
TrnExportDDE
Description 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.
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 in all.
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 all applications will support this
mode. See you applications documentation for details.
1 - Text (default)
2 - CSV
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.
iDisplayMode1 ... iDisplayMode8:
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.
By default, this argument is set to 3 (see the details for
options 1 and 2 below).
Invalid/Gated trend options:
746
TrnFlush
Description 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.
TrnGetBufEvent
Description Gets the event number of a trend at an offset for a specified pen. This function
only operates on an event-based trend.
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.
TrnGetBufTime
Description 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.
Return Value A time/date variable. 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.
END
/* Displays the trend date at offset 10 for the pen currently in
focus. The time will display at AN31. */
See Also Trend Functions
TrnGetBufValue
Description 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.
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().
TrnGetCluster
Syntax TrnGetCluster(AN)
AN: . . . . . . . . . . . . . The AN of the chosen trend graph.
Return Value The name of the cluster the trend graph is associated with.
See Also Trend Functions
TrnGetCursorEvent
Description 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.
Return Value The event number, or 0 (zero) if the trend cursor is disabled.
TrnGetCursorMSTime
Description Gets the time (in milliseconds from the previous midnight) at a trend cursor for
a specified pen.
Return Value The number of milliseconds since the previous midnight. If the trend cursor is
disabled, 0 (zero) is returned. If AN or Pen is invalid, 0 (zero) is returned and an
error code is set.
TrnGetCursorPos
Description Gets the offset of a trend cursor from its origin, in samples.
Syntax TrnGetCursorPos(AN)
AN: . . . . . . . . . . . . . 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.
TrnGetCursorTime
Description Gets the time and date at a trend cursor for a specified pen.
Return Value A time/date variable. If the trend cursor is disabled, 0 (zero) is returned. If AN or
Pen is invalid, 0 (zero) is returned and an error code is set.
TrnGetCursorValue
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().
TrnGetCursorValueStr
Description 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.
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.
TrnGetDefScale
Description 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.
TrnGetDisplayMode
Description Returns the display mode of the selected trend pen. The display mode is set
using TrnSetDisplayMode.
TrnGetEvent
Description 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
756
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.
Example /* Display the start event for the current pen of the trend at
AN20. */
DspText(31,0,TrnGetEvent(20,0,0));
See Also Trend Functions
TrnGetFormat
Description Gets the format of a trend tag being plotted by a specified pen.
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.
See Also Trend Functions
TrnGetGatedValue
Description 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
ensures the return of the correct value.
Syntax TrnGetGatedValue()
TrnGetInvalidValue
Description 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
ensures the return of the correct value.
Syntax TrnGetInvalidValue()
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
RETURN i;
END
See Also Trend Functions
TrnGetMode
Description Gets the mode (real-time or historical trending) of the trend pen.
ELSE
DspText(31,0,"Historical Trending");
END
See Also Trend Functions
TrnGetMSTime
Description 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
Return Value The number of milliseconds since the previous midnight. 0(zero) is returned if
an error occurs.
TrnGetPen
Return Value The trend tag (as a string) being plotted by Pen. If AN 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.
TrnGetPenComment
TrnGetPenFocus
Syntax TrnGetPenFocus(AN)
AN: . . . . . . . . . . . . . The AN of the chosen trend.
Return Value The pen currently in focus (between 1 and 8). If AN is invalid, -1 is returned and
an error code is set.
TrnGetPenNo
Description 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.
TrnGetPeriod
Description Gets the current display period of a trend. (To obtain the sampling period, use
the TrnInfo function.)
Syntax TrnGetPeriod(AN)
AN: . . . . . . . . . . . . . The AN of the chosen trend.
Return Value The current display period of a trend (in seconds), or 0 (zero) if an error occurs.
Example /* For the trend at AN20, get and display the current display
period. */
! If the period is 10 seconds
INT Period;
763
STRING Str;
Period=TrnGetPeriod(20);
Str=TimeToStr(Period,5);
DspStr(31,"",Str);
See Also Trend Functions
TrnGetScale
Description Gets the display scale of the trend tag being plotted by a specified pen.
Return Value The scale of the trend tag being plotted by Pen. If AN or Pen is invalid, 0 (zero) is
returned and an error code is set.
TrnGetScaleStr
Description 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.
Return Value The scale of the trend tag being plotted by Pen (as a string). If AN or Pen is
invalid, <na> is returned and an error code is set.
TrnGetSpan
Description 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 is automatically set to 0 (zero).
Syntax TrnGetSpan(AN)
AN: . . . . . . . . . . . . . The AN of the chosen trend.
765
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.
TrnGetTable
Description 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.
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.
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. */
See Also Trend Functions
TrnGetTime
Description 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.
TrnGetUnits
Description Gets the data units for the trend tag plotted by a specified Pen.
Return Value 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.
TrnInfo
Tag: . . . . . . . . . . . . . The name of the trend tag enclosed in quotation marks ""
(can be prefixed by the name of the cluster i.e.
ClusterName.Tag).
Type: . . . . . . . . . . . . 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.
ClusterName: . . . . . 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 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.
TrnIsValidValue
Syntax TrnIsValidValue(TrendValue)
TrendValue: . . . . . . . A trend value (of type REAL).
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
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
See Also Trend Functions
TrnNew
Description 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.
TrnPlot
Description 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.
For more advanced trend plotting, you can use the low-level plot functions.
rPeriod: . . . . . . . . . . The period (in seconds) of the trend plot. This can differ from
the actual trend period.
If you do not enter a period, it defaults to the sample period
of Tag1.
sTitle: . . . . . . . . . . . The title of the trend plot.
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 must enter
0 (zero) here.
iMode: . . . . . . . . . . . The color mode of the printer.
0 - Black and White
1 - Color
sComment: . . . . . . . The comment that is to display beneath the title of the trend
plot. You may pass an empty string if no comment is
required.
rLoScale1, HiScale1,......LoScale8, HiScale8:
The minimum and maximum on the vertical scale for the
trend line of each of the tags (Tag1. . . Tag8).
Example /* Prints a black and white plot to LPT1, containing the trend
lines of two variable tags (PV1 & PV2). The trend lines have a
starting time of 9am, on 11/10/96, 200 sample points, and a period
of 2 seconds. The trend line of PV1 will be on a vertical scale of
0-200, and PV2 will be on a vertical scale of 0-400. */
INT time;
Time = StrToDate("11/10/96") + StrToTime("09:00:00");
TrnPlot("LPT1:",200,Time,2,"Citect Trend
Plot","PV1","PV2","","","","","","",0,"Process variable operation
at shutdown",0,200,0,400);
See Also Trend Functions
774
TrnPrint
Description Prints the trend that is displayed on the screen (at AN) 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.
TrnSamplesConfigured
Description Gets the number of samples configured for the currently displayed trend.
Syntax TrnSamplesConfigured(AN)
AN: . . . . . . . . . . . . . The AN where the trend is located.
Return Value The number of samples configured for the trend, or 0 (zero) if an error occurs.
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));
See Also Trend Functions
TrnScroll
Description Scrolls the trend pen by a specified percentage (of span), or number of samples.
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);
See Also Trend Functions
TrnSelect
Description 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.
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 must use the special
value -2 as their AN. (See the example below).
TrnSetCursor
Description 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.
TrnSetCursorPos
Description 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.
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).
See Also Trend Functions
TrnSetDisplayMode
Description Specifies how raw trend samples are displayed on the screen.
TrnSetEvent
Description Sets the start event of a trend pen. This function only operates on an event-based
trend.
TrnSetPen
Description Sets the trend tag of a trend pen. The trend pen changes to the specified tag and
the trend is refreshed. The trend pen must be in the operator's area to be
781
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.
Return Value 0 (zero) if successful, otherwise an error is returned. Note that if a mixture of
periodic and event trends is detected, the return value is 0 (zero), but the
hardware alarm #329 is set.
TrnSetPenFocus
Description Sets the focus to a specified pen. After the focus is set, the focus pen is used with
other trend functions.
-3 - Make the previous pen the focus pen; do not skip 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 - Do not change the focus pen.
1...8 - Change Pen1. . .8 to be the focus pen.
Return Value The old pen focus number, or -1 if an error occurs. You can call the IsError()
function to get the actual error code.
Example
System Keyboard
Key Sequence NextPen
Command TrnSetPenFocus(20, -2)
Comment For the trend at AN20, make the next pen the
focus pen
See Also Trend Functions
TrnSetPeriod
Description 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. All pens have the same display period.
This function clears the span set by the TrnSetSpan() function.
Example
System Keyboard
Key Sequence ## Enter
Command TrnSetPeriod(20, Arg1)
Comment Set a new sampling period for the trend at AN20
See Also Trend Functions
TrnSetScale
Description Sets a new scale for a trend pen. In the automatic scaling mode, the zero and full
scales are automatically generated.
TrnSetSpan
Description 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 ensure a sufficient
sample rate to capture reliable real time data.
TrnSetTable
Description 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 must 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.
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 (i.e. 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: . . . . . 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.
ClusterName: . . . . . 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 "".
786
Return Value The actual number of samples read. The return value is 0 if an error occurs. You
can call the IsError() function to get the actual error code.
TrnSetTime
Description 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.
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. */
See Also Trend Functions
UserCreate
Description Creates a record for a new user. A new user of the specified type is created. The
name of the user must be unique.
UserCreateForm
Description 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 must be unique.
Syntax UserCreateForm()
Example UserCreateForm()
See Also Security Functions
UserDelete
Description Deletes the record for a user. Changes are written to both the Users database and
the runtime database in memory.
Syntax UserDelete(sName)
sName: . . . . . . . . . . The name of the user.
UserEditForm
Description 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.
Syntax UserEditForm()
Example /* Display a form for the user to create or delete user records. */
UserEditForm();
See Also Security Functions
UserInfo
Description Gets information about the operator who is currently logged-in to the system.
Syntax UserInfo(Type)
Type: . . . . . . . . . . . . The type of user information:
0 - Flag to indicate if anyone is logged in or not
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
Return Value The information (as a string). If an error occurs, an empty string is returned.
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
See Also Security Functions
UserPassword
Description Changes the password for the user. Changes are written to both the Users
database and the runtime database in memory.
790
UserPasswordExpiryDa
ys
Description 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().
Return Value The return value contains either the number of days before password expiry, or
one of two exception conditions:
0 to 365 - number of days
-1 - no expiry
-2 - user not found or password wrong
UserPasswordForm
Description 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.
Syntax UserPasswordForm()
Version
Syntax Version(Type)
Type: . . . . . . . . . . . . The type of version:
0 - Major version number
1 - Minor version number
2 - Revision number
792
3 - Version text
WhoAmI
Description Displays the user name and full name of the user currently logged-in to the
system. The names are displayed at the prompt AN.
Syntax WhoAmI()
Example /* Display the user's full name and user name at the prompt AN. */
WhoAmI();
See Also Security Functions
WinCopy
Description Copies the graphics image of the active window to the Windows Clipboard. You
can paste this Clipboard image into other applications.
Notes
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.
793
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.
See Also Window Functions
WinFile
Description Writes the graphics image of the active window to a file. The file is saved in the
CitectSCADA compressed .bmp format.
Notes
This function might not work as expected if called directly from the Kernel;
instead, this function should be called from a graphics page.
795
RRR2, GGG2 and BBB2 are decimal values for red, green and
blue in the range 000 to 255. They specify the colour to
change TO.
HHH, SSS and LLL are optional tolerance values to enable
swapping a range of colors. The tolerance values are applied
to the FROM color when replacing individual pixels in the
image. 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.
Comments may be placed at the end of each line, or on
individual lines, and must be proceeded with // or !.
Example map file:
043 043 255 155 205 255 025 000 025 //Change dark
blue to light blue using Hue and Luminance
tolerance of 25
000 000 000 255 255 255 //Swap black to white with
no tolerance
Note: A Hue tolerance range cannot overlap with another
specified Hue, or Hue tolerance range. If this occurs, there is
the risk that the color will not be swapped.
Example WinFile("DUMP");
/* Writes the active window to a file named DUMP in the current
directory. */
See Also Window Functions
797
WinFree
Description Removes the active display window. Note 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
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()
Example WinFree();
! Removes the active display window.
See Also Window Functions
WinGetFocus
Description 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.
Note that this is not the same as the window handle, returned from the
WndFind() function.
Example nCitectWin=WinGetFocus();
! Gets the number of the CitectSCADA window that has the keyboard
focus
See Also Window Functions
798
WinGetWndHnd
Description 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. Note that this is
not the same as a CitectSCADA window number returned from the
WinNumber() function.
WinGoto
Description 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). Note that this is not the same as the window
handle, returned from the WndFind() function.
WinMode
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.
WinMove
Description 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
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.
Example WinMove(100,50,500,300);
/* Moves the top-left corner of the active window to the pixel
coordinate 100,50 and size the window to 500 x 300 pixels. */
See Also Window Functions
WinNew
Description Opens a new display window, with a specified page displayed. The window can
later be destroyed with the WinFree() function.
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 arguement 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)
801
Return Value The window number of the window, or -1 if the window cannot be opened.
Note that this is not the same as the window handle returned from the
WndFind() function.
WinNewAt
Description Opens a new display window at a specified location, with a selected page
displayed. The window can later be destroyed with the WinFree() function.
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 arguement 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.
Return Value The window number of the window, or -1 if the window cannot be opened.
Note that this is not the same as the window handle returned from the
WndFind() function.
Example
Buttons
Text Mimic Page
Command WinNewAt("Mimic", 100, 20, 0)
Comment Display the mimic page in a new window at
coordinate 100, 20.
Buttons
Text Pop Page
Command WinNewAt("Popup", 100, 200, 2)
Comment Display the popup page in a child window at
coordinate 100, 200
804
Buttons
Text Pop Page
Command WinNewAt("Popup", 100, 200, 4)
Comment Display the popup page in a new window with no
maximize and minimize icons
System Keyboard
Key Sequence Pop ######## Enter
Command WinNewAt(Arg1, 100, 200, 2)
Comment Display a specified popup page in a child window
at coordinate 100, 200
System Keyboard
Key Sequence Pop ######## Enter
Command WinNewAt(Arg1, 100, 200, 4)
Comment Display a specified popup page in a new window
with no maximize and minimize icons
See Also Window Functions
WinNext
Syntax WinNext()
Return Value The window number of the window, or -1 if there is no next window. Note that
this is not the same as the window handle returned from the WndFind()
function.
WinNumber
Description Gets the window number of the active CitectSCADA window. This number can
be used with other functions to control the window.
805
Syntax WinNumber()
Return Value The window number of the window. Note that this is not the same as the
window handle returned from the WndFind() function.
Example ! Create a new window, but keep the active window the same:
Window=WinNumber();
WinNew("Alarm");
WinGoto(Window);
See Also Window Functions
WinPos
Description 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.
Example WinPos(100,50);
/* Moves the top-left corner of the active window to the pixel
coordinate 100,50. */
See Also Window Functions
WinPrev
Syntax WinPrev()
806
Return Value The window number of the window, or -1 if there is no next window. Note that
this is not the same as the window handle returned from the WndFind()
function.
WinPrint
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).
fromColour . . . . . . . The hex RGB color value (0xRRGGBB) to change into
toColour. The default value of -1 results in no colour change
(optional).
toColour. . . . . . . . . . The hex RGB color value (0xRRGGBB) into which fromColour
is changed. The default value of -1 results in no colour
change (optional).
Note: To change a color, a value must be specified for both
fromColour and toColour.
sMap:. . . . . . . . . . . . The file name or path of a text based map file used to specify
colours to swap when printing. By default Citect will look in
the bin directory for the map file. The format for the map file
is:
RRR1 GGG1 BBB1 RRR2 GGG2 BBB2 [HHH] [SSS] [LLL]
RRR1 GGG1 BBB1 RRR2 GGG2 BBB2 [HHH] [SSS] [LLL]
Where:
RRR1, GGG1 and BBB1 are decimal values for red, green and
blue in the range 000 to 255. They specify the colour to
change FROM.
RRR2, GGG2 and BBB2 are decimal values for red, green and
blue in the range 000 to 255. They specify the colour to
change TO.
HHH, SSS and LLL are optional tolerance values to enable
swapping a range of colors. The tolerance values are applied
to the FROM color when replacing individual pixels in the
image. 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.
Comments may be placed at the end of each line, or on
individual lines, and must be proceeded with // or !.
Example map file:
808
043 043 255 155 205 255 025 000 025 //Change dark
blue to light blue using Hue and Luminance
tolerance of 25
000 000 000 255 255 255 //Swap black to white with
no tolerance
Note: A Hue tolerance range cannot overlap with another
specified Hue, or Hue tolerance range. If this occurs, there is
the risk that the color will not be swapped.
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.
WinPrint("LPT3:",0,0,0,0x00FF00,0xFF0000);
!Changes green to red.
WinPrint("LPT3:",0,0,1,0x00FF00,0xFF0000);
!Changes green to red and black to white.
See Also Window Functions
WinPrintFile
Description Prints a file to the system printer. The file must be saved with the WinFile()
function.
Note: This function might not work as expected if called directly from the
Kernel; instead, this function should be called from a graphics page.
WinSelect
Description 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. Note that this is not the same
as the window handle returned from the WndFind()
function.
Example OldWindow=WinSelect(1);
! Selects window number 1.
Prompt("Message to Window 1");
! Sends message to window number 1.
WinSelect(2);
! Selects window number 2.
Prompt("Message to Window 2");
! Sends message to window number 2.
WinSelect(OldWindow);
! Selects original window.
See Also Window Functions
WinSize
Description Sizes the active window. The origin of the window does not move.
811
Example WinSize(200,100);
! Sizes the active window to 200 pixels wide x 100 pixels high.
See Also Window Functions
WinTitle
Syntax WinTitle(sTitle)
sTitle: . . . . . . . . . . . The new title for the window.
WndFind
Description 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).
812
The window title (caption) must 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.
Note 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 (i.e. the N is
omitted), you must 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. Note that this is not the same as a CitectSCADA window
number returned from the WinNumber() function.
WndGetFileProfile
WndGetProfile
Description Gets the value of a WIN.INI parameter. If the parameter has no value or does not
exist, the default value is returned.
Example KeyboardSpeed=WndGetProfile("Windows","KeyboardSpeed","20");
/* Sets KeyboardSpeed to "20" if the [Windows] KeyboardSpeed
parameter has no value or does not exist. */
See Also Window Functions
WndHelp
WndInfo
Description 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(Type)
Type: . . . . . . . . . . . . The system measurement to be retrieved. All measurements
are in pixels. The system measurement must 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.
816
WndPutFileProfile
WndPutProfile
Description Updates a parameter in WIN.INI. If the parameter does not exist, it is created.
Example WndPutProfile("Windows","KeyboardSpeed","20");
! Updates the [Windows] KeyboardSpeed
parameter in WIN.INI with "20".
See Also Window Functions
WndShow
WndViewer
Hardware/Cicode Errors
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.
Range Source Cause
0 - 31 PLC or I/O Device The I/O Device is reporting an error, or CitectSCADA is
Generic errors experiencing the reported error trying communicate with an I/O
Device. Often caused by incorrect configuration or faulty cabling.
256 - 511 General 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 faulty or non-existent.
2. Cicode
Cicode errors are generated when your project configuration calls a
Cicode function in an invalid way, or when a Cicode function fails 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.
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).
263 Cannot read file The specified file cannot be read. Either an error occurred during a
read operation, or the end of file was unexpectedly found, or a loss
of the file server occurred, or the operating system is out of
resources.
264 Cannot write to file The specified file cannot be written to. During a function call (that
tried to write to a file), a write error occurred. There could be a disk
full error, or a loss of the file server may have occurred, or the
operating system is out of resources.
265 Invalid file type An attempt was made to open a file of the wrong type, e.g. you tried
to open an ASCII file as a dBASE file.
266 Field not found in 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.
267 File mode is invalid An operation has been attempted on a file or device that is of the
wrong mode, e.g. you tried to perform a seek on a printer device.
Do not use this operation on this type of device.
268 Key not found in file The requested key was not found when a key search was
performed on a database device, i.e. the record specified on an
indexed search cannot be found. Either the record does not exist or
you have specified the wrong key.
825
This error can also occur if something is stopping the release of the
buffers, e.g. 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:
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.
296 Queue empty An attempt has been made to read an element from an empty
queue.
297 Semaphore owner The owner of a Cicode semaphore was halted, killed, or returned
died 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.
298 Semaphore timeout 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 error.
299 Cancelled 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.
300 Trend not found 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.
301 Trend pen not found 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.
302 Trend data not valid 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.
303 Invalid animation The AN specified in the function is not defined. You called one of
number the DspXXX animation functions, but you specified an animation
number that was out of range or that had been deleted.
829
This error may also occur if your swap file is large (i.e. greater than
20Mb). Reduce the size of your swap file. The swap file is
configured with the Windows Control Panel (386 Enhanced icon).
320 Cannot free window The WinFree() function has been called but CitectSCADA has no
windows left. (Note that the last window and any child windows
owned by the last window cannot be removed.)
21 Font cannot be found The specified font cannot be found. Check the font name.
322 LAN Failure CitectSCADA has detected a failure on the network.
323 Super Genie not A Super Genie variable has not been associated correctly. This
Associated error can occur if a variable passed to the Super Genie is the wrong
data type or the variable does not exist. The error will also occur if
the Ass() function has not been called for the variable.
325 Project is not Changes have been made to the project while the system was
compiled running. Either restart the system or shutdown and re-compile.
326 Could not run the The CitectSCADA compiler could not be found. Either the computer
CitectSCADA has run out of memory, or the compiler has been removed from its
compiler directory.
327 User type not found An attempt was made to create a user of a type that has not been
defined in the users database.
328 User already exists An attempt was made to create a new user with the same name as
an existing user.
329 Cannot have mixed An attempt was made to display both a periodic trend and an event
trends trend in the same trend window. Check the project configuration
(Trend Tags and Page Trends databases) for mixed trends
displayed in a trend window.
831
MAPI Errors
The table below describes the MAPI errors in Cicode.
Error
Error title Description
number
0 SUCCESS_SUCCESS The command completed successfully.
1 MAPI_USER_ABORT The command was aborted by the user.
2 MAPI_E_FAILURE General MAPI error.
3 MAPI_E_LOGIN_FAILURE The login failed, either the login user is unknown,
misspelt, or the password is incorrect.
4 MAPI_E_DISK_FULL 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.
5 MAPI_E_INSUFFICIENT_MEMORY Insufficient memory to complete the command.
6 MAPI_E_ACCESS_DENIED You do not have enough privilege to complete the
requested command.
8 MAPI_E_TOO_MANY_SESSIONS You have tried to open too many sessions to the
mail system.
834
Error
Error title Description
number
9 MAPI_E_TOO_MANY_FILES Too many attached files in a message.
10 MAPI_E_TOO_MANY_RECIPIENTS Too many recipients for a mail message.
11 MAPI_E_ATTACHMENT_NOT_FOUND Cannot find the attached file.
12 MAPI_E_ATTACHMENT_OPEN_FAILURE Cannot open the specified attached file. Most
likely the file does not exist.
13 MAPI_E_ATTACHMENT_WRITE_FAILURE Cannot write the attached file.
14 MAPI_E_UNKNOWN_RECIPIENT 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.
15 MAPI_E_BAD_RECIPTYPE Unknown recipient type.
16 MAPI_E_NO_MESSAGES No new messages to read.
17 MAPI_E_INVALID_MESSAGE The mail message is invalid.
18 MAPI_E_TEXT_TOO_LARGE 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.
19 MAPI_E_INVALID_SESSION Mail session is invalid. You should not get this error
message; contact Citect Technical Support.
20 MAPI_E_TYPE_NOT_SUPPORTED You should not get this error message; contact
Citect Technical Support.
21 MAPI_E_AMBIGUOUS_RECIPIENT The recipient of the mail message is ambiguous.
Specify the exact user name to which the mail is to
be sent.
22 MAPI_E_MESSAGE_IN_USE Mail message is in use. You should not get this
error message: contact Citect Technical Support.
23 MAPI_E_NETWORK_FAILURE Mail cannot be sent or received as the network has
failed.
24 MAPI_E_INVALID_EDITFIELDS You should not get this error message; contact
Citect Technical Support.
25 MAPI_E_INVALID_RECIPS You should not get this error message; contact
Citect Technical Support.
26 MAPI_E_NOT_SUPPORTED Command is not supported by this implementation
of MAPI.
Chapter 18: Browse Function Field Reference