Programming Reference
Programming Reference
List of Tables
List of Figures
Section 3: AnalogCond
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1
Interface Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1
Public Class Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.11
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.13
Section 4: ChannelMonitoring
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.5
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.16
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.23
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.28
Section 5: ConditionMonitoring
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.4
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.9
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.38
Section 6: CrossTaskData
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.6
Section 7: DescriptiveData
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.29
Section 8: Dictionaries
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.8
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.9
Section 9: DynamicDisturbanceRecorder
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.3
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.4
Special Considerations for COMTRADE Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.5
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.5
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.40
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.42
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.25
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.4
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.4
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.8
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.1
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.1
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.7
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.9
Retain Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.20
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.7
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.9
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.3
Global Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.3
Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.3
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.4
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.7
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.8
Figure 3.1 A Digital Filter Using Three (3) Coefficients for A(z)
and Five (5) for B(z) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.4
Figure 3.2 class_LimitedSplpfStepToDefault With a Time Con-
stant of 1000 ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.14
Figure 3.3 class_LimitedSplpfRampToDefault With a Time Con-
stant of 1000 ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.15
Figure 3.4 Plot of Total Signal and Filtered Output of the Low-
Pass Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.18
Usage
Command Structure
The command line interface is made available through a command prompt or shell win-
dow. During installation, the RTAC installation folder will be added to the user’s %PATH%
variable to ensure that commands can be executed. Commands are case insensitive. Com-
mands can then be issued via the command prompt in the following form:
AcRtacCmd command [options] <values>
where:
command is the main argument that must always appear first after AcRtacCmd.
options are specified with a short (e.g., -f) or long (e.g., --file) name. When options
for a command are given wrapped in square brackets, they are not required for the com-
mand. An option can be Boolean (in which case only the flag is required in the command)
or it can require the flag to be followed by a bound value as an option specifier. Omitted
Boolean options are treated as FALSE. For example:
AcRtacCmd command -v
would set the short name option -v to TRUE, while
AcRtacCmd command
Behavior
Commands are dispatched serially to ACSELERATOR RTAC. They are required not to return
until termination.
All commands will return an error status code and print a machine-parsable string to stdout.
See Command Returns on page 1.3 for more details.
Behavioral Requirements
The way that commands are processed includes the following constraints:
ä Commands do not return until termination. This preserves the order of a list of
commands and prevents commands from being sent when an RTAC is still busy.
ä All commands return error codes and print to stdout when complete. The user may
rely on these outputs to programmatically determine command success or failure and
to synchronize further input.
ä An error description shall be displayed to the user for invalid parameters and failed
commands.
ä Parallel invocation of commands may cause a race condition and should not be used.
One such example of this would be invoking commands from two separate console
instances accessing the same local database and/or devices. However, commands
shall be executed in the order received regardless of what console instances window
the command was issued from.
ä All future commands must obey these serial requirements.
Command Returns
All commands will return an exit code and print to stdout in the following format:
command:exitcode:"exit code description"
Table 1.1 lists the exit code status and their descriptions.
Help
All commands implement a help option that prints a human-readable description of valid
parameters and syntax for the command. For example, the following command outputs the
help file for the importxml command:
AcRtacCmd importxml --help
Startup Switches
As an advanced feature, you can modify the shortcut to ACSELERATOR RTAC to include
various startup runtime switches. These switches provide features not available in the soft-
ware in normal run mode. See start on page 1.39 for more information.
Command List
The syntax of available commands are as follows.
Commands
check
close
connect
convert
delete
disablepassword
disconnect
exportexp
exportlibrary
exportxml
help
importexp
importxml
info
list
login
lsproc
open
read
rename
rtacinfo
setpassword
start
stop
unlock
upgradefirmware
check
Initiates a build run of all objects in the POUs window.
Synopsis
AcRtacCmd check [-a <alias> | -i <pid>] [-j <project_password>] [-
n <name>]
Remarks
ä This command is used for test purposes when creating a library project. It causes a
build run of all objects currently available in the POUs window. Only the objects in
the POU window will be checked for syntax errors. This command is the same as
check all POOL objects in ACSELERATOR RTAC.
ä No compilation code will be generated.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
ä If the specified project is not open when using this command, the project will be
opened before processing and closed when complete. The process of opening and
closing the project automatically increases the time this command takes to complete.
ä This command is only supported on project version R132 or higher.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-j, --project_password <project_password>
The AcRTAC project password.
-n, --name <name>
The name of the project to build.
Examples
Feature: Verifying library code POU's
Before a library can be created and saved, the check command is used
to verify the library code in the POU's section.
Scenario: Check the POU's in a project with name "CheckExample" that has
invalid settings
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
And the project "CheckExample" exists as a 3530 project in the db
And the project "CheckExample" is unlocked
And the project "CheckExample" is open
When the argument string "check" is passed to AcRtacCmd.exe
Then "check:1:failure" can be found in the output
And the error level returned is: "1"
close
Closes the currently open project.
Synopsis
AcRtacCmd close [-a <alias> | -i <pid>]
Remarks
ä If no project is open, this command will not do anything and will return without
error.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Opening and closing AcSELerator RTAC projects.
Once a process is logged into a database, the open and close commands
are used to access the projects within a database.
Scenario: Open the project 'OpenTest' with a process using the alias
'LoginTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "LoginTest"
And admin has logged in with password TAIL
And the project "OpenTest" exists as a 3530 project in the db
And the project "OpenTest" is unlocked
When the argument string "open OpenTest -a LoginTest" is passed to
AcRtacCmd.exe
Then "open:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Close the project 'OpenTest' with a process using the alias
'LoginTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "LoginTest"
And admin has logged in with password TAIL
And the project "OpenTest" exists as a 3530 project in the db
And the project "OpenTest" is unlocked
And the project "OpenTest" is open
When the argument string "close -a LoginTest" is passed to AcRtacCmd.exe
Then "close:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Open the project 'OpenTest' with the last started process
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
And the project "OpenTest" exists as a 3530 project in the db
And the project "OpenTest" is unlocked
connect
This command is the same as Go Online in ACSELERATOR RTAC.
Synopsis
AcRtacCmd connect [options] <ipaddress> <username>
Remarks
ä The default for this command is to only log in to a device at <ipaddress> with <user-
name> and <password>.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
ä If the -s option is specified, the current project will be sent to the RTAC. This com-
mand does not prompt before overwriting project settings.
ä The -n option must be specified if the project is not open. This will open the project
before executing the command. The process of opening the project increases the
time this command takes to complete. The project will not close when the command
is complete.
ä The user may also send advanced project settings (listed in Table 1.2).
ä When in non-visual mode, the process will stay connected to the specified RTAC
until one of the following occur: the disconnect command is used, the project is
closed, or the process is stopped. The online time-out setting only applies when in
non-visual mode.
Values
<ipaddress>
RTAC IPv4 address
<username>
Remote RTAC account username with which to log in.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-r, --reinit
Reinitialize retain variables.
-n, --name <name>
The name of the project to send.
-p, --password <password>
Login password of remote RTAC. If not given, the command will attempt to
read from stdin. No prompt for a password will occur.
-s, --send
In addition to going online with the given RTAC, also send the specified project
from option -n or current open project.
Sends complete project.
Updates all settings
Restarts your RTAC.
Retains all settings through a restart.
Stores changes for future project reads.
-j, --project_password <project_password>
The AcRTAC project password.
--retain-password-vault
Update the Retain Password Vault with the given password parameters.
-b, --databaseport <databaseport>
The database port number.
-e, --rteport <rteport>
The rte port number.
Advanced Options
The following are additional settings that can be in a project:
-v, --advanced <key>
Allows specifying advanced options for sending projects. The <key> is a comma-
separated list of advanced settings shown in Table 1.2.
Examples
Feature: Connecting, disconnecting, and sending projects.
The connect and disconnect commands are used to send settings to a device.
convert
Converts a project to the version specified by <version> or to the RTAC type specified by
<type>
Synopsis
AcRtacCmd convert [-a <alias> | -i <pid>] [-d] [-n <new_name>] <name>
<type | version>
Remarks
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
ä Projects can only be converted from lower to higher firmware versions.
Values
<name>
The name of a project to convert
<version>
The r-number / RTAC firmware version.
<type>
The type of RTAC. Valid RTAC types are shown in Table 1.3.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-n, --new_name <new_name>
The new name for the converted project. If no name is provided, a new name
will be generated automatically.
-d, --delete
Remove original project.
Examples
Feature: Converting an AcRtac project to another version or device type
Because projects are locked to a device type and firmware version, the
convert command is needed.
Scenario: Attempt to Convert a project from 3530 to 3555 device when the
project does not exist
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
When the argument string "convert NoProject 3555" is passed to
AcRtacCmd.exe
Then "convert:1:failure" can be found in the output
And the error level returned is: "1"
delete
Removes an ACSELERATOR RTAC project with <name> from the ACSELERATOR RTAC
database.
Synopsis
AcRtacCmd delete [-a <alias> | -i <pid>] <name>
Remarks
ä If * is used in place of a project name, then all projects will be removed from the
ACSELERATOR RTAC Database.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
Values
<name>
The name of the project to delete.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Deleting AcSELerator RTAC projects from the database.
Once a process is logged into a database, the delete command is used to
remove projects from the database.
Scenario: Delete the project 'DeleteTest' with a process using the alias
'DeleteTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "DeleteTest"
And admin has logged in with password TAIL
And the project "DeleteTest" exists as a 3530 project in the db
And the project "DeleteTest" is unlocked
When the argument string "delete OpenTest -a LoginTest" is passed to
AcRtacCmd.exe
Then "delete:0:success" can be found in the output
And the error level returned is: "0"
And the project "DeleteTest" does not exists as a 3530 project in the db
disablepassword
Disables the password on a project.
Synopsis
AcRtacCmd disablepassword [-a <alias> | -i <pid>] [-n <name>]
Remarks
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-n, --name <name>
The name of the project to disable the password on.
Examples
Feature: Disable the password on a project.
disconnect
Disconnect from currently connected device. This is the same as Go offline in ACSELER-
ATOR RTAC.
Synopsis
AcRtacCmd disconnect [-a <alias> | -i <pid>]
Remarks
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Connecting, disconnecting, and sending projects.
The connect and disconnect commands are used to send settings to a device.
exportexp
Export a project with <name> as a .exp file.
Synopsis
AcRtacCmd exportexp [-a <alias> | -i <pid>] [-f <file>] <name>
Remarks
ä By default, the name of the created file is <name>.exp. The file will be saved in the
same directory from which this command is executed.
ä This command will overwrite the file if it already exists on the system.
ä Use -f <file> to specify the path and name of the file to export. For example,
to save the export in a directory called MyProjects on the local C: drive, as the file
project1, set <file> to C:\MyProjects\project1.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
Values
<name>
The name of the project to export.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-f, --file <file>
Name of file to export the project. Use this to specify the path to where the
export will be saved and/or to export the project with a different name than the
project name.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Importing and Exporting projects as .exp file
exportlibrary
Export a project with <name> as a .compiledlibrary.
Synopsis
AcRtacCmd exportlibrary [-a <alias> | -i <pid>] [-j <project_password>]
[-f <file>] [-n <name>]
Remarks
ä By default, the name of the created file is <name>.compiledlibrary and will be saved
in the same directory from which this command is executed.
ä This command will overwrite the file if it already exists on the system.
ä Use -f <file> to specify the path and name of the file to export. For example,
to save the export in a directory called MyProjects on the local C: as the file myli-
brary.compiledlibrary, set <file> to C:\MyProjects\mylibrary.compiledlibrary.
ä The -n option must be specified if the project is not open. This will open the project
before executing the command and close it upon completion. The process of opening
and closing the project automatically will increase the time this command takes to
complete.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
ä This command is only supported on project version R132 or higher.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-f, --file <file>
Name of file to export the project. Use this to specify the path to where the
export will be saved and/or to export the project with a different name than the
project name.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Export a project to a .compiled-library file
exportxml
Export the current project as an XML directory structure at <directory>.
Synopsis
AcRtacCmd exportxml [-a <alias> | -i <pid>] [-j <project_password>]
[-n <name>]
<directory>
Remarks
ä This command will overwrite the file if it already exists on the system.
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
ä The -n option must be specified if the project is not open. This will open the project
before executing the command and close it upon completion. The process of opening
and closing the project automatically will increase the time this command takes to
complete.
ä This command is only supported on project version R132 or higher.
Values
<directory>
The directory to place the XML file structure export. If destination directory
does not exist; it will be created.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-n, --name <name>
The name of the project to export.
-j, --project_password <project_password>
The AcRTAC project password.
Examples
Feature: Importing and Exporting projects into XML directory structure
Scenario: Import a new project named Xmlexample for a 3530 using version
R136 from xml structure using an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "XmlTest"
And admin has logged in with password TAIL
When the argument string "importxml 3530 R136 ../../FTProjects/XmlFT -n
Xmlexample -a XmlTest" is passed to AcRtacCmd.exe
Scenario: Import a new project named Xmlexample for a 3530 using version
R136 from xml structure without an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
When the argument string "importxml 3530 R136 ../../FTProjects/XmlFT -n
Xmlexample" is passed to AcRtacCmd.exe
Then "importxml:0:success" can be found in the output
And the error level returned is: "0"
help
Prints out a list of commands
Synopsis
AcRtacCmd help
Examples
Feature: Viewing Help Output
The AcRtacCmd help can be obtained by passing the --help argument.
If no argument is passed in, the help is displayed by default.
Scenario: Run the AcRtacCmd with the --help from CLI and obtain help
information
Given AcRtacCmd is in the system path
When the command "AcRtacCmd --help" is issued in a console
Then "--help" can be found in the output
And the error level returned is: "0"
Scenario: Running AcRtacCmd without any options also shows the help
information
Given AcRtacCmd is in the system path
When the command "AcRtacCmd" is issued in a console
Then "--help" can be found in the output
And the error level returned is: "0"
importexp
Creates a new project from a .exp file with name <file> and stores it in the local database.
Synopsis
AcRtacCmd importexp [-a <alias> | -i <pid>] [-n <name>] <file>
Remarks
ä The -n option allows the project name to be specified.
ä This command will print the name of the project created to stdout.
Values
<file>
Path to file to import.
Options
-a, --alias <alias>
Examples
Feature: Importing and Exporting projects as .exp file
importxml
Creates a new project with the default project name from a XML folder structure at <di-
rectory> and stores it in the local database.
Synopsis
AcRtacCmd importxml [-a <alias> | -i <pid>] [-n <name>] [-l] <type>
<version> <directory>
Remarks
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
ä The -n option allows the project name to be specified.
ä This command will print the name of the project created to stdout.
ä This command is only supported on project version R132 or higher.
Values
<directory>
The location on the disk of the XML directory root.
<type>
The type of RTAC. Valid RTAC types are shown in Table 1.4.
<version>
The r-number / RTAC firmware version.
-l, --library
Create imported project as library.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-n, --name <name>
The name to create the new project with. This will be used instead of the default
name.
Examples
Feature: Importing and Exporting projects into XML directory structure
Scenario: Import a new project named Xmlexample for a 3530 using version
R136 from xml structure using an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "XmlTest"
And admin has logged in with password TAIL
When the argument string "importxml 3530 R136 ../../FTProjects/XmlFT -n
Xmlexample -a XmlTest" is passed to AcRtacCmd.exe
Then "importxml:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Import a new project named Xmlexample for a 3530 using version
R136 from xml structure without an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
When the argument string "importxml 3530 R136 ../../FTProjects/XmlFT -n
Xmlexample" is passed to AcRtacCmd.exe
Then "importxml:0:success" can be found in the output
And the error level returned is: "0"
info
Displays state information relating to an RTAC process.
Synopsis
AcRtacCmd info [-a <alias> | -i <pid>]
Remarks
ä This command prints to stdout in the following format:
|database|project|connection|
–––––––––––––––––––––––––––––
<name of connected database>:<name of open project>:<online/offline>
The database field will be NONE if no database is open.
The project field will be NONE if no project is open.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Get status of AcSELerator RTAC processes.
To allow for better recovery of AcSELerator RTAC processes, the info
command returns the status of AcSELerator RTAC process.
Scenario: Get the status of an AcSELerator RTAC process using the last
started process
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
When the argument string "info" is passed to AcRtacCmd.exe
Then "info:0:success" can be found in the output
And the error level returned is: "0"
And "RTAC:NONE:offline" can be found in the output
list
List all projects in an ACSELERATOR RTAC database.
Synopsis
AcRtacCmd list [-a <alias> | -i <pid>]
Remarks
ä This command requires being logged into the ACSELERATOR RTAC database to
work.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: List projects in AcSELerator RTAC database
The list command is used to query the AcSELerator RTAC database for
projects and show what is stored.
login
Log into the ACSELERATOR RTAC database.
Synopsis
AcRtacCmd login [options] <username>
Values
<username>
The login username of the database account.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-d, --database <database>
Name of the database to log into. Default: RTAC.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-n, --port <port>
Port number to use when connecting to a database. Default: 5433
-p, --password <password>
Login password of database. If not given, the command will attempt to read
from stdin. No prompt for a password will occur.
-s, --server <server>
IP address of server on which the database is stored. Default: localhost.
Examples
Feature: Login to AcSELerator RTAC database
After the AcSELerator RTAC worker process has started, it must
authenticate against the RTAC database before any meaningful work
can be done.
lsproc
List all RTAC processes.
Synopsis
AcRtacCmd lsproc
Remarks
ä This command will list all running RTAC.exe processes.
ä Processes without an alias will only list their process ID.
ä The list will print out in the following format:
:1255
MyRTAC:6943
...
lsproc:0:success
Examples
Feature: Get list of AcSELerator RTAC processes.
lsproc returns a list of running RTAC processes. This list contains
both the alias and PID that can be used to issue commands to a
specific RTAC.exe instance.
Scenario: Get a list of all running AcSELerator RTAC processes when one
unnamed process is running
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
When the argument string "lsproc" is passed to AcRtacCmd.exe
Then "lsproc:0:success" can be found in the output
And the error level returned is: "0"
And ":1234" can be found in the output
Scenario: Get a list of all running AcSELerator RTAC processes when one
process is running with alias "lsprocTest"
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "lsprocTest"
When the argument string "lsproc" is passed to AcRtacCmd.exe
Then "lsproc:0:success" can be found in the output
And the error level returned is: "0"
And "lsprocTest:2468" can be found in the output
open
Opens a project in ACSELERATOR RTAC database with name <name>.
Synopsis
AcRtacCmd open [-a <alias> | -i <pid>] [-j <project_password>] <name>
Remarks
ä While some commands will automatically open a project when required, it is recom-
mended to first open a project with this command if multiple commands on the same
project will be executed. This will save time by not opening and closing a project
repeatedly during command execution.
Values
<name>
The name of the project to open.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-j, --project_password <project_password>
The AcRTAC project password.
Examples
Feature: Opening and closing AcSELerator RTAC projects.
Once a process is logged into a database, the open and close commands
are used to access the projects within a database.
Scenario: Open the project 'OpenTest' with a process using the alias
'LoginTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "LoginTest"
And admin has logged in with password TAIL
And the project "OpenTest" exists as a 3530 project in the db
And the project "OpenTest" is unlocked
When the argument string "open OpenTest -a LoginTest" is passed to
AcRtacCmd.exe
Then "open:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Close the project 'OpenTest' with a process using the alias
'LoginTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "LoginTest"
And admin has logged in with password TAIL
And the project "OpenTest" exists as a 3530 project in the db
And the project "OpenTest" is unlocked
And the project "OpenTest" is open
When the argument string "close -a LoginTest" is passed to AcRtacCmd.exe
Then "close:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Open the project 'OpenTest' with the last started process
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
And admin has logged in with password TAIL
And the project "OpenTest" exists as a 3530 project in the db
And the project "OpenTest" is unlocked
When the argument string "open OpenTest" is passed to AcRtacCmd.exe
Then "open:0:success" can be found in the output
And the error level returned is: "0"
read
Reads a project into the active local database from a remote RTAC.
Synopsis
AcRtacCmd read [-a <alias> | -i <pid>] [options] <ipaddress> <username>
Remarks
ä Note that after a successful read, if the overwrite option (-o, –overwrite) is specified,
an existing project with the same name will be renamed and then deleted. If this
overwrite process fails, the existing project or the read-in project may reflect their
temporary names.
ä If the overwrite option is not specified, the name may be an incremented version of
the remote project if the project name already exists.
ä The user may also send advanced read settings (listed in Table 1.5).
Values
<ipaddress>
RTAC IPv4 address
<username>
Remote RTAC account username with which to log in.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-d, --disable
You can choose to disable your RTAC before reading to speed up read time.
Note that this is only beneficial when the device contains more than 10,000
tags.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-o, --overwrite <overwrite>
Overwrites the existing project with the same name.
-n, --name <name>
The name of the new project.
-b, --databaseport <databaseport>
The database port number.
-p, --password <password>
Login password of remote RTAC. If not given, the command will attempt to
read from stdin. No prompt for a password will occur.
Advanced Options
The following are additional settings that can be in a project:
-v, --advanced <key>
Allows specifying advanced options for reading projects. The <key> is a comma-
separated list of advanced settings shown in Table 1.5.
Examples
Feature: Reading project settings from a RTAC.
rename
Renames a project to <name>.
Synopsis
AcRtacCmd rename [-a <alias> | -i <pid>] [-n <name>] <new_name>
Remarks
ä Use the -n option to rename an unopened project.
ä This command fails if the name already exists.
Values
<new_name>
New project name.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-n, --name <name>
The name of the project to rename. This must be specified if the project is not
open.
Examples
Feature: Rename an AcRtac project
Rename is used to change the name of a project in the database.
rtacinfo
Displays information associated with an RTAC.
Synopsis
AcRtacCmd rtacinfo [-a <alias> | -i <pid>] [-p <password>] [-b <databaseport>]
<ipaddress> <username>
Remarks
ä This command requires the username and password be provided.
ä This command prints to stdout in the following format:
|project|mot|fid|status|
––––––––––––––––––––––––
<name of project>:<MOT string of RTAC>:<FID string of RTAC>:<Status
of RTAC>
Values
<ipaddress>
IP address of the remote RTAC.
<username>
username of the remote RTAC.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-p, --password <password>
Login password of remote RTAC. If not given, the command will attempt to
read from stdin. No prompt for a password will occur.
-b, --databaseport <databaseport>
The database port number.
Examples
Feature: Display information associated with an RTAC.
setpassword
Sets the password on a project.
Synopsis
AcRtacCmd setpassword [-a <alias> | -i <pid>] [-n <name>]
<project_password>
Remarks
ä This command requires the provided password conforms with the same password
requirements enforced when a password is set using the user interface.
Values
<project_password>
New password to be set for the given project.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Set the password on a project.
start
Starts a new RTAC.exe process.
Synopsis
AcRtacCmd start [-a <alias>] [-s <startup switch>] [-v]
Remarks
ä The last started process will be the active process to which all other commands will
be directed to unless otherwise specified in the command.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-v, --visual
Startup Switches
-s, --switch <startup switch>
Starts RTAC.exe with additional options. The options are given as a comma-
separated list.
Examples
Feature: Starting and stopping AcSELerator RTAC processes.
Before any work can be done using the AcRtacCmd.exe tool, an instance of
AcSELerator RTAC must be launched to do that actual work requested. This
process should be stopped after the desired work is completed so that it
does not continue to run in the background and consume computing
resources. If no alias is provided, the process can only be identified by
PID afterwards. However, a reference to the last started process is
retained, so if "stop" is issued without an alias, it will stop the last
AcSELerator RTAC worker that was started.
Scenario: Run AcRtacCmd.exe from CLI with the argument "start" and an
alias
Given AcRtacCmd is in the system path
When the command "AcRtacCmd start -a NewAcRtacProcess" is issued in a
console
Then "start:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Run AcRtacCmd from CLI to stop the started process with an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "NewAcRtacProcess"
When the command "AcRtacCmd stop -a NewAcRtacProcess" is issued in a
console
Then "stop:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Run AcRtacCmd.exe from CLI with the argument "start" but
without an alias
Given AcRtacCmd is in the system path
When the command "AcRtacCmd start" is issued in a console
Then "start:0:success" can be found in the output
And the error level returned is: "0"
And "AcRtacCmd stop" can be issued in a console to clean up
stop
Stops the last started RTAC.exe.
Synopsis
AcRtacCmd stop [-a <alias> | -i <pid>]
Remarks
Use the options below to specify which RTAC.exe to close.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Starting and stopping AcSELerator RTAC processes.
Before any work can be done using the AcRtacCmd.exe tool, an instance of
AcSELerator RTAC must be launched to do that actual work requested. This
process should be stopped after the desired work is completed so that it
does not continue to run in the background and consume computing
resources. If no alias is provided, the process can only be identified by
PID afterwards. However, a reference to the last started process is
retained, so if "stop" is issued without an alias, it will stop the last
AcSELerator RTAC worker that was started.
Scenario: Run AcRtacCmd.exe from CLI with the argument "start" and an
alias
Given AcRtacCmd is in the system path
When the command "AcRtacCmd start -a NewAcRtacProcess" is issued in a
console
Then "start:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Run AcRtacCmd from CLI to stop the started process with an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "NewAcRtacProcess"
When the command "AcRtacCmd stop -a NewAcRtacProcess" is issued in a
console
Then "stop:0:success" can be found in the output
And the error level returned is: "0"
Scenario: Run AcRtacCmd.exe from CLI with the argument "start" but
without an alias
Given AcRtacCmd is in the system path
When the command "AcRtacCmd start" is issued in a console
unlock
Unlocks a project.
Synopsis
AcRtacCmd unlock [-a <alias> | -i <pid>] <name>
Remarks
ä The user may pass ‘*’ to unlock all projects in the database, which provides a useful
testing precondition.
Values
<name>
The name of the project to unlock.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
Examples
Feature: Unlocking AcSELerator RTAC projects.
Once a project is opened, the project is locked in the AcSELerator RTAC
database. If the project was not properly closed, it will remain locked.
The unlock command allows the project to be accessed again.
upgradefirmware
Upgrades the firmware of a target device with the provided .upg or .zip firmware upgrade
file.
Synopsis
AcRtacCmd upgradefirmware [options] <ipaddress> <username> <file>
Values
<ipaddress>
RTAC IPv4 address
<username>
Remote RTAC account username to login with.
<file>
Path to firmwareupgrade file.
Options
-a, --alias <alias>
Executes command on specified RTAC.exe process with given <alias>. If not
given, executes in the last started RTAC.exe process.
-i, --pid <pid>
Same as -a but takes a process ID instead of process name.
-p, --password <password>
Login password of remote RTAC. If not given, the command will attempt to
read from stdin. No prompt for a password will occur.
-b, --databaseport <databaseport>
The database port number.
Examples
Feature: Upgrade firmware on an RTAC
Assumptions
The following must be true for this example to work:
ä The user has a working directory at C:\TestConvertExpToXml\
ä This working directory has a folder C:\TestConvertExpToXml\MyProject
ä The default database account “admin” uses the default password “TAIL”
ä The filename of the .exp file is MyProject.exp
ä The name of the project in the .exp file is “MyProject”
ä The exported file/folder system will exist within the working directory in a subfolder
\MyProject
Procedure
Step 1. Place the MyProject.exp file into the directory C:\TestConvertExpToXml\
Step 2. Start a new AcRtacCmd session by entering AcRtacCmd start -a session1
Step 3. The command will respond as follows (note that the PID may be different
than shown in this example):
Step 10. Ensure the RTAC process is stopped before completing the session as follows:
Expected Result
The project definition should now exist in the following folder: C:\TestConvertExpToXml\MyProject\
Description
LibraryExtensionInstaller.exe is a standalone executable installed as part of ACSELERATOR
RTAC in the RTAC subdirectory ./SEL/AcSELerator/RTAC, relative to the ACSELERA-
TOR RTAC installation location (by default, C:/Program Files (x86)/).
Usage
To install the extension content, call the installer and pass in the .rext file containing the
extension as an argument, as in the following command line example:
> cd /Program Files (x86)/SEL/AcSELerator/RTAC
Behavior
ä The command line application will attempt to install all .library and .compiled-
library files found in the .rext file, whether or not they are already installed in the
library repository. This means existing libraries will be overwritten.
ä Files inside the versioned folders will be added to ACSELERATOR RTAC so that they
are exposed as a new entry in the Extensions menu in the project configuration screen
the next time ACSELERATOR RTAC is launched.
ä Subfolders inside the version folder are ignored.
ä No package signing validation is done at install time.
Usage
From within the RTAC subdirectory ./SEL/AcSELerator/RTAC, the installer can be pro-
vided a folder that contains various types of packages. For example:
> cd /Program Files (x86)/SEL/AcSELerator/RTAC
> LibraryExtensionInstaller.exe C:/Users/Alice/Desktop/myExtensions
Behavior
ä Only files present at the top level of the library folder will be installed (the installer
will not search recursively for library files).
ä The installer will attempt to install all IEC 61131 CODESYS libraries (.library and
.compiled-library files), allowing those libraries to be included in projects. Any ex-
isting libraries with the same name and version will be overwritten.
ä Any .rext packages that are discovered in the root of the folder will be installed as
described in Installing AcSELerator RTAC Extension Packages on page 2.1.
Return Value
The installer will return 0 only if all extensions within the .rext file were copied, all libraries
installed successfully, and no errors were encountered during execution. Otherwise, it will
return a value of –1.
If the return value is not 0, consult the log file to obtain particular details about the error
source of failure. Such errors may include a missing or incorrect command line parameter,
libraries that failed to install due to corruption, or other exceptions.
AnalogCond
Introduction
This library contains classes that allow for simplified processing of analog quantities within
applications. Generally, measured analog quantities require filtering and checks before
being used. This library provides this filtering via encapsulated classes.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Interface Definitions
This section outlines the various interfaces defined within this library.
I_Filter
Classes implementing this interface provide a filter for analog values.
ConditionValue (Method)
This method takes inputValue as the next input for the filter and provides an output for the
new conditioned value.
Inputs
Name IEC 61131 Type Description
inputValue REAL The new raw input to the filter.
Outputs
Name IEC 61131 Type Description
conditionedValue REAL The filtered output.
Return Value
IEC 61131 Type Description
BOOL True when filter windup is complete and conditionedValue output is fully
filtered.
Reset (Method)
This method resets the filter and clears any internal state.
I_LimitedSplpf
This interface extends the I_Filter interface described in I_Filter on page 3.1, meaning that
classes implementing this interface also implement the I_Filter methods. This interface is
implemented by classes that condition analog values through a limited, single-pole, low-
pass filter (SPLPF).
Classes implementing this interface provide the following features:
ä Conditioning of the raw input through a low-pass filter controlled by a time constant
defined in the object.
ä Controlled output if the class is in Alarm. In the event that the conditioning class is
in alarm, the class provides a result which approaches a predefined default value.
ä Output bounded by the limits defined in the object.
ä An out-of-bounds alarm which asserts if the input exceeds the high limit or falls
below the low limit.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
OutOfBoundsAlarm (Method)
Provides the out-of-bounds state of the ConditionValue() input.
Return Value
IEC 61131 Type Description
BOOL Returns true if the input value is out of the boundaries specified in the
object’s constructor.
class_PassThroughFilter
This class implements a simple pass-through, where conditionedValue is set directly to
inputValue. It is meant to be used in place of a filter during testing phases of development
where it may be desirable to bypass a filtering stage.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Filter
class_ArmaFilter
This class implements an AutoRegressive Moving Average (ARMA) filter, generally used
to filter oscillating signals. This implementation provides either Infinite Impulse Response
(IIR) or Finite Impulse Response (FIR) behavior, depending on the coefficients provided.
The filter implements the form:
B(z)
H(z) = A(z)
Where:
B(z) = b0 + b1 z −1 + b2 z −2 + . . . + bN z −N
A(z) = 1 − a1 z −1 − a2 z −2 − . . . − aM z −M
Obtaining the coefficients for low-pass, high-pass, band-pass, or band-stop filters is made
relatively simple using tools like Matlab or OCTAVE, but the mathematical methods for
obtaining these values are outside the scope of this document; the user of this library should
be aware that many filter designs used to obtain coefficients for this filter can produce nu-
merical instability. See the example in section 3 for a brief discussion on how to determine
if the filter is numerically stable or not.
Once the coefficients b0 to bN and a1 to aM are determined, they are loaded as initializa-
tion inputs to the class. These coefficients must be normalized, as the leading 1 in A(z) is
assumed in this class; in other words, a0 is always assumed to be exactly 1.
Figure 3.1 shows how the filter works when three (3) coefficients for A(z) and five (5)
coefficients for B(z) are provided. Note how the depth of the filter is normalized so that there
are as many A(z) branches as there are B(z) branches. Because there is one less coefficient
in the A(z) array (when including the assumed a0 = 1) than in the B(z) coefficient array, the
coefficient of the last branch a4 is set to zero (0). In this particular example, there are five
B(z) coefficients, and because each z value is shifted in time, four previous intermediate
values must be stored in the filter. This means that the filter is not sufficiently primed
until the 5th input value is provided. For this set of coefficients, the first four calls to
ConditionValue() will yield a partially filtered output value, and the method will return
false. The 5th call of the method, and all subsequent calls, will return true.
−1 × + + + +
a1 × a2 × a3 × 0 ×
Input + Z −1 Z −1 Z −1 Z −1
b1 × b2 × b3 × b4 ×
b0 × + + + + Output
Figure 3.1 A Digital Filter Using Three (3) Coefficients for A(z) and Five (5) for B(z)
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Filter
Initialization Inputs
Name IEC 61131 Type Description
aCoefficients ARRAY [1..g_p_MaxFilterOrder] Coefficients for A(z). The coeffi-
OF REAL cients must be normalized, as the
leading 1 is assumed and should not
be entered in this array.
bCoefficients ARRAY [0..g_p_MaxFilterOrder] Coefficients for B(z).
OF REAL
numACoefficients UINT(1..g_p_MaxFilterOrder) The number of coefficients within
the aCoefficients array.
numBCoefficients UINT(1..g_p_MaxFilterOrder + 1) The number of coefficients within
the bCoefficients array.
class_ArmaFilter_LREAL
This class implements an AutoRegressive Moving Average (ARMA) filter, generally used
to filter oscillating signals. This implementation provides either Infinite Impulse Response
(IIR) or Finite Impulse Response (FIR) behavior, depending on the coefficients provided.
The filter implements the form:
B(z)
H(z) = A(z)
Where:
B(z) = b0 + b1 z −1 + b2 z −2 + . . . + bN z −N
A(z) = 1 − a1 z −1 − a2 z −2 − . . . − aM z −M
The implementation of this filter is the same as the class_ArmaFilter, class_ArmaFilter on
page 3.3, but it retains greater precision internally. This allows for greater stability.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Filter
Initialization Inputs
Name IEC 61131 Type Description
aCoefficients ARRAY [1..g_p_MaxFilterOrder] Coefficients for A(z). The coeffi-
OF LREAL cients must be normalized, as the
leading 1 is assumed and should not
be entered in this array.
bCoefficients ARRAY [0..g_p_MaxFilterOrder] Coefficients for B(z).
OF LREAL
numACoefficients UINT(1..g_p_MaxFilterOrder) The number of coefficients within
the aCoefficients array.
numBCoefficients UINT(1..g_p_MaxFilterOrder + 1) The number of coefficients within
the bCoefficients array.
class_LimitedSplpfStepToDefault
Instantiate this class when a single-pole low-pass filter that has an imposed range of accept-
able values is desired. When in alarm, this class will cause the output to step, in a single
time step, to the defaultOutput set in the constructor method for the class.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_LimitedSplpf
LimitedSplpfStepToDefault (Method)
This method acts as the constructor and must be called before the class can operate. It
initializes the characteristics of the filter.
Inputs
Name IEC 61131 Type Description
highLimit REAL The largest valid value for the input variable.
lowLimit REAL The smallest valid value for the input variable.
defaultOutput REAL The conditioned output defaults to this value if the input
is out of range or the alarm is high.
timeConstant UINT Range: 100–60000 ms. The time constant to use for the
low-pass filter within this method.
Return Value
IEC 61131 Type Description
POINTER TO STRING Return a pointer to an error message if an error occurred. Return zero
if no errors exist.
Processing
This method:
ä Sets defaultOutput as the initial output and input to the filter in order to eliminate
“wind-up” during the first few scans.
ä Returns a pointer to an error message if lowLimit exceeds highLimit.
ä Returns a pointer to an error message if defaultOutput is less than lowLimit or greater
than highLimit.
bootstrap_SetInitialValue (Method)
This method may be called at startup if the user desires a value different than the default-
Output (set previously in the constructor method call) as the initial output.
Inputs
Name IEC 61131 Type Description
initialValue REAL Range: lowLimit ≤ initialValue ≤ highLimit. Sets the ini-
tial value to be used by the filter at startup.
Return Value
IEC 61131 Type Description
POINTER TO STRING Return a pointer to an error message if an error occurred. Return zero
if no errors exist.
Processing
This method:
ä Bypasses all internal filtering and changes both the input and conditioned output to
be equal to initialValue.
ä Returns a pointer to an error message if the constructor has not been called.
ä Returns a pointer to an error message if initialValue is less than lowLimit or greater
than highLimit set in the constructor.
I_LimitedSplpf—ConditionValue
This describes the behavior of this class when the ConditionValue() method is called.
ä When the constructor has not yet been called, then this method returns false and sets
the method output conditionedValue to zero (0).
ä The time between calls is limited to a minimum of 1 ms and a maximum of 60000 ms.
This section references the limited value as timeElapsedLimited.
ä The time constant used in calculating the output value, timeConstantUsed, is limited
such that it must exceed or equal five times the elapsed time between calls of this
method, timeElapsed.
ä When the inputValue is less than lowLimit, set in the constructor, then the input is
limited to lowLimit and the out-of-bounds internal flag is set.
ä When inputValue exceeds highLimit, set in the constructor, then the input is limited
to highLimit and the out-of-bounds internal flag is set.
ä When inputValue is within the limits outlined in the constructor, the input is filtered
through a low-pass filter in order to provide the output and the out-of-bounds internal
flag is reset.
ä When all of the following conditions are met:
â inputValue is less than highLimit
â inputValue is greater than the lowLimit
â Alarm property is false
this method computes the conditionedValue output equivalent to:
((inputValue – lastConditionedValue) • 0.632 • timeConstantU
1
sed •
timeElapsedLimited) + lastConditionedValue
where:
â inputValue is the current input to ConditionValue()
â lastConditionedValue is the input to ConditionValue() from the previous
scan
â timeConstantUsed is the range limited time constant
â timeElapsedLimited is the range limited elapsed time since the last scan
ä When the input is out of range, it is limited to the corresponding range value, and
on a subsequent call where the input is within the specified range, the conditioned
output ramps to that value from the limit where it was being held.
ä When the input is in alarm, the output, input, and any internal filtering values are set
to defaultOutput. Once the alarm is removed, the input is no longer overridden and
the output value ramps to the input value through the filter, i.e., steps to defaultOutput
when in alarm and ramps from defaultOutput back to inputValue after the alarm is
removed.
class_LimitedSplpfRampToDefault
Instantiate this class when single-pole low-pass filter that has an imposed range of accept-
able values is desired. When in alarm, this class ramps the conditioned value to default-
Output, set in the constructor method, at the same rate it would any other input.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_LimitedSplpf
LimitedSplpfRampToDefault (Method)
This method acts as the constructor and must be called before the class can operate. It
initializes the characteristics of the filter.
Inputs
Name IEC 61131 Type Description
highLimit REAL The largest valid value for the input variable.
lowLimit REAL The smallest valid value for the input variable.
defaultOutput REAL The conditioned output defaults to this value if the input
is out of range or the alarm is high.
timeConstant UINT Range: 100–60000 ms. The time constant to use for the
low-pass filter within this method.
Return Value
IEC 61131 Type Description
POINTER TO STRING Return a pointer to an error message if an error occurred. Return zero
if no errors exist.
Processing
This method:
ä Sets defaultOutput as the initial output and input to the filter in order to eliminate
“wind-up” during the first few scans.
ä Returns a pointer to an error message if lowLimit exceeds highLimit.
ä Returns a pointer to an error message if defaultOutput is less than lowLimit or greater
than highLimit.
bootstrap_SetInitialValue (Method)
This method may be called at startup if something other than the defaultOutput (set previ-
ously in the constructor method call) is desired as the initial value by the user.
Inputs
Name IEC 61131 Type Description
initialValue REAL Range: lowLimit ≤ initialValue ≤ highLimit. Sets the ini-
tial value to be used by the filter at startup.
Return Value
IEC 61131 Type Description
POINTER TO STRING Return a pointer to an error message if an error occurred. Return zero
if no errors exist.
Processing
This method:
ä Bypasses all internal filtering and changes both the input and conditioned output to
be equal to initialValue.
ä Returns a pointer to an error message if the constructor has not been called.
ä Returns a pointer to an error message if initialValue is less than lowLimit or greater
than highLimit set in the constructor.
I_LimitedSplpf—ConditionValue
This describes the behavior of this class when the ConditionValue() method is called.
ä When the constructor has not yet been called, then this method returns false and sets
the method output conditionedValue to zero (0).
ä The time between calls is limited to a minimum of 1 ms and a maximum of 60000 ms.
This section references the limited value as timeElapsedLimited.
ä The time constant used in calculating the output value, timeConstantUsed, is limited
such that it must exceed or equal five times the elapsed time between calls of this
method, timeElapsed.
ä When the inputValue is less than lowLimit, set in the constructor, then the input is
limited to lowLimit and the out-of-bounds internal flag is set.
ä When inputValue exceeds highLimit, set in the constructor, then the input is limited
to highLimit and the out-of-bounds internal flag is set.
ä When inputValue is within the limits outlined in the constructor, the input is filtered
through a low-pass filter in order to provide the output and the out-of-bounds internal
flag is reset.
ä When all of the following conditions are met:
â inputValue is less than highLimit
â inputValue is greater than the lowLimit
â Alarm property is false
this method computes the conditionedValue output equivalent to:
((inputValue – lastConditionedValue) • 0.632 • timeConstantU
1
sed •
timeElapsedLimited) + lastConditionedValue
where:
â inputValue is the current input to ConditionValue()
â lastConditionedValue is the input to ConditionValue() from the previous
scan
â timeConstantUsed is the range limited time constant
â timeElapsedLimited is the range limited elapsed time since the last scan
ä When the input is out of range, it is limited to the corresponding range value, and
on a subsequent call where the input is within the specified range, the conditioned
output ramps to that value from the limit where it was being held.
ä When the input is in alarm, the input is overridden and set to defaultOutput. This
allows the output value to ramp to defaultOutput through the filter. Once the alarm
is removed, the input is no longer overridden and the output value ramps to the input
value through the filter, i.e., ramps to defaultOutput through the filter when in alarm
and ramps from defaultOutput back to inputValue after the alarm is removed.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms:
ä SEL-3530
â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware
ä SEL-3505
â R134 firmware
class_LimitedSplpfStepToDefault—ConditionValue
The posted time is the average execution time of 100 consecutive calls.
class_LimitedSplpfRampToDefault—ConditionValue
The posted time is the average execution time of 100 consecutive calls.
class_ArmaFilter—ConditionValue
The posted time is the average execution time of 100 consecutive calls.
class_ArmaFilter_LREAL—ConditionValue
The posted time is the average execution time of 100 consecutive calls.
class_PassThroughFilter—ConditionValue
The posted time is the average execution time of 100 consecutive calls.
Benchmark Results
ConditionValue Timing Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
class_LimitedSplpfStepToDefault 15 11 2
class_LimitedSplpfRampToDefault 17 5 1
class_ArmaFilter 1 1 1
class_ArmaFilter_LREAL 1 1 1
class_PassThroughFilter 1 1 1
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
When this code is executed, the filteredValue will start at zero and move towards the input
value of 75 with each time step, according to the filter and time constant. After 100 time
steps, the output steps directly to the default value of 50 because the Alarm property was
set. Figure 3.2 shows an example of the filtered output plotted against time, where each
step is 100 ms.
When this code is executed, the filteredValue will start at zero and move towards the input
value of 75 with each time step, according to the filter and time constant. After 100 time
steps, the output ramps to the default value of 50 because the Alarm property was set.
Figure 3.3 shows an example of the filtered output plotted against time, where each step is
100 ms.
Objective
An oscillating signal can be run through a low-pass filter to remove high-frequency noise,
leaving only the lower frequency signals of interest.
Assumptions
The signal provided to the filter is generated in IEC 61131 code by adding a high-frequency
component, a low-frequency component, and a mid-frequency component. This signal is
then sent through an ARMA filter, with coefficients set using the Butterworth method to
remove the high-frequency component, leaving the mid- and low-range frequencies.
The signal sent to the filter is comprised using the following equations:
Solution
Coefficients for a Butterworth low-pass filter(http://octave.sourceforge.net/ signal/function/but-
ter.html), which will filter out the high-frequency noise with a filter depth of three (3), are
determined using OCTAVE (http://octave-online.net/), by entering the equation defined in
Code Snippet 3.3.
B =
4.1655 e -04 1.2496 e -03 1.2496 e -03 4.1655 e -04
A =
1.00000 -2.68616 2.41966 -0.73017
The number of coefficients required for a low-pass filter with depth three (3) is four (4),
so the global parameter g_p_MaxFilterOrder must be set to three (3) or greater, allowing
coefficients 0–3 to be provided.
This Butterworth filter is shown to be stable by checking that the roots of the A coefficients
have an absolute value less than 1. This can be done using the OCTAVE code shown in NOTE: An unstable filter will not
cause the filter to crash, but it will
Code Snippet 3.4. cause the filtered output to become
Infinity. Because of the way the ARMA
Code Snippet 3.4 OCTAVE Code to Check Stability of Filter model is constructed, the next output
after infinity is reached will be NaN
octave :1 > abs ( roots ([1.00000 -2.68616 2.41966 -0.73017]) ) (Not a Number). Once this happens,
ans = all future outputs of the filter will be
NaN until the filter is reset.
0.92455
0.92455
0.85420
The program shown in Code Snippet 3.5 generates the signals, passes the sum of these
signals into the low-pass filter, and provides the outputs into an array.
When this code is executed, the low-pass filter removes the high-frequency components
imposed on the samples, leaving the desired Sample2n and Sample3n low-frequency
components alone.
The plot in Figure 3.4 shows the three waveforms added together and the result of the filter.
The resulting wave is shifted in time; this time delay is expected from a filter.
Figure 3.4 Plot of Total Signal and Filtered Output of the Low-Pass Filter
ChannelMonitoring
Introduction
This library provides function blocks for performing data channel processing and supervi-
sion. The function blocks provide an alert that some aspect of a channel or indicator has
deviated from the parameters defined by the user. Example applications include detecting
maintenance conditions in a 3-phase CT/PT, alerting on an IED hardware failure, moni-
toring transformer through-fault current, or detecting protection communication channel
failures.
The fb_MultiChannelAlert, fb_ChannelAlert, and fb_IndicatorAlert blocks focus on chan-
nel supervision. Each adheres to the same principles of operation. An alert is generated
when a sustained excursion occurs or when repeated excursions are detected. An excursion
is defined as a channel, indicator, or function block output exceeding the threshold limit.
For function blocks that accept a Boolean data type input, an excursion begins with a tran-
sition from a FALSE to TRUE state. For function blocks that accept measured values (MV)
or REAL data type inputs, the absolute difference is calculated between the instantaneous
values of two channels or a channel and a reference value. An excursion in this context
is when the absolute difference exceeds a threshold value. The excursion time is used to
define when an alert occurs. If a single excursion is sustained for a length of time defined
by the excursion time, an alert is generated (Figure 4.1 and Figure 4.2). If multiple excur-
sions are detected equal to the chatter count within the excursion time, an alert is generated
(Figure 4.3 and Figure 4.4).
Each function block can be used to provide simple alerting or can be combined into more
complex monitoring schemes.
Figure 4.2 An Excursion Defined by the Indicator Equaling a TRUE Value for the
Excursion Time Generates an Alert
Figure 4.3 Multiple Excursions Defined by the Absolute Channel Difference Equaling
or Exceeding the Threshold Value Within the Excursion Time Generates
an Alert (Chatter Count = 3)
Figure 4.4 Multiple Excursion Defined by the Indicator Equaling a TRUE Value Within
the Excursion Time Generates an Alert (Chatter Count = 3)
Special Considerations
ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myfb_MultiChannelAlertObject.value;
// As is this
pt_myfb_MultiChannelAlertObject :=
ADR(myfb_MultiChannelAlertObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_AlertType
This enumeration defines the type of events returned by the function block status output.
This enumeration can be used interchangeably with DINT data types.
enum_ChannelAlert
This enumeration is used to define the channels responsible for a status alert and/or quality
alert. This enumeration can be used interchangeably with DINT data types.
Functions
fun_GetAlertString
This function takes the status returned by the function blocks in this library as an input and
returns a string value that can be used for logging.
Inputs
Name IEC 61131 Type Description
alert enum_AlertType Function block status value
Return Value
IEC 61131 Type Description
STRING Value matching the enum_AlertType
Processing
ä If the status is valid, the function returns a string corresponding to the enum_Alert-
Type.
ä If the supplied status is not valid, the function returns Invalid Input.
fun_GetChannelString
This function takes as an input the alert returned by the fb_MultiChannel function block
and returns a string value that can be used for logging.
Inputs
Name IEC 61131 Type Description
status enum_ChannelAlert Function block alert value
Return Value
IEC 61131 Type Description
STRING String value matching the enum_ChannelAlert
Processing
ä If status is valid, the function returns a string corresponding to the enum_Chan-
nelAlert.
ä If the supplied status is not valid, the function returns Invalid Input.
Function Blocks
fb_MultiChannelAlert
Compare two to three measured value (MV) tags to determine if one or more channels
deviate outside a threshold value for a time period or if repeated deviations occur within a
time period. This function block requires a minimum of two input channels.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable the function block
Channel_1 MV Data to monitor
Channel_2 MV Data to monitor
Channel_3 MV Data to monitor
ExcursionThreshold REAL Limit at which a deviation is detected
ChatterCount UDINT Number of deviations allowed within a time period
defined by the ExcursionTime
ExcursionTime TIME Maximum time a sustained deviation is allowed
LatchAlarm BOOL Defaults to true. If true, Alert will stay asserted
until Reset is asserted.
Reset BOOL Reset function block to default conditions
Outputs
Name IEC 61131 Type Description
ENO BOOL Indication that the function block is enabled
Alert SPS Alert condition and associated metadata
Status enum_AlertType Enumeration describing the function block state
ChannelStatus enum_ChannelAlert Enumeration describing the channels that generated the
status alert
QualityAlert BOOL Channel quality alert
QualityStatus enum_ChannelAlert Enumeration describing the channels that generated the
quality alert
Processing
ä ChatterCount, ExcursionTime, and LatchAlarm are set the first time the function
block is called. They cannot be altered after that time.
ä On a rising edge of ENO, the tracked chatter count and excursion time are reset to
zero.
ä Disabling the function block by setting EN to FALSE does not clear the function
block Alert.
ä When ENO is FALSE or Reset is TRUE, the Alert SPS quality reports as invalid.
ä The function block adheres to the following processing if ENO is TRUE.
ä Good channel quality is required for input processing. This is determined by the
input channel validity_t structure, i.e., AnalogQuantity.q.validity = good.
ä If a channel has bad quality, it is excluded from the excursion calculations and a
QualityAlert is generated.
ä Compare the instantaneous values of the input channels to determine if any channel
deviates from any other available channel.
ä If a QualityAlert is generated, the QualityStatus reports the offending channels as
described in enum_ChannelAlert.
ä If the minimum number of channels do not have good quality, Status is BAD_QUAL-
ITY as defined in the enum_AlertType.
ä If a channel deviates by more than ExcursionThreshold from any other channel for a
sustained period given by ExcursionTime, an Alert is generated.
ä If a channel repeatedly deviates by more than ExcursionThreshold from any other
channel and the number of deviations exceeds ChatterCount within a period given
by ExcursionTime, an Alert is generated.
ä If Alert is asserted, Status identifies the cause of the alert as described in enum_-
AlertType.
ä If an Alert is generated, ChannelStatus identifies the offending channels as described
in enum_ChannelAlert.
ä IF LatchAlarm is TRUE the outputs are fixed when an alert condition is detected and
will be held constant until a Reset is issued.
ä If Reset is asserted, the function block does not process any inputs and Status is
RESET as defined in enum_AlertType.
ä A falling edge of Reset returns the function block to a default state.
fb_ChannelAlert
Compare one measured value (MV) tag against a reference value to determine if the channel
deviates outside a threshold value for a time period or if repeated deviations occur within
a time period.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable the function block
Channel MV Data to monitor
ChannelReference REAL Channel reference value
ExcursionThreshold REAL Limit at which a deviation is detected
ChatterCount UDINT Number of deviations allowed within a time period
defined by the ExcursionTime
ExcursionTime TIME Maximum time a sustained deviation is allowed
LatchAlarm BOOL Defaults to true. If true, Alert will stay asserted
until Reset is asserted
Reset BOOL Reset function block to default conditions
Outputs
Name IEC 61131 Type Description
ENO BOOL Indication that the function block is enabled
Alert SPS Alert condition and associated metadata
Status enum_AlertType Enumeration describing the function block state
QualityAlert BOOL Channel quality alert
Processing
ä ChatterCount, ExcursionTime, and LatchAlarm are set the first time the function
block is called. They cannot be altered after that time.
ä On a rising edge of ENO, the tracked chatter count and excursion time are reset to
zero.
ä Disabling the function block by setting EN to FALSE does not clear the function
block Alert.
ä When ENO is FALSE or Reset is TRUE, the Alert SPS quality is invalid.
ä The function block adheres to the following processing if ENO is TRUE.
ä Good channel quality is required for input processing. This is determined by the
input channel validity_t structure, i.e., AnalogQuantity.q.validity = good.
ä If Channel has bad quality, no excursion calculation occurs and QualityAlert is as-
serted.
ä Compare the instantaneous values of Channel and ChannelReference to determine
if an excursion occurred.
ä If QualityAlert is asserted, Status is BAD_QUALITY, as defined in the enum_Alert-
Type.
ä If Channel deviates by more than ExcursionThreshold from the reference for a sus-
tained period given by ExcursionTime, an Alert is generated.
ä If Channel repeatedly deviates from the reference by more than ExcursionThresh-
old and the number of deviations exceeds ChatterCount within a period given by
ExcursionTime, an Alert is generated.
ä If Alert is asserted, Status identifies the cause of the alert as described in enum_-
AlertType.
ä IF LatchAlarm is TRUE the outputs are fixed when an alert condition is detected and
will be held constant until a Reset is issued.
ä If Reset is asserted, the function block does not process any inputs and Status is
RESET as defined in enum_AlertType.
ä A falling edge of Reset returns the function block to a default state.
fb_IndicatorAlert
Monitors one Boolean value for a sustained or chattering TRUE value.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable the function block
Indicator BOOL Data to monitor
ChatterCount UDINT Number of deviations allowed within a time period de-
fined by ExcursionTime
ExcursionTime TIME Maximum time a sustained deviation is allowed
Reset BOOL Reset function block to default conditions
Outputs
Name IEC 61131 Type Description
ENO BOOL Indication that the function block is enabled
Alert SPS Alert condition and associated metadata
Status enum_AlertType Enumeration describing the function block state
Processing
ä ChatterCount and ExcursionTime are set the first time the function block is called.
They cannot be altered after that time.
ä On a rising edge of ENO, the tracked chatter count and excursion time are reset to
zero.
ä Disabling the function block by setting EN to FALSE does not clear the function
block Alert.
ä When ENO is FALSE or Reset is TRUE and an alert condition is not detected, the
Alert SPS quality is invalid.
ä The function block adheres to the following processing if ENO is TRUE.
ä Monitor Indicator for a TRUE value.
ä If Indicator is TRUE for a sustained period given by ExcursionTime, an alert is gen-
erated.
ä If Indicator repeatedly switches between FALSE and TRUE and the number of de-
viations exceed ChatterCount within a period given by ExcursionTime, an Alert is
generated.
ä If Alert is asserted, Status identifies the cause of the alert as described in enum_-
AlertType.
ä Once an Alert is generated, the function block maintains its state at the time of the
alert until issued a reset.
ä If Reset is asserted, the function block does not process any inputs and Status is
RESET as defined in enum_AlertType.
ä A falling edge of Reset returns the function block to a default state.
fb_ChannelDerivative
Calculates the time derivative (rate of change) of a channel using finite difference approx-
imation and alerts upon excursion beyond a user-settable threshold.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable the function block
Reset BOOL Reset the function block to a default state
Channel MV Input signal to differentiate
DerivativeThreshold REAL Threshold, over which the absolute value of
Derivative will assert Alert. Must be greater than
or equal to 0.
PeriodicProcessing BOOL Set to TRUE to process Channel on a fixed inter-
val. Set to FALSE to process Channel based on
changes in the Channel time stamp.
Period TIME Channel evaluation period when
PeriodicProcessing = TRUE. Should be
greater than or equal to, and equally divisible by
the RTAC task time.
FilterLength INT The number of calculated derivatives to be aver-
aged in order to update the Derivative output. Can
be any odd integer between 1 and 21.
Outputs
Name IEC 61131 Type Description
ENO BOOL Indication that the function block is enabled
Alert SPS Indication of derivative excursion beyond
threshold
Status enum_AlertType Enumeration describing the function block
state
QualityAlert BOOL Channel quality alert
Derivative MV Average derivative of Channel over
ConditionedFilterLength + 1 Channel
samples
ConditionedFilterLength INT Adjusted FilterLength to ensure the filter
length used is an odd number bounded by 1
and 21.
Processing
ä The Derivative output is given in units of X per second where X is the units of the
Channel.instMag input.
ä PeriodicProcessing and FilterLength are set the first time the function block is called,
regardless of the state of the EN input. They cannot be altered after that time.
ä ENO is true when EN = TRUE and the function block initialization is completed
successfully.
ä Successful function block initialization is dependent on user input validation. If the
function block fails to initialize, Status is set to ERROR.
ä If DerivativeThreshold represents a floating point value of NAN, Inf, or -Inf when
the function block is first called, the function block fails to initialize.
ä Disabling the function block by setting EN to FALSE does not clear the Alert func-
tion block output variable.
ä While the Reset input is asserted, all internal variables and outputs are set to a default
value. The Status output is set to RESET.
ä When EN is FALSE or Reset is TRUE, the Alert SPS quality is invalid.
ä If the State output equals EXCURSION, Channel is not processed. The outputs are
held at their current state until a rising edge of the Reset input is detected.
ä The FilterLength input is evaluated against the requirements specified in the Inputs
table. If FilterLength does not conform to the requirements, ConditionedFilter-
Length becomes a bounded version of FilterLength and is used for processing the
Channel input.
ä For PeriodicProcessing = FALSE, Channel processing is triggered by changes
in the Channel.t.value time stamp. For this mode, the incremental derivative is
defined as the change in Channel.instMag divided by the change in the Chan-
nel.t.value time stamp between the current Channel sample (k) and previously pro-
cessed Channel sample (k - 1). The incremental derivative is assigned a time stamp
equal to the k sample t.value time stamp. This mode can be useful for real-time
streaming data sources such as IEEE C37.118 synchrophasors or off-line processing
of data sets containing time-stamped samples.
fb_ChannelIntegral
Calculates the area under the input channel magnitude and above a user-defined integration
bound using trapezoidal approximation between samples.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable the function block
Reset BOOL Reset the function block to default conditions
Channel MV Signal to integrate
SetPoint REAL Channel threshold used to initiate integration.
PeriodicProcessing BOOL Set to TRUE to process Channel on a fixed interval.
Set to FALSE to process Channel based on changes
in the Channel time stamp.
Period TIME Channel evaluation period when
PeriodicProcessing = TRUE. Should be
greater than or equal to, and equally divisible by
the RTAC task time.
LowerBound REAL Lower bound used in calculation of Integral. Must
be less than or equal to SetPoint.
DebounceTime TIME Time required for channel to be above or below Set-
Point in order for the associated SetPoint excursion
time to be considered the beginning or end of an
integration period.
Outputs
Name IEC 61131 Type Description
ENO BOOL Indication that the function block is enabled
Alert SPS Indication of a completed integration period
Status enum_AlertType Enumeration describing the function block state
QualityAlert BOOL Asserts when channel quality is bad or integral out-
put accuracy is suspect
ExcursionTimeOn dateTime_t Time stamp marking the start of an integration pe-
riod
ExcursionTimeOff dateTime_t Time stamp marking the end of an integration period
Integral MV The integral of Channel below Channel.instMag
and above LowerBound, bounded by Excursion-
TimeOn and ExcursionTimeOff
Peak MV Peak value of Channel between ExcursionTimeOn
and ExcursionTimeOff
Processing
ä The Integral output is given in units of X*seconds where X is the units of the Chan-
nel.instMag input.
ä Period and PeriodicProcessing are set the first time the function block is called,
regardless of the state of the EN input. They cannot be altered after that time.
ä ENO is true when EN = TRUE and the function block initialization is completed
successfully.
ä Successful function block initialization is dependent on user input validation. If the
function block fails to initialize, Status is set to ERROR.
ä If any of the following conditions are true during the first call of the function block,
the function block fails to initialize.
1. SetPoint represents a floating point value of NAN, Inf, or -Inf.
2. LowerBound represents a floating point value of NAN, Inf, or -Inf or is a
defined number greater than SetPoint.
3. PeriodicProcessing = TRUE and Period is less than or equal to zero.
4. DebounceTime is less than zero.
ä All inputs other than Period and PeriodicProcessing can be modified during run-
time. However, SetPoint, LowerBound, and DebounceTime are held static while
State = EXCURSION or EXPIRATION. While not held static, these inputs shall
be validated against the previously stated conditions.
ä While Channel.instMag represents a floating point value of NAN, Inf, or -Inf or
any variable input is deemed invalid, the Status is set to ERROR. The cached k - 1
sample is not updated.
ä Deasserting EN during integration will pause integration calculations. Outputs will
retain their state and the cached k - 1 sample will be discarded. Re-asserting EN
will resume integration using newly received data.
ä While Reset is TRUE, Alert.q.validity, Integral.q.validity, and
Peak.q.validity are set to invalid.
ä While the Reset input is asserted, all outputs are reset to default values. The Status
output is set to RESET. A falling edge of the Reset input returns Status to NO_-
DEVIATION.
ä While Alert.stVal = TRUE and Status is COMPLETE, the function block halts
data processing. Outputs are frozen until Reset is asserted.
ä The function block adheres to the following processing if ENO is TRUE and Status
is not COMPLETE.
ä For PeriodicProcessing = FALSE, Channel processing is triggered by changes
in the Channel.t.value time stamp. This mode can be useful for real-time streaming
data sources such as IEEE C37.118 synchrophasors or off-line processing of data
sets containing time-stamped samples.
ä For PeriodicProcessing = TRUE, the Channel state is evaluated periodically at
the interval specified by the Period input. The timer runs while EN = TRUE AND
Reset = FALSE. In this mode, the input Channel is assigned time stamps from the
RTAC system clock. This mode can be useful for real-time processing of deadbanded
data sources where no time-stamp update is meant to be interpreted as a repeated
value. When PeriodicProcessing = TRUE, the applied Period setting should be
greater than and equally divisible by the RTAC task time.
ä The incremental update to the Integral output is defined as the area of the trapezoid
bound by the following two points and the line defined by LowerBound:
â Channel.instMag at Channel.t time for the most recently processed sample
(k).
Z t=ExcursionT imeOf f
Integral.instM ag ≈ (ChannelP rocess(t) − LowerBound) dt
t=ExcursionT imeOn
(Equation 4.1)
where ChannelProcess(t) is the physical process being measured and represented by
Channel.instMag measurements.
ä The function block updates the Integral output continuously during the integration
period. This enables external evaluation the current integral result against an auxil-
iary excursion threshold.
ä The Peak output contains the magnitude, quality and time-stamp information from
the Channel sample in which Channel.instMag was at a maximum value over the
integration period. For repeated maximums, the most recent maximum Channel
value is applied to Peak.
ä During integration, the Integral output is assigned a quality that represents the lowest
quality indicators of all Channel samples used in the integration calculation.
ä If the Integral.q.validity does not equal good then the output QualityAlert is
asserted.
ä If Channel.instMag is already in excess of SetPoint when EN is asserted or after
a manual reset, ExcursionTimeOn is assigned the time stamp of the first processed
Channel sample. This time stamp is not expected to represent the approximate time
of SetPoint crossing. In this instance, the output QualityAlert is asserted.
fb_IndicatorTimeDelta
Monitors the time-stamp difference between the assertions of two Single Point Status (SPS)
indicators and alerts upon time-difference excursion beyond a user-defined threshold.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable the function block
Reset BOOL Reset the function block to default conditions
Indicator1 SPS Indicator anticipated to assert first
Indicator2 SPS Indicator anticipated to assert second
TimeDiffThreshold REAL Absolute time-stamp difference at which alert con-
dition is triggered. Must be greater than 0. Units
are in seconds.
WaitTime TIME Maximum time allowed between indicator .stVal
assertions before internal variables are cleared.
Must be greater than TimeDiffThreshold.
Outputs
Name IEC 61131 Type Description
ENO BOOL Indication that the function block is enabled
Alert SPS Indication that the calculated TimeDifference has ex-
ceeded TimeDiffThreshold
QualityAlert BOOL Indicator quality alert
TimeDifference REAL Signed time-stamp difference: Indicator2.t.value
minus Indicator1.t.value. Units are in seconds
Status enum_AlertType Enumeration describing the function block state
Processing
ä TimeDiffThreshold and WaitTime inputs are held static on the first task cycle. There-
fore, they cannot be changed during runtime.
ä ENO is true when EN = TRUE and the function block initialization is completed
successfully.
ä Successful function block initialization is dependent on user input validation. If the
function block fails to initialize, Status is set to ERROR.
ä If any of the following conditions are true during the first call of the function block,
the function block fails to initialize.
1. WaitTime is less than TimeDiffThreshold.
2. TimediffThreshold is less than zero seconds.
ä The function block can be reset either from a user asserted RESET or an internal
reset because of the expiration of WaitPeriod. If reset, outputs return to a default
state. Outputs are held in this state while RESET is TRUE.
ä Disabling the function block by setting EN to FALSE does not clear the function
block Alert.
ä When ENO is FALSE or Reset is TRUE, the Alert SPS quality is set to invalid.
ä The function block adheres to the following processing if ENO is TRUE.
ä Good Indicator quality is required for input processing. This is determined by the
input indicator validity_t structure, i.e., SPS.q.validity = good.
ä If either input indicator has bad quality, processing is halted, QualityAlert is asserted,
Status is set to BAD_QUALITY, and Alert.q.validity is set to invalid. Note that
this does not trigger a reset, nor does it require a reset to clear.
ä If Status is EXPIRATION, input processing stops until a user-initiated RESET is
executed.
ä The WaitPeriod timer is initiated by the rising edge of Indicator1.stVal or Indicator2.stVal
while the other indicator’s .stVal is deasserted.
ä If the WaitPeriod timer expires before the remaining indicator .stVal asserts, a reset
is initiated and the function block returns to normal operation.
ä If the remaining indicator .stVal asserts before the WaitPeriod timer has elapsed,
the signed time difference between the input indicators is calculated and assigned to
TimeDifference.
ä TimeDifference is defined as Indicator2.t.value minus Indicator1.t.value,
where each respective time stamp is recorded at the rising edge of the indicators’
.stVal.
ä The TimeDifference output is accurate to within plus or minus 500 microseconds.
ä If Indicator2.stVal asserts before Indicator1.stVal, the output TimeDiffer-
ence represents a negative time difference.
ä If ABS(TimeDifference) > TimeDiffThreshold, Alert.stVal asserts and Alert.t
is set equal to the RTAC system time.
ä If Alert.stVal is TRUE, Status is set to EXPIRATION.
Classes
class_TimeAlignment (Class)
This class implements a relative time-alignment algorithm in the RTAC logic engine for
the purpose of grouping measurements from various data sources by time stamp. This
guarantees time-coherence of data that are passed on to subsequent user logic.
Time alignment groups channel samples based on two qualifiers:
1. Time of Arrival. Time alignment employs a wait window, allowing samples with
similar time stamps to arrive at the RTAC at different times. Relative time alignment
dictates that a wait window for a given time stamp opens upon the receipt of the first
sample with that time stamp. A time-aligned data set is made available when all
expected data arrive within the wait window or if the wait time reaches the user-
settable maximum.
2. Time Stamp Value. Time alignment employs time-stamp rounding to group time
stamps whose values differ by less than a defined amount.
Figure 4.5 depicts a relative time alignment scenario where samples with matching time
stamps arrive within the wait window.
Figure 4.6 depicts a relative time alignment scenario where most samples with matching
time stamps arrive within the wait window and one sample with the matching time stamp
arrives after the window has closed.
This time alignment implementation includes the following guarantees and limitations: NOTE: For additional information
on time alignment, see IEEE
ä Output channels are updated with a data set whose original sample time stamps vary C37.247-2019, Standard for Phasor
from each other by no more than 1/MaximumRate. Data Concentrators for Power
Systems—Section 4.1 and Annexes D,
E, and F.
ä Output channels are updated with a data set whose original samples were received
at the RTAC within MaximumWaitTime from the receipt of the first received sample
for that set.
ä Output channels share the same time stamp and consecutive output time stamp up-
dates differ by no less than 1 / MaximumRate.
ä A maximum of 8000 individual tags can be time-aligned per instance of class_-
TimeAlignment.
This class should be operated via the following sequence:
1. Call the BootstrapChannelSet methods to specify the input channels and corre-
sponding output channels.
2. Once all desired channel sets have been bootstrapped, call Run() as frequently or
faster than the input channel update rate.
3. Call GetDataSet() while NumDataSetsAvailable is greater than zero to update
output channels.
Inputs
Name IEC 61131 Type Description
MaximumRate UDINT (1–24000) Samples/second: Maximum time alignment rate.
MaximumWaitTime UDINT (4–5000) Milliseconds: The amount of time that the class
waits to receive all expected samples for a given
time stamp. Values less than the task cycle time
are rounded up to the task cycle time.
Outputs
Name IEC 61131 Type Description
NumDataSetsAvailable UDINT The number of available time-aligned data sets.
Error BOOL Indicates an internal error.
ErrorMessage STRING(255) Description of the current error state.
BootstrapChannelSet_MV (Method)
This method adds an input/output set of MV channels for monitoring and updating respec-
tively.
Inputs/Outputs
Name IEC 61131 Type Description
InputChannel MV The input channel.
OutputChannel MV The output channel.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after the first call to Run()
ä Returns FALSE if the maximum bootstrapped tag limit (8000) has been reached.
BootstrapChannelSet_CMV (Method)
This method adds an input/output set of CMV channels for monitoring and updating re-
spectively.
Inputs/Outputs
Name IEC 61131 Type Description
InputChannel CMV The input channel.
OutputChannel CMV The output channel.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after the first call to Run().
ä Returns FALSE if the maximum bootstrapped tag limit (8000) has been reached.
BootstrapChannelSet_INS (Method)
This method adds an input/output set of INS channels for monitoring and updating respec-
tively.
Inputs/Outputs
Name IEC 61131 Type Description
InputChannel INS The input channel.
OutputChannel INS The output channel.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after the first call to Run().
ä Returns FALSE if the maximum bootstrapped tag limit (8000) has been reached.
BootstrapChannelSet_SPS (Method)
This method adds an input/output set of SPS channels for monitoring and updating respec-
tively.
Inputs/Outputs
Name IEC 61131 Type Description
InputChannel SPS The input channel.
OutputChannel SPS The output channel.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after the first call to Run().
ä Returns FALSE if the maximum bootstrapped tag limit (8000) has been reached.
Run (Method)
Call this method once per scan, or faster, after completing all necessary calls to the Boot-
strapChannel methods.
Processing
Input Validation and General Processing
ä The first call to Run() validates and locks the MaximumRate, MaximumWaitTime,
inputs to the current value.
ä After the first call to Run(), any calls to the BootstrapChannel methods are ignored.
ä If Run() is called before any calls to the BootstrapChannel methods, Error is as-
serted and ErrorMessage indicates a failure to initialize.
ä If any user input does not conform to the specified limits, Error is asserted and
ErrorMessage indicates the invalid input.
ä Processing is halted while Error is true.
ä While Error is true, ErrorMessage provides additional information about current
error condition. Otherwise, ErrorMessage is empty.
ä Input channels are monitored for changes in time stamp. Changes in data value are
ignored if not accompanied by a time stamp change.
General Time Alignment
ä Under ideal conditions, time alignment receives one sample from each input channel
per time stamp.
ä The receipt of a qualifying time stamp opens a time-alignment wait window. A quali-
fying time stamp is generally greater than the time stamp of the most recently opened
wait window by at least 1 / MaximumRate. See Typical Scenarios and Expected
Output for exceptions.
ä A wait window remains open for a duration no greater than MaximumWaitTime to
receive an expected sample from each input channel, starting with the arrival time
of the first sample with that time stamp.
ä An “expected sample” for a given wait window contains a time stamp that is within
plus or minus 0.5 / MaximumRate from the wait window time stamp.
ä If multiple samples from a single channel contain time stamps that are eligible for
inclusion in an active wait window, the most recently received sample is used.
ä A given wait window closes when expected samples from all input channels are
received or when the wait time equals MaximumWaitTime.
ä NumDataSetsAvailable increments by one or more when the wait window with
the oldest time stamp closes.
ä If a wait window closes before all expected samples are received, the .q.validity at-
tribute of the missing channels within the time aligned data set are set to invalid and
the channel value is set equal to the following:
1. REAL : 0.000
2. DINT : 0
3. BOOL : FALSE
ä Sample time stamp quality is passed from input to output channel without modifica-
tion.
ä Samples from a given channel that are received out of order (in regard to the time
stamp values) will not result in out-of-order time-aligned output updates.
ä The number of cached time aligned data sets represented by NumDataSetsAvailable,
will not exceed 2*(MaximumWaitTime/1000)*MaximumRate. If NumDataSetsAvailable
equals this number, the oldest cached data sets are discarded when new data sets are
made available.
ä MaximumRate defines the minimum time stamp difference between consecutive out-
put channel updates. This setting can be useful when up- or down-scaling input
channel rates to a desired rate.
Typical Scenarios and Expected Output
ä Ideal: A sample for each channel arrives with the same time stamp at the same time
or at slightly different times within the wait window. The NumDataSetsAvailable
output is incremented and the resulting data set contains no missing data indicators.
ä Some Late Data: A sample for each channel arrives with the same time stamp,
but one or more arrive after the wait time has reached MaximumWaitTime. The
NumDataSetsAvailable output is incremented and the resultant data set contains
missing data indicators for the late data.
ä No Data: If no data arrive for any channel, no work is done and the outputs will not
update.
ä A Majority of Channels Undergo a Large Jump Forward or Backward in Time Stamp:
Starting with the ideal case, if a simple majority of channels jump forward or back-
ward in time stamp (within the same task cycle) by an amount that is more than two
times the greater of 1 / MaximumRate or MaximumWaitTime (typically due to a
clock shift resulting from a settings change or reset), output data sets contain some
missing data indicators for the majority group until all wait windows from the old
time reference are closed. At that point, the output data sets contain missing data
indicators for all minority group channels until the time stamps of the two groups
reconverge.
ä A Minority of Channels Undergo a Large Jump Forward or Backward in Time Stamp:
Starting with the ideal case, if a simple minority of channels jump forward or back-
ward in time stamp (within the same task cycle) by an amount that is more than two
times the greater of 1 / MaximumRate or MaximumWaitTime (typically due to a
clock shift resulting from a settings change or reset), output data sets contain miss-
ing data indicators for the minority channel group until the time stamps of the two
groups reconverge.
ä All Channels Undergo a Large Jump Forward or Backward in Time Stamp: Starting
with the ideal case, if all channels jump forward or backward in time stamp (within
the same task cycle) by an amount that is more than two times the greater of 1 /
MaximumRate or MaximumWaitTime (typically due to a clock shift resulting from a
settings change or reset), output data sets contain some missing data indicators until
all wait windows from the old time reference are closed.
ä Tie Condition: If exactly half of the channels undergo a large jump forward or back-
ward in time stamp by more than two times the greater of 1 / MaximumRate or
MaximumWaitTime (typically due to a clock shift resulting from a settings change
or reset), the tie is broken based on the .quality.clockNotSynchronized and .qual-
ity.accuracy attributes of the time stamps. If a tie condition still persists, the group
with time stamps nearest the pre-jump time reference is favored. If both groups are
equidistant from the pre-jump time reference, the group with time stamps further in
the future is favored. The time-aligned data set contains missing data indicators for
the non-favored channel group.
ä Down-Conversion: If any input channel updates in time stamp at a rate that is greater
than MaximumRate, the channel rate is down-converted to MaximumRate by discard-
ing the extra samples.
ä Up-Conversion: Channels that update at less than MaximumRate are represented by
missing data indicators within some of the outgoing data sets. This assumes that at
least one input channel updates at MaximumRate. The time-alignment class waits
a full MaximumWaitTime before completing a time-aligned data set that contains
missing data indicators.
GetDataSet (Method)
This method updates the output channels with the oldest available set of time-aligned data.
Outputs
Name IEC 61131 Type Description
MissingData BOOL One or more output channels were updated with missing
data indicators.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
The following steps are executed if class_TimeAlignment output NumDataSetsAvailable
is greater than zero. Otherwise, no work is done and returns FALSE.
ä Updates all output channels with the oldest available time-aligned data set.
ä If any channel within the data set contains missing data indicators, sets MissingData
to TRUE.
ä Decrements class_TimeAlignment output: NumDataSetsAvailable.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R135-V1 firmware
ä SEL-3505
â R135-V1 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V1 firmware
fun_GetAlertString
The cost of a call to fun_GetAlertString.
fun_GetChannelString
The cost of a call to fun_GetChannelString.
fb_MultiChannelAlert No Alert
The cost of a call to fb_MultiChannelAlert when all channels are active and no alert is
generated.
fb_ChannelAlert No Alert
The cost of a call to fb_ChannelAlert when no alert is generated.
fb_ChannelAlert Timed
The cost of a call to fb_ChannelAlert when the input differs from the reference long enough
to generate an alert. This is the run time on the scan the alert begins.
fb_ChannelAlert Chatter
The cost of a call to fb_ChannelAlert when the input differs from the reference often enough
to generate an alert. This is the run time on the scan the alert begins.
fb_IndicatorAlert No Alert
The cost of a call to fb_IndicatorAlert when no alert is generated.
fb_IndicatorAlert Timed
The cost of a call to fb_IndicatorAlert when the input is true long enough to generate an
alert. This is the run time on the scan the alert begins.
fb_IndicatorAlert Chatter
The cost of a call to fb_IndicatorAlert when the input is true often enough to generate an
alert. This is the run time on the scan the alert begins.
fb_ChannelDerivative Alert
The cost of a call to fb_ChannelDerivative while Status = EXCURSION and Alert.stVal
= TRUE.
fb_IndicatorTimeDelta No Deviation
The cost of a call to fb_IndicatorTimeDelta while it is in a Status = NO_DEVIATION state
(Both indicators’ inputs are deasserted).
Light Load
1. Time aligned channels : 40 (evenly divided among CMV, MV, INS, and SPS chan-
nels)
2. Channel data rate : 10 (msg/sec)
3. MaximumWaitTime setting value : 200 (ms)
Medium Load
1. Time aligned channels : 800 (evenly divided among CMV, MV, INS, and SPS chan-
nels)
2. Channel data rate : 50 (msg/sec)
3. MaximumWaitTime setting value : 1000 (ms)
Heavy Load
1. Time aligned channels : 8000 (evenly divided among CMV, MV, INS, and SPS
channels)
2. Channel data rate : 50 (msg/sec)
3. MaximumWaitTime setting value : 1000 (ms)
Note: The heavy load scenario is not recommended for SEL-3530 or SEL-3505 plat-
forms.
For each bracket, the cost of calls to the Run and GetDataSet methods are evaluated sepa-
rately.
For each bracket, and each evaluated class method, two additional operating conditions are
considered, as described below.
1. No missing data: This operating condition guarantees synchronized timestamp up-
dates among all channels and that all channel timestamp values match at any given
time. The incoming data streams are already effectively time-aligned. The result of
this operating condition on class_TimeAlignment is that wait windows are opened
and closed on the same task cycle, such that the class instance operates in an effec-
tive bypass mode.
2. Missing data: This operating condition is identical to the ’No missing data’ con-
dition with one exception. One of the input channels never updates. This forces
the class instance to wait for the full MaximumWaitTime before publishing a time-
aligned data set with missing data indicators for the non-updating channel. This
worst-case scenario causes the class instance to continually buffer the maximum
amount of data.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3530 SEL-3505 SEL-3555
fun_GetAlertString 7 18 1
fun_GetChannelString 8 16 1
fb_MultiChannelAlert No Alert 16 22 2
fb_MultiChannelAlert 1 Channel Timed 21 30 4
fb_MultiChannelAlert All Channel Timed 21 30 4
fb_MultiChannelAlert 1 Channel Chatter 24 34 4
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
This solution uses the fb_ChannelAlert function block to monitor for differences between
CTs. The Phase A measurements are obtained from the relays and compared against a
reference measurement (see Code Snippet 4.1).
Solution
This solution uses the fb_MultiChannelAlert function block to monitor the three phases of
a CT. The phase measurements are obtained from the relays on both the generator and load
sides of a breaker. All the phases are compared against each other to detect damage or a
maintenance condition in CT/PT windings.
IF Gen_Alert_Generated.Q THEN
Gen_Status_Message := fun_GetAlertString(GenFB_Status);
Gen_Channel_Message := fun_GetChannelString(GenAlertCause);
END_IF
IF Bus_Alert_Generated.Q THEN
Bus_Status_Message := fun_GetAlertString(BusFB_Status);
Bus_Channel_Message := fun_GetChannelString(BusAlertCause);
END_IF
Solution
This solution uses the fb_StatusAlert function block to detect a TRUE condition in either a
communications diagnostic or hardware indicator. An appropriate communications chan-
nel diagnostic, such as the Offline bit in GOOSE, is monitored for communications channel
failure. The HALARM Relay Word bit in an IED is monitored for hardware failures only
if the communications channel is online.
(*If the offline status is false, monitor the HALARM Relay Word bit.
Note this is a separate offline bit than that used in the
ProtectionChannelMonitor*)
EnableHardwareMonitoring := NOT Communication_Client_Offline;
Solution
This solution uses the fb_ChannelIntegral function block to monitor a measured power
quantity and calculate the integral over time while the power is in excess of a user-defined
peak-demand threshold. This example assumes the following:
1. Power measurements are received from a SEL-351 Modbus client, using a holding
register named “KW3DI” (type = APC), polling interval of two seconds.
2. A virtual tag list called HMI_Controls was created for program control and status
outputs. Virtual tag list tags shown in this example are defined as the following data
types.
ä Aggregation_Complete: SPS
ä Aggregator_Reset: SPC
ä Demand_Threshold: MV (Analog Control)
ä KWH_During_Peak: MV
ä MaxKWDuringPeak: MV
ä Monitor_Enabled: SPS
ä Monitor_Quality_Alert: SPS
ä Peak_End_Time: STR
ä Peak_Start_Time: STR
ä Peak_Time_Active: SPS
PROGRAM prg_KWH_Track
VAR
Enable : BOOL;
Aggregator : fb_ChannelIntegral;
Joules_to_KWH : REAL := 3600000;
KWH_During_Peak : REAL;
Peak_Start_Time : dateTime_t;
Peak_End_Time : dateTime_t;
QualityAlert : BOOL;
END_VAR
//Load outputs
KWH_During_Peak := Aggregator.Integral.instMag / Joules_to_KWH;
HMI_Controls.KWH_During_Peak := Aggregator.Integral;
HMI_Controls.KWH_During_Peak.instMag := KWH_During_Peak;
HMI_Controls.KWH_During_Peak.mag := KWH_During_Peak;
HMI_Controls.MaxKWDuringPeak := Aggregator.Peak;
Solution
This solution uses the fb_IndicatorTimeDelta function block to monitor the state of the
Offline POU output pin of an SEL client. If a user-settable time period elapses before the
Offline pin deasserts, the function block will output an alert. This example assumes that an
SEL-735 SEL client named SEL_735_2_SEL was previously added to the RTAC project.
Solution
This solution uses the fb_Derivative function block to monitor a the Number_Of_Logon_-
Errors system tag and set an alarm if the rate of change in logon errors exceeds a settable
threshold. This example assumes the following:
1. A virtual tag list called HMI_Controls was created for program control and status
outputs. Virtual tag list tags shown in this example are defined as the following data
types.
ä RemoteAccessTracker_Reset: operSPC
ä RemoteAccessAlarm: SPS
ä RemoteAccessAlarmDetails: STR
Solution
This solution applies a single instance of class_TimeAlignment to time align the three
channels. This example assumes the following:
1. The RTAC project is of version R145 or later.
2. The project contains three clients with the following types/names:
ä C37.118 : SEL_421_1_C37_118 : Station Name = ’PMU3’
ä AXION PRCTPT Module : SEL_PRCTPT_1_ECAT
ä SEL : SEL_351_1_SEL
3. The SystemTags: Data_Rate setting matches the message rate setting in the remote
C37.118 server.
IF RunOnce THEN
//Bootstrap the input channels.
TA1.BootstrapChannelSet_CMV(inputChannel := SEL_421_1_PMU3.Phasor0,
outputChannel := TimeAlignedC37118Phasor);
TA1.BootstrapChannelSet_CMV(inputChannel :=
SEL_PRCTPT_1_ECAT.VA_PM, outputChannel :=
TimeAlignedAXIONPhasor);
TA1.BootstrapChannelSet_CMV(inputChannel :=
SEL_351_1_SEL.FM_INST_I0, outputChannel :=
TimeAlignedSELFMPhasor);
RunOnce := FALSE;
END_IF
//If time-aligned data sets are available, update the target tags once per
task cycle.
IF TA1.NumDataSetsAvailable > 0 THEN
TA1.GetDataSet(MissingData => DataMissing);
//If a time-aligned data set was returned with no missing data,
process time aligned samples
IF NOT DataMissing THEN
//In this contrived example, the SEL client zero-sequence magnitude
is used to qualify the
//subsequent magnitude difference calculation.
IF TimeAlignedSELFMPhasor.instCVal.mag >
c_ImbalanceMagThreshold THEN
MagnitudeDiff :=
ABS(TimeAlignedC37118Phasor.instCVal.mag -
TimeAlignedAXIONPhasor.instCVal.mag);
END_IF
END_IF
END_IF
ConditionMonitoring
Introduction
This library provides functionality to facilitate power system and industrial asset manage-
ment.
Special Considerations
ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
Enumerations
enum_CTPT_MonitorMode
This enumeration defines the operating method of the class_StreamingCTPTMonitor.
enum_GenericDataClass
This enumeration specifies a class of data and is intended for use by class_CmReportWriter
enum_PhaseID
This enumeration allows for the specification of a particular electrical phase.
enum_ReportContentType
This enumeration defines the general data structures found in ASCII reports. It is used in
coordination with regular expressions to aid in the formatting of the output report file.
Structures
struct_CTPTGroupStatus
This structure contains status information relevant to all monitored assets of a given class
instance.
struct_CTPTStatusOutput
This structure contains the status information for a single monitored CT or PT.
struct_DetailColLabel
This structure specifies a label and data class for a given column in a Detail CSV file.
struct_GenericDataPoint
This structure specifies a single value and associated data class.
Interfaces
I_Cm (Interface)
This interface is implemented by any class in the ConditionMonitoring library that requires
specifically formatted data logging to CSV report files. This interface is intended to be used
with class_CmReportWriter. This interface supports the logging of data for two use cases.
1. Human-readable CSV reports. Event-driven SOE and periodic summary data.
Properties
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
GetDetailColLabels (method)
This method allows the implementing class to specify the column label information that
will appear for its columns in the Detail CSV file. A queue object is provided for the
implementing class to populate. An implementing class can opt to bypass the genera-
tion/processing of the Detail file by leaving this method implementation blank.
Inputs/Outputs
Name IEC 61131 Type Description
LabelQ Queue.class_Deque Double-ended queue with elementSize =
SIZEOF(struct_DetailColLabel)
GetSoeColLabels (method)
This method allows the implementing class to specify the SOE column label information
that will appear for its columns in the SOE/Summary CSV file. A queue object is provided
for the implementing class to populate. An implementing class can opt to bypass the
generation/processing of SOE content within the SOE/Summary file by leaving this
method implementation blank.
Inputs/Outputs
Name IEC 61131 Type Description
LabelQ Queue.class_Deque Double-ended queue with elementSize =
SIZEOF(STRING(255))
GetSummaryColLabels (method)
This method allows the implementing class to specify the Summary column label infor-
mation that will appear for its columns in the SOE/Summary CSV file. A queue object
is provided for the implementing class to populate. An implementing class can opt to
bypass the generation/processing of Summary content within the SOE/Summary file
by leaving this method implementation blank.
Inputs/Outputs
Name IEC 61131 Type Description
labelQ Queue.class_Deque Double-ended queue with elementSize =
SIZEOF(STRING(255))
GetDetailRow (method)
This method allows an implementing class to transfer a set of data points to be represented
on a single row of the Detail CSV file.
Inputs/Outputs
Name IEC 61131 Type Description
rowQ Queue.class_Deque Double-ended queue with elementSize =
SIZEOF(struct_GenericDataPoint)
Outputs
Name IEC 61131 Type Description
timeStamp sel_iec_types.timeStamp_t A time stamp to appear on the timestamp column for
this row in the Detail CSV file.
Return Value
IEC 61131 Type Description
BOOL TRUE if the queue was populated successfully.
GetSoeRow (method)
This method allows an implementing class to transfer a set of strings to be represented in
SOE columns on a single row of the SOE/CSV file. The order in which strings are loaded
into the provided queue should correspond to the queue order in which SOE labels were
provided via the GetSoeColLabels method.
Inputs/Outputs
Name IEC 61131 Type Description
rowQ Queue.class_Deque Double-ended queue with elementSize =
SIZEOF(STRING(255)).
Outputs
Name IEC 61131 Type Description
timeStamp sel_iec_types.timeStamp_t A time stamp to appear on the timestamp column for
this row in the Detail CSV file.
assetID STRING(255) An identifier for the asset that the SOE content per-
tains to.
Return Value
IEC 61131 Type Description
BOOL TRUE if the queue was populated successfully.
GetSummaryRow (method)
This method allows an implementing class to transfer a set of strings to be represented on
a single row of the SOE/CSV file. The order in which strings are loaded into the provided
queue should correspond to the queue order in which summary labels were provided via
the GetSummaryColLabels method.
Inputs/Outputs
Name IEC 61131 Type Description
rowQ Queue.class_Deque Double-ended queue with elementSize =
SIZEOF(STRING(255))
Outputs
Name IEC 61131 Type Description
timeStamp sel_iec_types.timeStamp_t A time stamp to appear on the timestamp column for
this row in the Detail CSV file.
assetID STRING(255) An identifier for the asset that the SOE content per-
tains to.
Return Value
IEC 61131 Type Description
BOOL TRUE if the queue was populated successfully.
Classes
class_StreamingCTPTMonitor (Class)
This class implements a monitor for health assessment of power system CTs and PTs
through use of streaming data from connected IEDs. The method of operation is rooted
in sample-by-sample comparative analysis between recorded measurements from a given
CT or PT and a reference measurement. In this way, notable differences in measurements
among the redundant measurement transformers can be flagged as a transformer malfunc-
tion. The following diagram shows one example topology for which this monitoring system
can be applied.
Figure 5.1 Redundant Source and Load-Side CT Monitoring Group on a Single Feeder
Line
A scaling factor setting is provided in order to optionally incorporate CTs or PTs into a
redundant CT/PT group that would otherwise be excluded due to separation via a power
transformer. The following diagram depicts a three-CT monitoring group whose low-side
CT measurements must be scaled as a condition for inclusion in the group.
Figure 5.2 CT Monitoring Group With Applied Scaling for Transformer Low-Side CTs
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Cm
Class I/O
Inputs
Name IEC 61131 Type Description
InputTypeIsAngle BOOL If TRUE, input measurements (MV.instMag
and INS.stVal) will be monitored as an angle
in degrees. Similarly, CMV.instCVal.ang will
be monitored. If FALSE, input measurements
(Mv.instMag and INS.stVal) will be monitored
as magnitudes and CMV.instCVal.mag will be
monitored. Defaults to FALSE.
InstanceName STRING(255) Unique name of the class instance. Used for
reporting purposes. Must conform to sel_file
naming requirements.
ChatterCountThreshold UDINT Limit of channel excursions beyond Ini-
tialize().AlarmThreshold within Initial-
ize().AlarmPickupTime before Alert.stVal
asserts. Defaults to 1000.
Outputs
Name IEC 61131 Type Description
Error BOOL Indicates an internal error.
ErrorMessage STRING(255) Description of the current error state.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
ä Warning_SCADA and Warning_SOE are asserted if any of the following are true
for the struct_CTPTStatusOutput for any monitored asset on any phase. This is ref-
erenced below as the Warning condition.
1. MonitorEnabled = FALSE
2. QualityAlert = TRUE
ä Warning_SCADA will remain asserted after an above warning condition clears for a
duration of 10 seconds. During this period, WarningSCADADropoutTimerActive
is asserted.
ä Warning_SOE will remain asserted after an above warning condition clears for a
minimum of 10 seconds and a maximum of 60 minutes. During this period, Warn-
ingSOEDropoutTimerActive is asserted. If a new warning condition is observed
within 10 seconds after the deassertion of Warning_SOE, then the associated dropout
time is doubled. If no new warning condition is observed within 10 seconds after the
deassertion of Warning_SOE, the associated dropout time is set to 10 seconds. This
dynamic dropout time logic is implemented to aid in minimizing excess logging of
chattering warning conditions and is depicted in Figure 5.4.
ä Warning_SOE and Warning_SCADA follow the status of the Initialize.Enable in-
put without delay, as depicted in Figure 5.4.
ä Alert is asserted if any monitored asset on any phase has Alert.stVal = TRUE.
ä Alert will remain asserted after the above condition clears for a duration of Initialize.AlarmPickupTime
seconds. During this period. AlarmDropoutTimerActive is asserted.
ä AlertTimestamp is populated with the t.value.dateTime attribute of the struct_-
CTPTStatusOutput.Alert element of any monitored channel that observes an
struct_CTPTStatusOutput.Alert.stVal assertion on the given task cycle.
ä AlertEdge will pulse for one cycle on the rising edge of any monitored channel
struct_CTPTStatusOutput.Alert.stVal element.
The below figure depicts the pickup/dropout behavior of the Alarm/Warning indica-
tors.
Where:
â Ave(k–1) is initialized to 0 at the start of runtime.
â i is initialized to 1 at the start of runtime and increments once per sample.
â i is gated at imax where imax is determined by the following equation.
ä Reference Measurement
ä Alert
ä Monitor Disabled
ä Quality Alert
ä Status
ä Monitor Group
4. SOE row entries shall include as many as 80 comma-delimited CtPt IDs, starting
at ‘Monitor Group’ column.
5. Summary column labels:
ä Summary Element
ä Summary Value
6. Three summary rows will be made available.
ä <InstanceName>:Status : Status category for the group (NOMINAL/WARN-
ING/ALERT).
ä <InstanceName>:Status Description : Additional information describing the
group status.
ä <InstanceName>:Ave Group <Magnitude Percent> <or> <Angle Deviation> :
The current value of the GroupStatus.AveragePercentDeviation or Group-
Status.AverageAngleDeviation.
7. Detail column label format per bootstrapped CtPt: <InstanceName>:<CtPtID>:<Data-
Label>, where <DataLabel> is defined below:
ä Alert Mag (ANALOG)
ä Angle Deviation (ANALOG)
ä Percent Mag Deviation (ANALOG)
ä Reference Measurement (ANALOG)
ä Status (STRING)
8. The content loaded into the rowQ variable by GetDetailRow(), GetSoeRow(), and
GetSummaryRow() is sourced from the struct_CTPTStatusOutput structure for the
given asset.
9. SummaryOrder = 0 (indicating that summary data shall appear to the left of the
SOE data).
10. The NumAvailableSoeRows property increments for any monitored channel on ei-
ther of the following conditions and will decrement upon a call to GetSoeRow():
ä Rising edge of Alert.stVal
ä Rising edge of QualityAlert OR NOT MonitorEnabled
11. The NumAvailableDetailRows property increments for any monitored channel on
the following condition and will decrement upon a call to GetDetailRow():
ä Rising edge of Alert.stVal
12. The NumAvailableSummaryRows property is set to 3 and will decrement upon a
call to GetSummaryRow(). When this property equals 0, it is set back to 3 after a
5-second dropout period.
Bootstrap Methods
The following methods initialize all measurement channels and associated metadata for
monitored CT/PTs, reference CT/PTs, and breakers/switches. A bootstrap method should
be called for each CT or PT to be monitored by the class_StreamingCTPTMonitor instance.
Several bootstrap methods are provided to support the various data types through which
CT/PT data may be delivered.
bootstrap_MonitoredCMV (Method)
Bootstrap a monitored CT or PT whose measurements are delivered as a magnitude/an-
gle pair via a CMV data type. Note: When initialization input InputTypeIsAngle =
TRUE, the .instCVal.ang is used for monitoring. Otherwise, .instCVal.mag is used.
Inputs/Outputs
Name IEC 61131 Type Description
Channel CMV The CT or PT data channel to be monitored.
StatusOutput struct_CTPTStatusOutput The target structure to be updated with monitored
status information for the given CT or PT.
Inputs
Name IEC 61131 Type Description
CtPtID STRING(255) A string identifier for the CT or PT.
Phase enum_PhaseID The electrical phase represented by the channel.
ScaleFactor REAL Scale factor for transformer turns ratio compensation.
Defaults to 1.0. Else defaults to 0.
RotationFactor REAL Angle rotation factor for transformer turns ratio com-
pensation. Defaults to 0. Disregarded if class input
InputTypeIsAngle = FALSE.
NodeID UINT Topology node index (1–64) to which the asset
is connected. Will be disregarded during run-
time if Initialize.MonitorMode = DEFINED_-
REFERENCE.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if NodeID is outside of the specified bounds.
ä Returns FALSE if class input InputTypeIsAngle = TRUE and RotationFactor is
outside the range (–180 to 180).
bootstrap_MonitoredMV (Method)
Bootstrap a monitored CT or PT whose measurements are represented as an MV data type.
Note: The .instMag portion the MV is used for monitoring.
Inputs/Outputs
Name IEC 61131 Type Description
Channel MV The CT or PT data channel to be monitored.
StatusOutput struct_CTPTStatusOutput The target structure to be updated with monitored
status information for the given CT or PT.
Inputs
Name IEC 61131 Type Description
CtPtID STRING(255) A string identifier for the CT or PT.
Phase enum_PhaseID The electrical phase represented by the channel.
ScaleFactor REAL Scale factor for transformer turns ratio or angle ro-
tation compensation. Defaults to 1.0 if class input
InputTypeIsAngle = FALSE. Else defaults to 0.
NodeID UINT Topology node index (1–64) to which the asset is
connected. Will be disregarded during runtime if
Initialize.MonitorMode = DEFINED_REFERENCE.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if NodeID is outside of the specified bounds.
ä Returns FALSE if class input InputTypeIsAngle = TRUE and ScaleFactor is out-
side the range (–180 to 180).
bootstrap_MonitoredINS (Method)
Bootstrap a monitored CT or PT whose measurements are represented as an INS data type.
Inputs/Outputs
Name IEC 61131 Type Description
Channel INS The CT or PT data channel to be monitored.
StatusOutput struct_CTPTStatusOutput The target structure to be updated with monitored
status information for the given CT or PT.
Inputs
Name IEC 61131 Type Description
CtPtID STRING(255) A string identifier for the CT or PT.
Phase enum_PhaseID The electrical phase represented by the channel.
ScaleFactor REAL Scale factor for transformer turns ratio or angle ro-
tation compensation. Defaults to 1.0 if class input
InputTypeIsAngle = FALSE. Else defaults to 0.
NodeID UINT Topology node index (1–64) to which the asset is
connected. Will be disregarded during runtime if
Initialize.MonitorMode = DEFINED_REFERENCE.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if NodeID is outside of the specified bounds.
ä Returns FALSE if class input InputTypeIsAngle = TRUE and ScaleFactor is out-
side the range (–180 to 180).
bootstrap_ReferenceCMV (Method)
Bootstrap a reference CT or PT whose measurements are delivered as a magnitude/an-
gle pair via a CMV data type. Note: When initialization input InputTypeIsAngle =
TRUE, the .instCVal.ang is used for monitoring. Otherwise, .instCVal.mag is used.
When MonitorMode = DEFINED_REFERENCE has been passed into the Initialize()
method, all monitored CT/PTs for a given enum_PhaseID will be evaluated against a ref-
erence with a matching enum_PhaseID.
Inputs/Outputs
Name IEC 61131 Type Description
Channel CMV The CT or PT data channel to be used as a reference for the
specified phase.
Inputs
Name IEC 61131 Type Description
Phase enum_PhaseID The electrical phase represented by the channel.
ScaleFactor REAL Scale factor for transformer turns ratio or angle rotation
compensation. Defaults to 1.0.
RotationFactor REAL Angle rotation factor for transformer turns ratio com-
pensation. Defaults to 0. Disregarded if class input
InputTypeIsAngle = FALSE.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if a reference channel for the specified enum_PhaseID was already
bootstrapped.
ä Returns FALSE if class input InputTypeIsAngle = TRUE and RotationFactor is
outside the range (–180 to 180).
bootstrap_ReferenceMV (Method)
Bootstrap a reference CT or PT whose measurements are represented as an MV data type.
Note: The .instMag portion of the MV is used for monitoring. All monitored CT/PTs
will be evaluated against the reference when MonitorMode = DEFINED_REFERENCE has
been passed into the Initialize() method.
Inputs/Outputs
Name IEC 61131 Type Description
Channel MV The CT or PT data channel to be used as a reference for the
specified Phase.
Inputs
Name IEC 61131 Type Description
Phase enum_PhaseID The electrical phase represented by the channel.
ScaleFactor REAL Scale factor for transformer turns ratio or angle ro-
tation compensation. Defaults to 1.0 if class input
InputTypeIsAngle = FALSE. Else defaults to 0.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if a reference channel for the specified enum_PhaseID was already
bootstrapped.
ä Returns FALSE if class input InputTypeIsAngle = TRUE and ScaleFactor is out-
side the range (–180 to 180).
bootstrap_ReferenceINS (Method)
Bootstrap a reference CT or PT whose measurements are represented as an INS data type.
All monitored CT/PTs will be evaluated against the reference when MonitorMode = DEFINED_-
REFERENCE has been passed into the Initialize() method.
Inputs/Outputs
Name IEC 61131 Type Description
Channel INS The CT or PT data channel to be used as a reference for the
specified Phase.
Inputs
Name IEC 61131 Type Description
Phase enum_PhaseID The electrical phase represented by the channel.
ScaleFactor REAL Scale factor for transformer turns ratio or angle ro-
tation compensation. Defaults to 1.0 if class input
InputTypeIsAngle = FALSE. Else defaults to 0.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if a reference channel for the specified enum_PhaseID was already
bootstrapped.
ä Returns FALSE if class input InputTypeIsAngle = TRUE and ScaleFactor is out-
side the range (–180 to 180).
bootstrap_BreakerSwitch (Method)
Bootstrap a breaker or disconnect switch by specifying the status channel and associated
node IDs. The class uses breaker/switch status to dynamically assess topology and create
sub-groupings of monitored assets for relative reference monitoring. Specify breaker in-
formation when monitoring PT schemes with significant topology dependence (e.g., PTs
across an entire breaker-and-a-half scheme).
ä Bootstrapped breakers/switches will only be incorporated during runtime if MonitorMode
= RELATIVE_REFERENCE is passed into the Initialize() method.
ä Breakers/switches are serial elements and require the specification of two topology
nodes.
Inputs
Name IEC 61131 Type Description
Phase enum_PhaseID The electrical phase associated with the breaker/switch.
NodeIdOne UINT Topology node (1–64) to which the asset is connected.
NodeIdTwo UINT Topology node (1–64) to which the asset is connected.
Inputs/Outputs
Name IEC 61131 Type Description
Status SPS Status element for the given breaker/switch. .stVal Interpreted
as TRUE = closed.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä Returns FALSE if called after a successful call to Initialize().
ä Returns FALSE if either node ID is outside of the specified range.
Initialize (Method)
This method registers the global inputs for the class.
Inputs/Outputs
Name IEC 61131 Type Description
EN BOOL Global monitor enable.
MinimumMagnitude REAL Minimum CT or PT channel magnitude at
which the monitor will enable. If class input
InputTypeIsAngle = TRUE, any bootstrapped
CMV channels will have their post-scaled instC-
val.mag values checked against this minimum.
AlertThreshold REAL Percentage deviation from the reference (for
InputTypeIsAngle = FALSE) or angle
(degrees) deviation from the reference (for
InputTypeIsAngle = TRUE) at which an alert
condition can occur.
Inputs
Name IEC 61131 Type Description
AlertPickupTime TIME Maximum time a sustained deviation be-
yond AlertThreshold is allowed. After
the initial deviation, momentary normal-
ization is disregarded.
MonitorMode enum_CTPT_MonitorMode Relative or defined reference. If defined
reference is selected, bootstrapped break-
ers/switches will be ignored.
MaximumWaitTime UDINT Time-alignment wait time in millisec-
onds as specified by ChannelMonitor-
ing.class_TimeAlignment.
MaximumRate UDINT Time-alignment rate as specified by
ChannelMonitoring.class_TimeAlign-
ment. Set to zero to bypass time
alignment.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors were encountered.
Processing
ä The following inputs are set on the first call to initialize() and cannot be later
modified:
â AlertPickupTime
â MonitorMode
â MaximumWaitTime
â MaximumRate
ä The following inputs are allowed to change dynamically during runtime:
â EN
â MinimumMagnitude
â AlertThreshold
ä When MonitorMode = DEFINED_REFERENCE, a given monitored CT/PT phase must
correspond to a reference phase specified by a call to the respective Bootstrap_-
Reference method.
ä Initialize() will return FALSE in any of the following scenarios:
â The MonitorMode input is not a valid enumeration element in the enum_-
CTPT_MonitorMode enumeration.
â Initialize() is called again after a previous call to Initialize() has al-
ready returned TRUE.
â MonitorMode = RELATIVE_REFERENCE and less than two monitored CTs
or PTs have been defined via the bootstrap methods. In this scenario, the class
output Error is TRUE and ErrorMessage indicates that less than the minimum
number of monitored CTs/PTs were initialized.
â MonitorMode = DEFINED_REFERENCE and one or more bootstrapped moni-
tored CT or PTs have an enum_PhaseID that is not represented among the boot-
strapped reference CTs or PTs. In this scenario, the class output Error is TRUE
and ErrorMessage indicates that one or more required reference CTs/PTs were
not defined.
â MonitorMode = DEFINED_REFERENCE and less than one monitored CT or PT
has been defined via the bootstrap methods. In this scenario, the class output
Error is TRUE and ErrorMessage indicates that less than the minimum number
of monitored CTs/PTs were initialized.
Monitor Groups
A Monitor Group is defined here as a collection of measurement channels representing
assets that are monitored against a shared reference. When dynamic topology elements
like breakers/switches have been bootstrapped, a given monitor group may be a full set of
bootstrapped monitored channels or a subset. The number of operating monitor groups is
allowed to change dynamically with changes in topology.
ä For MonitorMode = DEFINED_REFERENCE, all measurement channels bootstrapped
by the bootstrap monitored channel methods for a given phase are considered mem-
bers of a single static monitor group. Breaker/switch status information is ignored.
ä When MonitorMode = RELATIVE_REFERENCE and no breaker/switches have been
bootstrapped, a given monitor group is defined as a collection of monitored channels
with matching node IDs. This allows for static sub-grouping of monitored channels.
ä When MonitorMode = RELATIVE_REFERENCE and breaker/switches have been boot-
strapped, a given monitor group is defined as a collection of monitored channels
whose node IDs are represented among a set of node-contiguous closed breaker-
s/switches. (Note that each breaker/switch is associated with two node IDs.) This
group association only holds for monitored channels and breaker/switches of identi-
cal phase.
Run (Method)
Call this method once per scan after completing all necessary calls to the Bootstrap methods
and Initialize().
Processing
ä Evaluates the status of any bootstrapped breaker/switch. If any change is detected,
the monitor groups are recalculated.
ä Applies the user-specified scaling factor to each monitored and reference channel.
" N M
#
X X
Ref erenceSample = (X1 (n)) − (M axOutlier(Xm )) ÷ (N − M )
n=1 m=1
(Equation 5.3)
Where:
â N is the number of bootstrapped monitored CTs/PTs with .q.validity =
good.
â X1 is the post-scaled set of samples representing each bootstrapped CT/PT for
a given time stamp.
â Xm + 1 is the Xm sample set minus the greatest outlier of the Xm sample set.
â M is the number of outliers to remove, where:
ã M = (N / 2) - 1 for even values of N.
ã M = (N - 1) / 2 for odd values of N.
For example, for the instantaneous sample set (50, 52, 10, 55, 900, 54, 51, 0):
â N=8
â M=3
â Reference sample = (50 + 52 + 55 + 54 + 51) / 5
ä If less than two monitored CTs/PTs have .q.validity = good for the given sam-
ple, then the reference measurement is set to ‘0’ and is given .q.validity = invalid.
|M on_CT P T − Ref |
· 100 > Initialize.AlertT hreshold
Ref
(Equation 5.4)
ã For class input InputTypeIsAngle = TRUE:
Where:
ã Mon_CTPT is the monitored CT/PT data channel sample after being scaled
by ScaleFactor (or RotationFactor when InputTypeIsAngle = TRUE).
ã Ref is the reference data channel sample from the bootstrapped reference
CT/PT or the approximated reference from equation Equation 5.3 .
â After an alert condition clears, Alert.stVal will remain asserted for a dropout
duration of Initialize.AlertPickupTime.
â Alert.q.validity = invalid if MonitorEnabled is FALSE.
â Alert.t updates with the RTAC system time upon a rising or falling edge of
Alert.stVal.
â Alert is not updated while QualityAlert is TRUE.
â Alert is not updated while MonitorEnabled is FALSE.
â QualityAlert is TRUE while any of the following conditions are met:
ã The monitored CT/PT data channel has q.validity 6=good.
ã For MonitorMode = DEFINED_REFERENCE, the reference data channel
for the associated Phase has q.validity 6=good.
ã For MonitorMode = RELATIVE_REFERENCE, less than two monitored
CT/PT data channels have q.validity = good.
â AlertMag is updated with the instantaneous value of the monitored channel
on the rising edge of Alert.stVal and is set to zero on the falling edge of
Alert.stVal
â PercentDeviation is continuously updated with the signed version of the left
hand side of Equation 5.4 when class input InputTypeIsAngle = FALSE.
PercentDeviation is left blank when InputTypeIsAngle = TRUE.
â AngleDeviation is continuously updated with the signed version of the left side
of Equation 5.5 when class input InputTypeIsAngle = TRUE. AngleDevia-
tion is left blank when InputTypeIsAngle = FALSE.
â ReferenceMeasurement is continuously updated with the reference measure-
ments that the given CtPt is monitored against.
â NodeGroup is continuously updated with a list of node index values associ-
ated with this group. This list may change dynamically for scenarios where
breakers/switches have been bootstrapped and MonitorMode = RELATIVE_-
REFERENCE. Otherwise, the list will include all CtPt ID indexes for monitored
channels that have been bootstrapped for the given phase and will remain static.
class_CmReportWriter (Class)
This class supports the generation of reports useful for condition monitoring of power sys-
tem assets.
Special Considerations
ä This class writes comma-delimited format files to the RTAC file system.
ä This class provides file names in accordance with IEEE C37.232.
ä This class writes files to the RTAC file system but does not manage the target direc-
tory.
This class is intended to generate all reports necessary for an arbitrary number of instances
of a single class that implements the I_Cm interface. Thus, this class assumes that all
bootstrapped sources use the same implementation of I_Cm.
This class writes one to two types of report files, depending on the I_Cm implementation
of the bootstrapped sources.
Detail File
The detail file provides one column per granular data element per asset. This provides a
simple format for machine processing and analytic generation. The detail file contains one
required column. The first column always contains a time stamp for the event. The column
label is Timestamp. The time stamp format is yyyy-mm-dd-hh:mm:ss.xxxxxx.
All other columns of the detail file are defined by one or more implementing class in-
stances. The column labels take the form <CustomLabel>:<DataTypeIdentifier>, where
CustomLabel and DataTypeIdentifier are provided via the GetDetailColLabels method.
DataTypeIdentifier takes on one of the following values:
1. A : Analog quantity (Floating point).
2. D : Boolean quantity (TRUE/FALSE).
3. S : String (maximum of 255 characters).
The DataTypeIdentifier is intended to provide context about the content of a given column
to assist in machine processing. For example, the following are column labels 1–5 for a
hypothetical Detail file.
Timestamp, Asset1.VA.Mag:A, Asset1.Alert:D, Asset2.VA.Mag:A, Asset2.Alert:D
SOE/Summary File
The SOE/Summary file provides one column per data element category shared by all assets.
This file can contain either SOE or Summary content or both depending on the given class’s
implementation of this interface. The SOE/Summary file contains three required columns
that will appear as the first three columns in the file:
1. Column Label - ‘Timestamp’ : Time stamp displayed in yyyy-mm-dd-hh:mm:ss.xxxxxx
format
2. Column Label - ‘Log Type’ : Log descriptor (‘Event’ or ‘Summary’)
3. Column Label - ‘Asset ID’ : Asset descriptor
All other column labels of the SOE/Summary file are defined by the first implementing
class instance that has been bootstrapped into class_CmReportWriter. All objects boot-
strapped into class_CmReportWriter must be instances of a single class. Therefore, it
can be assumed that each instance supports an identical set of SOE/Summary column
labels. For example, bootstrapping one instance of a class_StreamingCtPtMonitor and one
instance of a class_BreakerMonitor would be an invalid configuration.
This class should be operated in the following fashion:
1. Call Bootstrap_Source for all participating class instances of a single class that
implements the I_Cm interface.
2. Call Initialize once all sources have been bootstrapped.
3. If Initialize returns TRUE, call Run once per task cycle.
Inputs
Name IEC 61131 Type Description
SummaryPeriod TIME Interval between summary reports within
the SOE/Summary file. Set to T#0s to dis-
able summary reporting.
SummaryTrigger BOOL Manual trigger for generating summary con-
tent within the SOE/Summary file.
Directory STRING(100) Target directory. Must conform to SEL sel_-
file limitations.
StationID STRING(16) Station ID string, used for IEEE C37.232
COMNAME formatting.
DeviceID STRING(16) Device ID string, used for IEEE C37.232
COMNAME formatting.
CompanyName STRING(16) Company name string, used for IEEE
C37.232 COMNAME formatting.
FileNamePostFix STRING(16) Comma-separated additions to the given file
name.
MaxSoeFileSize UDINT Maximum SOE file size in bytes before a
new file is created.
MaxSoeFileDur UDINT Maximum SOE file duration in hours.
MaxDetailFileSize UDINT Maximum Detail file size in bytes before a
new file is created.
MaxDetailFileDur UDINT Maximum Detail file duration in hours
MaxRowsOfDetailHistory UDINT Maximum Number of Detail File rows
cached in RAM for historical analysis. Set
to zero to disable.
RecordInUTC BOOL Record in UTC or local time.
Outputs
Name IEC 61131 Type Description
Initialized BOOL Class is initialized for report generation.
CurrentSoeFileSize UDINT Current size in bytes of the SOE/Summary file.
CurrentDetailFileSize UDINT Current size in bytes of the Detail file.
Error BOOL Indicates an internal error state.
ErrorMsg STRING(255) Message describing an internal error state.
Bootstrap_Source (Method)
Call this method to register a ConditionMonitoring class instance for report generation.
Inputs
Name IEC 61131 Type Description
CmApplication I_Cm Instance of a class or FB that implements the I_Cm in-
terface.
Processing
1. Sets CmApplication.pt_History to the address of the internal CSV object man-
ager.
2. Sets CmApplication.ReportingBootstrapped = TRUE.
3. Adds the address of the I_Cm interface implementation to a queue.
Initialize (Method)
Call this method to initialize the class.
Processing
1. Returns FALSE if any of the following are TRUE:
ä No sources have been bootstrapped.
ä Any of the class input file name elements do not pass SelUtils.fun_IsValid-
Filename() with NameScheme = SEL_FILEIO_IEEE_COMNAME.
2. Else sets the input file name components as static variables (cannot be changed after
Initialize returns TRUE).
3. If no errors were encountered, sets Initialized = TRUE.
Return Value
IEC 61131 Type Description
BOOL TRUE if no errors were encountered.
Run (Method)
Call this method once per scan.
Processing
1. If Initialized = TRUE and at least one source has been bootstrapped via Boot-
strap_Source():
ä Opens any last-known SOE/Summary and/or Detail files for continued log-
ging.
2. Checks the bootstrapped sources for Summary content on the SummaryPeriod in-
terval.
3. Continuously checks the bootstrapped sources for SOE and Detail content.
4. If SOE/Summary content found, writes directly to file.
5. If Detail content found, writes directly to file.
6. Prior to writing content to file, checks the file age. If in excess of max file duration
setting, writes content to a new file.
7. Checks size of SOE/Summary and Detail files every 30 seconds.
8. If file size exceeds associated max file size setting, a new file is created the next
time content is written to file.
9. If Detail content found and MaxRowsOfDetailHistory > 0, writes row to an
internal CSV object (instance of DescriptiveData.class_CsvManager).
class_IedReportConverter (Class)
This class supports the conversion of ASCII and CASCII reports collected from IEDs to
standard format, machine-readable files.
This class is intended for use by the IED Report Manager extension but can be used directly
if a custom directory management scheme is required.
Special Considerations
ä This class supports ASCII or CASCII input files.
ä This class supports output files in CSV format.
ä This class allows output file name configuration for compliance with IEEE C37.232.
ä This class writes files to the RTAC file system but does not manage the target direc-
tory.
This class should be operated in the following fashion:
1. If a CSV-formatted output file is desired, call Bootstrap_ReportRegExRule()
for each regular expression necessary to parse the desired content from the file.
Otherwise, if a copy of the original IED report file is desired, make no calls to the
Bootstrap_ReportRegExRule() method.
2. Call Bootstrap_Report() to initialize the application inputs for the class.
3. Call Run() once per scan after Bootstrap_Report() returns TRUE.
4. Call RequestReportConversion() to initiate processing of the original IED re-
port file.
5. Make subsequent calls to RequestReportConversion() when the original IED
report file updates and Busy = FALSE.
Regular Expressions will be applied sequentially based on the order in which they
were Bootstrapped. Each parse operation will begin at the index at which the previous
operation ended.
Inputs
Name IEC 61131 Type Description
LogRuntimeErrors BOOL Default is FALSE. Set to TRUE to log runtime
errors to the SOE log.
MaxCycleTimeUsage UDINT(10–10000) Milliseconds. Default is 10. Maximum time per
task cycle that the Run method will do work.
InstanceID STRING Identification string for the class instance. Used
for SOE logging and internal file management.
Outputs
Name IEC 61131 Type Description
Initialized BOOL TRUE if Bootstrap_Report() returns TRUE.
Busy BOOL While TRUE, the class will not accept report conver-
sion requests.
ActiveFileName STRING(255) Name of the most recent file written to the file system.
Error BOOL Indicates an error condition.
ErrorMessage STRING(255) Description of the error condition.
Bootstrap_ReportRegExRule (Method)
Call this method to specify a regular expression and associated metadata necessary to parse
content from the original IED report.
Inputs
Name IEC 61131 Type Description
Type enum_ReportContentType Report content type to be parsed using RegEx.
Label STRING(252) Identifier for the data parsed by RegEx. This string will
be used in the CSV-formatted output file to label the
respective data column(s). It does not need to match
the relay word label from the ASCII or CASCII re-
sponse. Three bytes are reserved for internally used
metadata.
RegEx STRING(255) Regular expression characterization string. Must meet
the Perl5 RegEx syntax requirements. All JSON con-
trol characters must be escaped using the backslash (\)
character.
Instances UINT Number of times that RegEx will be applied to capture
sequential data from the original IED report file.
Formatting considerations
Type = SEQUENCE
Sequence content is described here as a repeating data pattern, which is represented as rows
and columns of space-separated or comma-separated alphanumeric character sets preceded
by a set of column labels where the number of discrete character sets per row matches the
number of column labels.
ä Label should be formatted as a comma-separated list of column labels.
ä RegEx should match no more than the entire row, excluding the trailing newline and
carriage return, using one or more capture groups.
ä Instances should be set equal to the desired number of rows of column data to be
captured.
Type = SUMMARY
Summary content is described here as a non-repeating data element from the report.
ä If Label contains the comma (0x2C) character, only characters preceding the first
instance of the comma will be passed to the output file.
ä If RegEx contains more than one capture group, only the content matched by the first
capture group in the list will be passed to the output file.
ä For this mode, Instances is forced to 1 and disregarded.
Return Value
IEC 61131 Type Description
BOOL TRUE if no errors were encountered.
Processing
1. Returns FALSE if Initialized is TRUE.
2. Else, returns TRUE.
Bootstrap_Report (Method)
Call this method to specify the necessary inputs to this class. This method should be called
once.
Inputs
Name IEC 61131 Type Description
InputFile STRING(255) The full file name of the original IED report. The
character “/” delimits the folder path. This path must
begin with “/” and end with the full file name, includ-
ing extension.
OutputDirectory STRING(164) The target directory for the formatted report. The
character “/” delimits the folder path. Must begin
with “/”. If the directory does not exist, it will be
created.
OutputFilePostfix STRING(67) The string appended to the end of the file name, prior
to the file format extension. Must include the file ex-
tension.
ReportsPerFile UINT The number of formatted report data sets
contained within the output file. A new
file will be created on the following call to
RequestReportConversion() when the number
of report data sets in the current file reaches this
number, the RTAC reboots, or new RTAC settings
are sent.
File name elements for Inputfile and OutputDirectory may contain all printable ASCII
characters between (space) and (tilde) except for ", ’, :, <, %, >, ?, \, and |. They cannot
contain any file path manipulation variables (//, /./, /../).
File name elements for OutputFilePostfix may contain all printable ASCII characters
between (space) and (tilde) except for ", ’, :, ;, <, %, >, [, ], $, {, }, ?, \, and |.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if errors were encountered.
Processing
1. Returns FALSE if Initialized is TRUE.
2. If InputFile, OutputDirectory, or OutputFilePostFix contain illegal characters as
specified above, returns FALSE, asserts Error, and ErrorMessage indicates the use
of illegal characters on the specified input.
3. If ReportsPerFile is zero, returns FALSE, asserts Error, and ErrorMessage indi-
cates that ReportsPerFile must be non-zero.
RequestReportConversion (Method)
Call this method to initiate a conversion of the file specified by InputFile into a formatted
report.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if errors were encountered.
Processing
1. Returns FALSE if Busy is TRUE.
2. Returns FALSE if Initialized is FALSE.
3. Else, executes the following:
a. Deasserts Error and clears ErrorMessage.
b. Asserts Busy.
Run (Method)
Call this method once each processing interval to handle all asynchronous operations.
Processing
1. If Busy = FALSE and Initialized = TRUE and RequestReportConversion() re-
turns TRUE, executes the following:
ä Asserts Error if the original IED report specified by InputFile was not found
within the FILES directory of the virtual file system or the file could not be
parsed using the specified regular expressions. ErrorMessage specifies the
error condition details.
ä Deasserts Busy on rising edge of Error.
Note that for this example, the noted Bootstrap_ReportRegExRule() calls must be
made in the same order in which they are listed above.
The resultant formatted file for this example is shown below:
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes the following:
1. Two C37.118 protocol clients, IED1 and IED2, are added to the project.
2. A C37.118 data rate of 30 messages per second is used for IED1 and IED2.
3. System topology matches that of Figure 5.2.
4. IED1 collects 3-phase measurements from CT1 and CT3.
5. IED2 collects 3-phase measurements from CT2.
6. CT1 is on the low-side of the transformer and associated current measurements
must be scaled down by the transformer ratio as a pre-condition for inclusion in the
monitoring group.
7. CT3 is used for reference measurements only.
Solution
The user can apply one instance of class_Streaming_CTPT_Monitor to facilitate this mon-
itoring scheme.
IF RunOnce THEN
//Bootstrap the reference CT phases (CT3)
CT_Monitor.bootstrap_ReferenceCMV(channel := IED1_IED1.CT3_IA,
phase := enum_PhaseID.PHASE_A,
scaleFactor := 1);
CT_Monitor.bootstrap_ReferenceCMV(channel := IED1_IED1.CT3_IB,
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1);
CT_Monitor.bootstrap_ReferenceCMV(channel := IED1_IED1.CT3_IC,
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED1_IED1.CT1_IB,
outputStatus := CT_Status_Matrix[1, enum_PhaseID.PHASE_B],
ctPtId := 'CT1B',
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1/TxfrmrTurnsRatio);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED1_IED1.CT1_IC,
outputStatus := CT_Status_Matrix[1, enum_PhaseID.PHASE_C],
ctPtId := 'CT1C',
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1/TxfrmrTurnsRatio);
//Bootstrap group 2
CT_Monitor.bootstrap_MonitoredCMV(channel := IED2_IED2.IA,
outputStatus := CT_Status_Matrix[2, enum_PhaseID.PHASE_A],
ctPtId := 'CT2A',
phase := enum_PhaseID.PHASE_A,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED2_IED2.IB,
outputStatus := CT_Status_Matrix[2, enum_PhaseID.PHASE_B],
ctPtId := 'CT2B',
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED2_IED2.IC,
outputStatus := CT_Status_Matrix[2, enum_PhaseID.PHASE_C],
ctPtId := 'CT2C',
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1);
RunOnce := FALSE;
END_IF
IF Initialized THEN
//Update the monitor enable variable
Monitor_Enable := NOT (IED1_C37_118_POU.Offline OR
IED2_C37_118_POU.Offline);
CT_Status_String_Matrix[inc, enum_PhaseID.PHASE_A] :=
CONCAT(CONCAT('CT : ',
CT_Status_Matrix[inc,enum_PhaseID.PHASE_A].CtPtID),'
is disabled due to insufficient measurement
quality');
ELSE
CT_Status_String_Matrix[inc, enum_PhaseID.PHASE_A] :=
CONCAT(CONCAT('CT : ',
CT_Status_Matrix[inc,enum_PhaseID.PHASE_A].CtPtID),'
is operational');
END_IF
Assumptions
This example assumes the following:
1. System topology matches that of Figure 5.1.
2. Four C37.118 protocol clients; IED1, IED2, IED3, and IED4; are added to the
project.
3. A C37.118 data rate of 30 messages per second is used for IED1, IED2, IED3, and
IED4.
Solution
The user can apply one instance of class_Streaming_CTPT_Monitor to facilitate this mon-
itoring scheme.
IF RunOnce THEN
//Bootstrap A,B,C phase CTs for CT groups 1 - 4
//Bootstrap group 1
CT_Monitor.bootstrap_MonitoredCMV(channel := IED1_IED1.IA,
outputStatus := CT_Status_Matrix[1, enum_PhaseID.PHASE_A],
ctPtId := 'CT1A',
phase := enum_PhaseID.PHASE_A,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED1_IED1.IB,
outputStatus := CT_Status_Matrix[1, enum_PhaseID.PHASE_B],
ctPtId := 'CT1B',
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED1_IED1.IC,
outputStatus := CT_Status_Matrix[1, enum_PhaseID.PHASE_C],
ctPtId := 'CT1C',
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1);
//Bootstrap group 2
CT_Monitor.bootstrap_MonitoredCMV(channel := IED2_IED2.IA,
outputStatus := CT_Status_Matrix[2, enum_PhaseID.PHASE_A],
ctPtId := 'CT2A',
phase := enum_PhaseID.PHASE_A,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED2_IED2.IB,
outputStatus := CT_Status_Matrix[2, enum_PhaseID.PHASE_B],
ctPtId := 'CT2B',
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED2_IED2.IC,
outputStatus := CT_Status_Matrix[2, enum_PhaseID.PHASE_C],
ctPtId := 'CT2C',
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1);
//Bootstrap group 3
CT_Monitor.bootstrap_MonitoredCMV(channel := IED3_IED3.IA,
outputStatus := CT_Status_Matrix[3, enum_PhaseID.PHASE_A],
ctPtId := 'CT3A',
phase := enum_PhaseID.PHASE_A,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED3_IED3.IB,
outputStatus := CT_Status_Matrix[3, enum_PhaseID.PHASE_B],
ctPtId := 'CT3B',
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED3_IED3.IC,
outputStatus := CT_Status_Matrix[3, enum_PhaseID.PHASE_C],
ctPtId := 'CT3C',
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1);
//Bootstrap group 4
CT_Monitor.bootstrap_MonitoredCMV(channel := IED4_IED4.IA,
outputStatus := CT_Status_Matrix[4, enum_PhaseID.PHASE_A],
ctPtId := 'CT4A',
phase := enum_PhaseID.PHASE_A,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED4_IED4.IB,
outputStatus := CT_Status_Matrix[4, enum_PhaseID.PHASE_B],
ctPtId := 'CT4B',
phase := enum_PhaseID.PHASE_B,
scaleFactor := 1);
CT_Monitor.bootstrap_MonitoredCMV(channel := IED4_IED4.IC,
outputStatus := CT_Status_Matrix[4, enum_PhaseID.PHASE_C],
ctPtId := 'CT4C',
phase := enum_PhaseID.PHASE_C,
scaleFactor := 1);
RunOnce := FALSE;
END_IF
IF Initialized THEN
//Update the monitor enable variable
Monitor_Enable := NOT (IED1_C37_118_POU.Offline OR
IED2_C37_118_POU.Offline
OR IED3_C37_118_POU.Offline OR IED4_C37_118_POU.Offline);
ELSIF CT_Status_Matrix[inc,
enum_PhaseID.PHASE_B].QualityAlert THEN
CT_Status_String_Matrix[inc, enum_PhaseID.PHASE_B] :=
CONCAT(CONCAT('CT : ',
CT_Status_Matrix[inc,enum_PhaseID.PHASE_B].CtPtID),'
is disabled due to insufficient measurement
quality');
ELSE
CT_Status_String_Matrix[inc, enum_PhaseID.PHASE_B] :=
CONCAT(CONCAT('CT : ',
CT_Status_Matrix[inc,enum_PhaseID.PHASE_B].CtPtID),'
is operational');
END_IF
Assumptions
This example assumes the following:
1. System topology matches that of Figure 5.3.
2. Three IEEE C37.118 protocol clients; IED1, IED2, and IED3 are added to the
project.
3. An IEEE C37.118 data rate of 30 messages per second is used for IED1, IED2, and
IED3.
4. IED1 takes measurements from PT1, PT2, Bk1, Bk2, and Sw1.
5. IED2 takes measurements from PT3, PT4, Bk3, Bk4, Sw2, and Sw3.
6. IED3 takes measurements from PT5, PT6, Bk5, Bk6, and Sw4.
Solution
The user can apply one instance of class_Streaming_CTPT_Monitor to facilitate this mon-
itoring scheme.
IF RunOnce THEN
//////////Bootstrap all assets monitored by IED1//////////
//Bootstrap A phase PTs 1 and 2
Monitor.bootstrap_MonitoredCMV(CtPtID := 'PT1A',
phase := enum_PhaseID.PHASE_A,
ScaleFactor := 1.0,
NodeID := 1,
Channel := IED1_PMU1.VALPM,
OutputStatus := Phase_A_Status_Matrix[1]);
Monitor.bootstrap_MonitoredCMV(CtPtID := 'PT2A',
phase := enum_PhaseID.PHASE_A,
ScaleFactor := 1.0,
NodeID := 3,
Channel := IED1_PMU1.VAZPM,
OutputStatus := Phase_A_Status_Matrix[2]);
//Bootstrap Breaker 1
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 1,
NodeIdTwo := 2,
Status := IED1_PMU1._52AA1);
//Bootstrap Breaker 2
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 2,
NodeIdTwo := 4,
Status := IED1_PMU1._52AA2);
//Bootstrap disconnect switch 1
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 2,
NodeIdTwo := 3,
Status := IED1_PMU1.IN101);
////////// ////////// ////////// ////////// //////////
/////
Monitor.bootstrap_MonitoredCMV(CtPtID := 'PT4A',
phase := enum_PhaseID.PHASE_A,
ScaleFactor := 1.0,
NodeID := 6,
Channel := IED2_PMU1.VAZPM,
OutputStatus := Phase_A_Status_Matrix[4]);
//Bootstrap Breaker 3
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 4,
NodeIdTwo := 6,
Status := IED2_PMU1._52AA1);
//Bootstrap Breaker 2
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 6,
NodeIdTwo := 7,
Status := IED2_PMU1._52AA2);
//Bootstrap disconnect switch 2
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 4,
NodeIdTwo := 5,
Status := IED2_PMU1.IN101);
//Bootstrap disconnect switch 3
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 7,
NodeIdTwo := 8,
Status := IED2_PMU1.IN102);
////////// ////////// ////////// ////////// //////////
/////
Monitor.bootstrap_MonitoredCMV(CtPtID := 'PT6A',
phase := enum_PhaseID.PHASE_A,
ScaleFactor := 1.0,
NodeID := 10,
Channel := IED3_PMU1.VAZPM,
OutputStatus := Phase_A_Status_Matrix[6]);
//Bootstrap Breaker 5
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 7,
NodeIdTwo := 9,
Status := IED3_PMU1._52AA1);
//Bootstrap Breaker 6
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 1,
NodeIdTwo := 9,
Status := IED3_PMU1._52AA2);
//Bootstrap disconnect switch 4
Monitor.bootstrap_BreakerSwitch(Phase := enum_PhaseID.PHASE_A,
NodeIdOne := 9,
NodeIdTwo := 10,
Status := IED3_PMU1.IN101);
////////// ////////// ////////// ////////// //////////
/////
RunOnce := FALSE;
END_IF
IF Initialized THEN
//Update the monitor enable variable
Monitor_Enable := NOT (IED1_C37_118_POU.Offline OR IED2_C37_118_POU.Offline
OR IED3_C37_118_POU.Offline);
Assumptions
This example assumes the following:
1. The connected SEL-710-5 relay is using R100 firmware.
2. A client named SEL_710_5_1_SEL is added to the project.
3. The client is configured with a Flex parse message with the following non-default
settings applied:
ä Flex Message Name : MSR
ä Command String : MSR<CR><LF>
ä Capture To File : True
4. The client POU input pin Send_Flex_Parse_Message_MSR is asserted on demand
by additional user logic.
5. The RTAC main task cycle time is 100 ms.
Solution
This solution uses a single instance of the class_IedReportConverter to convert the content
of the client report to a CSV file.
VAR
ReportConverter : class_IedReportConverter :=
(LogRuntimeErrors := TRUE,
MaxCycleTimeUsage := 50,
InstanceID := 'SEL_710-5_1_MSR');
InputReportFile : STRING :=
'/FLEX_PARSE/SEL_710_5_1_SEL/SEL_710_5_1_SEL_MSR.capture';
Code Snippet 5.5 Example SEL-710-5 MSR Report Collection Code Body
IF NOT InitializeAttempted THEN
FOR i := 1 TO c_numRegEx DO
ReportConverter.Bootstrap_ReportRegexRule(ContentType[i], Labels[i], Instances[i],
InRegex[i]);
END_FOR
ReportConverter.Bootstrap_Report(InputFile := InputReportFile,
OutputDirectory := OutDirectory,
OutputFilePostFix := OutputPostFix,
ReportsPerFile := NumReports);
InitializeAttempted := TRUE;
END_IF
IF ReportConverter.Initialized THEN
Tedge(CLK := SEL_710_5_1_SEL_POU.Send_Flex_Parse_Message_MSR_DN);
IF Tedge.Q AND NOT ReportConverter.Busy THEN
ReportConverter.RequestReportConversion();
END_IF
END_IF
ReportConverter.Run();
Assumptions
This example assumes the following:
1. The connected SEL-710-5 relay is using R100 firmware.
2. A client named SEL_710_5_1_SEL is added to the project.
3. The client is configured with a Flex parse message with the following non-default
settings applied:
ä Flex Message Name : FFT
ä Command String : MET FFT<CR><LF>
ä Capture To File : True
4. The client POU input pin Send_Flex_Parse_Message_FFT is asserted on demand
by additional user logic.
5. The RTAC main task cycle time is 100 ms.
Solution
This solution uses a single instance of the class_IedReportConverter to convert the content
of the client report to a CSV file.
VAR
ReportConverter : class_IedReportConverter :=
(LogRuntimeErrors := TRUE,
MaxCycleTimeUsage := 50,
InstanceID := 'SEL_710-5_1_FFT');
InputReportFile : STRING :=
'/FLEX_PARSE/SEL_710_5_1_SEL/SEL_710_5_1_SEL_FFT.capture';
Code Snippet 5.7 Example 710-5 FFT Report Conversion Code Body
IF NOT InitializeAttempted THEN
FOR i := 1 TO c_numRegEx DO
ReportConverter.Bootstrap_ReportRegexRule(ContentType[i], Labels[i], Instances[i],
InRegex[i]);
END_FOR
ReportConverter.Bootstrap_Report(InputFile := InputReportFile,
OutputDirectory := OutDirectory,
OutputFilePostFix := OutputPostFix,
ReportsPerFile := NumReports);
InitializeAttempted := TRUE;
END_IF
IF ReportConverter.Initialized THEN
Tedge(CLK := SEL_710_5_1_SEL_POU.Send_Flex_Parse_Message_FFT_DN);
IF Tedge.Q AND NOT ReportConverter.Busy THEN
ReportConverter.RequestReportConversion();
END_IF
END_IF
ReportConverter.Run();
CrossTaskData
Introduction
The purpose of this library is to take a mutual exclusion (mutex) implementation that uses
the SysSem semaphore library and wrap it into single function block calls to provide sim-
ple function blocks. Mutex data region creation depends upon the size of a user-defined
structure.
In computer science, mutex refers to a basic concurrency control requirement that the crit-
ical sections of two concurrent processes cannot occur simultaneously. This requirement
prevents race conditions.
In this particular case, the mutex allows one task to write the data and another to read
the data. The mutex guarantees that the data remain intact. This is important because
Real-Time Automation Controller (RTAC) automation and main tasks run with different
priorities. To illustrate this, imagine a structure containing a value “stVal” and a time stamp
“t” and that a low-speed task is writing periodically to this value and time stamp. Then
imagine that a high-speed task uses this information for some computation. If there were no
mutex in place, the lower priority main task may write only the “strVal” and be interrupted
by the higher priority automation task. The logic running on the automation task would
then be reading a newly updated “stVal” for which there is a “t” from the previous “stVal”
instead of the time stamp that should be associated with the value. The mutex protects the
integrity of the data, ensuring complete transfer of information.
The library contains a preset number of reserved mutexes defined by a global parameter.
Each mutex has an identification number (ID) that is an integer value between 1 and the
number the global parameter defines. Writer function blocks each claim one of the IDs,
define the size of the mutex, and then set aside memory for the mutex as necessary.
Initialization of the writer and reader function blocks results in verification to ensure that
only a single writer function block and a single reader function block exist per mutex ID.
After initialization, the only input necessary for the function block is the address of the data
set that you want to read from and write to.
Special Considerations
The writer function block should never be instantiated in a method or a function. Because
memory allocation occurs in order to create the mutex, writer function blocks must be
instantiated in a program or global variable list. Declaring a writer function block in either
a function or a method causes undesired behavior.
Each mutex ID may be referenced by no more than one writer function block.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Function Blocks
fb_CrossTaskWrite
If data exist on one task to be shared with another, use this function block on the task
publishing the data. Only one writing function block may place data in a given mutex.
Initialization Inputs
Name IEC 61131 Type Description
id UDINT The ID of the mutex that the writer will own
(range [1..g_p_N_CrossTaskIDs]).
sizeOfStruct UDINT The size of the structure, as returned by the SIZEOF()
function.
Inputs
Name IEC 61131 Type Description
pt_Struct DWORD The address of the variable from which to read, as returned
by the ADR() function.
Outputs
Name IEC 61131 Type Description
Error STRING(80) Any internal errors display here as a human-readable string. The
string is empty if no errors are present.
Processing
ä You must call the function block body to obtain a lock on the mutex with the ID
specified.
ä If the mutex is already locked (indicating another operation is in progress), the op-
eration waits until the lock is released and it obtains the mutex.
ä After obtaining the mutex, this function block copies the data referenced by pt_Struct
into protected, internal memory and the lock is released.
fb_CrossTaskRead
If data exist on one task to be shared with another, use this function block on the task reading
the data. More than one reading function blocks may pull data from the same mutex.
Initialization Inputs
Name IEC 61131 Type Description
id UDINT The ID of the mutex from which this function block reads
(range [1..g_p_N_CrossTaskIDs]).
Inputs
Name IEC 61131 Type Description
pt_Struct DWORD The address of the variable to which the function block writes
the data, as returned by the ADR() function.
Outputs
Name IEC 61131 Type Description
Error STRING(80) Any internal errors display here as a human-readable string. The
string is empty if no errors are present.
Processing
ä You must call the function block body to obtain a lock on the mutex with the ID
specified.
ä If the mutex is already locked (indicating another operation is in progress), the op-
eration waits until the lock is released and it obtains the mutex.
ä After obtaining the mutex, the function block copies the data from protected, internal
memory into the location referenced by pt_Struct and the lock is released.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms:
ä SEL-3505
â R135-V2 firmware
ä SEL-3530
â R135-V2 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V2 firmware
fb_CrossTaskRead10
The posted time is the average execution time of 1000 calls in which a lock is obtained and
data are read from the mutex. This constitutes the worst case for this call. The variable
moved between tasks is an IEC 61131 dataset containing 10 UDINTs.
fb_CrossTaskWrite10000
The posted time is the average execution time of 1000 calls in which a lock is obtained and
data are written into the mutex. This constitutes the worst case for this call. The variable
moved between tasks is an IEC 61131 dataset containing 10000 UDINTs.
fb_CrossTaskRead10000
The posted time is the average execution time of 1000 calls in which a lock is obtained and
data are read from the mutex. This constitutes the worst case for this call. The variable
moved between tasks is an IEC 61131 dataset containing 10000 UDINTs.
Benchmark Results
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
You have declared your IEC 61131 datatype, dt_myAStruct; here we use the declaration
found in Code Snippet 6.1.
Solution
Create a writing program on the high-speed task, as shown in Code Snippet 6.2.
Create a reading program on the slow-speed task, as shown in Code Snippet 6.3.
// First, read in all the data from the mutex to the local variable.
_SlowReader(pt_Struct := ADR(_SlowA), Error => _ErrorA);
// Now use _SlowA structure information as you wish.
_TheAvar := _SlowA.a;
_TheBvar := _SlowA.b;
Assumptions
You have declared your IEC 61131 datatype, dt_myBStruct; here we use the declaration
found in Code Snippet 6.4.
c : REAL;
END_STRUCT
END_TYPE
Solution
Create a writing program on the slow-speed task, as seen in Code Snippet 6.5.
Create a reading program on the high-speed task, as seen in Code Snippet 6.6.
// First, read in all the data from the mutex to the local variable.
_FastReader(pt_Struct := ADR(_FastB), Error => _ErrorB);
DescriptiveData
Introduction
The DescriptiveData library includes classes intended to interpret and manage data struc-
tures formatted in common exchange formats.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myDescriptiveDataObject.value;
// As is this
pt_myDescriptiveDataObject := ADR(myDescriptiveDataObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent. This section should be included if there are enumeration POUs in the
library.
enum_JsonType
Enumeration Description
BASE Outermost shell of JSON structure.
VALUE JSON element that describes an actual string value.
KEY JSON element describing key for key-value pair. The child node of this key-
value pair is not required to be a string, it may also be a JSON LIST, MAP, or
VALUE.
MAP JSON element wrapping structure of key-value pairs. Represents the outer
shell of a dictionary-like structure.
LIST JSON element wrapping multiple child JSON object nodes. Child nodes may
be JSON LIST, MAP, VALUE, or any combination of these types.
enum_MatrixAccessMethod
Enumeration Description
e_NOT_SPECIFIED Initial enumeration state.
e_ROW Append or extract data sets on a per-row basis.
e_COLUMN Append or extract data sets on a per-column basis.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_JsonElement
Name IEC 61131 Type Description
JSON_TYPE enum_JsonType Enumerated description of the
JSON element’s type.
INDEX UDINT Index marking the element’s
location in the internal vec-
tor managed by class_JsonMan-
ager.
PARENT UDINT Index marking the location of
the element’s parent in internal
vector managed by class_Json-
Manager.
CHILD UDINT Index marking the location of
the element’s child in internal
vector managed by class_Json-
Manager.
PREVIOUS UDINT Index marking the location of
the previous sibling element
(contained within either a LIST
or MAP) in internal vector man-
aged by class_JsonManager.
NEXT UDINT Index marking the location of
the next sibling element (con-
tained within either a LIST or
MAP) in internal vector man-
aged by class_JsonManager.
LEVEL UDINT Depth of element in JSON
structure tree stored within
internal vector managed by
class_JsonManager.
DATA STRING(255) Data string that serves to store
either the key-string or the
value-string if the described
element is either a KEY or
VALUE, respectively.
pt_CONTENT POINTER TO SELString.class_SELString Pointer to the class_SELString
which stores the JSON con-
tents, either the key-string or
the value-string if the described
element is either a KEY or
VALUE.
Classes
This library provides the following classes as extensions of the IEC 61131 function block.
class_JsonManager(Class)
This class provides the necessary functionality to read JSON (JavaScript Object Notation)
data structures from any structure whose characters are accessible by byte-wise opera-
tions (example structures include Dynamic Vectors, STRINGs, and arrays of BYTEs). The
JSON standard is fully described at json.org.
This class also provides functionality to create a new blank JSON structure and then pop-
ulate it with simple key-value pairs. The value portion must be a simple string value and
cannot contain a map, list, or nested key-value pair.
A purely fictitious example of a JSON structure is shown below.
1 {
2 "device": {
3 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
4 "device name": "SEL-RTAC",
5 "licensed features": {
6 "features": [
7 {"hmi": true},
8 {"library": "fileio"},
9 {"library": "dynamicdisturbancerecorder"},
10 {"protocol": "IEC 61850 GOOSE"}
11 ]
12 },
13 "project": "Factory Default",
14 "users logged in": 1
15 }
16 }
The JSON format describes several data structure types, including key-value pair structures
and ordered lists. The official JSON format describes these two structure types as being
the foundational structures for the format as follows.
ä Key-Value Pair Structures: A collection of name/value pairs. In various languages,
this is realized as an object, record, struct, dictionary, hash table, keyed list, or asso-
ciative array.
ä Ordered List Structures: An ordered list of values. In most languages, this is
realized as an array, vector, list, or sequence.
The JSON standard defines support for various data types that may represent a value,
though in this class all value types are treated as strings and managed as IEC 61131-3
STRING(255) objects. This means that although JSON defines the ability to use Boolean,
numeric, and null types directly without the requirement of wrapping values in double-
quotes (i.e., the " character), this JSON class treats all values as strings, and will not apply
any type-specific conversions to generate IEC 61131-3 compliant BOOL, INT, or REAL
types. Such conversions are the responsibility of the user.
The JSON standard defines an object to be an “unordered set of name/value pairs,” in
essence, a dictionary. In the context of this class, JSON objects are represented by the
construction of MAP, KEY, and any child structure(s). These various types are described
and enumerated by enum_JsonType.
The MAP, LIST, and KEY types all support child structures, each of which may subse-
quently be any of the aforementioned types. VALUE structures do not support child struc-
tures because they are deemed to be the innermost structure in the JSON hierarchy. All
direct children of any MAP structure must be KEYs.
As per the JSON standard, this class will interpret all keys of key-value pairs that are
wrapped in double quotes (i.e., the " character). If keys in the JSON structure being parsed
are not wrapped in double quotes, an error will be thrown to indicate parsing failure.
White space including horizontal tabs, linefeed characters, carriage returns, and single
spaces may separate delimiting characters and respective key or value entries; backspace
and formfeed characters are not supported in such locations.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Outputs
Name IEC 61131 Type Description
Error BOOL TRUE if the class is unable to parse a JSON data structure
or a navigational or extraction method fails due to an invalid
JSON architecture.
ErrorDesc STRING(255) The last error encountered is described here and will only be
displayed when Error is TRUE.
Current struct_JsonElement The JSON structural element that is currently in scope. This
structure describes all of the relationships between the ele-
ment currently in scope and all relatives (parent/child/previ-
ous/ next).
ParseBytes (Method)
Call this method with an array of bytes that are desired to be parsed into an equivalent
JSON structure in the class_JsonManager.
Calling this method overwrites the JSON structure information parsed by any previous
calls. If more than one call per processing interval is expected, instantiate a single class_-
JsonManager for each call.
Inputs
Name IEC 61131 Type Description
pt_byte POINTER TO BYTE Address of the first byte in an array of bytes that should be
parsed into a JSON structure interpretation by the class_Json-
Manager.
Length UDINT Number of bytes in the array of bytes that should be parsed
and interpreted by the class_JsonManager.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if JSON structure is parsed successfully.
Processing
ä ParseBytes() call sets Error to FALSE and clears the ErrorDesc string.
ä ParseBytes() iterates over array of bytes and generates representative JSON structure
in class_JsonManager to describe the input.
ä ParseBytes() method enforces the maximum string value lengths for both keys and
values of JSON key-value pairs.
ä ParseBytes() method enforces JSON structure formatting according to JSON format-
ting guidelines provided by the JSON standard.
Down (Method)
Call this method to force the class_JsonManager to move down into a nested data structure
object (node) to reference the elements in that node’s scope.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_JsonManager successfully navigates to nested
node.
Processing
ä Down() call validates that child node exists. Returns FALSE if child node does not
exist.
ä Down() sets class_JsonManager to view the scope of child node.
Next (Method)
Call this method to force the class_JsonManager to move to the next sibling data structure
object (node) in a series to reference the elements in that node’s scope.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_JsonManager successfully navigates to next node
in series.
Processing
ä Next() call validates that relative sibling node exists. Returns FALSE if next sibling
node does not exist.
ä Next() call validates that relative sibling node is not self. Returns FALSE if next
sibling node’s index is equal to current node’s index.
ä Next() sets class_JsonManager to scope of the next node in series.
Previous (Method)
Call this method to force the class_JsonManager to move to the previous sibling data struc-
ture object (node) in a series to reference the elements in that node’s scope.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_JsonManager successfully navigates to previous
node in series.
Processing
ä Previous() call validates that relative sibling node exists. Returns FALSE if previous
sibling node does not exist.
ä Previous() call validates that relative sibling node is not self. Returns FALSE if
previous sibling node’s index is equal to current node’s index.
ä Previous() sets class_JsonManager to scope of the previous node in series.
Root (Method)
Call this method to direct the class_JsonManager to reset scope of the manager class to the
outermost, so-called root location, of the JSON structure. This method provides a means
for resetting the manager’s view of the structure following Get() method calls that enter
the nesting of the JSON structure. As the Get() method is called for entering nesting one
JSON level at a time, the Root() method is used to exit all nested levels in one step.
The JSON structure example shown below will observe the behavior described immediately
following the example upon a call to the Root() method at any time during operation.
1 {
2 "device": {
3 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
4 "device name": "SEL-RTAC",
5 "licensed features": {
6 "features": [
7 {"hmi": true},
8 {"library": "fileio"},
9 {"library": "dynamicdisturbancerecorder"},
10 {"protocol": "IEC 61850 GOOSE"}
11 ]
12 },
13 "project": "Factory Default",
14 "users logged in": 1
15 }
16 }
Calling the Root() method at any point while navigating the JSON structure shown above
will set the class_JsonManager’s view to the outermost layer. In essence, the very first curly
bracket that is listed before device will be used as the root location as it serves to describe
the outermost MAP of the structure. Upon such an operation, the root position would be
of type MAP and show a class_JsonManager index of 1, a parent element node index of 0,
and a child element node index of 2. The aforementioned child would logically be of type
KEY with a key name of “device”.
The root location will never describe a next or previous index, and although it may or may
not describe a child element node index, it will always describe a parent element node
index, which will always be zero.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_JsonManager successfully navigates to root.
Processing
ä Root() sets class_JsonManager to scope of the root node in JSON structure.
Up (Method)
Call this method to force the class_JsonManager to move up from a nested data structure
object (node) to reference the elements in that node’s parent’s scope.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_JsonManager successfully navigates to parent
node.
Processing
ä Up() call validates that parent node is not base-level, returns FALSE otherwise.
ä Up() sets class_JsonManager to scope of the parent node.
Get (Method)
Call this method to obtain the available value from a keyed dictionary or ordered list from
the internally managed JSON structure. If the obtained value cannot be represented as
a string (i.e., the sub-structure is a list or dictionary), this method will move the class_-
JsonManager reference to that sub-structure in preparation for the next Get() method or
the next navigational method (i.e., Up(), Down(), Next(), Previous(), or Root()).
In order to facilitate both keyed and ordered data retrieval, this method accepts an input
as a STRING(255) that can materialize as either the key of a key-value pair, or a string
representation of the zero-based index for an element in a list of objects.
The Get() method utilizes a combination of both a method return value and the class_-
JsonManager’s Error and ErrorDesc outputs. This combination is especially useful in
providing feedback to the user regarding whether the operation performed by the Get()
method resulted in one of three states. These three states are not a form of enumerated
states, but rather a combination of class and method outputs and method returns. These
states are meant to describe successful string extraction, successful structure extraction
without a string, or unsuccessful extraction where neither string or child structure could be
extracted.
When a string (VALUE) is successfully extracted from the JSON element, the Get()
method output is set with the string value, and the return value is set to TRUE. In situ-
ations where the Get() method is able to find the keyed or indexed structure, but no valid
VALUE is associated with that element (i.e., the child is of type: MAP, LIST, or KEY) the
output will be left unaltered as an empty string, and the return value will be set to FALSE.
If the particular key or index requested with the Get() method cannot be found in the cur-
rent scope, the method will both return FALSE and indicate an error by use of the Error
and ErrorDesc outputs of the class_JsonManager.
In addition to setting the output string of the method to equal the VALUE of the JSON
element and setting the return value to TRUE, when the string extraction is successful,
the Get() method will set the class_JsonManager scope to the element’s parent entry.
That is to say, if a VALUE is extracted from a key-value pair, the parent KEY of that key-
value pair will become the active scope of the class_JsonManager. In this way, sequential
iteration over a list of values, or map of key-value pairs can be performed in a logical flow.
Furthermore, upon such successful extraction, the method returns TRUE and clears the
class ErrorDesc output while setting Error to FALSE.
In instances where this method cannot return a value directly (i.e., the child is of type MAP,
LIST, or KEY) but the particular key or index exists in the class_JsonManager, the method
will move as appropriate to the new scope of this key or index and it will remain in this
position to support continued nesting and iteration for value extraction. This will result
in the return value being set to FALSE and the output being set to an empty string. In
instances where this method cannot find the key or index due to lack of its presence in
the current scope, the class_JsonManager will be reset to the root location (the outermost
JSON structure), the Error output will be set to TRUE, and ErrorDesc output will indicate
a failure to find the requested key or index in the current scope.
In situations where the class_JsonManager is referencing a MAP or LIST, this method will
automatically nest itself into the first child node of the MAP or LIST to clearly interpret the
keys or list entries of the structure and allow for clear JSON navigation. Conversely, if the
class_JsonManager references a JSON element that is described as a non-valid JSON type
(i.e., BASE), this method will return FALSE and indicate error by means of the Error and
ErrorDesc outputs.
Shown below is an example of a JSON structure upon which the Get() method can be
called to extract various data points.
1 {
2 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
3 "device name": "SEL-RTAC",
4 "licensed features": {
5 "features": [
6 {"hmi": true},
7 {"library": "fileio"},
8 {"library": "dynamicdisturbancerecorder"},
9 {"protocol": "IEC 61850 GOOSE"}
10 ]
11 },
12 "project": "Factory Default",
13 "users logged in": 1
14 }
Immediately following the parsing operation of the above data structure, the Get() method
will have access to retrieve the various structures of the outermost keys. That is to say that
the following strings would be valid arguments for the Get() method at the root location.
If a user is to use the Get() method to extract the structure related to the "licensed features"
key, the class_JsonManager will change scope to provide access to a new set of valid keys
as shown below.
[ "features" ]
Furthermore, if a user leverages the Get() method to extract the "features" key, a new set
of valid arguments will be allowed, but as these subsequent elements are children of a LIST,
they should be accessed by zero-based index. As such, the valid arguments are now a set
of strings as shown below.
In summary, after parsing the above JSON data structure, and directly using the Get()
method to extract data associated with a particular key, a string value will be output if
the particular data structure associated with the key/index input is of type VALUE. Thus,
referencing a VALUE containing a valid string, the return will be set TRUE and output
loaded with the data string. Conversely, if the particular structure is of any other JSON
type and the key/index exists, the class_JsonManager will navigate to the scope of that
structure and return FALSE without setting any error indication.
Inputs
Name IEC 61131 Type Description
KeyIndex STRING(255) String representing the particular key or index of the data that
should be extracted.
Outputs
Name IEC 61131 Type Description
Value STRING(255) String representing the particular VALUE associated with its
keyed or indexed parent.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if string value successfully extracted, FALSE if failure oc-
curs or if substructure is not of type VALUE.
Processing
ä Get() call sets class error output to FALSE and sets error description string output
to an empty string (i.e., ’ ’).
ä Get() call validates that current scope allows for extraction of values associated with
the particular key or index.
ä Get() performs nesting as necessary to enter the scope of either MAP or LIST types.
ä Get() iterates over the keys or indices currently visible in the JSON structure and
tests each key or index against the input KEY to identify the appropriate value string
to extract.
ä Get() stores the extracted value in the output VALUE string if found and sets the re-
turn value of the method to TRUE before setting the class_JsonManager back to the
value’s parent location.
ä Get() moves the class_JsonManager to the scope of the particular key or index if
found, sets the return value of the method to FALSE, and empties the output string
(i.e., sets the output value to ’ ’).
ä Get() moves the class_JsonManager to the root location if the provided key/index in-
put is not found in the current scope. Additionally, the class error flag and description
string will be set to indicate such failure to locate key or index.
GetSELString (Method)
Call this method to obtain the available value from a keyed dictionary or ordered list as
a SELString from the internally managed JSON structure. If the obtained value cannot
be represented as a string (i.e., the sub-structure is a list or dictionary), this method will
move the class_JsonManager reference to that sub-structure in preparation for the next
GetSELString() method or the next navigational method (i.e., Up(), Down(), Next(),
Previous(), or Root()).
This method has identical functionality and processing to the previously-described Get()
method, except a class_SELString is first cleared and if the key or list index is valid is then
populated with the Value.
Inputs
Name IEC 61131 Type Description
KeyIndex STRING(255) String representing the particular key or index of the data that
should be extracted.
Inputs/Outputs
Name IEC 61131 Type Description
Value SELString.class_SELString SELString representing the particular VALUE associ-
ated with its keyed or indexed parent.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_SELString value successfully extracted, FALSE if
failure occurs or if substructure is not of type VALUE.
DumpStructure (Method)
Call this method to obtain the data structure contained within the class_JsonManager and
store the structure in a vector appropriately sized to contain struct_JsonElement elements.
Inputs/Outputs
Name IEC 61131 Type Description
StructVector DynamicVectors.class_BaseVector Dynamic vector object sized appropriately
to contain struct_JsonElement elements.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the full data structure is loaded successfully.
Processing
ä DumpStructure() call clears StructVector.
ä DumpStructure() call validates that current JSON vector is valid and not empty; re-
turns FALSE otherwise.
ä DumpStructure() iterates over each element contained in JSON structure and ap-
pends elements to StructVector.
GetNextValue (Method)
Call this method to obtain the next available value from a keyed dictionary or ordered list
in the current scope of the internally managed JSON structure.
Outputs
Name IEC 61131 Type Description
Value STRING(255) The value of next key if present scope is a MAP or next list value
if the present scope is a LIST.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the next element in the MAP or list was successfully
loaded into the Value Output.
Processing
ä If current scope is the outermost element of a LIST or MAP, navigate down into the
list or map. After navigating down, if a value is present at this scope (such as with a
list), load this value into the Value output and return.
ä Navigate to the next element.
ä If Current element is a KEY, navigate down until a VALUE can be extracted and
loaded into the Value output.
ä If parent of Current element is a LIST, navigate down until a VALUE can be extracted
and loaded into the Value output.
GoToIndex (Method)
Call this method to navigate to a specified element in the JSON structure and load it to the
current scope.
Inputs
Name IEC 61131 Type Description
NewIndex UDINT Index of the JSON vector which should be loaded as the Cur-
rent scope.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the specified element was successfully loaded as the cur-
rent scope.
Processing
ä Validate that the JSON structure contains at least the BASE element and an initial
LIST or MAP entry.
ä Validate that NewIndex is not 0 or a value greater than the size of the JSON structure.
ä Load the element specified by NewIndex into the Current scope of the class_Json-
Manager.
Reset (Method)
Call this method to reset a JSON structure that had previously been populated by calls to
either ParseBytes() or AddKeyValuePair().
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the JSON structure was successfully reset.
Processing
ä Resets and clears any existing content in the JSON structure.
ä Resets and clears any previously serialized data.
ä Clears any existing error conditions.
ä Creates a single base element in the JSON structure representing the outermost ele-
ment of the structure.
AddKeyValuePair (Method)
Call this method to add a new key-value pair to a new JSON structure or one that was
previously re-initialized with the Reset() method. All Keys are added sequentially as level
2 elements in a contiguous map that exists at level 1 of the JSON structure. Values are
added as single level 3 elements beneath their respective Key. Values must be a simple
string element and cannot contain a map, list, or nested key-value pair.
A sample JSON structure that can be created with AddKeyValuePair() is shown below:
1 {
2 "fid" : "SEL-3530-R148-V2-Z000015-D20210414",
3 "device name" : "SEL-RTAC",
4 "project" : "Factory Default",
5 "users logged in" : "1",
6 "hmi enabled" : "true",
7 "key" : "value"
8 }
Inputs
Name IEC 61131 Type Description
Key STRING(255) Specifies the name of the key.
Value STRING(255) Specifies the value to associate with the key.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the key-value pair was successfully added to the JSON
structure.
Processing
ä Verifies if the JSON structure is empty and sets up the initial BASE element if re-
quired.
ä Verifies that the specified Key name is unique to any previously added Keys. Will
set the Error and ErrorDesc outputs and return FALSE if the Key name already
exists.
ä If required, a MAP JSON element will be added to the JSON structure at INDEX 1,
LEVEL 1.
ä Adds the new Key-Value pair to the end of the existing JSON structure.
ä Updates the PREVIOUS and NEXT properties of the first and last Keys in the JSON
structure to link to the new Key element as their sibling.
ä Updates the Current scope of the JSON manager to the root MAP element.
AddKeyValuePairSELString (Method)
Call this method to add a new key-value pair to new JSON structure or one that was previ-
ously re-initialized with the Reset() method. The Value component of the pair is assigned
from a SELString variable.
This method has identical functionality and processing to the previously-described AddKeyValuePair()
method, except the Value is assigned from a class_SELString variable.
Inputs
Name IEC 61131 Type Description
Key STRING(255) Specifies the name of the key.
Inputs/Outputs
Name IEC 61131 Type Description
Value SELString.class_SELString Specifies the SELString value to associate with the key.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the key-value pair was successfully added to the JSON
structure.
SerializeJson (Method)
Call this method to obtain the data structure contained within the class_JsonManager and
translate the contents into an array of BYTEs containing JSON compliant ASCII format-
ting. A pointer to the array of bytes is available via the pt_SerializedData property and the
NumSerializedBytes property can be used to determine the length of the array.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the JSON structure is successfully serialized.
Processing
ä A SerializeBytes() call iterates over each item contained in the JSON structure and
writes out machine-formatted (no human-readable format ’helpers’ such as carriage
returns or tabulation is included) JSON-compliant characters into the array of bytes
specified at pt_Byte.
ä The resulting serialized data is stored in an internal data array managed by the class_-
JsonManager instance. A pointer to the array of data is available via the pt_Serial-
izedData property and the length of the array is available via the NumSerializedBytes
property.
class_CsvManager(Class)
This class provides the necessary functionality to write/read CSV (comma separated value)
content to/from the RTAC logic engine. This documentation references a CSV object. This
object is a two-dimensional data buffer that uses dynamic memory allocation to adjust in
size. This object serves as a prototype CSV data set and allows CSV content to be read
from an external buffer and/or appended incrementally by row or column. The object can
then be serialized (written to a byte string) at the user’s discretion for easy consumption by
a file writer.
This class can be configured to switch between various CSV composition modes during
run-time by calling the provided ’init’ methods whenever a mode switch is desired.
Inputs
Name IEC 61131 Type Description
LogRuntimeErrors BOOL If TRUE, the library logs runtime errors in the
RTAC Sequence of Events (SOE) log.
Outputs
Name IEC 61131 Type Description
Initialized BOOL When TRUE, CsvManager is ready for append,
extraction, or serialization operations. Default is
FALSE.
Busy BOOL When TRUE, CsvManager is actively processing.
Default is FALSE.
CsvParsed BOOL Pulses for one cycle after completion of a CSV
parse operation that was initiated via InitReadWrite-
Mode(). Default is FALSE.
PercentParsed REAL A number between 0 and 100 representing the com-
pletion percentage of the parse operation. Default is
0.
CsvSerialized BOOL Pulses for one cycle after completion of a CSV se-
rialization operation that was initiated via Serial-
izeCsv(). Default is FALSE.
PercentSerialized REAL A number between 0 and 100 representing the com-
pletion percentage of the serialize operation. Default
is 0.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
InitReadWriteMode (Method)
This method initializes the CSV manager in read/write mode and initiates a CSV parse
operation.
ä This mode allows existing CSV content to be parsed, modified, and written.
ä This mode forces AppendMode := e_ROW.
ä CSV content to be parsed must contain a consistent number of comma-delimited
elements per line.
Inputs/Outputs
Name IEC 61131 Type Description
inVector DynamicVectors.class_ByteVector A byte vector loaded with CSV content via
FileIO.class_FileReader2.AppendToVector()
or equivalent.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if InVector.Size = 0 or Busy = TRUE. Otherwise, returns
TRUE.
Processing
1. If InVector.Size = 0, returns FALSE.
2. If Busy = TRUE, returns FALSE.
3. Else does the following:
ä Sets class outputs to default values.
ä Clears the CSV object if not already clear.
ä Sets AppendMode := e_ROW.
ä Requests a parse operation to be executed by the Run() method.
ä Sets Busy = TRUE.
InitWriteColumnMode (Method)
This method initializes the CSV manager with a blank CSV object.
ä This mode allows for the creation of new CSV content via column append operations.
ä This mode forces AppendMode := e_COLUMN.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if Busy = TRUE. Otherwise, returns TRUE.
Processing
1. If Busy = TRUE, returns FALSE.
2. Else does the following:
ä Sets class outputs to default values.
ä Sets AppendMode := e_COLUMN.
InitWriteRowMode (Method)
This method initializes the CSV manager with a blank CSV object and a fixed label row.
ä This mode allows for the creation of new CSV content via row append operations.
ä This mode forces AppendMode := e_ROW.
Inputs
Name IEC 61131 Type Description
pt_Labels POINTER TO STRING(255) A pointer to a contiguous memory space contain-
ing a collection of column labels.
numLabels UDINT The number of labels to append.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if Busy = TRUE or on invalid input. Otherwise, returns
TRUE.
Processing
1. If Busy = TRUE, returns FALSE.
2. Checks the memory space defined by the inputs, if invalid, returns FALSE.
3. Else does the following:
ä Sets class outputs to default values.
ä Sets AppendMode := e_ROW.
ä Clears the CSV object if not already clear.
ä Sets NumColumns = numLabels.
ä Sets Initialized := TRUE.
SerializeCsv (Method)
This method initiates an asynchronous serialization of the CSV object into a CSV formatted
byte string.
Return Value
IEC 61131 Type Description
BOOL Returns False if errors were encountered. Otherwise, returns TRUE.
Processing
1. If Initialized = FALSE or Busy = TRUE, returns FALSE.
2. Else does the following:
ä Sets Busy to TRUE.
ä Sets PercentSerialized to 0.
ä Requests a serialization operation to be conducted by the Run() method
SerializeRow (Method)
This method converts a memory-contiguous collection of STRING(255) objects to a byte
string that can be used for direct file writing via a FileIO.FileWriter.AppendBytes() method
call. This method can be used independently from the other methods and does not require
Initialized = TRUE. Note: This method does not affect the CsvSerialized or Per-
centSerialized class outputs.
Inputs
Name IEC 61131 Type Description
pt_sourceData POINTER TO STRING(255) A pointer to a contiguous memory space con-
taining the row content.
numElements UDINT Number of STRING(255) elements in the data
set.
Outputs
Name IEC 61131 Type Description
pt_serializedRow POINTER TO BYTE Pointer to the first byte of serialized row data.
numSerializedBytes UDINT Number of serialized bytes.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if invalid input. Otherwise, returns TRUE.
Processing
1. Returns FALSE if any of the following are TRUE:
ä pt_sourceData = 0
ä numElements = 0
2. Else, does the following:
ä Copies each STRING(255) (up to but not including the null byte) into a con-
tiguous memory space, separated by ASCII commas (,).
ä Appends an ASCII newline followed by a carriage return to the end of the
serialized bytes.
AppendColumn (Method)
This method appends a new column to the CSV object.
Inputs
Name IEC 61131 Type Description
label STRING(255) Column label, to appear in row 1 of the CSV
object.
pt_sourceData POINTER TO STRING(255) Pointer to the data.
numElements UDINT Number of elements in the data set.
appendToFront BOOL Set to TRUE to append data set as the first
column of the CSV object. Set to FALSE to
append as the last column.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if invalid input. Otherwise, returns TRUE.
Processing
1. Returns FALSE if any of the following are TRUE:
ä Busy = TRUE
ä Initialized = FALSE
ä AppendMode = e_ROW
ä The memory space defined by the inputs is invalid.
ä numElements = 0
2. Else, does the following:
ä Appends label to an internal buffer.
ä Appends numElements of content from pt_sourceData to the CSV object.
ä Increments NumColumns by one.
AppendRow (Method)
This method appends a new row to the CSV object.
Inputs
Name IEC 61131 Type Description
pt_sourceData POINTER TO STRING(255) Pointer to the data.
numElements UDINT Number of elements in the data set.
appendToTop BOOL Set to TRUE to append data set as the first row
of the CSV object. Set to FALSE to append as
the last row.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if invalid input. Otherwise, returns TRUE.
Processing
1. Returns FALSE if any of the following are TRUE:
ä Busy = TRUE
ä Initialized = FALSE
ä AppendMode = e_COLUMN
ä The memory space defined by the inputs is invalid.
ä numElements = 0
ä numElements <> NumColumns
2. Else, does the following:
ä Else appends numElements of content from pt_sourceData to the CSV object.
ä Increments NumRows by one.
DeleteDataSets (Method)
This method deletes one or more columns or rows from the CSV object. For row deletion
operations, the label row is not eligible for deletion.
Inputs
Name IEC 61131 Type Description
deleteMode enum_MatrixAccessMethod Specify deletion by row or column.
numToDelete UDINT The number of columns or rows to delete.
deleteFromFront BOOL Set to TRUE to delete starting with the first
row or column. Set to FALSE to delete start-
ing with the last row or column.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if invalid input. Otherwise, returns TRUE.
Processing
1. Returns FALSE if any of the following are TRUE:
ä If Busy = TRUE
ä Initialized = FALSE
ä deleteMode is an invalid enumeration entry
ä numToDelete is greater than NumColumns or NumRows (depends on delete-
Mode)
2. Else, does the following:
ä Removes numToDelete rows or columns from the CSV object.
ä Decrements NumColumns or NumRows by numToDelete (depends on delete-
Mode).
ExtractDataSetToQueue (Method)
This method copies one column or row from the CSV object into a designated double-ended
queue.
Inputs
Name IEC 61131 Type Description
extractMode enum_MatrixAccessMethod Specify extraction by row or column.
dataSetIndex UDINT A one-based row or column index for the data
set to be extracted. Row index one corresponds
to the first row after the label row.
Inputs/Outputs
Name IEC 61131 Type Description
targetQueue Queue.class_Deque Queue with elementSize := SIZEOF(STRING(255))
to contain the extracted dataset.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if invalid input. Otherwise, returns TRUE.
Processing
1. Returns FALSE if any of the following are TRUE:
ä If Busy = TRUE
ä Initialized = FALSE
ä extractMode is an invalid enumeration entry
ä dataSetIndex is zero or greater than NumColumns or NumRows (depends
on extractMode)
2. Else, does the following:
ä Calls Recycle() on TargetQueue.
ä Copies row or column and pushes to the back of TargetQueue.
ExtractDataSetToVector (Method)
This method copies one column or row from the CSV object into a designated dynamic
vector.
Inputs
Name IEC 61131 Type Description
extractMode enum_MatrixAccessMethod Specify extraction by row or column.
dataSetIndex UDINT A one-based row or column index for the data
set to be extracted. Row index one corresponds
to the first row after the label row.
Inputs/Outputs
Name IEC 61131 Type Description
targetVector DynamicVectors.class_BaseVector Dynamic vector with elementSize :=
SIZEOF(STRING(255)) to contain the ex-
tracted dataset.
Return Value
IEC 61131 Type Description
BOOL Returns FALSE if invalid input. Otherwise, returns TRUE.
Processing
1. Returns FALSE if any of the following are TRUE:
ä If Busy = TRUE
ä Initialized = FALSE
ä extractMode is an invalid enumeration entry
ä dataSetIndex is zero or greater than NumColumns or NumRows (depends
on extractMode)
2. Else, does the following:
ä Calls Recycle() on TargetVector.
ä Copies row or column and pushes to the back of TargetVector.
ExtractCell (Method)
This method copies the contents of one cell of the CSV Object and returns the STRING
value.
Inputs
Name IEC 61131 Type Description
rowIndex UDINT The one-based row index of the target cell.
colIndex UDINT The one-based column index of the target cell.
isLabel BOOL When TRUE, the column label at colIndex is returned.
rowIndex is ignored.
Return Value
IEC 61131 Type Description
STRING(255) Returns the STRING value of the cell at rowIndex , colIndex.
Processing
1. Returns a null string if any of the following are TRUE:
ä Busy = TRUE
ä Initialized = FALSE
ä rowIndex is zero or greater than NumRows while isLabel = FALSE
OverwriteCell (Method)
This method overwrites the contents of one cell of the CSV Object.
Inputs
Name IEC 61131 Type Description
rowIndex UDINT The one-based row index of the target cell.
colIndex UDINT The one-based column index of the target cell.
newValue STRING(255) The content with which the cell will be overwritten.
isLabel BOOL When TRUE, the column label at colIndex is returned.
rowIndex is ignored.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if cell was overwritten.
Processing
1. Returns FALSE if any of the following are TRUE:
ä Busy = TRUE
ä Initialized = FALSE
ä rowIndex is zero or greater than NumRows while isLabel = FALSE
ä colIndex is zero or greater than NumColumns
2. Else, the original cell content will be deleted, any found ASCII commas (,) within
newValue will be removed and the result will be written to the cell.
Run (Method)
This method must be called once per scan for handling all asynchronous operations.
Processing
1. If Busy = FALSE and InitReadWriteCsv() was called prior to this call of the Run()
method:
ä Parses the content specified by the inputs of InitReadWriteMode() into the
CSV object.
ä ASCII comma characters as well as newline and carriage returns will be dis-
carded.
ä 5 milliseconds per task cycle will be provided to the Run method for CSV
parse operations.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that a JSON data structure defined by the user is to be parsed. This
JSON structure is to be defined as follows, with three keys in the outermost MAP of the
structure.
1 {
2 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
3 "licensed features": {
4 "features": [
5 {"hmi": true},
6 {"library": "fileio"}
7 ]
8 },
9 "device name": "SEL-RTAC"
10 }
Solution
In order to appropriately extract the keys from this JSON structure, the string must first
be parsed, and because the exact number of key-strings in the JSON structure is known,
the keys can be loaded into an array of STRING(255)s with that exact number of elements.
Note, however, this is not an advisable operation when the number of keys is either unknown
or could change.
Assumptions
This example assumes that a JSON data structure to be parsed by the user is already stored in
a globally accessible class_ByteVector. This particular object is assumed to have a variable
name of JsonInVector. This JSON structure is to be defined as follows, with three keys in
the outermost MAP of the structure, and various nested structures contained within.
1 {
2 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
3 "licensed features": {
4 "features": [
5 {"hmi": true},
6 {"library": "fileio"}
7 ]
8 },
9 "device name": "SEL-RTAC"
10 }
Solution
In order to appropriately extract the desired values from this JSON structure, two STRING(255)
variables must first be provisioned to contain the values which will be extracted.
Assumptions
This example assumes that a JSON data structure defined by the user has already been
declared as an array of bytes accessible globally; this array will be considered to be named
g_ByteArray, and will contain a number of bytes recorded by g_ByteArrayLength.
1 {
2 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
3 "licensed features": {
4 "features": [
5 {"hmi": true},
6 {"library": "fileio"}
7 ]
8 },
9 "device name": "SEL-RTAC"
10 }
Considering the above listed JSON structure, the assumption will be made that the maxi-
mum size of the internal JSON structure will be 128 struct_JsonElement elements; as such,
the initial number of vector elements will be set to 128 as an arbitrary size.
Solution
Code Snippet 7.3 prg_DumpJson
PROGRAM prg_DumpJson
VAR
RunOnce : BOOL := TRUE;
JsonElems : DynamicVectors.class_BaseVector(
SIZEOF(struct_JsonElement), 128 );
JsonParser : class_JsonManager;
END_VAR
Assumptions
This example assumes that a JSON text file with the content such as the following is the
desired end-point. The FileIo library must be inserted into the project in order to perform
the file writer operation.
1 {
2 "SystemTags.FID" : "SEL-3530-R148-V2-Z000015-D20210414",
3 "SystemTags.CPU_Burden_Percent" : "5",
4 "SystemTags.SystemTags.Memory_KBytes_Remaining" : "123456",
5 "SystemTags.SystemTags.Memory_KBytes_Used" : "100000"
6 }
Solution
Code Snippet 7.4 prg_AddKeyValuePairsToJson
PROGRAM prg_AddKeyValuePairsToJson
VAR
PopulateJson : BOOL;
RunOnce : R_TRIG;
JsonParser : class_JsonManager;
FileWriter : fileio.class_FileWriter('/RTAC_statistics.json');
TempString : STRING(255);
TempSELString : class_SELString;
END_VAR
END_IF
FileWriter.Run();
Solution
Code Snippet 7.5 prg_WriteRowCsv
PROGRAM prg_WriteRowCsv
VAR CONSTANT
c_fileName : STRING := 'TestCsvFile.csv';
c_numColumns : UDINT := 6;
c_columnLabels : ARRAY [1 .. c_numColumns] OF STRING(255) :=
['System Time' ,'CPU Burden' , 'Main Board Temp', 'Memory
Kbytes Used', 'Rail (5V)', 'IRIG OK'];
c_fileLength : UDINT := 60000; //Duration of the file in
milli-seconds
c_samplecollectionPeriod : TIME := T#1S;
END_VAR
VAR
csvManager : class_CsvManager := (LogRuntimeErrors := TRUE);
writer : FileIO.class_FileWriter(fileName := c_fileName);
stage : UINT;
complete : BOOL;
//Status outputs
csvManagerInitialized : BOOL;
csvManagerError : BOOL;
csvManagerErrorDesc : STRING(255);
csvManagerNumRows : UDINT;
csvManagerNumColumns : UDINT;
END_VAR
1:
IF csvManager.NumRows < numRowsPerFile THEN
//collect a set of samples once the sample collection timer asserts
//Pass the temp row vector to the csv manager, to be added to the
bottom of the internal CSV object.
//This should provide us with an ordering of samples from oldest at
the top to newest at the bottom.
csvManager.AppendRow(pt_sourceData := tempRow.pt_Data, numElements
:= tempRow.Size, appendToTop := FALSE);
END_IF
//If all rows have been added, move to the next stage
ELSE
stage := stage + 1;
END_IF
2:
//Initiate serialization of the CSV content
IF NOT csvManager.Busy AND_THEN csvManager.SerializeCsv() THEN
stage := stage + 1;
END_IF
3:
//When complete, push the content to the file writer buffer
IF csvManager.CsvSerialized THEN
writer.AppendBytes(pt_data := csvManager.pt_SerializedData,
numBytes := csvManager.NumSerializedBytes);
stage := stage + 1;
END_IF
4:
//When the file writer has completed the file write operation, assert the
'complete' indicator
IF writer.BytesLeft = 0 THEN
complete := TRUE;
END_IF
END_CASE
//Update the status outputs (informational - not required for the basic
function of this example)
csvManagerInitialized := csvManager.Initialized;
csvManagerError := csvManager.Error;
csvManagerErrorDesc := csvManager.ErrorDesc;
csvManagerNumRows := csvManager.NumRows;
csvManagerNumColumns := csvManager.NumColumns;
Assumptions
This example assumes the following:
1. A CSV formatted file named TestCsvFile.csv exists in the RTAC’s top level of the
file system (i.e., the /FILES folder).
2. TestCsvFile.csv contains 6 columns of data, with at least 11 rows of data.
3. The data represented by the six columns within TestCsvFile.csv can be labeled as
follows.
ä column 1 : Timestamp
ä column 2 : CPU Burden Percent
ä column 3 : Main board temperature
ä column 4 : Kbytes of memory used
ä column 5 : 5V rail measurement
ä column 6 : IRIG OK status
A file that satisfies these assumptions is generated by the previous example.
Solution
Code Snippet 7.7 prg_ReadWriteCsv
PROGRAM prg_ReadWriteCsv
VAR CONSTANT
c_originalFileName : STRING := 'TestCsvFile.csv';
c_numRowsToDelete : UDINT := 10;
c_samplecollectionPeriod : TIME := T#1S;
END_VAR
VAR
csvManager : class_CsvManager := (LogRuntimeErrors := TRUE);
inputVector : DynamicVectors.class_ByteVector;
tempRow : DynamicVectors.class_BaseVector(elementSize :=
SIZEOF(STRING(255)), numElements := 0);
numRowsPerFile : UDINT;
sampleCollectionTimer : TI;
systemTime : STRING(255);
sampleCpuBurden : STRING(255);
sampleMbTemp : STRING(255);
sampleKbUsed : STRING(255);
sample5vRail : STRING(255);
sampleIrigOK : STRING(255);
reader : fileIO.class_FileReader2;
writer : fileIO.class_FileWriter(FileName :=
'TestCsvFile_Latest.csv');
stage : UINT;
complete : BOOL;
//Status outputs
csvManagerInitialized : BOOL;
csvManagerError : BOOL;
csvManagerErrorDesc : STRING(255);
csvManagerNumRows : UDINT;
csvManagerNumColumns : UDINT;
END_VAR
1:
//When complete, copy data into a vector and pass the vector to the
CSV manager
IF (reader.BytesInBuffer > 0) AND NOT csvManager.Busy THEN
//Copy the content into a vector
reader.AppendToVector(startByte := 0, vector := inputVector);
//Initialize CsvWriter in read/write mode and request a
parse operation
csvManager.InitReadWriteMode(inVector := inputVector);
stage := stage + 1;
END_IF
2:
//When the data has been parsed into the internal CSV object,
delete the oldest 10 rows
IF csvManager.CsvParsed THEN
//First, take note of how many rows the file should have at
the end of this operation
numRowsPerFile := csvManager.NumRows;
IF csvManager.NumRows > c_numRowsToDelete THEN
csvManager.DeleteDataSets(deleteMode :=
enum_MatrixAccessMethod.e_ROW,
numToDelete := c_numRowsToDelete,
deleteFromFront := TRUE);
stage := stage + 1;
END_IF
END_IF
3:
//Add new rows to the end until our total number of rows matches
the expected number
IF csvManager.NumRows < numRowsPerFile THEN
//Recycle tempRow
tempRow.Recycle();
//Now append the row to the top of the internal CSV object
csvManager.AppendRow(pt_sourceData := tempRow.pt_Data, numElements
:= tempRow.Size, appendToTop := FALSE);
END_IF
ELSE
stage := stage + 1;
END_IF
4:
//Now serialize the modified CSV object
5:
//Once complete, append the serialized content to the file writer
buffer
IF csvManager.CsvSerialized THEN
writer.AppendBytes(pt_data := csvManager.pt_SerializedData,
numBytes := csvManager.NumSerializedBytes);
stage := stage + 1;
END_IF
6:
//Flag completion of file writing
IF writer.BytesLeft = 0 THEN
complete := TRUE;
END_IF
END_CASE
Solution
Code Snippet 7.9 prg_WriteMixedFormatCsv
PROGRAM prg_WriteMixedFormatCsv
VAR CONSTANT
c_fileName : STRING := 'MixedFormatCSV.csv';
c_fileLength : UDINT := 60000; //Duration of the file in
milli-seconds
c_samplecollectionPeriod : TIME := T#1S;
END_VAR
VAR
csvManager : class_CsvManager := (LogRuntimeErrors := TRUE);
writer : FileIO.class_FileWriter(fileName := c_fileName);
systemFID : STRING(255);
systemPartNo : STRING(255);
systemTime : STRING(255);
sampleCpuBurden : STRING(255);
sampleMbTemp : STRING(255);
systemTimeVector : DynamicVectors.class_BaseVector(elementSize :=
SIZEOF(STRING(255)), numElements := 0);
cpuBurdenVector : DynamicVectors.class_BaseVector(elementSize :=
SIZEOF(STRING(255)), numElements := 0);
temperatureVector : DynamicVectors.class_BaseVector(elementSize :=
SIZEOF(STRING(255)), numElements := 0);
tempRow : DynamicVectors.class_BaseVector(elementSize :=
SIZEOF(STRING(255)), numElements := 0);
stage : UINT;
complete : BOOL;
//Status outputs
csvManagerInitialized : BOOL;
csvManagerError : BOOL;
csvManagerErrorDesc : STRING(255);
csvManagerNumRows : UDINT;
csvManagerNumColumns : UDINT;
END_VAR
1:
//Accumulate data for the CSV file
systemPartNo := SystemTags.PARTNO.strVal;
systemFID := SystemTags.FID.strVal;
2:
//Append columns
csvManager.AppendColumn(label := 'FID', pt_sourceData :=
ADR(systemFID), numElements := 1, appendToFront := FALSE);
csvManager.AppendColumn(label := 'Part Number', pt_sourceData :=
ADR(systemPartNo), numElements := 1, appendToFront := FALSE);
csvManager.AppendColumn(label := 'System Time', pt_sourceData :=
systemTimeVector.pt_Data, numElements := systemTimeVector.Size,
appendToFront := FALSE);
csvManager.AppendColumn(label := 'CPU Burden', pt_sourceData :=
cpuBurdenVector.pt_Data, numElements := cpuBurdenVector.Size,
appendToFront := FALSE);
csvManager.AppendColumn(label := 'Mainboard Temp', pt_sourceData :=
temperatureVector.pt_Data, numElements :=
temperatureVector.Size, appendToFront := FALSE);
//Advance stage
stage := stage + 1;
3:
//Initiate serialization of the CSV content
IF NOT csvManager.Busy AND_THEN csvManager.SerializeCsv() THEN
stage := stage + 1;
END_IF
4:
//When complete, push the content to the file writer buffer
IF csvManager.CsvSerialized THEN
writer.AppendBytes(pt_data := csvManager.pt_SerializedData,
numBytes := csvManager.NumSerializedBytes);
stage := stage + 1;
END_IF
5:
//When the file writer has completed the file write operation,
assert the 'complete' indicator
IF writer.BytesLeft = 0 THEN
complete := TRUE;
END_IF
END_CASE
//Update the status outputs (informational - not required for the basic
function of this example)
csvManagerInitialized := csvManager.Initialized;
csvManagerError := csvManager.Error;
csvManagerErrorDesc := csvManager.ErrorDesc;
csvManagerNumRows := csvManager.NumRows;
csvManagerNumColumns := csvManager.NumColumns;
Assumptions
This example assumes the following:
1. A CSV formatted file named ColumTestCsvFile.csv exists in the RTAC’s top level
of the file system (i.e., the /FILES folder).
2. The data in the file is represented by five columns with the following labels:
ä column 1 : FID
ä column 2 : Part Number
ä column 3 : System Time
ä column 4 : CPU Burden Percent
ä column 5 : Mainboard Temp
3. Where columns 1 and 2 are considered header data and contain only a single entry
in the first row following the label row.
A file that satisfies these assumption is generated by the previous example.
Solution
Code Snippet 7.11 prg_ReadMixedFormatCsv
PROGRAM prg_ReadMixedFormatCsv
VAR CONSTANT
c_originalFileName : STRING := 'MixedFormatCSV.csv';
END_VAR
VAR
csvManager : class_CsvManager := (LogRuntimeErrors := TRUE);
inputVector : DynamicVectors.class_ByteVector;
reader : fileIO.class_FileReader2;
burdenSample : STRING(255);
burdenSum : REAL;
i : UDINT;
stage : UINT;
complete : BOOL;
//Status outputs
csvManagerInitialized : BOOL;
csvManagerError : BOOL;
csvManagerErrorDesc : STRING(255);
csvManagerNumRows : UDINT;
csvManagerNumColumns : UDINT;
END_VAR
1:
//When complete, copy data into a vector and pass the vector to the
CSV manager
IF (reader.BytesInBuffer > 0) AND NOT csvManager.Busy THEN
//Copy the content into a vector
reader.AppendToVector(startByte := 0, vector := inputVector);
//Initialize CsvWriter in read/write mode and request a
parse operation
csvManager.InitReadWriteMode(inVector := inputVector);
stage := stage + 1;
END_IF
2:
//When the data has been parsed into the internal CSV object, grab
the first row
3:
//Now extract the entire column of cpu burden samples, which are
expected to reside in column 4
IF csvManager.NumColumns >= 4 THEN
IF csvManager.ExtractDataSetToVector(extractMode :=
enum_MatrixAccessMethod.e_COLUMN,
dataSetIndex := 4, targetVector := cpuBurdenVector)
THEN
//Sum the cpu burden samples
FOR i := 0 TO cpuBurdenVector.Size - 1 DO
cpuBurdenVector.GetCopyOfElement(index := i,
pt_destination := ADR(burdenSample));
burdenSum := burdenSum +
STRING_TO_REAL(burdenSample);
END_FOR
//Calculate the average burden over the sample set
averageCpuBurden := burdenSum /
UDINT_TO_REAL(cpuBurdenVector.Size);
stage := stage + 1;
END_IF
END_IF
4:
complete := TRUE;
END_CASE
//Update the status outputs (informational - not required for the basic
function of this example)
csvManagerInitialized := csvManager.Initialized;
csvManagerError := csvManager.Error;
csvManagerErrorDesc := csvManager.ErrorDesc;
csvManagerNumRows := csvManager.NumRows;
csvManagerNumColumns := csvManager.NumColumns;
Dictionaries
Introduction
This library implements a collection of data structures for storing key value pairs. This
allows for storing of information indexed by a unique key string.
Determine which data structure to use by looking at the characteristics of the available
structures, and choose the one best suited to the job and environment at hand.
This library supplies a single implementation. It is a self-balancing binary search tree as
described in class_BinaryTreeDictionary on page 8.3.
The iterators in this document all refer to being locked out. This refers to the state of the
object being such that a non NULL(0) value cannot be retrieved from Next() without a
new call to Begin().
Special Considerations
ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myObject.value;
// As is this
pt_myObject := ADR(myObject);
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Aliases
This section lists aliases defined by this library.
DATA_VAL
ALIAS IEC 61131 Type
DATA_VAL __XWORD
Structure Definitions
This section lists structures defined by this library.
struct_KeyValuePair
This structure is a simple storage object for holding key-value pairs.
Classes
This section contains the basic definitions, descriptions, and public methods for the public
classes that can be instantiated by the user.
class_BinaryTreeDictionary
This class provides a self-balancing binary search tree that stores key-value pairs. To allow
this class to accommodate various data types, the value stored is a DATA_VAL, which can
store a single 32-bit value or a pointer to a user-defined data structure.
A binary search tree ensures arrangement of all nodes in order by key such that, given a
node, all keys in the left subtree are less than the key of the given node and all keys in the
right subtree are greater than the key of the given node (Figure 8.1).
Binary search trees provide insert, search, and deletion times that are related to the number
of items in the tree(N) by log(N ) on average. Under some circumstances, the organization
of the simple tree yields much worse performance. Consider a tree created by inserting the
keys C, K, and then L (as shown in Figure 8.2).
Note that the nodes are arranged linearly, rather than as one parent with two children. This
causes the behavior of all operations to tend toward a linear performance curve, as opposed
to the log(N ) described previously. To prevent the performance degradation of an unbal-
anced tree, the binary tree supplied implements a self-balancing algorithm. If inserting or
deleting a node leaves the tree unbalanced, the self-balancing tree performs rotations and
moves of the nodes in the tree to maintain balance. (Figure 8.3).
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
GetData (Method)
This method provides the data associated with the provided key.
Inputs
Name IEC 61131 Type Description
key STRING(g_p_KeyStringLength) The key for the desired value.
Outputs
Name IEC 61131 Type Description
data DATA_VAL The value stored at this key. This value is only valid if the return
value is TRUE.
Return Value
IEC 61131 Type Description
BOOL TRUE if the key provided is found in the binary tree, FALSE otherwise.
Processing
Returns the data associated with the provided key.
Insert (Method)
This method inserts a new value into the binary tree.
Inputs
Name IEC 61131 Type Description
key STRING(g_p_KeyStringLength) The key for the desired value.
data DATA_VAL Data to store in the binary tree.
Return Value
IEC 61131 Type Description
BOOL TRUE if the key-value pair was successfully added to the tree. FALSE
otherwise.
Processing
If key already exists in the tree, data replaces the data stored in key. If key does not already
exist in the tree, a new node that stores both key and data is inserted into the tree. Depending
on the state of the tree, the insertion may cause the tree to rebalance.
Delete (Method)
This method removes the key-value pair from the binary tree.
Inputs
Name IEC 61131 Type Description
key STRING(g_p_KeyStringLength) The key for the desired value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the key-value pair was found and deleted.
Processing
This method deletes a key-value pair from the binary search tree. Depending on the state
of the tree after deletion, the tree may be rebalanced to maintain lookup performance.
Clear (Method)
This method empties the binary tree.
Processing
This method completely empties the binary tree. It frees any memory allocated to the
binary tree. Upon completion of this method, the binary tree object is of size zero and
cannot be iterated over.
Begin (Method)
Use this method in conjunction with Next(), NextValue(), and NextKey(). This method
places the internal iterator on the first key-value object.
Processing
After this method completes, the following are true:
ä The iterator is not locked out.
ä A subsequent Next() outputs the first key-value object.
ä For an empty tree, Next() returns FALSE and leaves the iterator locked out.
Next (Method)
Use this method in conjunction with Begin(). Next() returns the key-value pair at the
present internal iterator position and then increments the iterator.
Outputs
Name IEC 61131 Type Description
entry struct_KeyValuePair The key-value pair at the present iterator position. If the end of
the iterator has been reached, key is an empty string and data
is zero.
Return Value
IEC 61131 Type Description
BOOL TRUE if a key-value pair was found. FALSE otherwise.
NextKey (Method)
Use this method in conjunction with Begin(). NextKey() returns the key at the present
internal iterator position and then increments the iterator.
Outputs
Name IEC 61131 Type Description
key STRING(g_p_KeyStringLength) The key at the present iterator position. If the end
of the iterator has been reached, key is an empty
string.
Return Value
IEC 61131 Type Description
BOOL TRUE if a key-value pair was found. FALSE otherwise.
NextValue (Method)
Use this method in conjunction with Begin(). NextValue() returns the value at the
present internal iterator position and then increments the iterator.
Outputs
Name IEC 61131 Type Description
value DATA_VAL The value at the present iterator position. If the end of the iter-
ator has been reached value is zero.
Return Value
IEC 61131 Type Description
BOOL TRUE if a key-value pair was found. FALSE otherwise.
Size (Property)
This method provides the number of nodes within the tree.
Return Value
IEC 61131 Type Description
UDINT The number of nodes within the tree.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R134 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 1 GB DDR ECC SDRAM
â SEL-3532 RTAC Conversion Kit
â R132 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware
Insert
This records the average time taken to insert 1024 sorted key-value pairs into the tree. The
test is repeated 100 times and the average time taken for a single execution of Insert()
is recorded.
GetData
This test calls GetData() on each of 1024 entries in the tree. The test is repeated 100
times and the average time taken for a single execution of GetData() is recorded.
Delete
This test calls Delete() 1024 times on a populated tree. The test is repeated 100 times
and the average time taken for a single execution of Delete() is recorded.
Clear
This test records the average time required to clear the tree populated with 1024 nodes. The
test is repeated 100 times and the average time taken for a single execution of Clear() is
recorded.
Begin
This test records the time required to reset the iterator. Begin() is called 1024 times on
a populated tree. The test is repeated 100 times and the average time taken for a single
execution of Begin() is recorded.
Next
This test iterates across a full tree of 1024 nodes. The test is repeated 100 times and the
average time taken for a single execution of Next() is recorded.
NextKey
This test iterates across a full tree of 1024 nodes. The test is repeated 100 times and the
average time taken for a single execution of NextKey() is recorded.
NextValue
This test iterates across a full tree of 1024 nodes. The test is repeated 100 times and the
average time taken for a single execution of NextValue() is recorded.
Benchmark Results
Values less than one microsecond have been rounded up.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
First the user initializes the full tree. Later, she can iterate across the entire structure to
receive those data in key alphabetical order.
Assumptions
This example assumes that there is a user-specified IEC 61131 data type that is defined as
shown in Code Snippet 8.2 and a function using that particular structure as shown in Code
Snippet 8.3.
Solution
First the user initializes the full tree. Later, based on some request, the required data can
be retrieved.
MyBinaryLookupTree : class_BinaryTreeDictionary;
CurrentJob : STRING(g_p_KeyStringLength);
pt_CurrentData : POINTER TO struct_JobDefinition;
Job1Data : struct_JobDefinition :=
(JobName := 'My First Job', Duration := 10, Input := 17.5);
Job2Data : struct_JobDefinition :=
(JobName := 'My Second Job', Duration := 5, Input := 31.75);
Job3Data : struct_JobDefinition :=
(JobName := 'My Third Job', Duration := 30, Input := 3.25);
IdleData : struct_JobDefinition :=
(JobName := 'No Current Job', Duration := 0, Input := 0);
END_VAR
IF Initializing THEN
//First put the data into the tree as key value pairs
MyBinaryLookupTree.Insert('Job1', ADR(Job1Data));
MyBinaryLookupTree.Insert('Job2', ADR(Job2Data));
MyBinaryLookupTree.Insert('Job3', ADR(Job3Data));
MyBinaryLookupTree.Insert('Idle', ADR(IdleData));
Initializing := FALSE;
Working := TRUE;
END_IF
CASE JobSelector OF
1: CurrentJob := 'Job1';
2: CurrentJob := 'Job2';
3: CurrentJob := 'Job3';
ELSE
CurrentJob := 'Idle';
END_CASE
IF Working THEN
CurrentData := MyBinaryLookupTree.GetData(CurrentJob, data =>
pt_CurrentData);
fun_DoWork(pt_currentData);
END_IF
DynamicDisturbanceRecorder
Introduction
The DynamicDisturbanceRecorder library contains classes designed to simplify the collec-
tion of data points from within the logic engine of the Real-Time Automation Controller
(RTAC). All data must be added to the logging object by using the supported bootstrap
methods and, as such, the data must originate from a data structure supported by the log-
ging object selected. The maximum rate at which points are logged is dependent on the
task cycle of the Main Task. See the ACSELERATOR RTAC® SEL-5033 Software Instruction
Manual for more details on configuring the task cycle.
Each object within the library stores the collected data into a file format specific to that
object. The four available file formats are listed below:
ä Time-Aligned CSV: This format is an ASCII comma-separated value (CSV) file that
aligns all point values with a single time value that represents the data. The order
in which the data points are bootstrapped determines the position of the data points
in the log. A null entry in this format is represented as a blank entry (no characters)
delimited by two commas. Supported data structures and simple types include BCR,
UDINT, CMV, REAL, DPS, INS, DINT, MV, SPS, BOOL, STR, and STRING(80).
ä SOE CSV: This format is an ASCII CSV file in which each log represents the status
value of a bootstrapped point and a time value. The layout of the CSV file is de-
signed for NERC PRC-002-2-compliant Sequence of Events Recording (SER) data
formatting. Additional information in the log includes the time code (offset from
UTC), station name, and device name. Each detected change generates a log that is
a separate line in the file. Supported data structures and simple types include: BCR,
UDINT, CMV, REAL, DPS, INS, DINT, MV, SPS, BOOL, STR, and STRING(80).
ä COMTRADE: Two COMTRADE files are generated that adhere to IEC 60255-
24:2013 and IEEE Std. C37.111-2013: a CFG file and a DAT file. The CFG file
is an ASCII file that includes information pertinent to the interpretation of the DAT
file. The maximum size of the CFG file cannot exceed 10 MB. The DAT file contains
the log entries and is a binary file formatted in FLOAT32. Supported data structures
and simple types include CMV, MV, REAL, INS, DINT, SPS, and BOOL. The order
of the points in the DAT is the order in which the supported data structures are listed
above and then in the order the points are bootstrapped. Within each data structure
type, the order of the points is determined by the order in which the points are boot-
strapped. For the COMTRADE format, missing data will be filled with hex value
0xFF7FFFFF in the binary DAT file for analog points. For binary points, missing
data will be represented as a zero. See the referenced standards above for more detail
pertaining to the COMTRADE file format.
ä SOE Harvester CSV: This format is an ASCII CSV file with formatting that matches
that of the standard ’SOE CSV’ record type, thus it is also formatted to be NERC
PRC-002-2-compliant. The file name is assigned with IEEE C37.232-2011 ("COM-
NAME") naming. This class is meant to be applied with protocol client devices
performing SER collection and logging from IEDs; this mainly applies to SEL and
Modbus client devices. These client devices should be time synchronized and must
also produce SER records that are created in the same time zone. RTAC SOE con-
tents are written to file based on a trigger derived from a configured time reference
or a periodic interval. The log file is configurable for a variable number of triggered
writes that append the SOE data, allowing for the user to create a new log file with
each trigger or append new records to the previous log file a desired number of times.
Each object also has specific triggering mechanisms that trigger the collection of the boot-
strapped points. The objects may contain one or more triggering options, but only one
trigger option can be used per instantiated object. When the trigger condition is met, a log
or log entry is created. The maximum log or log entry size is 10 MB. The log will at min-
imum contain a time value and the status data of the bootstrapped points. Additional data
may also be present depending on the file format chosen. These triggers are categorized
into the following four categories:
ä Timestamp Change: Available file formats for the Timestamp Change trigger in-
clude time-aligned CSV, COMTRADE and SOE Harvester CSV. This trigger method
monitors the bootstrapped points for changes in the dateTime_t data structure. A de-
tected change in any dateTime_t data structure within a bootstrap point creates a log
with a time value. Changes detected in simple data types do not generate logs be-
cause the data do not contain a time stamp. Each log entry contains all the points for
which a time change was detected. By default, the first dateTime_t data structure for
which a time change is detected is the time reference of the log entry. This is the time
that is associated with the log entry. A user can specify a timeStamp_t data structure
that is used as the time reference to better control when log entries are created and
what time stamp is associated with the log. Any detected change in the dateTime_t
data structure of the time reference generates a log and the time value associated with
that log is derived from the dateTime_t data structure of the time reference. When
used with the SOE Harvester CSV record format, only an update to the timestamp of
the tag specified as the time reference will cause the buffered records to be written to
the CSV file. Time variance is an optional setting that allows users to set a window
around the time reference. If a time change is detected during the scan, but the time
value of that data point does not fall within the time window relative to time refer-
ence, it will not be included in the log. Points that do not change or are outside the
time window have a null entry. This entry maintains the columnar position in the log
entry as determined by the file format. The exception is for simple types. All simple
types are included in any log generated.
ä Data Change: The only file format available for the Data Change trigger is SOE
CSV. This trigger method monitors the bootstrapped points for changes in the re- NOTE: For MV and CMV data
structures, the monitored quantity is
spective status value for the data structure. If a change in the status is detected, a the deadbanded attribute. For
distinct log entry is created for that point that reflects the time of change and data example, for a CMV, the mag and ang
attributes are monitored.
status. The time of change is derived from the dateTime_t data structure of the boot-
strapped point. In the case of simple types, system time is assigned to each change
in state.
ä Periodic: Available file formats for the Periodic trigger include time-aligned CSV,
COMTRADE and SOE Harvester CSV. This trigger method periodically samples all
points at the specified interval regardless of whether the time value or the data status
value of the bootstrapped point changed. The time value for the log entry is the
system time of the RTAC at the time of the periodic interval. All data are sampled,
so no null entries are present. This is a snapshot of the points as they are in the RTAC
logic engine at the time of the periodic interval. At the expiration of each periodic
timer interval, buffered SOE Harvester CSV record contents will be written to the
text file.
ä Trigger: Available file formats include time-aligned CSV and COMTRADE. Trig-
gered file records cannot exceed 10 MB in total file size. This trigger method mon-
itors a Boolean value specified by the user. When the Boolean trigger condition is
evaluated as TRUE, a file is generated that contains a configurable number of pre-
trigger and post-trigger log entries in addition to a log entry for the time the trigger
asserted. New log entries are created each task cycle; the amount of time captured by
an individual log can be calculated by multiplying the number of scans (pre-trigger
count, post-trigger count, and the trigger scan) by the task cycle time setting of the
RTAC. If a trigger condition is detected before the minimum configured pre-trigger
cycles are met, a log will be created that contains the available pre-trigger log entries
plus the trigger and the post-trigger log entries. If a trigger condition is detected be-
fore a previous trigger event is processed, it will be ignored. Like the Periodic type
trigger, a value is populated for each bootstrapped point, regardless of change in data
status or time stamp.
Each object is intended to be configured one time at program start. The initial configuration
determines the trigger behavior, file parameters, and file management for the object. The
type of object instantiated determines the format of the logs in the saved file.
For optimal file system performance, each object must be configured such that the rate of
file generation does not exceed the ability of the file system to process the created files. For
example, if an object is configured to log data at a fast rate or with a small maximum file
size and this configuration results in a file being created every 10 processing cycles, the
file system will not be able to process the files at a rate equal to the creation rate. When
configuring your object, ensure that files are not created more frequently than every 100
processing cycles. This behavior is tuned by setting the MaxFileSize appropriately for the
application. To verify that the object is creating files at an unsustainable rate, monitor the
ActiveFileName output pin. If this name is changing faster than once every 100 processing
cycles, the object may encounter issues when trying to create or delete files.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myDynamicDisturbanceRecorderObject.value;
// As is this
pt_myDynamicDisturbanceRecorderObject :=
ADR(myDynamicDisturbanceRecorderObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_DataLogger
This enumeration defines the types of data loggers used to record data.
Classes
class_TimeAlignedCsv (Function Block)
This class monitors and logs bootstrapped data points. Each time the Run method is called,
it scans the bootstrapped points for the trigger criteria described by the DataLogType input
setting. If a change is detected based on that criteria, the information is formatted and
written to a time-aligned CSV file.
The log is then written into the directory specified by DirectoryPath. A new log will start
after MaxFileSize is reached. The number of files stored in the directory is dependent on
the following two settings: MaxFolderSize and MaxNumDays. So long as the cumulative
size of the stored logs does not exceed MaxFolderSize, the file system will store logs for
MaxNumDays. If the cumulative number of logs exceeds MaxFolderSize, the directory
manager will delete the oldest files until the number of logs is less than MaxFolderSize.
File names will begin with the start time of the log and will be appended with FilePostFix.
For the trigger condition mechanism, an additional instance number will be appended to
ensure uniqueness. This number will increment each time a log is generated and will reset
with a settings change or when the maximum number of 65535 is reached.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable data recording.
RecordTimeInUtc BOOL Convert log time into UTC time. Information in
the timestamp_t of the log source is used for this
calculation.
RefTime timestamp_t Provides a time-stamp reference for log creation;
ignored unless the DataLogType input is config-
ured for TIME_CHANGE triggers.
TimeVariance UDINT Time window in milliseconds applied to the time
reference. If a change in the dateTime_t structure
for a bootstrapped point is detected and within the
time window, it is included in the log entry. Set
to 0 to disable. Ignored unless the DataLogType
input is configured for TIME_CHANGE triggers.
DataLogType enum_DataLogger Specifies what trigger mechanism is used to create
logs.
DirectoryPath STRING(127) The full directory path at which files generated by
this function block can be found.
FilePostfix STRING(16) The string appended after the time stamp in
the generated file name. When configured us-
ing TRIGGER_EVENT as the DataLogType, the
FilePostfix will be limited to 8 characters. Any
additional characters will be truncated.
MaxFolderSize LINT The maximum size, in bytes, for the specified di-
rectory path.
MaxFileSize DINT The maximum file size, in bytes, at which a new
file will be created for subsequent logging opera-
tions. Defaults to 10 MB for TRIGGER_EVENT
records.
MaxNumDays DINT The maximum number of days for which log files
are allowed to persist in a specified directory path.
LoggingInterval TIME Time in milliseconds for cyclic recording; ignored
unless the DataLogType input is configured for
PERIODIC triggers.
TriggerSignal BOOL Monitored variable that initiates a record, only for
DataLogType TRIGGER_EVENT.
PreTriggerCycles UDINT Number of processing cycles prior to the trigger
event for which data will be recorded; ignored
unless DataLogType TRIGGER_EVENT trigger.
Minimum of 1 pre-trigger cycle is required. If
configured for less than the minimum, the setting
will default to 1.
Outputs
Name IEC 61131 Type Description
ENO BOOL The logging block is enabled.
ActiveFileName STRING(255) Name of the file that logs are being written to.
ConsumedDirectorySize ULINT Size of all files in the monitored directory.
MonitoredPoints UDINT Total number monitored points.
Error BOOL Something has prevented this block from suc-
cessfully writing data to file. This can indicate
an out of space condition or that too many data
points are being monitored for the CPU of the
RTAC to handle.
ErrorDesc STRING(255) Message describing the source of the Error
flag.
bootstrap_MonitorBCR (Method)
A configuration method for adding BCR points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the BCR point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data BCR The BCR point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the BCR point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorUDINT (Method)
A configuration method for adding UDINT points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the UDINT point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data UDINT The UDINT point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the UDINT point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorCMV (Method)
A configuration method for adding CMV points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the CMV point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data CMV The CMV point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the CMV point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorREAL (Method)
A configuration method for adding REAL points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the REAL point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data REAL The REAL point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the REAL point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorDPS (Method)
A configuration method for adding DPS points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the DPS point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data DPS The DPS point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the DPS point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorINS (Method)
A configuration method for adding INS points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the INS point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data INS The INS point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the INS point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorDINT (Method)
A configuration method for adding DINT points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the DINT point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data DINT The DINT point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the DINT point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorMV (Method)
A configuration method for adding MV points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the MV point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data MV The MV point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the MV point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSPS (Method)
A configuration method for adding SPS points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the SPS point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data SPS The SPS point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the SPS point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorBOOL (Method)
A configuration method for adding BOOL points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the BOOL point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data BOOL The BOOL point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the BOOL point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSTR (Method)
A configuration method for adding STR points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the STR point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data STR The STR point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the STR point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSTRING (Method)
A configuration method for adding STRING points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the STRING point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data STRING The STRING point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the STRING point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
Run (Method)
This method must be called every scan to ensure proper functionality, which includes scan-
ning data points and writing files.
Processing
ä The first time the method is called, it blocks all future bootstrap methods from adding
new points.
ä For DataLogType TIME_CHANGE, points are considered changed if the dateTime_-
t data structure has changed since the previous scan and the change falls within the
window, relative to the time reference, specified by TimeVariance. Changes in simple
type values do not trigger a log but are included in every log.
ä For DataLogType PERIODIC, all points are considered changed if LoggingInterval
is reached.
ä For DataLogType TRIGGER_EVENT, all points are considered changed when log-
ging data points during the pre- and post-trigger cycles.
ä Scans all data points. If they have changed, the data are formatted for logging.
ä If a log entry is generated, the class writes one line containing a time value with mil-
lisecond precision and one comma-separated column for each data point monitored.
If the value of the data point changed since the last scan, the new value is written
to the log entry; otherwise, a null entry is created. This ensures that the columnar
position of all data points is maintained.
ä Manage the total size of the directory path folder to ensure that the cumulative size
of the logs does not exceed MaxDirectorySize.
ä So long as MaxDirectorySize is not exceeded, the logs will be maintained for MaxNum-
Days.
ä If MaxDirectorySize is exceeded before MaxNumDays is reached, the oldest file is
deleted. This repeats until the cumulative directory size is less than MaxDirectory-
Size.
ä Starts a new file if the active log file exceeds the maximum file size, if the project
settings are changed, or if trigger condition is detected.
ä The EN pin must be TRUE to scan and write new log entries.
ä When EN is FALSE, no data point changes are detected.
ä A rising edge on EN clears all pending logs so that only changes since the EN tog-
gling to true will be written to future logs.
ä Deleting metadata in the .RetainedState and .unsent files in the specified directory
may result in inconsistent logging behavior.
class_SoeCsv
This class monitors and logs bootstrapped data points. Each time the Run method is called,
it scans the bootstrapped points for the trigger criteria described by the DataLogType input
setting. The only supported trigger mechanism for this class is DATA_CHANGE. If a
change is detected based on that criteria, the information is formatted and written to a
comma-separated value (CSV) file. The log is then written into the directory specified by
DirectoryPath. A new log starts after the MaxFileSize is reached or at the beginning of a
new day if StartNewLogPerDay is set to TRUE.
The number of files stored in the directory is dependent on two settings: MaxFolderSize
and MaxNumDays. So long as the cumulative size of the stored logs does not exceed
MaxFolderSize, the file system stores logs for MaxNumDays. If the cumulative number
of logs exceeds MaxFolderSize, the directory manager deletes the oldest files until the
cumulative log directory size is less than MaxFolderSize. File names begin with the start
time of the log and are appended with FilePostFix.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable data recording.
RecordTimeInUtc BOOL Convert log time into UTC time. Information in
the timestamp_t of the log source is used for this
calculation.
DirectoryPath STRING(127) The full directory path at which files generated by
this function block can be found.
FilePostfix STRING (16) The string which is appended after the time stamp
from the file name.
MaxFolderSize ULINT The maximum size, in bytes, for the specified di-
rectory path.
MaxFileSize UDINT The maximum file size, in bytes, at which a new
file will be created for subsequent logging opera-
tions.
MaxNumDays UDINT The maximum number of days log files are al-
lowed to persist in specified directory path.
StartNewFilePerDay BOOL If TRUE, a new log file will start at the beginning
of a new day.
Outputs
Name IEC 61131 Type Description
ENO BOOL The logging block is enabled.
ActiveFileName STRING(255) Name of the file that logs are being written to.
ConsumedDirectorySize ULINT Size of all files in the monitored directory.
MonitoredPoints UDINT Total number monitored points.
Error BOOL Something has prevented this block from suc-
cessfully writing data to file. This can indicate
an out of space condition or that too many data
points are being monitored for the CPU of the
RTAC to handle.
ErrorDesc STRING(255) Message describing the source of the Error
flag.
bootstrap_MonitorBCR (Method)
A configuration method for adding BCR points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the BCR point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data BCR The BCR point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the BCR point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorUDINT (Method)
A configuration method for adding UDINT points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the UDINT point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data UDINT The UDINT point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the UDINT point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorCMV (Method)
A configuration method for adding CMV points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the CMV point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data CMV The CMV point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the CMV point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorREAL (Method)
A configuration method for adding REAL points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the REAL point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data REAL The REAL point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the REAL point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorDPS (Method)
A configuration method for adding DPS points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the DPS point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data DPS The DPS point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the DPS point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorINS (Method)
A configuration method for adding INS points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the INS point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data INS The INS point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the INS point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorDINT (Method)
A configuration method for adding DINT points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the DINT point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data DINT The DINT point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the DINT point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorMV (Method)
A configuration method for adding MV points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the MV point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data MV The MV point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the MV point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSPS (Method)
A configuration method for adding SPS points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the SPS point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data SPS The SPS point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the SPS point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorBOOL (Method)
A configuration method for adding BOOL points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the BOOL point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data BOOL The BOOL point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the BOOL point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSTR (Method)
A configuration method for adding STR points to be monitored by a time-aligned CSV or
SOE CSV object. This method will only add the STR point to be monitored if called before
calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data STR The STR point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the STR point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSTRING (Method)
A configuration method for adding STRING points to be monitored by a time-aligned CSV
or SOE CSV object. This method will only add the STRING point to be monitored if called
before calling the function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) Label describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
Inputs/Outputs
Name IEC 61131 Type Description
data STRING The STRING point to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the STRING point was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
Run (Method)
This method must be called every scan to ensure proper functionality, which includes scan-
ning data points and writing files.
Processing
ä The first time the method is called, it blocks all future bootstrap methods from adding
new points.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable data recording.
RecordTimeInUtc BOOL Convert log time into UTC time. Information in the
timestamp_t of the log source is used for this calcu-
lation.
RefTime timestamp_t Provides a time stamp reference for log creation, ig-
nored unless the DataLogType input is configured
for TIME_CHANGE triggers.
TimeVariance UDINT Time window in milliseconds applied to the time ref-
erence. If a change in the dateTime_t structure for a
bootstrapped point is detected and within the time
window it is included in the log entry. Set to 0 to
disable. Ignored unless the DataLogType input is
configured for TIME_CHANGE triggers.
DataLogType enum_DataLogger Specifies which trigger mechanism is used to create
logs.
DirectoryPath STRING(50) The full directory path at which files generated by
this function block can be found.
FilePostfix STRING(50) The string that is appended after the time stamp from
the file name.
MaxFolderSize ULINT The maximum size, in bytes, for the specified direc-
tory path.
MaxFileSize UDINT The maximum file size, in bytes, at which a new file
will be created for subsequent logging operations.
Defaults to 10 MB for TRIGGER_EVENT records.
MaxNumDays UDINT The maximum number of days log files are allowed
to persist in specified directory path.
LoggingInterval TIME Time in milliseconds for cyclic recording; ignored
unless the DataLogType input is configured for PE-
RIODIC triggers.
TriggerSignal BOOL Monitored variable that initiates a record; only for
DataLogType TRIGGER_EVENT.
PreTriggerCycles UDINT Number of processing cycles prior to the trigger
event for which data will be recorded; ignored unless
DataLogType TRIGGER_EVENT trigger. Mini-
mum 1 pre-trigger cycle is required. If configured
for less than the minimum, the setting will default to
1.
PostTriggerCycles UDINT Number of processing cycles post-trigger event for
which data will be recorded; ignored unless Data-
LogType TRIGGER_EVENT trigger. Minimum 1
post-trigger cycle is required. If configured for less
than the minimum, the setting will default to 1.
SystemFrequency DINT Primary frequency of the analog signal measured by
the COMTRADE oscillography.
SortNanoseconds UDINT Maximum allowed number of nanoseconds that the
time stamp reordering mechanism is allowed to run
each scan. Default is 1,000,000 (1 millisecond).
Outputs
Name IEC 61131 Type Description
ENO BOOL The logging block is enabled.
ActiveFileName STRING(255) Name of the file that logs are being written to.
ConsumedDirectorySize ULINT Size of all files in the monitored directory.
AnalogPoints UDINT Total number of analog points.
DigitalPoints UDINT Total number of digital points.
Error BOOL Something has prevented this block from suc-
cessfully writing data to file. This can indicate
an out of space condition or that too many data
points are being monitored for the CPU of the
RTAC to handle.
ErrorDesc STRING(255) Message describing the source of the Error
flag.
bootstrap_MonitorCMV (Method)
A configuration method for adding CMV points to be monitored by a COMTRADE object.
This method will only add the CMV point to be monitored if called before calling the
function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(1) The description to use when describing the phase identifier
for the data.
component STRING(16) The description to use when describing the physical com-
ponent that is represented by the data.
unit STRING(16) The description to use when describing the engineering
units to associate with the data.
Inputs/Outputs
Name IEC 61131 Type Description
data CMV The CMV to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the CMV was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorREAL (Method)
A configuration method for adding REAL points to be monitored by a COMTRADE object.
This method will only add the REAL point to be monitored if called before calling the
function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(2) The description to use when describing the phase identifier
for the data.
component STRING(16) The description to use when describing the physical com-
ponent that is represented by the data.
unit STRING(16) The description to use when describing the engineering
units to associate with the data.
Inputs/Outputs
Name IEC 61131 Type Description
data REAL The REAL to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the REAL was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorMV (Method)
A configuration method for adding MV points to be monitored by a COMTRADE object.
This method will only add the MV point to be monitored if called before calling the function
block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(2) The description to use when describing the phase identifier
for the data.
component STRING(16) The description to use when describing the physical com-
ponent that is represented by the data.
unit STRING(16) The description to use when describing the engineering
units to associate with the data.
Inputs/Outputs
Name IEC 61131 Type Description
data MV The MV to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the MV was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorINS (Method)
A configuration method for adding INS points to be monitored by a COMTRADE object.
This method will only add the INS point to be monitored if called before calling the function
block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(2) The description to use when describing the phase identifier
for the data.
component STRING(16) The description to use when describing the physical com-
ponent that is represented by the data.
unit STRING(16) The description to use when describing the engineering
units to associate with the data.
Inputs/Outputs
Name IEC 61131 Type Description
data INS The INS to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the INS was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorDINT (Method)
A configuration method for adding DINT points to be monitored by a COMTRADE object.
This method will only add the DINT point to be monitored if called before calling the
function block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(2) The description to use when describing the phase identifier
for the data.
component STRING(16) The description to use when describing the physical com-
ponent that is represented by the data.
unit STRING(16) The description to use when describing the engineering
units to associate with the data.
Inputs/Outputs
Name IEC 61131 Type Description
data DINT The DINT to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the DINT was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorSPS (Method)
A configuration method for adding SPS points to be monitored by a COMTRADE object.
This method will only add the SPS to be monitored if called before calling the function
block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(1) The description to use when describing this data in files
generated by the data recorder class.
component STRING(16) The description to use when describing this data in files
generated by the data recorder class.
defaultState BOOL The default state.
Inputs/Outputs
Name IEC 61131 Type Description
data SPS The SPS to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the SPS was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
bootstrap_MonitorBOOL (Method)
A configuration method for adding BOOL points to be monitored by a COMTRADE object.
This method will only add the BOOL to be monitored if called before calling the function
block itself.
Inputs
Name IEC 61131 Type Description
channel STRING(62) The description to use when describing the data source.
station STRING(62) The description to use when describing the grouping of the
data.
ph STRING(1) The description to use when describing this data in files
generated by the data recorder class.
component STRING(16) The description to use when describing this data in files
generated by the data recorder class.
defaultState BOOL The default state.
Inputs/Outputs
Name IEC 61131 Type Description
data BOOL The BOOL to be included in the log files.
Return Value
IEC 61131 Type Description
BOOL TRUE if the BOOL was added for logging.
Processing
ä Store a reference to the point and the associated metadata for future logging and
comparison.
ä Return true if the point will be monitored moving forward, false otherwise.
Run (Method)
This method must be called every scan to ensure proper functionality, which includes scan-
ning data points and writing files.
Processing
ä The first time the method is called, it blocks all future bootstrap methods from adding
new points.
ä For DataLogType TIME_CHANGE, points are considered changed if the dateTime_-
t data structure has changed since the previous scan and the change falls within the
window, relative to the time reference, specified by TimeVariance. Changes in simple
type values do not trigger a log but are included in every log.
ä For DataLogType PERIODIC, all points are considered changed if LoggingInterval
is reached.
ä For DataLogType TRIGGER_EVENT, all points are considered changed when log-
ging points during the pre- and post-trigger cycles.
ä Scan all data points. If they have changed, prepare them for logging.
ä Write log entry containing the sample number and a time offset from the beginning of
the log with millisecond precision and the bootstrapped data. Log entries are stored
in the binary DAT file in the FLOAT32 format.
ä The log entries and the CFG file information are written to a temporary file until
the log is completed. Once completed, the log is stored as a CFG and DAT file in a
subdirectory that has the same naming convention as that of the CFG and DAT file.
ä Manage the total size of the directory path folder and the number of files in the
respective data path based on the MaxDirectorySize.
ä Start a new file if the active log file exceeds the maximum file size or if project
settings change or if trigger condition is detected.
ä The logs will be maintained for the MaxNumDays if the MaxDirectorySize is not
exceeded.
ä If MaxDirectorySize is exceeded before MaxNumDays of logs is reached, files are
deleted in day increments until the cumulative size of the logs is less than MaxDi-
rectorySize.
ä The EN pin must be TRUE to scan and write new log entries.
ä When EN is FALSE, no data point changes are detected.
ä A rising edge on EN clears all pending logs so that only changes since the EN tog-
gling to true will be written to future logs.
ä Deleting metadata in the TEMP and SHADOW directories in the specified directory
may result in inconsistent logging behavior.
class_SoeHarvesterCsv
This class monitors the RTAC SOE and logs entries from any bootstrapped remote origin
sources to a CSV file. When the Run method is being called each task cycle, the class
will query the RTAC’s SOE logger for new entries upon a detection of a rising edge on the
QueryRecords input and queue any that are encountered. To ensure detection of new SOEs,
ensure the QueryRecords input is tied to a BOOL quantity that automatically pulses period-
ically such as the output of an interval timer. Once new records are detected, the RTAC will
continuously query for new records until there are none remaining; the QueryingRecords
output will be asserted during this time. Only SOE records belonging to the Category of
’Remote’ and with an Origin field matching a bootstrapped remote device name are for-
matted and queued to be written to the log file. Also, each time the Run method is called,
it checks for presence of the trigger criteria described by the DataLogType input setting.
The supported trigger mechanisms for this class are TIME_CHANGE and PERIODIC. If
a trigger is detected based on the configured criteria, the queued information is formatted
and written to a comma-separated value (CSV) file, into the directory specified by Direc-
toryPath. A new log file starts after TriggersPerFile is reached and a subsequent trigger is
encountered.
The number of files stored in the directory is dependent on two settings: MaxFolderSize
and MaxNumDays. So long as the cumulative size of the stored logs does not exceed
MaxFolderSize, the file system stores logs for MaxNumDays. If the cumulative number
of logs exceeds MaxFolderSize, the directory manager deletes the oldest files until the cu-
mulative log directory size is less than MaxFolderSize. File names are formatted for IEEE
C37.232-2011 ("COMNAME") and begin with the start time of the log and are appended
with FilePostFix. The total length of the combined DirectoryPath and FilePostFix strings
cannot exceed 230 characters.
A file named .StateTracker is maintained in the same directory as the CSV text files. It
contains the record ID for the most recent SOE content written to the CSV text file and
is used at startup to ensure the class doesn’t retrieve and write duplicate SOE entries into
the CSV text files. If the record ID contained in the .StateTracker file is ever cleared from
the RTAC SOE database (via a manual Delete Logs operation from the Web Interface, or
the record aging out of the database due to insertion of 30000 newer records) then the
.StateTracker file is automatically removed and the class enters an internal mode where it
scans for new records based on the bootstrapped criteria.
This class requires a minimum firmware RTAC version of R148 to operate. Firmware
versions less than R149 may produce CSV records with an additional 1 hour offset if the
class is configured with RecordTimeInUtc equal to FALSE while daylight savings time is
not active.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable data recording.
RecordTimeInUtc BOOL Convert file-name time code and log entry time into
UTC time. UTC_Offset information contained in the
timestamp of the RTAC SOE record is used for this
calculation.
RefTime timestamp_t Provides a time-stamp reference for log creation; in-
put is ignored unless the DataLogType input is con-
figured for TIME_CHANGE triggers.
DataLogType enum_DataLogger Specifies what trigger mechanism is used to create
logs. TIME_CHANGE and PERIODIC are sup-
ported.
DirectoryPath STRING(127) The full directory path at which files generated by
this function block can be found.
FilePostfix STRING(127) The string which is appended after the time stamp
from the file name.
MaxFolderSize ULINT The maximum size, in bytes, for the specified direc-
tory path.
MaxNumDays UDINT The maximum number of days log files are allowed
to persist in specified directory path.
LoggingInterval TIME Time in milliseconds for cyclic recording; ignored
unless the DataLogType input is configured for PE-
RIODIC triggers.
TriggersPerFile UDINT The maximum number of triggered writes to append
to a single output CSV file before creating a new one
at the next trigger.
QueryRecords BOOL Assert to query the database for SOE records.
Outputs
Name IEC 61131 Type Description
ENO BOOL The logging block is enabled.
ActiveFileName STRING(255) Name of the file that logs are being written to.
ConsumedDirectorySize ULINT Size of all files in the monitored directory.
Error BOOL Something has prevented this block from suc-
cessfully writing data to file. This can indicate
a file system error such as an out-of-space con-
dition or the inability to write a file.
ErrorDesc STRING(255) Message describing the source of the Error
flag.
QueryingRecords BOOL The RTAC SOE Log is being actively queried
for records.
bootstrap_RemoteSource (Method)
A configuration method for adding a specific remote source to be monitored in the RTAC’s
SOE Database.
Inputs
Name IEC 61131 Type Description
DeviceName STRING(255) Name of device expected to be present in the
Origin field in the RTAC’s SOE database.
Note that this name does not contain the trail-
ing _SEL or _Modbus identifier that is present
in the device name in the AcSElerator RTAC
project. E.g., a device in the project named
as SEL_351_1_SEL will be specified in this
input value as SEL_351_1.
StationLabel STRING(255) Label used for Station field in the resultant
CSV text file.
DeviceLabel STRING(255) Label prepended to SOE description before
being placed in the Device field in the resul-
tant CSV text file.
TrimTrailingDescription BOOL Detect and remove additional descriptive text
contained in parenthesis from the end of the
SOE description field, following the new state.
Used by third party devices capable of log-
ging to RTAC SOE database. E.g., given an
SOE message entry of "Latch Bit 1 Asserted
(LT01)" from a bootstrapped origin source,
the resulting CSV log entry is written as:
"<SOE log timestamp>,<UTC code>,<sta-
tionLabel>,<deviceLabel> Latch Bit 1,As-
serted"
Return Value
IEC 61131 Type Description
BOOL TRUE if the device was added for SOE Harvester CSV log file generation.
Processing
ä Store a reference to the specified device as a monitored Origin
ä Return true if RTAC SOE log entries with an Origin matching the specified device-
Name will be added to the SOE CSV file moving forward, false otherwise.
ä Calls after the first call of the Run() method are ignored.
Run (Method)
This method should be called every scan to ensure proper functionality, which includes
scanning the RTAC SOE log for new contents and writing buffered data to text files. This
method should only be called after all the desired bootstrap_RemoteSource calls have been
completed.
Processing
ä The first time the method is called, it blocks all future bootstrap methods from adding
new remote origin device sources.
ä For each new RTAC SOE record matching a bootstrapped origin device source, write
one line containing a time value with millisecond precision, time code, station label,
device label, SOE message text and the final word of the SOE message text as the
data status value. The SOE Harvester CSV class assumes that all SER records for
an IED will follow the message format of "My SER Message <STATE>" where the
"<STATE>" portion of the message will be isolated as the final CSV component for
the "value" column. E.g., given an SOE message entry of "Latch Bit 1 Asserted"
from a bootstrapped origin source, the resulting CSV log entry is written as: "<SOE
log timestamp>,<UTC code>,<StationLabel>,<DeviceLabel> Latch Bit 1,Asserted"
ä Upon a rising edge on the QueryRecords input, the SOE database is scanned for new
records matching bootstrapped criteria. Any new records that are detected are added
to an internal queue to be later written to file.
ä If the trigger condition configured by the DataLogType, RefTime and LoggingInter-
val inputs is asserted, then queued SOE content is written to the CSV log file.
ä SOE Record content is written to the CSV log file in ascending order of the records
as they exist in the RTAC SOE database.
ä Manage the total size of the directory path folder and the number of files in the
respective data path based on MaxDirectorySize.
ä The CSV files will be maintained for MaxNumDays if the MaxDirectorySize is not
exceeded.
ä If the MaxDirectorySize is exceeded before MaxNumDays of logs is reached, the
oldest file is deleted. This repeats until the cumulative directory size is less than the
MaxDirectorySize.
ä Upon encountering a trigger condition, start a new CSV file if the number of previ-
ously encountered triggers is equal to TriggersPerFile.
ä The EN pin must be TRUE to scan for new SOE content and create CSV text files.
NOTE: Deleting or otherwise
ä When EN is FALSE, no work is done modifying metadata in the
.StateTracker file in the specified
ä Following the first write to a CSV file, every 60 seconds a file named .StateTracker directory may result in inconsistent
CSV logging behavior, causing either
is written in the directory specified by DirectoryPath. This file tracks the record ID loss of data or extraneous record
of the most recent SOE record written to the CSV file. generation.
ä A falling edge on EN clears all queued SOE content that has not been written to a
CSV text file. A rising edge of EN will read in the .StateTracker information and use NOTE: If a falling edge on EN
the content to re-queue any SOE records that were not written to a CSV file. occurs after SOE records have been
written to the CSV text file, but before
the .StateTracker file has been
updated at its regular 60 second
interval, these SOE records will be
duplicated in a new CSV text file upon
the class re-enabling and a trigger
condition being encountered.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134-V1 firmware
ä SEL-3530
â R134-V1 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R139 firmware
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
class_SoeCsv
DATA_CHANGE Average 2540.4 1374.7 54.2
Maximum 10977.8 5904.3 321.1
Minimum 380.3 251.7 8.1
Std Deviation 2722.5 1366.7 55.9
class_Float32COMTRADE
TIME_CHANGE Average 314.6 204.9 16.7
Maximum 4636.9 1909.5 297.4
Minimum 102.1 76.5 3.8
Std Deviation 548.5 272.1 19.6
PERIODIC Average 276.9 171.9 12.7
Maximum 4845.8 1943.9 202.0
Minimum 66.3 32.2 2.0
Std Deviation 509.7 283.2 18.6
TRIGGERED Average 391.3 208.6 14.5
Maximum 3025.8 1297.5 102.9
Minimum 163.1 76.9 5.5
Std Deviation 399.2 227.8 14.8
class_TimeAlignedCSVManager
TIME_CHANGE Average 1057.1 631.8 29.2
Maximum 6555.3 3841.6 399.1
Minimum 245.9 275.3 4.1
Std Deviation 749.7 376.6 36.6
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that the data tags provided as inputs to the bootstrap methods exist
in the project.
Solution
For a periodic logger, the user can create a program as shown in Code Snippet 9.1. The
sample log output is shown in Code Snippet 9.2.
INIT := TRUE;
END_IF
Assumptions
This example assumes that the data tags provided as inputs to the bootstrap methods exist
in the project.
Solution
For an SOE logger, the user can create a program as shown in Code Snippet 9.3. The sample
log output is shown in Code Snippet 9.4.
Assumptions
This example assumes that the data tags provided as inputs to the bootstrap methods exist
in the project.
Solution
For a COMTRADE time change logger, the user can create a program as shown in Code
Snippet 9.5. The sample log output is shown in Code Snippet 9.6.
Assumptions
This example assumes that the devices provided to the bootstrap methods (MySELClient
and MyModbusClient) exist in the project and are configured to retrieve SER data from the
IED and store it in the RTAC’s SOE Logger. These devices are also time synchronized and
generate SER records in the sample time zone.
Solution
For an SOE Harvester CSV logger, the user can create a program as shown in Code Snip-
pet 9.7.
Given entries in the RTAC SOE Logger such as those in Figure 9.1, the sample log output
is equivalent to that shown in Figure 9.2.
The RTAC SOE Log contains the following entries:
DynamicVectors
Introduction
This library provides a vector data type for storing objects of various types, including arbi-
trary user-created objects. In general, a vector is an array of elements that is dynamically
sized. As such, a vector allows elements to be added or removed and can contain an arbi-
trary number of elements. A vector also allows random access to its elements.
In addition to the vector classes, this library provides two factory functions for creating
vectors: fun_NewBaseVector() and fun_NewTypeVector(). Calling a factory function
creates a new object and returns a pointer to that object. For example, every call to fun_-
NewBaseVector() returns a pointer to a newly created class_BaseVector object.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myVectorObject.value;
// As is this
pt_myVectorObject := ADR(myVectorObject);
Versions 3.5.1.0 and older can be used on RTAC firmware version R132 and higher.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_DynamicVectorType
This enumeration is used for specifying the desired type of vector to the fun_NewVector()
function.
Enumeration Description
BYTE_VECTOR Enumeration for class_ByteVector.
WORD_VECTOR Enumeration for class_WordVector.
DWORD_VECTOR Enumeration for class_DwordVector.
LWORD_VECTOR Enumeration for class_LwordVector.
REAL_VECTOR Enumeration for class_RealVector.
LREAL_VECTOR Enumeration for class_LrealVector.
POINTER_VECTOR Enumeration for class_PointerVector.
Functions
fun_NewBaseVector (Function)
This function creates a new class_BaseVector and returns a pointer to the newly created
vector. The returned POINTER TO BYTE must be cast to the correct type before it is
used. A vector created with this function must be destroyed with fun_DeleteVector()
when it is no longer needed.
Inputs
Name IEC 61131 Type Description
elementSize UDINT The size of each element in the vector.
Return Value
IEC 61131 Type Description
POINTER TO BYTE Pointer to the newly created vector. This pointer is null if the vector
could not be created.
Processing
ä Creates a new vector with the specified elementSize and returns a pointer to the newly
created vector.
ä Returns a null pointer if the vector could not be created.
fun_NewTypeVector (Function)
This function creates a new vector of the type specified and returns a pointer to the newly
created vector. The returned POINTER TO BYTE must be cast to the correct type before it
is used. A vector created with this function must be destroyed with fun_DeleteVector()
when it is no longer needed.
Inputs
Name IEC 61131 Type Description
vectorType enum_DynamicVectorType The desired type of vector.
Return Value
IEC 61131 Type Description
POINTER TO BYTE Pointer to the newly created vector. This pointer is null if the vector
could not be created.
Processing
ä Creates a new vector of the type specified and returns a pointer to the newly created
vector.
ä Returns a null pointer if the vector could not be created.
fun_DeleteVector (Function)
This function deletes a vector created with fun_NewBaseVector() or fun_NewTypeVector().
After deletion, any pointers to the deleted vector are no longer valid.
Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to delete.
Return Value
IEC 61131 Type Description
BOOL TRUE if vector is successfully deleted. False if an error occurs.
Interfaces
This library provides the following interface.
I_Vector
This interface is implemented by any class that provides a vector data type.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Append (Method)
This method appends an array of elements to the end of the vector.
Inputs
Name IEC 61131 Type Description
pt_array POINTER TO BYTE Pointer to the first element to append to the vector.
numElements UDINT The number of elements to copy from the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the elements are successfully appended to the vector. FALSE if
an error occurs.
Processing
ä If pt_array is null, the vector is not modified and this method returns FALSE.
ä If pt_array is valid and numElements is zero, the vector is not modified and this
method returns TRUE.
ä If appending to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the
vector is not modified and this method returns false.
Clear (Method)
Deallocates all memory associated with the vector. Call this method only if the vector is
instantiated with limited scope (i.e., if it is instantiated as a local variable of a function or
method).
Return Value
IEC 61131 Type Description
BOOL TRUE if the vector successfully deallocates its internal memory. FALSE
if an error occurs.
Recycle (Method)
This method removes all elements from the vector without modifying the memory allocated
to the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if the vector successfully removes all elements. FALSE if an error
occurs.
Processing
All elements are removed from the vector.
ä After recycling, the Size property of the vector is zero.
ä The MaxSize property is unchanged after a call to Recycle().
ä This method neither allocates nor frees any memory.
Resize (Method)
This method resizes the vector so it can contain the number of elements specified without
requiring any additional memory allocations.
Inputs
Name IEC 61131 Type Description
newSize UDINT The desired number of elements for the resized vector to con-
tain without requiring a memory reallocation.
Return Value
IEC 61131 Type Description
BOOL TRUE if the vector is successfully resized. FALSE if an error occurs.
Processing
This method resizes the vector so it can contain the number of elements specified without
requiring any additional memory allocations.
ä If the specified newSize is zero, then the vector is resized to g_p_DefaultVectorSize
or the present number of elements, whichever is greater.
ä If the specified newSize is greater than zero and less than the present number of
elements, the vector is resized to the present number of elements.
ä If the specified newSize is greater than the number of elements, the vector is resized
to the specified newSize.
ä If the specified newSize equals the present maximum size of the vector, the vector is
not resized and the method returns TRUE.
Classes
class_BaseVector
This class implements a generic vector that internally handles dynamic allocation of mem-
ory. This vector can handle objects of arbitrary size so long as the number of bytes required
for each element is the same. This vector stores its internal data in a contiguous block of
memory.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
Initialization Inputs
Name IEC 61131 Type Description
elementSize UDINT The number of bytes required for each element this vector
will hold. If zero, then default to one.
numElements UDINT The number of elements to account for initially. If zero,
then use the default.
GetCopyOfElement (Method)
This method copies the element at the zero-based index specified from the vector to the
destination pointer.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the element to copy from the vector.
pt_destination POINTER TO BYTE A pointer to the destination to which the element is
copied.
Return Value
IEC 61131 Type Description
BOOL TRUE if the specified element is copied. FALSE if an error occurs.
Processing
If index or pt_destination are invalid, nothing is copied and false is returned.
PopTo (Method)
This method copies the last element in the vector to the provided pointer location and then
deletes the last element.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the element is
copied.
Return Value
IEC 61131 Type Description
BOOL TRUE if the last element is successfully copied and removed from the vec-
tor. FALSE if an error occurs.
Processing
ä Copies the last element in the vector to the provided pointer location.
ä Removes the last element in the vector.
ä If the vector does not contain any elements (i.e., the size is zero), the method returns
false without modifying the vector.
ä If pt_destination is invalid or the element cannot be copied, then the vector is not
modified and false is returned.
PushFrom (Method)
Copies the bytes from the provided pointer location to a new element at the end of the
vector. Allocates additional memory if the vector does not have enough memory to contain
the new element.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the element is copied.
Return Value
IEC 61131 Type Description
BOOL TRUE if the new element is added to the vector. FALSE if an error occurs.
Processing
ä Copies the element at pt_source to a new element at the end of the vector.
ä If the vector Size is MaxSize before the addition of the new element, the vector
allocates additional memory. If the memory allocation fails, FALSE is returned and
the vector is not modified.
ä If pt_source is invalid, FALSE is returned and the vector is not modified.
SetElement (Method)
This method sets the element in the vector, specified by the index (zero-based), to the
contents of the source pointer.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the vector element to set.
pt_source POINTER TO BYTE A pointer to the source from which the element is copied.
Return Value
IEC 61131 Type Description
BOOL TRUE if the specified element is set. FALSE if an error occurs.
Processing
ä Sets the element in the vector at index to the contents of pt_source.
ä If index or pt_source is invalid, FALSE is returned and the vector is not modified.
class_ByteVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element BYTE The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element BYTE A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element BYTE The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value BYTE The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
class_WordVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element WORD The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element WORD A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element WORD The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value WORD The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
class_DwordVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element DWORD The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element DWORD A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element DWORD The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value DWORD The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
class_LwordVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element LWORD The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element LWORD A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element LWORD The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value LWORD The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
class_RealVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element REAL The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element REAL A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element REAL The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value REAL The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
class_LrealVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element LREAL The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element LREAL A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element LREAL The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value LREAL The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
class_PointerVector
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified, zero-based index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element POINTER TO BYTE The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully added to the vector. FALSE if an error
occurs.
Processing
If pushing element to the vector requires more memory than is currently available in the
vector, the library allocates additional memory. If the memory allocation fails, the vector
is not modified and this method returns FALSE.
SetAt (Method)
This method provides write access to any element within the vector using a zero-based
index.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value POINTER TO BYTE The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and FALSE is returned.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R134 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 1 GB DDR ECC SDRAM
â SEL-3532 RTAC Conversion Kit
â R132 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134 firmware
Append
The time to append 1000 objects to the vector.
Clear
The time to clear a vector of 1000 objects.
GetAt
The worst case time for retrieving an arbitrary index out of a vector of length 1000.
SetAt
The worst case time for setting an arbitrary index in a vector of length 1000.
Push32
The performance of Push when Size = MaxSize = 32.
Push1024
The performance of Push when Size = MaxSize = 1024.
Pop
The performance of a pop of the 1000th element of a vector.
Recycle
The time to remove all data from a vector of 1000 objects.
Resize Down
The performance of a manual resize from 2048 elements to 32 elements.
Resize Up
The performance of a manual resize from 32 elements to 2048 elements.
NewVector
The performance of requesting a new vector of the desired type.
Benchmark Results
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
To satisfy the objective, the user can create a program as shown in Code Snippet 10.1.
// Pop all five elements off the vector and store in an array.
FOR i := 1 TO 5 DO
byteVector.Pop(element => popArray[i]);
END_FOR
// The size after popping the bytes off the vector is zero.
sizeAfterPop := byteVector.Size;
END_IF
Solution
To satisfy the objective, the user can create a program as shown in Code Snippet 10.2.
// Pop all five elements off the vector and store in an array.
FOR i := 1 TO 5 DO
pt_byteVector^.Pop(element => popArray[i]);
END_FOR
// The size after popping the bytes off the vector is zero.
sizeAfterPop := pt_byteVector^.Size;
Assumptions
This example assumes that there is a user-specified IEC 61131 data type defined as shown
in Code Snippet 10.3.
Solution
To satisfy the objective, the user can create a program as shown in Code Snippet 10.4.
// Pop all five elements off the vector and store in an array.
FOR i := 1 TO 5 DO
baseVector.PopTo(ADR(popArray[i]));
END_FOR
// The size after popping the bytes off the vector is zero.
sizeAfterPop := baseVector.Size;
END_IF
Resizing a Vector
Objective
This example demonstrates resizing a vector. Resizing a vector changes how much memory
the vector reserves for the addition of new elements.
Addition of elements to a vector when it does not have space forces the vector to allocate
additional memory. Memory allocation is a relatively slow operation, so it can be useful to
have extra memory reserved by the vector to avoid unnecessary memory allocations. If it
is known how many elements the vector will store, it can be resized once to avoid multiple
slow memory allocations.
Resizing a vector is also useful for releasing memory from the vector. If a vector contained
100 elements previously, but currently only contains 10, the vector will still reserve memory
for the previously removed 90 elements. If the vector no longer needs to store 90 additional
elements, that memory can be returned to the system. A vector will not automatically
release memory back to the system.
Code Snippet 10.5 shows the resizing of a vector to return memory to the system.
Solution
To satisfy the objective, the user can create a program as shown in Code Snippet 10.5.
Email
Introduction
The Email library allows emails to be sent easily from a Real-Time Automation Controller
(RTAC) to a Simple Mail Transfer Protocol (SMTP) email server. These emails can contain
periodic information about process status, alert on-call staff to process anomalies, or send
collected event reports or other attachments directly to email accounts or mobile devices.
Though this library does some parsing of the inputs provided, it is not meant to fully support
all features of SMTP. Test all emails to ensure that the formatting of the arguments does
not create an email the SMTP server receiving the request will ignore.
This library uses the HELO message and local IP address to open each email. This means
that any features requiring the EHLO extensions, including user authentication and encryp-
tion, are not supported.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myEmailClientObject.value;
// As is this
pt_myEmailClientObject := ADR(myEmailClientObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_RecipientType
Enumeration Description
MAIL_TO This recipient will be a direct target of the email.
MAIL_CC This recipient will receive a copy of the email.
MAIL_BCC This recipient will receive a blind copy of the email.
Function Blocks
Function Blocks (FB), if declared in a program or a Global Variable List (GVL), maintain
their state from one processing scan to the next. They should be called during each task
cycle using their input pins to manage their behavior.
Initialization Inputs
Name IEC 61131 Type Description
localIPAddr STRING(15) The IP address this RTAC should use to communicate
with the email server. Set this to 0.0.0.0 to leave From
IP information off of the message request and use an ar-
bitrary interface for communication.
mailServerIP STRING(15) The IP address of the email server.
Inputs
Name IEC 61131 Type Description
Send BOOL Initiate a new email communication.
Inputs/Outputs
Name IEC 61131 Type Description
ToEmail STRING(254) The email address of the message recipient.
ToName STRING(255) The name of the email recipient.
CcEmail STRING(254) The email address to receive a copy of the message.
CcName STRING(255) The name of the copied recipient.
FromEmail STRING(254) The email address of the message sender.
FromName STRING(255) The name of the message sender.
Subject STRING(255) The subject of the message.
BodyStr STRING(255) The body of the message.
Outputs
Name IEC 61131 Type Description
Busy BOOL Indication that the function block is sending an email.
SentMsg STRING(255) The first 255 characters of the last message the function block
sent to the SMTP server.
Error BOOL TRUE if the last attempt to send an email failed.
ErrorStr STRING(80) A description of why the last email transmission failed.
Processing
The fb_SimpleEmailClient function block body does the following:
ä Checks to see if a message is processing.
ä Validates the email addresses provided. Allowed characters include all alphanumeric
characters, ., !, #, $, %, &, +, -, /, =, ?, ^, _, {, }, |, ~, and @.
ä Replaces names containing double quotes with empty strings.
ä Sends a new message to the defined recipients if the function block is not busy and
it detects a rising edge on Send.
ä Works to complete the previously begun email transfer if the function block is busy.
ä Sets Busy to TRUE if it is waiting on the server to complete an email request.
Initialization Inputs
Name IEC 61131 Type Description
localIPAddr STRING(15) The IP address this RTAC should use to communicate
with the email server. Set this to 0.0.0.0 to leave From
IP information off of the message request and use an
arbitrary interface for communication.
localPort UINT The outgoing client port from which emails shall be
sent. Setting this to zero will allow the OS to select
an ephemeral port.
mailServerIP STRING(15) The IP address of the email server.
mailServerPort UINT The port number of the email server. For SMTP, this
is should normally be set to 25, but the user may set it
otherwise if their server is configured accordingly.
Classes
Classes are a particular implementation of a function block. They provide methods and
properties, which normal function blocks do not provide.
class_EmailClient (Class)
This class provides the ability to craft an email message over time and allows for multiple
recipients, dynamic message body lengths, and vector attachments. This class is identical
to class_EmailClient2 with the exception that class_EmailClient2 allows the client to define
the outgoing and destination ports for the client and server, respectively. By contrast, this
class sets the local port to 0, allowing the client OS to select an ephemeral port number.
The destination/server port is set to 25 (the standard SMTP interface port). As such, this
class can be used when there are no special requirements imposed on local or destination
port numbers.
Initialization Inputs
Name IEC 61131 Type Description
localIPAddr STRING(15) The IP address this RTAC should use to communicate
with the email server. Set this to 0.0.0.0 to leave From
IP information off of the message request and use an ar-
bitrary interface for communication.
mailServerIP STRING(15) The IP address of the email server.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
AddRecipient (Method)
This method adds a recipient for subsequent outgoing emails when they are sent. This
method may not be called and will return FALSE while Busy is TRUE and the client is
busy sending an email.
Inputs
Name IEC 61131 Type Description
recipientType enum_RecipientType To, Cc, or Bcc.
Inputs/Outputs
Name IEC 61131 Type Description
emailAddress STRING(254) The email address of the recipient.
name STRING(255) The name of the recipient.
Return Value
IEC 61131 Type Description
BOOL TRUE if emailAddress is valid and the recipient was added.
Processing
The AddRecipient() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Checks that the emailAddress contains only allowed characters. Allowed characters
include all alphanumeric characters, ., !, #, $, %, &, +, -, /, =, ?, ^, _, {, }, |, ~, and
@.
ä Verifies that names do not contain double quotes.
ä Stores the email address and name to add to the recipient field defined by recipient-
Type of subsequent emails.
ä Returns FALSE if the email address was not added.
AttachVector (Method)
This method allows the user to add a raw byte vector as an attachment. The vector does not
need to be encoded in base64-MIME because this will be performed internally, nor will
data be modified as a result of calling this function. This method may not be called and
will return false while Busy is TRUE and the client is busy sending an email.
Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector A byte vector of data to be attached when email is sent.
name STRING The name for the attachment, as it shall appear in each recipient’s
email.
Return Value
IEC 61131 Type Description
BOOL TRUE if data was successfully stored with name.
Processing
The AttachVector() method does the following:
ä Verifies the client is not busy sending an email by checking that Busy is FALSE.
ä Verifies both data and name are non-empty.
ä Copies and encodes data in base64-MIME format, storing the encoded data as an
attachment to be appended to an email.
ä Returns FALSE if attachment was not added.
ClearAttachments (Method)
This method removes all stored attachments. Freeing large amounts of memory is expen-
sive, so this should be called infrequently. This method may not be called and will return
FALSE while Busy is TRUE and the client is busy sending an email.
Processing
The ClearAttachments() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Deletes all email attachments stored by the email client object.
ClearRecipients (Method)
This method removes all stored recipients. This method may not be called and will return
false while Busy is TRUE and the client is busy sending an email.
Processing
The ClearRecipients() method does the following:
ä Verifies the class is not busy sending email by verifying Busy is FALSE.
ä Deletes all stored email recipients.
Run (Method)
Main state machine, which must be called every task cycle. It handles communication
with the socket to send emails over multiple scans. This method only performs work after
Send() is called and Busy is TRUE; otherwise, the call has no effect.
Processing
The Run() method does the following:
ä Sits idle until Send() is called.
ä Sets and clears the Busy state.
ä Opens communication with the email server.
ä Queues data for the email server.
ä Closes the connection with the email server when the send is complete.
Send (Method)
This method sends the presently configured email. It does not clear any internal state of
the class, so the same email could be sent a second time by calling Send() again.
Return Value
IEC 61131 Type Description
BOOL TRUE if the class will send the message to the email server.
Processing
The Send() method does the following:
ä Verifies that the class is not already busy sending email.
ä Verifies at least one recipient has been defined.
ä Verifies the sender has been set.
ä Sends a request to the email server to send the configured email.
ä Returns FALSE if any check fails.
SetBodyBytes (Method)
Sets the content of the body of the email to the provided bytes. This method may not be
called and will return FALSE while Busy is TRUE and the client is busy sending an email.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The bytes to use as the body of the email.
numBytes DINT The number of bytes to use as the body.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The SetBodyBytes() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Validates access to pt_data.
ä Copies numBytes worth of data into internal storage.
ä Replaces any periods beginning lines with two periods to prevent incorrect body
termination.
ä Returns false if the body construction failed.
SetBodySELString (Method)
Sets the body of the email to the content of the SELString provided. This method may not
be called and will return FALSE while Busy is TRUE and the client is busy sending an NOTE: See the SELString Library
documentation for more details on
email. class_SELString objects.
Inputs/Outputs
Name IEC 61131 Type Description
data class_SELString The string to use as the body of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The SetBodySELString() method does the following:
ä Verifies the class is not busy sending email by verifying Busy is FALSE.
ä Copies the contents of data into internal storage.
ä Replaces any periods beginning lines with two periods to prevent incorrect body
termination.
ä Returns false if the body construction failed.
SetBodyString (Method)
Sets the body of the email to the provided string. This method may not be called and will
return FALSE while Busy is TRUE and the client is busy sending an email.
Inputs/Outputs
Name IEC 61131 Type Description
data STRING(255) The string to use as the body of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The SetBodyString() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Copies the contents of data into internal storage.
ä Replaces any periods beginning lines with two periods to prevent incorrect body
termination.
ä Returns false if the body construction failed.
SetBodyVector (Method)
Sets the body of the email to the content of the vector provided. This method may not be
called and will return FALSE while Busy is TRUE and the client is busy sending an email.
Inputs
Name IEC 61131 Type Description
data I_Vector The content to use as the body of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The SetBodyVector() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Validates the data provided can be used.
ä Copies the contents of data into internal storage.
ä Replaces any periods beginning lines with two periods to prevent incorrect body
termination.
ä Returns FALSE if the body construction failed.
SetSender (Method)
This method sets the sending email address for outgoing email. This method may not be
called and will return false while Busy is TRUE and the client is busy sending an email.
Inputs/Outputs
Name IEC 61131 Type Description
emailAddress STRING(254) The email address of the sender.
name STRING(255) The name of the sender.
Return Value
IEC 61131 Type Description
BOOL TRUE if emailAddress is valid and the sender was set.
Processing
The SetSender() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Checks that emailAddress contains only allowed characters. Allowed characters in-
clude all alphanumeric characters, ., !, #, $, %, &, +, -, /, =, ?, ^, _, {, }, |, ~, and
@.
ä Sets emailAddress as the originating email address for outgoing emails.
ä Returns FALSE if the sender was not set.
SetSubjectBytes (Method)
Sets the subject of the email to the provided bytes. This method may not be called and will
return FALSE while Busy is TRUE and the client is busy sending an email.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The bytes to use as the subject of the email.
numBytes DINT The number of bytes to use as the subject.
Return Value
IEC 61131 Type Description
BOOL TRUE if the subject content of the email was successfully populated.
Processing
The SetSubjectBytes() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Validates access to pt_data.
ä Copies numBytes worth of data into internal storage.
ä Returns FALSE if the subject construction failed.
SetSubjectSELString (Method)
Sets the subject of the email to the content of the SELString provided. This method may
not be called and will return FALSE while Busy is TRUE and the client is busy sending an NOTE: See the SELString Library
documentation for more details on
email. class_SELString objects.
Inputs/Outputs
Name IEC 61131 Type Description
data class_SELString The string to use as the subject of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the subject content of the email was successfully populated.
Processing
The SetSubjectSELString() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Copies the contents of data into internal storage.
ä Returns FALSE if the subject construction failed.
SetSubjectString (Method)
Sets the subject of the email to the provided string. This method may not be called and will
return false while Busy is TRUE and the client is busy sending an email.
Inputs/Outputs
Name IEC 61131 Type Description
data STRING(255) The string to use as the subject of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the subject content of the email was successfully populated.
Processing
The SetSubjectString() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Copies the contents of data into internal storage.
ä Returns false if the subject construction failed.
SetSubjectVector (Method)
Sets the subject of the email to the content of the vector provided. This method may not be
called and will return FALSE while Busy is TRUE and the client is busy sending an email. NOTE: See the DynamicVectors
Library documentation for more
details on the I_Vector interface.
Inputs
Name IEC 61131 Type Description
data I_Vector The content to use as the subject of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the subject content of the email was successfully populated.
Processing
The SetSubjectVector() method does the following:
ä Verifies the class is not busy sending email by verifying that Busy is FALSE.
ä Validates the data provided can be used.
ä Copies the contents of data into internal storage.
ä Returns false if the subject construction failed.
class_EmailClient2 (Class)
The functionality, properties, and behavior of this class are identical to that in class_Email-
Client (Class) on page 11.4, with the exception of requiring two additional variables in the
class declaration: a local port number and a destination email server port number. These
inputs allow the user to define the outgoing local port as well as the destination email server
port. If the localPort parameter is zero, then the operating system will select an ephemeral
port number. The SMTP email server port should normally be set to 25, but may be set
otherwise if the SMTP email server is configured accordingly.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_EmailClient
Initialization Inputs
These inputs are necessary during instantiation of the class.
Initialization Inputs
Name IEC 61131 Type Description
localPort UINT The outgoing client port from which emails shall be
sent. Setting localPort to zero will allow the OS to se-
lect an ephemeral port.
localIPAddr STRING(15) The IP address this RTAC should use to communicate
with the email server. Set this to 0.0.0.0 to leave From
IP information off of the message request and use an
arbitrary interface for communication.
mailServerPort UINT The port number of the email server. This is nearly al-
ways port 25 for SMTP, but the user may set it otherwise
if the server listening port is configured accordingly.
mailServerIP STRING(15) The IP address of the email server.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134-V1 firmware
ä SEL-3530
â R134-V1 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware
class_EmailClient.AddRecipient()
The posted time is the average execution time of 100 method calls adding a recipient when
the class is not busy. The email address and name strings are the maximum length.
class_EmailClient.AttachVector()
The posted time is the average execution time of 100 method calls attaching a vector when
the class is not busy. The attachment name string is the maximum length and the content
is 255 characters.
class_EmailClient.ClearAttachments()
The posted time is the average execution time of 100 method calls when clearing 10 file
attachments. To ensure the most work possible, the attachments must already be encoded
as Base64 before they are cleared. The class is not busy when the method is called.
class_EmailClient.ClearRecipients()
The posted time is the average execution time of 100 method calls when clearing 10 To
recipients, 10 Cc recipients, and 10 Bcc recipients. The class is not busy when the method
is called.
class_EmailClient.Send()
The posted time is the average execution time of 100 method calls. The class is not busy
when the method is called.
class_EmailClient.SetBodyBytes()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient.SetBodySELString()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient.SetBodyString()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient.SetBodyVector()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient.SetSender()
The posted time is the average execution time of 100 method calls when setting a maximum
length email address and name. The class is not busy when the method is called.
class_EmailClient.SetSubjectBytes()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient.SetSubjectSELString()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient.SetSubjectString()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient.SetSubjectVector()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient2.AddRecipient()
The posted time is the average execution time of 100 method calls adding a recipient when
the class is not busy. The email address and name strings are the maximum length.
class_EmailClient2.AttachVector()
The posted time is the average execution time of 100 method calls attaching a vector when
the class is not busy. The attachment name string is the maximum length and the content
is 255 characters.
class_EmailClient2.ClearAttachments()
The posted time is the average execution time of 100 method calls when clearing 10 file
attachments. To ensure the most work possible, the attachments must already be encoded
as Base64 before they are cleared. The class is not busy when the method is called.
class_EmailClient2.ClearRecipients()
The posted time is the average execution time of 100 method calls when clearing 10 To
recipients, 10 Cc recipients, and 10 Bcc recipients. The class is not busy when the method
is called.
class_EmailClient2.Send()
The posted time is the average execution time of 100 method calls. The class is not busy
when the method is called.
class_EmailClient2.SetBodyBytes()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetBodySELString()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetBodyString()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetBodyVector()
The posted time is the average execution time of 100 method calls when setting the email
body to contain 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetSender()
The posted time is the average execution time of 100 method calls when setting a maximum
length email address and name. The class is not busy when the method is called.
class_EmailClient2.SetSubjectBytes()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetSubjectSELString()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetSubjectString()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
class_EmailClient2.SetSubjectVector()
The posted time is the average execution time of 100 method calls when setting the email
subject to 255 characters. The class is not busy when the method is called.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fb_SimpleEmailClient Busy Time 714 449 40
fb_SimpleEmailClient Longest Scan Busy Time 81 49 5
fb_SimpleEmailClient2 Busy Time 703 446 40
fb_SimpleEmailClient2 Longest Scan Busy Time 11 52 8
class_EmailClient.AddRecipient() 120 72 13
class_EmailClient.AttachVector() 1543 871 78
class_EmailClient.ClearAttachments() 836 335 24
class_EmailClient.ClearRecipients() 5 2 1
class_EmailClient.Run() Busy Time 178 98 17
class_EmailClient.Run() Busy Time w/ER 245 139 17
class_EmailClient.Run() Longest Scan Time 871 518 56
class_EmailClient.Run() Longest Scan Time w/ER 3839 1640 83
class_EmailClient.Send() 883 537 68
class_EmailClient.SetBodyBytes() 828 498 60
class_EmailClient.SetBodyBytes() w/ER 93158 51279 5579
class_EmailClient.SetBodySELString() 988 539 50
class_EmailClient.SetBodySELString w/ER 115792 61122 5855
class_EmailClient.SetBodyString() 861 581 60
class_EmailClient.SetBodyVector() 807 519 53
class_EmailClient.SetBodyVector() w/ER 93246 51173 5553
class_EmailClient.SetSender() 98 58 14
class_EmailClient.SetSubjectBytes() 49 31 9
class_EmailClient.SetSubjectSELString() 1091 498 48
class_EmailClient.SetSubjectString() 66 42 11
class_EmailClient.SetSubjectVector() 17 9 4
class_EmailClient2.AddRecipient() 118 72 12
class_EmailClient2.AttachVector() 1569 845 80
class_EmailClient2.ClearAttachments() 962 322 24
class_EmailClient2.ClearRecipients() 5 2 1
class_EmailClient2.Run() Busy Time 183 97 16
class_EmailClient2.Run() Busy Time w/ER 245 142 16
class_EmailClient2.Run() Longest Scan Time 925 526 49
class_EmailClient2.Run() Longest Scan Time w/ER 3874 1628 86
class_EmailClient2.Send() 936 540 73
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
The user has in some way defined triggers that will set Alarm1 or Alarm2 to TRUE when
appropriate events occur and allow them to return FALSE afterwards.
Solution
The user can create a fb_SimpleEmailClient to provide brief notifications as shown in Code
Snippet 11.1.
This example sends an email to different people determined by the alert received and also
sends a text message to an on-call telephone number using Short Message Service (SMS).
Alarm1 : BOOL;
Alarm2 : BOOL;
END_VAR
IF Alarm1 THEN
ManagerEmail := DayEmail;
BodyString := 'The daytime plant has lost main power';
END_IF
IF Alarm2 THEN
ManagerEmail := NightEmail;
BodyString := 'The nighttime plant has lost main power';
END_IF
Emailer( Send := Alarm1 OR Alarm2,
ToEmail := OncallPhone, ToName := '',
CcEmail := ManagerEmail, CcName := '',
FromEmail := FromEmail, FromName := FromName,
Subject := SubjectLine, BodyStr := BodyString);
Assumptions
The user has a task that runs and builds a readable log file “details.txt” accessible through
the File Manager features of the RTAC. NOTE: See the FileIO Library
documentation for details on how to
The user has in some way defined a trigger that will set TaskDone to TRUE when appro- access this area programmatically.
Solution
The user can create a class_EmailClient to provide brief notifications as seen in Code Snip-
pet 11.2.
This example sends an email containing the text of the log file to the user and a manager.
FileBuffer : class_ByteVector;
LogFileReader : class_FileReader;
END_VAR
Assumptions
The user has configured Alarm to trigger on events of some manner, and has also written
data to ProcessControlData. The user has included DynamicVectors in their project.
Solution
The user can create a class_EmailClient to provide notifications with raw data attachments
as shown in Code Snippet 11.3.
This example sends an email with raw data attachments to various technicians or other field
personnel.
Troubleshooting
As a communication module, this library depends several things:
1. Correct IP address entered for both the local host (either 0.0.0.0 or an IP that can
route to the mail server) and the mail server.
ä If using 0.0.0.0 as the local IP address, ensure the network that can reach the
mail server is set as the primary gateway. This is set via the RTAC web HMI.
ä If the local IP address is set to the real IP address rather than 0.0.0.0, the
primary gateway does not need to be set.
2. Access to the mail server via port 25.
3. The mail server must be configured to allow email from the RTAC. This may include
but is not limited to: allowing the RTACs IP address to send mail, permitting the
“from name” that the RTAC uses, as well as the “from email address.”
For full information as to what is happening to a sent message, check the logs on the mail
server handling the request.
To quickly check the behavior of a given setup, one can manually test the communications
from a computer on the same subnet as the RTAC by opening a raw TCP channel to the
mail server on port 25 and issuing the same sequence of commands issued by this library.
All sections in teal should be replaced with values from your environment. All new lines
are represented by the ASCII for carriage return followed by new line (many applications
will insert this just by pressing enter).
HELO RTAC_IP
MAIL FROM:<RTAC_EMAIL_ADDR>
RCPT TO:<TO_ADDR>
RCPT TO:<CC_ADDR>
DATA
From: "FROM_NAME"<RTAC_EMAIL_ADDR>
To: "TO_NAME"<TO_ADDR>
Cc: "CC_NAME"<CC_ADDR>
Subject: Email from RTAC
BODY OF MESSAGE
.
QUIT
EmailPlus
Introduction
The EmailPlus library provides SMTP client functionality. Emails can contain plain text
and attachments. The user can specify multiple recipients, including carbon copy and blind
carbon copy recipients. This library supports user authentication, Transport Layer Security
(TLS) encryption, and detailed logging for each email sent. The EmailPlus library can be
configured in two separate behavior modes via the EmailType parameter in the Initialize
method:
ä Triggered Report - Use AddRecipient, AddAttachment, and AppendToBodyFromQueue/SELString/String/Vector
during runtime to manually define recipients, attachments and body content before
asserting the Send input and issuing an email.
ä Monitored Alarm - Use Bootstrap_MonitoredAlarm and BootStrap_GroupRecipient
to define a set of monitored SPS or BOOL tags along with a list of preconfigured re-
cipients for each configured group of tags. When the SPS or BOOL tags assert or
deassert, an “SOE-style” email will be issued to the recipients with the body con-
tent containing a time stamp, a custom assert or deassert message, and an optional
message with accompanying analog value.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myEmailPlusObject.value;
// As is this
pt_myEmailPlusObject := ADR(myEmailPlusObject);
ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
ä This library requires that all sender and recipient email addresses be formatted as
<local part>@<domain>, the total length of which must be 3–254 characters.
â <local part> must satisfy the following requirements:
ã Allowed characters: alphanumeric, ., !, #, $, %, &, ’, *, +, -, /, =, ?, ^, _, `,
{, |, }, ~
ã May not start or end with a “.”
ã May not contain “..”
ã Must be 1–64 characters in length
â <domain> must satisfy the following requirements:
ã Allowed characters: alphanumeric, ., -, with the exception of an IPv4 ad-
dress as the domain, which must be enclosed in square brackets [ and ],
(e.g., [1.2.3.4])
ã May not start or end with a “.”
ã May not contain “..”
ã Must be 1–252 characters in length
ä Attachment file paths may contain alphanumeric characters, _, -, ., and /. They cannot
contain any path manipulation character sets (//, /./, /../).
ä The SMTP server address may be a valid IPv4 address or a hostname.
â An IPv4 address must be formatted as a.b.c.d, where a, b, c, and d are each
numbers between 0 and 255.
â A hostname must satisfy the following requirements:
ã The hostname consists of one or more “labels”, concatenated together by
“.”.
ã A label may contain alphanumeric characters and “-”.
ã A label may not begin or end with “-”.
ã A label must be 1–63 characters in length.
ã The hostname must be 1–253 characters in length.
ä Email body text will be limited to 256 characters per line. Any lines that exceed
this limit will be broken at 256 characters and spread across multiple lines. To avoid
undesired line breaks, format body text with line breaks in desired locations, keeping
line length below the limit.
ä Email body text must not exceed 65,535 bytes and will be truncated if it exceeds this
limit.
ä The subject and email body may contain ASCII characters 16#01 to 16#7F, inclusive.
ä Each call to append to the email body accepts content type as a parameter for the
section of the body being appended. The email body content type determines how
the email client will interpret the body text. The library allows the user to select plain
text for text to be rendered as-is, or HTML for content formatted as HTML.
ä The Initialize() method has a class input named UseSmtps that specifies whether
SMTPS protocol is to be used to communicate with the server. If TRUE, the entire
communication session with the server is encrypted in an SSL/TLS wrapper. SMTPS
communications typically occur over TCP port 465. If FALSE, the initial communi-
cations with the server occur in plaintext. However, if the server reports support for
the STARTTLS function, TLS will be activated using that command before any sen-
sitive information is sent. This type of communications exchange typically occurs
over TCP port 587. Note that in general, the use of SMTPS and/or TCP port 465 is
deprecated; however, many email servers still support it for compatibility reasons.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_BodyContentType
Format of email body content. Used with the AppendToBodyFromQueue/SELString/String/Vector
methods.
Enumeration Description
PLAIN_TEXT Email body content is interpreted as plain text.
HTML Email body content is interpreted as HTML.
enum_EmailerType
Configuration mode of this class_EmailClient instance. Used with the EmailerType input
in the Initialize() method.
Enumeration Description
REPORT This EmailPlus instance is configured for Triggered Reports.
ALARMS This EmailPlus instance is configured for Monitored Alarms.
enum_MonitoredAlarmAnalogMode
Configure the type of alarm transition with which to include the optional Monitored Alarm
analog input. Used with the AnalogMode input in the Bootstrap_MonitoredAlarm()
method.
Enumeration Description
NONE Do not include any optional analog value with the alarm email.
ON_ASSERT On assert of the monitored alarm, include the optional analog value with the
alarm email.
ON_DEASSERT On deassert of the monitored alarm, include the optional analog value with
the alarm email.
ON_EITHER On assert or deassert of the monitored alarm, include the optional analog
value with the alarm email.
enum_MonitoredAlarmAnalogTagType
Tag Type of a variable used as a Monitored Alarm optional analog input. Used with the
AnalogTagType input in the Bootstrap_MonitoredAlarm() method to specify the tag
type assigned to the pt_AnalogVariable input.
Enumeration Description
NONE No Monitored alarm analog variable.
BCR_ANALOG Monitored alarm analog is a BCR variable.
DINT_ANALOG Monitored alarm analog is a DINT variable.
INS_ANALOG Monitored alarm analog is an INS variable.
MV_ANALOG Monitored alarm analog is a MV variable.
REAL_ANALOG Monitored alarm analog is a REAL variable.
UDINT_ANALOG Monitored alarm analog is a UDINT variable.
enum_MonitoredAlarmTagType
Tag type of a variable used for a monitored alarm. Used with the TagType input to specify
the variable type assigned to the pt_Variable input in the Bootstrap_MonitoredAlarm()
method.
Enumeration Description
BOOL_ALARM Monitored alarm is a BOOL variable.
SPS_ALARM Monitored alarm is a SPS variable.
enum_RecipientType
The type of email recipient. Used with AddRecipient() method.
Enumeration Description
MAIL_TO This recipient is a direct target of the email.
MAIL_CC This recipient receives a copy of the email.
MAIL_BCC This recipient receives a blind copy of the email.
Classes
class_EmailClient (Class)
This class provides the ability to craft an email over time and allows for multiple recip-
ients, dynamic message body lengths with optional encoding commands, and adding at-
tachments. The class authenticates to the SMTP server at the specified IP address and port
and sends the email, optionally using TLS encryption. As of library version 3.5.2.0, two
configuration modes are supported: 1. Triggered Report mode 2. Monitored Alarms mode
Inputs
Name IEC 61131 Type Description
Send BOOL Asserting Send triggers the next email to be sent.
Ignored while Busy is asserted.
MaintenanceMode BOOL Asserting this input disables email sending func-
tionality via the Send trigger or any bootstrapped
monitored alarms.
Outputs
Name IEC 61131 Type Description
Initialized BOOL This pin asserts when the class finishes initialization.
Calls to any method other than Run() are ignored while
this is deasserted.
RuntimeErrors STR Lists any runtime errors encountered.
Status STR Lists the present status of the emailer. In Moni-
tored Alarm configuration this includes indications of
a startup delay and other activity.
Busy BOOL If TRUE, calls to any method other than Run() and as-
sertions of Send are ignored.
Processing
ä While Initialized is deasserted, calls to the Run() method and assertions of Send
have no effect.
ä Once Initialize() is called and the class successfully completes initialization,
resulting in the assertion of Initialized, any further calls to Initialize() are ig-
nored.
ä Each email must be constructed through calls to the various class methods before
Send is asserted.
ä When Send is asserted:
â Busy asserts and the class attempts to send the email. Any invalid email fields
result in a failure to send the email, and the class sets an appropriate error in
RuntimeErrors.
â If the parameters of the email are valid but the time-out is reached before the
class has finished sending the email, the email is not sent and the class sets an
appropriate error in RuntimeErrors.
â If the class instance is configured for logging, any runtime errors are logged to
the RTAC Sequence of Events (SOE) log.
â Email content and parameters are cleared.
â Busy deasserts.
AddAttachment (Method)
This method adds an attachment to the subsequent outgoing email. Any number of at-
tachments can be added. When the email is sent, if the total size of attachments is greater
than MaxAttachmentSize, the attachments will be broken up across multiple emails. This
method returns FALSE and has no effect when Busy is TRUE or Initialized is FALSE.
Attachments must be added before each assertion of Send.
Inputs
Name IEC 61131 Type Description
filePath STRING(248) The path of the file to attach.
Return Value
IEC 61131 Type Description
BOOL TRUE if attachment was successfully added.
Processing
The AddAttachment() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not add the at-
tachment.
ä Returns FALSE if the attachment cannot be added and sets an appropriate error in
RuntimeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the attachment is added.
AddRecipient (Method)
This method adds a recipient for the subsequent outgoing emails. Any number of recipi-
ents can be added. This method returns FALSE and has no effect when Busy is TRUE or
Initialized is FALSE. At least one recipient must be added before the assertion of Send.
Note: Email addresses greater than 254 characters in length will be truncated.
Inputs
Name IEC 61131 Type Description
recipientType enum_RecipientType To, Cc, or Bcc.
emailAddress STRING(254) The email address of the recipient.
Return Value
IEC 61131 Type Description
BOOL TRUE if emailAddress is valid and the recipient is successfully added.
Processing
The AddRecipient() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not add the recip-
ient.
ä Checks that the email address contains only allowed characters.
ä Adds the email address to the appropriate recipient field for the subsequent email.
ä Returns FALSE if the email address cannot be added and sets an appropriate error
in RuntimeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the recipient is added.
AppendToBodyFromQueue (Method)
Sets the body of the email to the content of the queue provided. This method returns FALSE
and has no effect when Busy is TRUE or Initialized is FALSE. The body must be set before
each assertion of Send. This method can be called multiple times to append repeatedly to
the body.
NOTE: See the Queue library
documentation for more details on
Inputs/Outputs the class_ByteDeque class.
Inputs
Name IEC 61131 Type Description
bodyContentType enum_BodyContentType The content type used to interpret this section
of the email body.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The AppendToBodyFromQueue() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not set the body
of the email.
ä Copies the contents of bodyQueue into internal storage, marking the content type
according to bodyContentType.
ä Returns FALSE if the body construction failed and sets an appropriate error in Run-
timeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the body is successfully set.
AppendToBodyFromSELString (Method)
Sets the body of the email to the content of the SELString provided. This method returns
FALSE and has no effect when Busy is TRUE or Initialized is FALSE. The body must be
set before each assertion of Send. This method can be called multiple times to append to
the body repeatedly.
Inputs
Name IEC 61131 Type Description
bodyString POINTER TO class_SELString Pointer to the SELString to use as the
body of the email.
bodyContentType enum_BodyContentType The content type used to interpret this
section of the email body.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The AppendToBodyFromSELString() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not set the body
of the email.
ä Copies the contents of bodyString into internal storage, marking the content type
according to bodyContentType.
ä Returns FALSE if the body construction failed and sets an appropriate error in Run-
timeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the body is successfully set.
AppendToBodyFromString (Method)
Sets the body of the email to the provided string. This method returns FALSE and has no
effect when Busy is TRUE or Initialized is FALSE. The body must be set before each asser-
tion of Send. This method can be called multiple times to append to the body repeatedly.
Inputs
Name IEC 61131 Type Description
bodyString STRING(255) The string to use as the body of the email.
bodyContentType enum_BodyContentType The content type used to interpret this section
of the email body.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The AppendToBodyFromString() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not set the body
of the email.
ä Copies the contents of bodyString into internal storage, marking the content type
according to bodyContentType.
ä Returns FALSE if the body construction failed and sets an appropriate error in Run-
timeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the body is successfully set.
AppendToBodyFromVector (Method)
Sets the body of the email to the content of the vector provided. This method returns
FALSE and has no effect when Busy is TRUE or Initialized is FALSE. The body must be
set before each assertion of Send. This method can be called multiple times to append to
the body repeatedly.
NOTE: See the DynamicVectors
library documentation for more
Inputs details on the I_Vector interface.
Return Value
IEC 61131 Type Description
BOOL TRUE if the body content of the email was successfully populated.
Processing
The AppendToBodyFromVector() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not set the body
of the email.
ä Copies the contents of bodyVector into internal storage, marking the content type
according to bodyContentType.
ä Returns FALSE if the body construction failed and sets an appropriate error in Run-
timeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the body is successfully set.
Bootstrap_GroupRecipient (Method)
Add an email recipient associated with a set of Group Numbers to be used when this
EmailPlus instance is configured for Monitored Alarms. This method returns FALSE and
has no effect when Busy is TRUE or Initialized is FALSE.
Inputs
Name IEC 61131 Type Description
emailAddress STRING(254) The email address to associate with the recipient.
groupMask WORD A bit pattern representing Alarms Groups 1–10 (bit 0 =
Group 1, bit 9 = Group 10) to associate with the recipient.
Must not exceed a numeric value of 1023.
Return Value
IEC 61131 Type Description
BOOL TRUE if the group recipient was successfully added.
Processing
The Bootstrap_GroupRecipient() method does the following:
ä If Busy is TRUE, Initialized is FALSE, or Initialized is TRUE but Initialize()
was not called with an EmailerType of enum_EmailerType.ALARMS, returns FALSE
and does not add the recipient.
ä Checks that the email address contains only allowed characters.
ä Checks that the group mask does not exceed a numberic value of 1023.
ä Adds the email address to MAIL_TO field associated with the group numbers spec-
ified by the bit-mask.
ä Returns FALSE if the email address cannot be added and sets an appropriate error
in RuntimeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the recipient is added.
Bootstrap_MonitoredAlarm (Method)
Add a monitored alarm along with its various assert and deassert messages and pickup/-
dropout timers; used when this EmailPlus instance is configured for Monitored Alarms.
Inputs
Name IEC 61131 Type Description
TagType enum_MonitoredAlarmTagType The tag type of the monitored
alarm.
pt_Variable POINTER TO BYTE Pointer to the variable repre-
senting the monitored alarm.
GroupNumber UINT Group number (1–10) to asso-
ciate with the monitored alarm.
AssertMsg STRING(255) Assert message to include in
the email body content when a
rising-edge trigger is detected
on the monitored alarm.
PUDelayTime TIME Optional pickup delay time to
associate with the monitored
alarm before an email is trig-
gered.
DeassertMsg STRING(255) Deassert message to include in
the email body content when a
falling-edge trigger is detected
on the monitored alarm.
DODelayTime TIME Optional dropout delay time to
associate with the monitored
alarm before an email is trig-
gered.
AnalogMode enum_MonitoredAlarmAnalogMode Optionally include an analog
value to associate with the
monitored alarm.
AnalogTagType enum_MonitoredAlarmAnalogTagType Tag type of the optional analog
value associated with the mon-
itored alarm.
pt_AnalogVariable POINTER TO BYTE Pointer to the variable repre-
senting the optional analog tag.
AnalogMsg STRING(255) Optional message to associate
with the analog quantity.
Return Value
IEC 61131 Type Description
BOOL TRUE if the monitored alarm was successfully added.
Processing
The Bootstrap_MonitoredAlarm() method does the following:
ä If Busy is TRUE, Initialized is FALSE, or Initialized is TRUE but Initialize()
was not called with an EmailerType of enum_EmailerType.ALARMS, returns FALSE
and does not add the monitored alarm.
ä Checks that the Tag Type specified by the TagType input is a valid enum_Moni-
toredAlarmTagType.
ä Checks that the pointer address specified by pt_Variable is non-zero.
ä Checks that the group number specified by GroupNumber is between 1 and 10.
ä Checks that at least one non-zero-length string is assigned to AssertMsg and De-
assertMsg.
ä Checks that the analog mode specified by the AnalogMode input is a valid enum_-
MonitoredAlarmAnalogMode.
ä If AnalogMode is not equal to enum_MonitoredAlarmAnalogMode.NONE then checks
that the analog tag type specified by AnalogTagType is a valid enum_MonitoredAlar-
mAnalogTagType and that the pointer address specified by pt_AnalogVariable is
non-zero.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Adds the grouped alarm and returns TRUE if all the checks above passed, FALSE if
otherwise.
ClearRecipients (Method)
This method clears all recipients. This method returns FALSE and has no effect when Busy
is TRUE or Initialized is FALSE. After calling this method, at least one recipient must be
added before the next assertion of Send.
Return Value
IEC 61131 Type Description
BOOL TRUE if recipients are successfully cleared.
Processing
The ClearRecipients() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not clear recipi-
ents.
ä Returns FALSE if recipients cannot be cleared and sets an appropriate error in Run-
timeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if recipients are successfully cleared.
Initialize (Method)
This method configures the class for a configuration mode (Triggered Report or Monitored
Alarms), communication with the SMTP server, and logging. After this method is called
and Initialized asserts, these parameters cannot be modified.
Note: Leave SmtpUserName and SmtpPassword blank if authentication is not desired.
Inputs
Name IEC 61131 Type Description
EmailerType enum_EmailerType The type of emailer this EmailPlus instance rep-
resents.
SmtpServerAddress STRING(253) Hostname or IPv4 address of the SMTP server.
SmtpServerPort UINT(1..65534) TCP port of the SMTP server.
UseSmtps BOOL If TRUE, TLS encryption is required.
SmtpUsername STRING(255) Username for authentication to the SMTP server.
If not set, the class attempts to send the email
without authentication.
SmtpPassword STRING(255) Password for authentication to the SMTP server.
If not set, the class attempts to send the email
without authentication.
MaxAttachmentSize UINT(1..30) Maximum cumulative size (MB) of attachments
for an email.
LogRuntimeErrors BOOL If TRUE, logs runtime errors to the RTAC SOE
log.
Timeout UINT(1..65535) Time-out in seconds for sending an email. This
should be set appropriately according to network
latency and attachment size.
StartupDelay UDINT(1..10) Startup Delay in minutes to pause before process-
ing monitored alarms.
Return Value
IEC 61131 Type Description
BOOL TRUE if parameters were successfully set.
Processing
The Initialize() method does the following:
ä If the Initialized class output is TRUE:
â Returns FALSE and does not affect class parameters.
Run (Method)
This method must be called every task cycle. It performs the sending of emails.
Processing
The Run() method does the following:
ä Runs logging for the class.
ä If MaintenanceMode is asserted, returns and does no work. While in this mode, the
Status output will contain a message indicating that maintenance mode is active.
ä If Busy is FALSE, Initialized is TRUE, Initialize() was called with an Emailer-
Type of enum_EmailerType.REPORT, and Send is asserted:
â Asserts Busy.
â Composes the email.
â Attempts to send the email. If the total size of attachments is greater than
MaxAttachmentSize, the attachments will be broken up across multiple emails.
â Clears the body and attachments list.
â If the email cannot be sent, sets any appropriate errors in RuntimeErrors.
â If the class instance is configured for logging, any runtime errors are logged to
the RTAC SOE log.
â Deasserts Busy.
â If the email was sent successfully, clears RuntimeErrors.
ä If Busy is FALSE, Initialized is TRUE, and Initialize() was called with an
EmailerType of enum_EmailerType.ALARMS:
â If the startup delay is active, the Status output will indicate this state along
with a time remaining value. Once the startup delay expires, regular processing
commences.
â Each bootstrapped monitored alarm is ran through its configured pickup delay
or dropout delay timer and if those expire, a rising- or falling-edge trigger is
activated.
â If an AssertMsg has been configured and a rising-edge trigger was detected,
an email body is constructed with a time stamp and the assert message. If
an optional analog has been configured for OnAssert or OnEither mode, the
optional analog message and tag value are appended to the email body.
SetSender (Method)
This method sets the sending email address for outgoing email. This method returns
FALSE and has no effect when Busy is TRUE or Initialized is FALSE. A sender must
be set before asserting Send.
Note: Email addresses greater than 254 characters in length will be truncated.
Inputs
Name IEC 61131 Type Description
emailAddress STRING(254) The email address of the sender.
Return Value
IEC 61131 Type Description
BOOL TRUE if emailAddress is valid and the sender was set.
Processing
The SetSender() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not set the sender.
ä Checks that emailAddress contains only allowed characters.
SetSubject (Method)
Sets the subject of the email to the provided string. This method returns FALSE when Busy
is TRUE or Initialized is FALSE.
Inputs
Name IEC 61131 Type Description
subject STRING(255) The string to use as the subject of the email.
Return Value
IEC 61131 Type Description
BOOL TRUE if the subject line of the email was successfully populated.
Processing
The SetSubject() method does the following:
ä If Busy is TRUE or Initialized is FALSE, returns FALSE and does not set the subject.
ä Copies the contents of subject into internal storage.
ä Returns FALSE if the subject construction failed and sets an appropriate error in
RuntimeErrors.
ä If the class instance is configured for logging, any runtime errors are logged to the
RTAC SOE log.
ä Returns TRUE if the subject is successfully set.
Troubleshooting
The following steps can help identify issues that may prevent the library from successfully
sending emails.
ä Confirm that the parameters set in the Initialize() method are correct.
ä Set LogRuntimeErrors to TRUE in the Initialize() method and monitor the
RTAC SOE log for information logged by the library during runtime. These log
items will be of Tag Type “EmailPlus”.
ä Visit the Diagnostics page of the RTAC web interface and select the Log Files link.
Download the file vcsmtpd.log and review the log information for the most recent
email attempt (at the bottom of the file).
ä Check the log files of the SMTP server. Confirm that it is configured to accept email
from the RTAC’s IP address, that the authentication parameters are correct, and that
the sender is allowed by the SMTP server.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
The user can create a Triggered Report EmailPlus instance as shown in Code Snippet 12.2:
IF FirstScan THEN
Client.Initialize(EmailerType := enum_EmailerType.REPORT,
SmtpServerAddress := '192.168.1.2',
SmtpServerPort := 25,
UseSmtps := FALSE,
SmtpUsername := '',
SmtpPassword := '',
MaxAttachmentSize := 1,
LogRuntimeErrors := FALSE,
Timeout := 10,
StartupDelay := 1
);
Client.SetSubject('RTAC Report');
Client.SetSender('rtac@selinc.com');
FirstScan := FALSE;
Client.AddRecipient(enum_RecipientType.MAIL_TO,
'email_recipient@selinc.com');
Client.AddRecipient(enum_RecipientType.MAIL_TO,
'another_email_recipient@selinc.com');
END_IF
IF Client.Initialized THEN
SendTrig(CLK := SystemTags.Lamp_Test_Button_Status.stVal);
IF SendTrig.Q THEN
System_Time := SYS_TIME();
BodyString := CONCAT(DT_TO_STRING(System_Time.value.dateTime),
'$R$N');
BodyString := CONCAT(BodyString, 'CPU Burden Percent: ');
BodyString := CONCAT(BodyString,
DINT_TO_STRING(SystemTags.CPU_Burden_Percent.stVal));
Client.AppendToBodyFromString(BodyString,
EmailPlus.enum_BodyContentType.PLAIN_TEXT);
END_IF
Client.Send := SendTrig.Q;
END_IF
Client.Run();
Solution
The user can create a Monitored Alarms EmailPlus instance as shown in Code Snippet 12.3:
IF FirstScan THEN
Client.Initialize(EmailerType := enum_EmailerType.ALARMS,
SmtpServerAddress := '192.168.1.2',
SmtpServerPort := 25,
UseSmtps := FALSE,
SmtpUsername := '',
SmtpPassword := '',
MaxAttachmentSize := 1,
LogRuntimeErrors := FALSE,
Timeout := 10,
StartupDelay := 1
);
Client.SetSubject('RTAC Report');
Client.SetSender('rtac@selinc.com');
FirstScan := FALSE;
Client.Bootstrap_GroupRecipient('email_recipient@selinc.com', 1023);
Client.Bootstrap_MonitoredAlarm(
TagType := EmailPlus.enum_MonitoredAlarmTagType.SPS_ALARM,
pt_Variable := ADR(SystemTags.Lamp_Test_Button_Status),
GroupNumber := 1,
AssertMsg := 'Lamp Test Button Asserted',
PUDelayTime := T#500MS,
DeassertMsg := 'Lamp Test Button Deasserted',
DODelayTime := T#500MS,
AnalogMode := enum_MonitoredAlarmAnalogMode.ON_EITHER,
AnalogTagType := enum_MonitoredAlarmAnalogTagType.INS_ANALOG,
pt_AnalogVariable := ADR(SystemTags.CPU_Burden_Percent),
AnalogMsg := 'CPU Burden Percent');
END_IF
Client.Run();
FTPSync
Introduction
The FTPSync library allows a user to specify content to be monitored and synced with a
File Transfer Protocol (FTP) server automatically. This library monitors specified folders
and IEDs to detect when files are added or modified and sends those files to the FTP server.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myFTPSyncObject.value;
// As is this
pt_myFTPSyncObject := ADR(myFTPSyncObject);
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_SyncStatus
This structure contains the sync status for a single monitored IED or directory.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_EventType
The type of event to monitor for a given IED.
Enumeration Description
CEV SEL Compressed ASCII format event report.
COMTRADE Binary COMTRADE format event report.
MMS_COMTRADE Binary COMTRADE format event report collected via MMS protocol.
Classes
class_FtpSync (Class)
This class monitors directories and collected CEV and COMTRADE events for new or
modified files and sends those files to an FTP server on the specified interval.
Inputs
Name IEC 61131 Type Description
EnableSFTP BOOL If TRUE, the client uses SFTP.
FtpServerAddress STRING(15) IP address of the FTP server. Must be in the
form XXX.XXX.XXX.XXX, where XXX is an in-
teger between 0 and 255.
FtpServerPort UINT The TCP port number (0-65535) of the ftp
server.
UserName STRING(32) Username for the FTP server. Must be 1 to 32
characters and contain only alphanumeric char-
acters and underscore.
Password STRING(32) Password for the FTP Server. Must be 1 to 32
characters and may contain all printable ASCII
characters, excluding the single quote, double
quote, and backtick.
RemoteTargetDirectory STRING(100) The target directory where the RTAC repli-
cates the monitored RTAC directory structure
and places files and events. Must be 1 to 100
characters and may contain all printable ASCII
characters, excluding the single quote and dou-
ble quote.
SyncInterval TIME The interval at which monitored directories and
IEDs are checked for updates. The range is 1 to
60 minutes. Or set to 0 to disable periodic sync.
SyncTimeout UDINT The maximum time in seconds allowed for a
file transfer operation. Defaults to 30. Mini-
mum is 1.
SyncTrigger BOOL Triggers a file sync in lieu of waiting for the
sync interval to expire. May be a Boolean vari-
able or Boolean expression, and is not required.
LogRuntimeErrors BOOL If TRUE, the library logs runtime errors in the
RTAC Sequence of Events (SOE) log.
Outputs
Name IEC 61131 Type Description
Initialized BOOL This pin asserts when the class finishes initializa-
tion. The sync interval and SyncTrigger are ig-
nored while this pin is deasserted.
FileSyncInProgress BOOL This pin is TRUE while the FTP client is sending
files to the FTP server.
Processing
ä Once Run() has been called, any further changes to the class inputs are ignored.
ä Upon the first call of Run(), the class begins the initialization process, which in-
cludes creating the monitored directory structure on the remote FTP server. If the
server does not allow directory creation, the sync fails. Once initialization has fin-
ished, the Initialized pin asserts.
ä On each sync interval expiration or sync trigger assertion, the RTAC uploads any
new or updated monitored content that has not been synced into the appropriate
remote target directory. For example, events from an IED named SEL_351S_1 on
the RTAC in the directory /EVENTS/CEV/SEL_351S_1 are placed in the directory
<RemoteTargetDirectory>/EVENTS/CEV/SEL_351S_1 on the server.
ä If a monitored directory contains additional subdirectories, these directories are ig-
nored. Only files in the specified directories are monitored.
ä File names beginning with a period are ignored.
ä If the FTP client cannot send a file to the FTP server, it populates the RunTimeErrors
output pin with the error message. The FTP client then attempts to sync any other
directories and IEDs to the server. The client tracks the state of the directory or IED
that could not be fully synced and tries again on the next sync interval.
bootstrap_AddMonitorDirectory (Method)
This method adds a directory to be monitored. This method only adds directories to be
monitored if called prior to the first Run() method call.
Inputs
Name IEC 61131 Type Description
directoryName STRING(100) The directory to be monitored. Must be 1 to 100 char-
acters and may contain all printable ASCII characters
between 16#20 (Space) and 16#7E (~), excluding ", ’, :,
<, %, >, ?, \, and |. Cannot contain any file path manip-
ulation character sequences (//, /./, /../)
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the directory is successfully listed for monitoring.
bootstrap_AddMonitorEvent (Method)
This method adds an IED to monitor for collected events to sync. This method only adds
IEDs to be monitored if called prior to the first Run() method call.
Inputs
Name IEC 61131 Type Description
iedName STRING(100) The IED to be monitored for events.
eventType enum_EventType The collected event format (CEV or COMTRADE).
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the IED is successfully listed for monitoring.
bootstrap_AddMonitorEventByPath (Method)
This method allows any events within the /EVENTS folder to be synced that may not be
available via bootstrap_AddMonitorEvent(), and requires the full path to the events,
beginning with /EVENTS. This method only adds IEDs to be monitored if called prior to
the first Run() method call.
Inputs
Name IEC 61131 Type Description
iedEventPath STRING(100) The full path to be monitored for events.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the IED is successfully listed for monitoring.
GetSyncStatus (Method)
This method returns the sync status for a given directory or IED.
Inputs
Name IEC 61131 Type Description
statusIndex UINT A number between 1 and NumSyncFolders, corresponding
to a directory or IED being monitored.
Return Value
IEC 61131 Type Description
struct_SyncStatus The current sync status for the indicated directory or IED.
Run (Method)
This method performs directory and IED monitoring. Call this method once each process-
ing cycle after configuration is complete.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes the following:
ä The RTAC project contains an SEL client collecting CEV events called SEL_Client,
a Modbus client collecting COMTRADE events from a GE relay called GE_Client,
an Axion module generating COMTRADE events called SEL_CTPT_1, and a Record-
ing Group instance generating COMTRADE events called RECORDINGGROUP1.
ä The RTAC has directory Dir1 with file File1.txt in it and directory Dir2 with file
File2.txt in it.
ä An FTP server exists with IP address 192.168.1.10, and the RTAC is networked to
communicate with it.
ä The FTP server has an existing user with username RTACUser and the password
TAIL, with read, write, delete, and append file permissions in the FTPFiles directory.
Solution
A program can be created to run an instance of class_FtpSync to sync the files and events,
as shown in Code Snippet 13.1.
IF FirstScan THEN
FtpSync.EnableSFTP := FALSE;
FtpSync.FtpServerAddress := '192.168.1.10';
FtpSync.FtpServerPort := 21;
FtpSync.UserName := 'RTACUser';
FtpSync.Password := 'TAIL';
FtpSync.RemoteTargetDirectory := 'FTPFiles';
FtpSync.SyncInterval := T#5M;
FtpSync.LogRuntimeErrors := TRUE;
FtpSync.SyncInfoDirectory := 'FTPSync_1';
FtpSync.bootstrap_AddMonitorDirectory('/Dir1');
FtpSync.bootstrap_AddMonitorDirectory('/Dir2');
FtpSync.bootstrap_AddMonitorEvent('SEL_Client', enum_EventType.CEV);
FtpSync.bootstrap_AddMonitorEvent('GE_Client', enum_EventType.COMTRADE);
FtpSync.bootstrap_AddMonitorEvent('SEL_CTPT_1',
enum_EventType.COMTRADE);
// All Recording Group events share a common folder
FtpSync.bootstrap_AddMonitorEventByPath('/EVENTS/COMTRADE');
FirstScan := FALSE;
END_IF
FtpSync.Run();
Assumptions
This example assumes the following:
ä Files will be sent over SFTP.
ä An SFTP server exists with IP address 192.168.1.10, and the RTAC is networked to
communicate with it.
ä The SFTP server allows connections on Port 22.
ä The RTAC has a directory FilesToSync with File1.txt in it.
ä The SFTP server has an existing user with username RTACUser with read, write,
delete, and append file permissions in the FTPFiles directory, and the FTPFiles di-
rectory is in the FTP root. The password for the user can be set to anything (because
it will not be used) or left blank if required as such by the SFTP server. Consult
the SFTP server’s documentation pertaining to public key authentication for more
information.
Solution
First, the RTAC’s public SSH key must be prepared. In the RTAC web interface, select
SSH Keys under Security. Copy the contents of the Host Key text box between "—–
BEGIN SSH2 PUBLIC KEY —–" and "—– END SSH2 PUBLIC KEY —–".
Paste the copied text into an empty text file (e.g., in Notepad++). At the beginning of the
file, type "ssh-rsa", followed by a space. At the end of the file, type a space, followed
"RTACUser@", followed by the RTAC hostname. To find the RTAC hostname, select
Interface under Network in the web interface..
The text should all be on a single line and look similar to this (shown with line wrapping
enabled):
At this point, the host key can be copied to the SFTP server. The steps involved vary
depending on the SFTP server. Consult the SFTP server’s documentation pertaining to
public key authentication for more information.
Once the key is properly configured and placed on the SFTP server, a program can be
created to run an instance of class_FtpSync to sync the files to the SFTP server, as shown
in Code Snippet 13.2. Note the use of "HOST_SSH_KEY" as the password. This causes
FTPSync to use public key authentication.
IF FirstScan THEN
Syncer(EnableSFTP := TRUE,
FtpServerAddress := '192.168.1.10',
FtpServerPort := 22,
UserName := 'RTACUser',
// 'HOST_SSH_KEY' here forces use of public key
authentication
Password := 'HOST_SSH_KEY',
RemoteTargetDirectory := '/FTPFiles',
SyncInterval := T#1M,
LogRuntimeErrors := TRUE,
SyncInfoDirectory := '/SyncInfo',
);
Syncer.bootstrap_AddMonitorDirectory('/FilesToSync');
FirstScan := FALSE;
END_IF
Syncer.Run();
FallingConductorProtection
Introduction
This library is intended to provide systems to detect and preemptively mitigate dangerous
conditions in modern electric power systems caused by downed conductors. The classes,
structures, functions, and function blocks in this library should be used as protection sys-
tems designed to operate on a wide-area network, coordinating multiple protective devices
or other IEDs capable of taking protective action.
Global Constants
The library applies the following global constants which are useful in providing common
constants and references.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_AffirmativeDetectionType
The enum_AffirmativeDetectionType enumeration is used as an input for the FallingCon-
ductorProtection class implemented in this library to provide a means of describing the
number of detection methods required by the class to assert a trip command.
Enumeration Description
MONITORING_ONLY No protective response (trip commands) should
be applied; the class should provide monitoring
functionality only.
SINGLE_METHOD_PICKUP FallingConductorProtection schemes may inter-
vene with at least one positive detection method.
DOUBLE_METHOD_PICKUP FallingConductorProtection schemes may inter-
vene with at least two positive detection methods.
enum_SwitchType
The enum_SwitchType enumeration describes the possible variations a switch in a Falling-
ConductorProtection scheme may be described with to permit the protection algorithms to
make control and blocking determinations.
Enumeration Description
BREAKER_SWITCH A switch associated with an IED that can act on received trip con-
trols and disconnect the zone from the substation feeder.
FUSE_TAP A fused tap off of a line that is capable of breaking a circuit but not
receiving trip controls. Typically used to divide a circuit into dis-
crete zones of FC protection. The FUSE_TAP designation should
be assigned to the first switch connected in series to the fuse in
the segmented zone. In the event of a detected blown fuse for a
given zone, a switch configured as a FUSE_TAP is flagged as a
possible source of the blown fuse.
NON_OPERATIONAL A switch or sensory point on a circuit that is not capable of break-
ing a circuit as part of a FallingConductorProtection scheme.
SUBSTATION_BREAKER A switch associated with an IED located at a substation whose
voltage inputs are connected to Bus PTs that are not capable of
generating falling conductor events. These switches can act on
received Trip signals for a falling conductor detected in their zone
but cannot make trip determinations on their own.
FUSE_SOURCE A switch located on the boundary of a zone of FC protection on
the source side of a FUSE_TAP. This switch will not execute any
FallingConductorProtection algorithms because blown fuse con-
ditions located in the associated child zone and detected by the as-
sociated FUSE_TAP could be misinterpreted as FallingConduc-
tor methods.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_AdvancedSettings
The struct_AdvancedSettings structure is a collection of advanced settings for class_Falling-
ConductorMonitor that have default values but which are adjustable by the end user.
struct_DetectedType
The struct_DetectedType structure is used to monitor the various detection methods for
each of the switches and zones composing a circuit for the FallingConductorProtection
detection algorithm (class_FallingConductorMonitor).
struct_ProtTypeEnable
The struct_ProtTypeEnable structure is used to identify the enabled detection methods for
an individual zone.
struct_SwitchStatus
The struct_SwitchStatus structure represents all of the input and calculated quantities that
are respectively evaluated for each switch.
struct_ZoneStatus
The struct_ZoneStatus structure represents all of the calculated quantities that are respec-
tively evaluated for each zone.
Classes
The FallingConductorProtection library provides classes designed to be implemented as
monitoring or protection systems related to power system falling or downed conductors.
class_FallingConductorMonitor (Class)
The falling conductor monitor is an algorithm designed to utilize distributed, high-accuracy,
time-aligned system measurements to detect falling electric conductors. It does this by in-
terpreting parameters that describe the electrical phenomena linked to events where an
electrical conductor is severed and begins to fall. When an overhead conductor breaks,
there is typically a delay of approximately 1.37 seconds before the conductor contacts the
earth. This delay provides an opportunity for the algorithm to detect the condition and react
to isolate the conductor.
Synchrophasor measurements from phasor measurement units (PMUs) located at power
distribution circuits are relayed to RTACs serving as phasor data concentrators (PDCs) for
time alignment. The time-aligned data is monitored in order to detect falling conductor
faults that may occur in the distribution circuits. Under steady-state operating conditions,
with no faults in the circuit, the voltage sequence components along with derivatives of the
phase voltages are calculated in the PDC RTAC. These calculated quantities are monitored
for abnormality in case of falling conductor faults. Methods for detecting falling conductors
include the following:
1. Voltage change (i.e., dV/dt) method
2. Zero-sequence voltage (i.e., V0) magnitude method
3. Zero-sequence voltage (i.e., V0) angle method
4. Negative-sequence voltage (i.e., V2) magnitude method
5. Negative-sequence voltage (i.e., V2) angle method
gorithm will not process the specific detection method for the zone. This format provides
additional flexibility for detection between zones, allowing different zones to enable subsets
of the class’ enabled methods to provide tailored detection where needed while maintaining
sensitivity.
Specific Considerations
ä Use of this class dictates that the RTAC upon which it is running uses a cycle-time
to be set at approximately one-third of the IEEE C37.118 message period.
ä The number of streaming data sources employed by this class will significantly im-
pact the overall performance and execution timing; thus, it may dictate which pro-
cessing platform should be used for satisfactory results.
ä To avoid any implementation challenges with achieving high performance timing
with the class, use of the SEL-3555 and/or SEL-3560 platforms is recommended.
ä All SOE entries generated by this class will be associated with the logging category
of “FallingConductor”.
In addition to the overcurrent pickup values (usually only configured on the primary feeder
in a circuit) each IED also provides a FAULT status available in its incoming PMU data.
This status is typically sourced from the FAULT logic equation in the IED and is another
means of remotely signaling that the field IED has detected a traditional overcurrent sce-
nario. Another condition that is monitored for and used for blocking is the presence of
an external disturbance; this would manifest itself as a given falling conductor detection
method picking up a switch defined as a SUBSTATION_BREAKER. In this scenario, the
disturbance can be assumed to be upstream from the distribution network being monitored
for falling conductor conditions, and thus the falling conductor algorithms are blocked to
allow for upstream protection to act upon the fault.
After these faults have been cleared by traditional protective systems, falling conductor
detection will be unblocked to allow for falling conductor protection. This blocking scheme
is illustrated in Figure 14.1 above.
to surpass the
Blown Fuse BlownFuseQualificationTime
specified, denoted in the figure at left
BlownFuseVoltageThreshold + as Fuse_PU.
Switch N Voltage -
Switch Availability
In addition to the blocking algorithms described above which are used to block detection
at a circuit (class) level, additional blocking is performed at the switch level. This is done
to prevent sending commands to devices that have intentionally been excluded from the
falling conductor algorithm, or those whose communication status has come into question.
This determination is evaluated as switch availability and is logically determined on a per-
switch basis as shown in Figure 14.4 below. The Availability status of a switch is exposed
in the struct_SwitchStatus of that switch, in addition to a CommsOK flag that is determined
by a logical AND of the IED Offline Indication and a regularly updating time stamp on the
tag specified by the RTTIn bootstrap_Switch input.
Switches that provide a connection between zones (for example, PMU2 in the examples
above) will be bootstrapped twice, once in each zone. These switches will often be boot-
strapped with input signals (voltages, currents, etc.) from the same IED. These 2 switches
are referred to as siblings, and each is processed independently in its respective zone for
falling conductor criteria.
Switches can be described as fuse taps or as non-operational switches, both of which cannot
clear faults on demand (i.e., they cannot act on received trip signals from the algorithm).
As a result, these switches must be able to rely upon other breaker switches located in their
zone (or in a parent zone) to clear any faults that they detect.
In cases where these non-operational switches are situated at the end of a line or tap as
monitors and an upstream recloser or breaker is present in the same zone, this recloser or
breaker will be responsible for clearing faults and will inherently accept this responsibil-
ity. This is illustrated in the top illustration of Figure 14.5. However, in situations where
the non-operational monitor exists in place of the previously described breaker (e.g., all
switches in a zone are non-operational, and thus cannot clear faults in the zone), a par-
ent zone reference must be described to provide a means of clearing faults. In this way, a
non-operational zone can transfer trip responsibility to its parent (upstream) zone which is
operational. This topology is illustrated in the bottom of Figure 14.5. A fault that occurs
in a given zone will not issue trips to any child zones that reference it as a parent.
If a zone normally has tripping capabilities but all switches with a closed 52A contact
status that are designated as type BREAKER_SWITCH or SUBSTATION_BREAKER
have entered an unavailable state (as defined by the switch availability conditions above),
then any tripping operations will be deferred to a configured parent zone that still possesses
tripping capabilities.
For controllable switches that provide a connection to a child zone that is further down-
stream from the substation feeder, the breaker switch designation should only be assigned
to the sibling switch (associated with the same IED) present in the child zone, as tripping
this switch in the parent zone would not disconnect the faulted zone from the source. Given
the example shown in the top illustration in Figure 14.5, this means that when PMU2 is
bootstrapped as a switch in Zone 1, it should be designated as a line monitor, and PMU1
would be bootstrapped as the breaker switch as it would be responsible for isolating the
zone from the source. In Zone 2, when PMU2 is bootstrapped as a switch, it should be
assigned the breaker switch designation.
EnableVoltageChangeDetection
dVdtEnable (in zone)
dVA.instMag
dt -
-dVdtPickup +
dVB.instMag
dt -
-dVdtPickup +
N_MSGS
dV
dVC.instMag dt Detect
dt - dV RST
dt
-dVdtPickup +
dV0.instMag
dt +
dV0dtPickup -
Figure 14.6 Voltage Change Method (dV/dt) Logic to Determine Falling Conductor
Criteria
|V 2| + |V 2| Detect
V2MagPickup -
|V 2| RST
Figure 14.7 Zero- and Negative-Sequence Voltage Magnitude (|V0| and |V2|) Method
Logic for Determining Falling Conductor Criteria
Inputs
Name IEC 61131 Type Description
Enable BOOL System Enable.
DataRate INT C37.118 Rate of data transmis-
sion. Normally fed from Sys-
temTags.Data_Rate tag.
LogRuntimeOperations BOOL If TRUE, runtime errors, falling
conductor detection, and trip op-
erations are logged in the RTAC
SOE viewer (defaults to TRUE).
AlarmOnFaultySensor BOOL If TRUE and if LogRuntimeOp-
erations is TRUE, faulty sensor
SOE entries will be logged as
alarms (defaults to TRUE).
AlarmOnBlownFuse BOOL If TRUE and if LogRuntimeOp-
erations is TRUE, blown fuse
detection SOE entries will be
logged as alarms (defaults to
TRUE).
SystemNominalVoltage REAL Nominal system line-to-neutral
voltage in units specified by
phase measurement inputs.
AffirmativeDetectionCount enum_AffirmativeDetectionType Control to specify number of
affirmative detection methods
required for tripping (defaults
to MATCH_ENABLED_-
METHOD_PICKUP).
EnableVoltageChangeDetection BOOL Enable/disable dV/dt-based
fault detection.
dVdtPickup REAL Phase voltage magnitude rate-
of-change pickup (in units spec-
ified by phase measurement in-
puts; e.g., volts per second - de-
faults to 5000).
EnableV0MagnitudeDetection BOOL Enable/disable zero-sequence
voltage magnitude-based fault
detection.
V0MagPickup REAL Zero-sequence voltage magni-
tude pickup (in units specified by
phase measurement inputs - de-
faults to 1000).
EnableV2MagnitudeDetection BOOL Enable/disable negative-
sequence voltage magnitude-
based fault detection.
V2MagPickup REAL Negative-sequence voltage mag-
nitude pickup (in units specified
by phase measurement inputs -
defaults to 2000).
EnableV0AngleDetection BOOL Enable/disable zero-sequence
voltage angle-based fault
detection.
Outputs
Name IEC 61131 Type Description
Enabled BOOL System enable indicator
Licensed BOOL Indicator of successful license check for
FallingConductorProtection
AlgorithmsEnabled BOOL Indicator of Enable status of FallingConductor-
Protection detection algorithms
Error BOOL System error indicator
ErrorDesc STRING(255) Descriptive message of applicable error
Trip BOOL Indicator that a Trip signal has been sent to one
or more switches
FaultySensorAlarm SPS Faulty sensor detection alarm
FaultySensorDesc STRING(255) Faulty sensor detection description
dI0dtSpikeAlarm SPS Zero-sequence current rate-of-change spike
alarm
dI0dtSpikeDesc STRING(255) Zero-sequence current rate-of-change spike de-
scription
BlownFuseDetected SPS Blown fuse detection indicator
BlownFuseDesc STRING(255) Blown fuse detection description
BlockingFaultAlarm SPS System blocking fault alarm
BlockingFaultDesc STRING(255) System blocking fault description
dVdtFaultDetect BOOL dV/dt fault detection indicator
V0MagFaultDetect BOOL V0 magnitude fault detection indicator
V2MagFaultDetect BOOL V2 magnitude fault detection indicator
V0AngFaultDetect BOOL V0 angle fault detection indicator NOTE: Note that legacy Falling
V2AngFaultDetect BOOL V2 angle fault detection indicator Conductor applications may have
used a common GOOSE transmit bit
RoundTripTimeOutput SPS Round-trip time output for measuring round- (shared by all circuits) for Round Trip
trip network delay between RTAC and switch Time calculation purposes. This
devices; toggles once per second and is typi- should be avoided and each circuit
(class) instance of
cally assigned to a GOOSE transmit bit class_FallingConductorMonitor should
use a unique GOOSE transmit bit that
is used only by the switches in that
particular circuit. This is to provide
the most accurate RoundTripTime
calculations for those switches.
bootstrap_Zone (Method)
This method should be called to create the zone references that will be used by the pro-
tection algorithms. This method should be called once for every zone in a circuit which
will be protected against falling conductor cases. Every call to the bootstrap_Zone method
should be completed before any calls to the bootstrap_Switch or Run methods. Any zone
that may be referred to as a ParentZoneReference by a switch should be bootstrapped before
the child zone where said switch is configured.
Inputs
Name IEC 61131 Type Description
ZoneName STRING(255) Name to be associated with zone
dVdtEnable BOOL Enable dV/dt falling conductor detection method
V0MagEnable BOOL Enable zero-sequence voltage magnitude falling con-
ductor detection method
V2MagEnable BOOL Enable negative-sequence voltage magnitude falling
conductor detection method
V0AngEnable BOOL Enable zero-sequence voltage angle falling conductor
detection method
V2AngEnable BOOL Enable negative-sequence voltage angle falling conduc-
tor detection method
Inputs/Outputs
Name IEC 61131 Type Description
PhaseAVoltage CMV Phase A voltage tag referencing measured input for
IEEE C37.118 client (PMU) intended as zone reference
voltage
PhaseBVoltage CMV Phase B voltage tag referencing measured input for
IEEE C37.118 client (PMU) intended as zone reference
voltage
PhaseCVoltage CMV Phase C voltage tag referencing measured input for
IEEE C37.118 client (PMU) intended as zone reference
voltage
ZoneStatus struct_ZoneStatus Status and indication structure which will be populated
at the end of every Run method call with the updated
zone information
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_FallingConductorMonitor successfully bootstraps
a new zone with the described parameters.
Processing
ä The method confirms that the Run method has not yet been called.
ä The ZoneName is verified as a valid string (i.e., not empty and not already existing
in class as previously bootstrapped zone).
ä Pending previous verification, the zone attributes are recorded as a reference for
falling conductor protection.
bootstrap_Switch (Method)
This method should be called to create the switch references which will be used by the
protection algorithms. This method should be called once for every reference to a zone by
a switch in a circuit which will be protected against falling conductor cases. That is to say,
that if a switch is a member of two zones (as in the case of most standard breakers), this
bootstrap method should be called twice, once for each zone (of which, there are two in
this case) which the switch holds reference to. All switch instances must define a unique
name. Every call to the bootstrap_Zone method should be completed before any calls to
this method, and similarly, all calls to the bootstrap_Switch method should be completed
before the first call to the Run method.
Inputs
Name IEC 61131 Type Description
SwitchName STRING(255) Name to be associated with switch
ZoneReference STRING(255) Name of the zone that the switch should be asso-
ciated with
ParentZoneReference STRING(255) Name of the zone that supersedes the zone which
this switch is associated with; i.e., this switch’s
parent zone
SwitchType enum_SwitchType Enumerated description of the switch type as
breaker, fuse tap, or non-operational switch
PhaseOCPickup REAL Set point for which traditional relay-based phase
overcurrent protection will interrupt circuit,
and which should not be managed by falling-
conductor protection
GroundOCPickup REAL Set point for which traditional relay-based
ground overcurrent protection will interrupt cir-
cuit, and which should not be managed by falling-
conductor protection
NOTE: Although
g_NO_REFERENCE_VOLTAGE may be
applied to one or even two of the
voltage inputs (i.e., PhaseAVoltage,
PhaseBVoltage, and PhaseCVoltage),
at least one of these inputs must
reference a valid voltage
measurement and not the
"NO_REFERENCE" placeholder. If this
condition is not met, the falling
conductor algorithm will result in an
error describing the invalid reference.
Inputs/Outputs
Name IEC 61131 Type Description
PhaseAVoltage CMV Phase A voltage tag referencing measured in-
put for IEEE C37.118 client (PMU) located at
switch; may be set to g_NO_REFERENCE_-
VOLTAGE if the zone’s reference voltage
should instead be used for protection algo-
rithms
PhaseBVoltage CMV Phase B voltage tag referencing measured in-
put for IEEE C37.118 client (PMU) located at
switch; may be set to g_NO_REFERENCE_-
VOLTAGE if the zone’s reference voltage
should instead be used for protection algo-
rithms
PhaseCVoltage CMV Phase C voltage tag referencing measured in-
put for IEEE C37.118 client (PMU) located at
switch; may be set to g_NO_REFERENCE_-
VOLTAGE if the zone’s reference voltage
should instead be used for protection algo-
rithms
PhaseACurrent CMV Phase A current tag referencing measured in-
put for IEEE C37.118 client (PMU) located at
switch
PhaseBCurrent CMV Phase B current tag referencing measured in-
put for IEEE C37.118 client (PMU) located at
switch
PhaseCCurrent CMV Phase C current tag referencing measured in-
put for IEEE C37.118 client (PMU) located at
switch
Switch52AStatus SPS Breaker status indicator (52A contact status)
reference for IEEE C37.118 client (PMU) lo-
cated at switch; may be set to g_BREAKER_-
CLOSED when no valid 52A breaker status is
measured at switch
OfflineIndicator BOOL IED offline status indicator to use to block what
may appear as a false positive falling conductor
detection
TripControlPointOut SPS SPS tag which may provide a means to trip
(open) this switch or breaker (such as a GOOSE
transmit tag configured as part of a message
subscribed to by an IED responsible for per-
forming the trip operation(s) in the field) under
conditions determined by falling conductor al-
gorithm; may be set to g_NO_REFERENCE_-
TRIP_CONTROL for switches that do not pro-
vide a means to execute tripping operations
(i.e., fuse-taps or non-operational switches)
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if class_FallingConductorMonitor successfully bootstraps
a new switch with the described parameters.
Processing
ä The method confirms that the Run method has not yet been called.
ä The method confirms that at least one zone has been associated with the class in-
stance, and thus, switches may be bootstrapped accordingly.
ä Both the ZoneReference and ParentZoneReference are verified as zones that have
been bootstrapped to the class instance, thus validating these references.
ä The SwitchName is verified as a valid string (i.e., not empty and not already existing
in class as previously bootstrapped switch).
ä Any voltages which have been set from g_NO_REFERENCE_VOLTAGE are set to
reference the associated zone’s voltage data.
ä Pending previous verification, the zone attributes are recorded as a reference for
falling conductor protection.
Run (Method)
This method must be called once every processing scan after all of the bootstrap methods
have been called to construct and model the electric circuit.
Processing
ä Enable input is mapped to Enabled output.
ä Boot delay timer is processed to verify that sufficient time has passed since RTAC
boot (as required by the advanced setting BootDelay) for algorithms to perform ex-
pectantly.
ä Protection pickup delay is calculated from the message interval and the protection
message count specified by Equation 14.1.
ä Protection pickup timers are run for each detection method, including:
â change of voltage over time (dVdt)
â zero-sequence voltage magnitude (V0Mag)
â negative-sequence voltage magnitude (V2Mag)
â zero-sequence voltage angle (V0Ang)
â negative-sequence voltage angle (V2Ang)
ä System initialization occurs on the first scan after the boot delay elapses or the class
Enable input sees a rising edge. This process resets sequence component and deriva-
tive calculations and verifies the number of switches in each zone.
ä Dynamic (changeable during runtime) number of concurrent falling conductor de-
tection methods required to issue trip is updated.
ä When the boot delay has passed, and on each call of the run method, the following
logic executes:
â All IEEE C37.118 system settings and time source information is updated.
â Sequence and derivative calculations are performed for each switch.
â The system is evaluated for a global blocking criteria which includes:
ã Verifying that no traditional fault types (i.e., phase-overcurrent, ground-overcurrent,
or zero-sequence current magnitude excursion) are detected for any switch boot-
strapped to the class.
ã Verifying that no faulty sensor criteria arises by determining if switches that share
a common control point, and whose 52A contact status indicates a closed breaker,
share voltage magnitude measurements within a tolerance specified as a percent of
nominal voltage by the advanced setting MaxSensorMagDifference.
ã Verifying that no previous trip commands have been issued to any zone boot-
strapped to the class for a time specified by the advanced setting TripSignalAsser-
tionPeriod.
update boot
Run() NOTE: Regardless of the presence
delay timer of blocking conditions such as a
traditional fault (e.g., overcurrent),
faulty sensor, or pre-existing trip
condition, the falling conductor
initialize system, algorithm will process trip and clear
is this first yes reset sequence conditions for every zone when the
scan? and derivative system is enabled to ensure trip
signals are cleared after the
calculations appropriate time delay.
no
update
method count
requirement
enabled and no
return
past boot delay?
yes
update
system info
update
calculations
yes
run falling
conductor
trip/clear
return
Figure 14.9 Primary Decision Tree Used to Perform Logic in the Run Method
BOOT_DLY
Reset Derivative and
Enable
Sequence Calculations
NOTE: In Figure 14.10, BOOT_DLY
is the time delay set by the advanced
setting BootDelay and TRIP_DO is the
time delay set by the advanced
EN dV PU setting TripSignalAssertionPeriod.
dt
EN PU
V 0MAG
S
EN PU P
V 2MAG Q TripControlPoint
TRIP_DO R
EN PU
V 0ANG
EN PU
V 2ANG
+
≥
AffirmativeDetectionCount -
ExcludeSwitch
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
ä The zones overlap on the recloser PMU2, however only Zone 2 should consider this
switch a controllable asset. Additionally, this means that these zones will each boot-
strap a unique switch to represent the recloser, but they will share the same 52A
contact status and the same trip control point. Zone 1 should bootstrap this switch as
NON_OPERATIONAL and Zone 2 should consider it of type BREAKER_SWITCH.
ä Due to the overlap of zones at PMU2 and the downstream connection that is observed
here, the switch bootstrapped to Zone 2 representing PMU2 will "inherit" Zone 1 as
the parent zone. This is not beneficial in this particular example, but if the recloser
at PMU2 were instead a simple line monitor without any ability to clear faults on
demand, this would provide the ability for PMU1 to clear faults detected anywhere
in Zone 2.
ä Both of the line monitors (PMU3 and PMU4) are only capable of monitoring system
conditions, neither one is capable of performing trip operations on command. How-
ever, since both of these monitors are downstream of the recloser at PMU2, they will
rely upon that recloser to clear any faults they detect.
ä Even though, as mentioned in the previous point, both PMU3 and PMU4 will rely
upon PMU2 to clear faults they detect, they do not reference Zone 1 as their parent
zone. This is because Zone 1 does not overlap with either of these monitors. If a
fault is detected by either of these monitors, the zone will record the fault, and thus
a trip control will be sent to the recloser at PMU2, which will inevitably clear the
fault for these monitors.
Assumptions
This example assumes that there are a number of IEEE C37.118 clients and IEC 61850
GOOSE transmit tags configured in the RTAC to allow for synchrophasor measurements
as the sensory inputs and GOOSE binary controls. These assumed devices are listed below
with their respective tags.
ä C37.118 Synchrophasor Clients
â PMU1
ã VAPM (Phase A Voltage at PMU1)
â PMU3
ã VAPM (Phase A Voltage at PMU3)
ã VBPM (Phase B Voltage at PMU3)
ã VCPM (Phase C Voltage at PMU3)
ã IAPM (Phase A Current at PMU3)
ã IBPM (Phase B Current at PMU3)
ã ICPM (Phase C Current at PMU3)
ã FAULT (IED FAULT Status from PMU3)
ã IEDHEALTHY (IED Health Status from PMU3)
ã PINGPONG (Incoming Round-Trip Time Status from PMU3)
â PMU4
ã VAPM (Phase A Voltage at PMU4)
ã VBPM (Phase B Voltage at PMU4)
ã VCPM (Phase C Voltage at PMU4)
ã IAPM (Phase A Current at PMU4)
ã IBPM (Phase B Current at PMU4)
ã ICPM (Phase C Current at PMU4)
ã FAULT (IED FAULT Status from PMU4)
ã IEDHEALTHY (IED Health Status from PMU4)
ã PINGPONG (Incoming Round-Trip Time Status from PMU4)
Additionally, in an effort to coordinate with traditional protection and avoid tripping for
standard phase or ground overcurrent at PMU1 and PMU2, the pickup settings for these
thresholds are specified as follows for the falling conductor detection instance.
ä Phase Overcurrent: 360 (units as specified by the current tag; i.e., PMU1.IAPM)
ä Ground Overcurrent: 180 (units as specified by the current tag; i.e., PMU1.IAPM)
Solution
To define and operate the logic required to operate falling conductor protection, the user
can create a program as shown in Code Snippet 14.1:
AdvSettings.BootDelay := T#5S;
PhaseCVoltage := PMU2_PMU2.VCPM,
ZoneStatus := ZoneStatuses[2] );
LD_VB1GGIO3_Ind020 := FCPInstance.RoundTripTimeOutput;
FaultLocation
Introduction
This library provides methods to determine fault conditions and distances using COM-
TRADE fault recordings.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myFaultLocationObject.value;
// As is this
pt_myFaultLocationObject := ADR(myFaultLocationObject);
ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_FaultType
This enumeration defines the fault type.
Enumeration Description
NoFaultFound No fault found.
AG A-phase to ground fault
BG B-phase to ground fault
CG C-phase to ground fault
AB A-phase to B-phase fault
BC B-phase to C-phase fault
CA C-phase to A-phase fault
ABG A-phase and B-phase to ground fault
BCG B-phase and C-phase to ground fault
CAG C-phase and A-phase to ground fault
ABC Three-phase fault
enum_PhaseRotation
This enumeration defines the phase rotation.
Enumeration Description
ABC ABC phase rotation.
ACB ACB phase rotation.
enum_WiringConfig
This enumeration defines the potential transformer wiring configuration.
Enumeration Description
WYE Wye-connected wiring configuration.
DELTA Delta-connected wiring configuration.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_FaultDetails
Classes
class_SingleEndedFault (Class)
This class calculates the fault distance, fault time, and fault type of a single-ended fault
recording by using fault data from a COMTRADE event file. Single-ended fault record-
ings include fault data that a device records on only one end of the transmission line. This
class only supports COMTRADE event recordings from SEL-2245-42 AC Protection Mod-
ules with 24 kHz sampling rates. For best results, use COMTRADE event recordings that
have at least 30 cycles of pre-fault and 30 cycles of post-fault data. This class outputs the
distance-to-fault when the inputs meet the following criteria:
ä A valid COMTRADE event file matching DeviceID with a trigger time equivalent
to TriggerTime ±TimeVar exists in the RTAC’s database prior to the expiration of
waitTime.
ä The COMTRADE event file contains the specified input channel names.
ä No single pole open condition has been identified prior to the fault identification.
(class_SingleEndedFault identifies a single pole open condition when any measured
phase current input is less than 5 percent of NominalCurrentInput.)
ä The class_SingleEndedFault identifies a fault for a duration greater than one cycle.
ä The size of the COMTRADE event data file is less than or equal to 10 MB.
This class calculates the distance-to-fault in per unit of the positive-sequence line impedance.
The LineLength setting is used to determine the units that the RTAC reports for the distance-
to-fault.
If the distance-to-fault calculation result is greater than LineLength, or an unbalanced line
condition exists before the fault, the class reports the FaultDistance quality as question-
able. If the distance-to-fault cannot be determined, the RTAC reports the fault location as
–999999 and sets the quality to invalid.
This class provides fault location details for the specified COMTRADE events using the
LocateFault() and Run() methods.
Outputs
Name IEC 61131 Type Description
FaultAnalysisInProgress BOOL TRUE while the Run() method is collecting
an event and preforming a distance-to-fault
calculation
FaultAnalysisDone BOOL Asserts TRUE for one processing interval
upon completing the fault location calculation
FaultAnalysisInfo struct_FaultDetails Fault location details including the distance-
to-fault, fault detection time, fault location
quality, and phases involved in fault
Error BOOL TRUE if any error occurs
ErrorDescription STRING(255) A description of the last error encountered
LocateFault (Method)
Call this method to calculate fault distance using the COMTRADE file that matches Devi-
ceID and TriggerTime ±TimeVar. This method passes its inputs to Run(), which calculates
fault location, fault type, and fault time for the transmission line that the input channel
names and line parameters define.
Inputs
Name IEC 61131 Type Description
DeviceID STRING(255) Name of the device that generates the COM-
TRADE event file
TriggerTime dateTime_t The trigger time of the event. If an exact
match does not exist, this method reads an
event within TimeVar milliseconds of Trig-
gerTime.
VaChannel STRING(255) Name of the A-phase voltage or A-B phase-
to-phase voltage channel in the COM-
TRADE file that is used for calculating the
fault location
VbChannel STRING(255) Name of the B-phase voltage or B-C phase-
to-phase voltage channel in the COM-
TRADE file that is used for calculating the
fault location
Processing
ä LocateFault() enforces input parameter range requirements and configures the COM-
TRADE event parameters to be read from the RTAC database. For values violating
the allowed range, LocateFault() sets Error to TRUE and updates ErrorDescription
for the input violation.
ä If no errors exist, LocateFault() sets FaultAnalysisInProgress to TRUE and passes
parameters to Run(), which reads the event from database and calculates a location
to the fault for the given input parameters.
Run (Method)
Call this method on every scan. It supervises the asynchronous operation required to read
an event file and calculate a fault location from a COMTRADE file.
Processing
ä When LocateFault() is called, Run() performs the following:
â Resets ErrorDescription and FaultDistance.
â Begins event read for the event containing DeviceID and TriggerTime.
ä If any errors occur during an event read from the database, Error is set to TRUE,
FaultAnalysisInProgress is set to FALSE, and ErrorDescription is populated with an
error message from class_ComtradeParser.
ä After the event is successfully read, Run() checks that the channel name inputs exist
in the event. Run() also validates that there are adequate event data to calculate a
fault location. If channel names are not found or there are not adequate event data,
Run() preforms the following:
â Sets FaultAnalysisInProgress to FALSE.
â Sets Error to TRUE and updates ErrorDescription.
ä When FaultAnalysisDone asserts, Run() preforms the following:
â Populates FaultAnalysisInfo with the fault location details.
â Sets FaultAnalysisInProgress and FaultAnalysisDone to FALSE after one pro-
cessing interval.
ä If any errors occur, Run() sets Error to TRUE, FaultAnalysisInProgress to FALSE,
and populates ErrorDescription appropriately.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes the following:
ä An SEL-2245-42 module is contained in the EtherCAT I/O Network and is named
"SEL_PRCTPT".
ä For best results, the SEL_PRCTPT recordings contain 30 cycles of pre-fault and 30
cycles of post-fault data.
ä A transmission line study has been conducted for a 100-mile line. The secondary
positive-sequence line impedance is 7.80∠84 and the secondary zero-sequence line
impedance is 24.80∠81.50.
ä The SEL_PRCTPT event trigger tag is triggered through external fault detection
logic that is not provided by this program.
Solution
Perform a call to class_SingleEndedFault each time an event trigger is detected. After the
class completes the fault analysis, write the fault type and distance-to-fault tags into logic
engine arrays.
Assumptions
This example assumes the following:
ä A Recording Group named DFR is added to the program.
ä DFR contains three SEL-2245-42 modules with the bus voltage being recorded on
Module 1, Line 1 current signals on Module 2, and Line 2 current signals on Module
3.
ä DFR contains analog channel names of VA1, VB1, VC1, IA2, IB2, IC2, IA3, IB3,
IC3.
ä DFR’s event trigger is triggered through external fault detection logic that is not
provided by this program.
ä Global variable boolean tags are programmed to indicate the faulted transmission
line. A Line 1 fault is indicated by g_Line1Fault, and a Line 2 fault is indicated by
g_Line2Fault.
ä A transmission line study is conducted for a 100-mile line with the following param-
eters:
â The Line 1 secondary positive-sequence line impedance is 7.40∠86.7 and the
secondary zero-sequence line impedance is 25.00∠82.50.
â The Line 2 secondary positive-sequence line impedance is 8.2∠84.7 and the
secondary zero-sequence line impedance is 24.00∠83.00.
Solution
Preform a call to class_SingleEndedFault each time the DFR event trigger is detected. Af-
ter the class completes its analysis, write the fault type and distance-to-fault tags to the
associated faulted line tags.
FileIO
Introduction
The FileIO library includes the internal RTAC sel_file and sel_ftp_client libraries. This
library provides function blocks that simplify asynchronous file management for basic file
read and write operations. It also provides access to the underlying firmware interface
libraries.
Because the classes this library provides manage asynchronous file operations, the user
must call the Run() method of instantiated classes on every scan to ensure that all queued
work is correctly performed and monitored. Each class provides various methods to initiate
new read or write operations, collect data, or cause other changes in state.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myFileIOObject.value;
// As is this
pt_myFileIOObject := ADR(myFileIOObject);
ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
ä All file read operations are done completely into RAM. This means that the reading
of large files that exceed the available RAM will not work as expected.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_FtpSendSchedule
Enumeration Description
ON_CLOSE When the previous log file is closed, as part of starting a new log file with the
StartNewLog() method, synchronize the closed log to the FTP server.
ON_UPDATE Send active log file each time an additional log is added.
sel_file.Enum_protocol_id
This enumeration is defined in the underlying sel_file library. It lists the protocols that can
create an event.
Enumeration Value
NO_PROTOCOL_SPECIFIED 0
SEL_CLIENT 1
SEL_SERVER 2
MODBUS_CLIENT 3
MODBUS_SERVER 4
DNP_CLIENT 5
DNP_SERVER 6
SEL_MIRRORED_BITS 7
C37118_CLIENT 8
GOOSE_RX 9
ACCESS_POINT_CLIENT 10
ACCESS_POINT_SERVER 11
GOOSE_TX 12
ETHERCAT 13
DNP_SERVER_FAILOVER 14
IEC61850_CLIENT 15
IEC61850_SERVER 16
NGVL 17
LG8979_CLIENT 18
LG8979_SERVER 19
IEC60870_CLIENT 20
IEC60870_SERVER 21
C37118_SERVER 22
SES92_SERVER 23
PGE2179_CLIENT 24
FLEX_PARSE_CLIENT 25
sel_file.Enum_event_type
This enumeration is defined in the underlying sel_file library. This enumeration defines the
types of events the database can store. It is part of the event handle and should be used to
help decide which sel_file.Enum_event_data to use when opening an event.
Enumeration Description
NO_EVENT_TYPE There is no event type associated with this file.
CEV_FILE A plaintext file containing event data.
COMTRADE A zipped folder containing the event data as COMTRADE files.
sel_file.Enum_event_data
This enumeration is defined in the underlying sel_file library. It defines how that library
attempts to open events.
Enumeration Description
RAW_DATA Return the data exactly as it is stored in the database.
CFG_FILE Treat the data as an archive and extract the first file with a .cfg extension.
DAT_FILE Treat the data as an archive and extract the first file with a .dat extension.
HDR_FILE Treat the data as an archive and extract the first file with a .hdr extension.
INF_FILE Treat the data as an archive and extract the first file with a .inf extension.
sel_file.Enum_sel_file_errors
This enumeration is defined in the underlying sel_file library. It defines the status of file and
SOE requests. After a call to a function, variables of this type will display IN_PROGRESS
for a time, after which they will change to some other value. NO_ERROR implies that
the task completed successfully, and SYSTEM_BUSY means that the driver already has
too many jobs queued that it must complete before accepting any more jobs. In this case,
a subsequent request might succeed if one of the queued jobs has been completed. Any
other result should be descriptive of the error encountered.
Enumeration Description
NO_ERROR The request completed successfully.
FILE_NOT_FOUND The requested file was not found in the file system.
INVALID_FILE_NAME The file name provided was invalid.
INVALID_FH The file handle provided was not for an open file.
INVALID_FILTER The filter provided was invalid.
INVALID_TIMESTAMP The time stamp provided was invalid.
FS_OUT_OF_SPACE The file system did not have enough space to perform the action.
DIR_LIST_NOT_INIT The directory iterator has not be initialized.
SYSTEM_BUSY The system is too busy to process the request.
TOO_MANY_TASKS The system has received requests from more than two tasks.
OPERATION_FAILED There was a system call failure while processing the request.
IN_PROGRESS The system is processing the request.
sel_ftp_client.Enum_sel_ftp_client_errors
This enumeration is defined in the underlying sel_ftp_client library. It defines the status of
FTP requests. After a call to a function, variables of this type will display IN_PROGRESS
for a time, after which they will change to some other value. NO_ERROR implies that
the task completed successfully, and SYSTEM_BUSY means that the driver already has
too many jobs queued that it must complete before accepting any more jobs. In this case,
a subsequent request might succeed if one of the queued jobs has been completed. Any
other result should be descriptive of the error encountered.
Enumeration Description
NO_ERROR The request successfully triggered an FTP attempt.
INIT_FAILED The FTP process is not responding.
INVALID_OPERATION There was a system call failure while processing the request.
INVALID_IP The IP address provided was not in the form XXX.XXX.XXX.XXX,
where XXX is an integer that is ≤ 255.
INVALID_USR_NAME The username provided contained invalid characters.
INVALID_PASSWORD The password provided contained invalid characters.
INVALID_FILE_NAME The file name provided contained invalid characters.
INVALID_MAX_TIME The time provided was less than or equal to 0.
FS_OUT_OF_SPACE The file system did not have enough space to perform the action.
SYSTEM_BUSY The system is too busy to process the request.
OPERATION_TIMEOUT The FTP attempt took longer than the provided time-out.
IN_PROGRESS The system is processing the request.
enum_FileType
Enumeration Description
ASCII COMTRADE data file is represented by ASCII data.
BINARY COMTRADE data file is represented by 16 bit binary data.
BINARY32 COMTRADE data file is represented by 32 bit binary data.
FLOAT32 COMTRADE data file is represented by 32 bit floating point data.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_EventDetails
Name IEC 61131 Type Description
Handle Struct_event_handle The details required to access this event via the
database.
Device STRING(32) The name of the device the event was collected
from.
TimeStamp DT The time stamp of the event as seconds since epoch.
TimeMilliseconds UINT The millisecond at which the event occurred.
FileSize DINT The size of the event in the database in bytes.
sel_file.Struct_event_handle
This struct is defined in the underlying sel_file library. This struct contains all information
required to uniquely identify an event in the database.
sel_file.Struct_soe_content
This struct is defined in the underlying sel_file library. This struct contains all value fields
returned by an SOE query.
sel_file.Struct_soe_content_id
This struct is defined in the underlying sel_file library. This struct contains all value fields
returned by an SOE query.
sel_file.Struct_soe_filter
This struct is defined in the underlying sel_file library. This struct contains all filters pos-
sible to apply to an SOE query. If left empty, no filter will be applied on that field.
The filter string must contain only letters (case-sensitive); numbers; the symbols _, -, and
“ ” (space); and the wildcard characters * and ?. The character * acts as a multicharacter
wildcard and the character ? acts as a single character wildcard when inside any string.
struct_ComtradeInfo
Name IEC 61131 Type Description
StationName STRING(64) Substation name or location
RecordingDeviceId STRING(64) Recording device name or identification
RevisionYear STRING(4) Standard revision year
TotalChannelCount UDINT Total number of channels
AnalogChannelCount UDINT Number of analog channels
DigitalChannelCount UDINT Number of digital channels
NominalLineFreq REAL Nominal line frequency Hz
NumOfSampleRates UINT Number of sample rates
NumSamples UDINT Number of samples in the event
StartTime datetime_t Event record start time
TriggerTime datetime_t Event record trigger time
FileType STRING(8) Data file type
TimeMultFactor REAL Multiplication factor for time differential field in
data file
TimeCode STRING(6) Time code units defined in IEEE Std C37.232-
2007
LocalCode STRING(6) Time difference between local time and UTC
with time code units defined in IEEE Std
C37.232-2007
TimeQualityCode STRING(1) IEEE Std C37.118 time quality indicator code
LeapSecondCode UINT Leap second indicator code
struct_AnalogChannelInfo
Name IEC 61131 Type Description
AnalogChannelIndex UDINT Analog channel index number
ChannelId STRING(128) Alphanumeric channel name
PhaseId STRING(2) Channel phase identification
CircuitComponent STRING(64) Circuit component
ChannelUnits STRING(32) Alphanumeric channel units
ChannelMultipler REAL Channel multiplier
ChannelOffset REAL Channel offset
Skew REAL Time skew between channels
MinimumValue REAL Data range minimum value
MaximumValue REAL Data range maximum value
PrimaryRatio REAL PT/CT primary ratio
SecondaryRatio REAL PT/CT secondary ratio
ChannelScaling STRING(1) Primary or secondary scaling identifier
struct_DigitalChannnelInfo
Name IEC 61131 Type Description
DigitalChannelIndex UDINT Digital channel index number
ChannelId STRING(128) Alphanumeric channel name
PhaseId STRING(2) Channel phase identification
CircuitComponent STRING(64) Circuit component
NormalChannelState BOOL Normal state of the channel
struct_SamplingInfo
Name IEC 61131 Type Description
SampleRate REAL The sample rate in Hz
EndSample UDINT The last sample number at the sample rate
Functions
This library provides the following functions, which allow single-operation asynchronous
actions. Each call has a status argument that must persist across multiple scans. Calling any
function does not complete the requested work, but rather queues the work to be performed
over multiple scans. This means you should only call a given function once per desired op-
eration. The system updates the status variable automatically when the operation completes
in either success or failure. Avoid reusing pointers or variables passed as VAR_IN_OUT
until the status variable used has changed from the value of IN_PROGRESS.
fun_FtpDownload
Use this function to download files to the local, sequestered file system from an FTP server.
Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
localPath STRING(255) The local path and file name to which you are writ-
ing. It must begin with “/” and contain the full file path.
It may contain all printable ASCII characters between
16#20(Space) and 16#7E(~) except for ", ', :, <, %, >, ?, \,
and |. It cannot contain any file path manipulation variables
(//, /./, /../).
remotePath STRING(255) The complete path and file name of the file to download
from the FTP server. It must contain only printable charac-
ters (ASCII values 0x32 to 0x7E inclusive), excluding sin-
gle and double quotation characters.
username STRING(32) The username to be used. This must only contain alphanu-
meric characters and “_”.
password STRING(32) The password for use on the FTP server. This may contain
any printable ASCII characters excluding the quote charac-
ters.
timeout UDINT The number of seconds for the FTP attempt to run before it
is canceled. This value must be greater than 0.
Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_ftp_client_errors The active status of this FTP event.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the FTP download request for processing.
ä Validates that the time-out exceeds zero seconds.
ä Validates that all string characters meet the prescribed requirements.
ä Validates that at least 250 MB of space are available in the file system for the down-
load contents.
ä Attempts to FTP the file onto the RTAC as an asynchronous event.
ä A status of NO_ERROR implies that the FTP command was successfully issued, the
FTP service completed, and the service returned no error code.
fun_FtpEventUpload
Use this function to upload event files from the database to an FTP server.
Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
localEvent Struct_event_handle The event file to upload.
remotePath STRING(255) The complete path and file name of the file to save on
the FTP server. It must contain only printable characters
(ASCII values 0x32 to 0x7E inclusive), excluding single
and double quotation characters.
username STRING(32) The username to be used. This must only contain alphanu-
meric characters and “_”.
password STRING(32) The password for use on the FTP server. This may contain
any printable ASCII characters excluding the quote char-
acters.
timeout UDINT The number of seconds for the FTP attempt to run before
it is canceled. This value must be greater than 0.
Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_ftp_client_errors The active status of this FTP event.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the FTP upload request for processing.
ä Attempts to FTP the file from the RTAC as an asynchronous event.
ä A status of NO_ERROR implies that the FTP command was successfully issued, the
FTP service completed, and the service returned no error code.
fun_FtpUpload
Use this function to upload individual files from the local, sequestered file system to an
FTP server.
Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
localPath STRING(255) The complete local path and file name to upload. It must
begin with “/” and contain the full file path. It may contain
all printable ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot
contain any file path manipulation variables (//, /./, /../).
remotePath STRING(255) The complete path and file name of the file to write on
the FTP server. It must contain only printable characters
(ASCII values 0x32 to 0x7E inclusive), excluding single
and double quotation characters.
username STRING(32) The username to be used. This must only contain alphanu-
meric characters and “_”.
password STRING(32) The password for use on the FTP server. This may contain
any printable ASCII characters excluding the quote charac-
ters.
timeout UDINT The number of seconds for the FTP attempt to run before it
is canceled. This value must be greater than 0.
Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_ftp_client_errors The active status of this FTP event.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the FTP upload request for processing.
ä Attempts to FTP the file from the RTAC as an asynchronous event.
ä A status of NO_ERROR implies that the FTP command was successfully issued, the
FTP service completed, and the service returned no error code.
fun_DeleteFile
Use this function to delete any file or empty folder from the sequestered file system.
Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path and file name of the file to delete. It may con-
tain all printable ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot contain
any file path manipulation variables (//, /./, /../).
Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_file_errors The variable where the state of the asynchronous task that is
deleting the file will be reported.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the file deletion request for processing.
ä If status later changes to NO_ERROR, the system successfully found and deleted the
file.
ä If status later changes to OPERATION_FAILED, the system failed to either find or
delete the file.
ä If status later changes to anything else, the system stopped the request before the
deletion command was issued.
fun_FileSize
Use this function to request the size of any file in the sequestered file system. If the size of
the file provided exceeds UDINT max (4,294,967,295) bytes, then the value that is returned
will roll over and equal the file size modulo 4,294,967,296.
Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path and file name for the size calculations. It may
contain all printable ASCII characters between 16#20(Space)
and 16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot
contain any file path manipulation variables (//, /./, /../).
Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_file_errors The variable where the state of the asynchronous task that
is obtaining the file size will be reported.
sizeInBytes UDINT After completion, this variable contains the size of the
file in bytes.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the file size request for processing.
ä If status later changes to NO_ERROR, sizeInBytes contains the file size.
ä If status later changes to OPERATION_FAILED, then the system failed to find the
file.
ä If status later changes to anything else, sizeInBytes is undefined.
fun_FilesystemFreeSpace
Use this function to validate how much usable space remains in the file system. FileIO
will not use all the space on the file system, and the value returned by this function reflects
that. When the value this function returns reaches zero, additional writes to the file system
through FileIO will fail.
Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_file_errors The variable where the state of the asynchronous task
that is obtaining the file system free space will be re-
ported.
spaceAvailable ULINT After completion, this variable contains the space left
in the file system that the FileIO library can use, in
bytes.
Processing
ä Sets status to IN_PROGRESS.
fun_SoeAscending
Use this function to request a limited number of SOEs from the database, beginning with
a specified time and moving toward the future.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content The array provided must have at least maxSoe-
Count members, or memory corruption will occur.
startTime DT The earliest time to include in the results. This
value must be between the years 2000 and 2037,
or the call will result in an error.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the num-
ber of Struct_soe_content objects that can fit in the
memory space pt_soeBuffer points to, or memory
corruption will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
fun_SoeDescending
Use this function to request a limited number of SOEs from the database, beginning with
a specified time and moving toward the past.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content The array provided must have at least maxSoe-
Count members, or memory corruption will occur.
startTime DT The latest time to include in the results. This value
must be between the years 2000 and 2037, or the
call will result in an error.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the num-
ber of Struct_soe_content objects that can fit in the
memory space pt_soeBuffer points to, or memory
corruption will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
fun_SoeWindow
Use this function to request a limited number of SOEs from the database, beginning with
a specified time and moving toward the specified, future end time.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content The array provided must have at least maxSoe-
Count members, or memory corruption will occur.
startTime DT The earliest time to include in the results. This
value must be between the years 2000 and 2037,
or the call will result in an error.
endTime DT The latest time to include in the results. This value
must be between the years 2000 and 2037, or the
call will result in an error.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the num-
ber of Struct_soe_content objects that can fit in the
memory space pt_soeBuffer points to, or memory
corruption will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
fun_LocalSoeGetID
Use this function to request the data of a single SOE after a provided time stamp. If the
system finds no SOE after the time stamp, it provides the nearest SOE before the time
stamp. If the system finds no SOEs, then status reports an error. Any data returned are for
an SOE the local RTAC generated.
Inputs
Name IEC 61131 Type Description
soeTime DT The time near which to search for an SOE. This value must be
between the years 2000 and 2037, or the call will result in an
error.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable where the state of the asynchronous task that
is obtaining the SOE id will be reported.
soeData Struct_soe_content_id The location that will be populated with the information de-
scribing the returned SOE.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeData contains the pertinent information
for one local SOE.
ä If status later changes to anything else, the contents of soeData are undefined.
fun_LocalSoeAscending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the future. The order of the returned SOEs is the time
of their creation on the RTAC, not the time of the actual event. The local RTAC generated
all returned SOEs.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE
Struct_soe_content_id data. The array provided must have at least
maxSoeCount members, or memory corruption
will occur.
startID STRING(80) The unique identifier of a local SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_-
soeBuffer. This number must exceed zero to ob-
tain a non-error result and it must not exceed the
number of Struct_soe_content_id objects that
can fit in the memory space pt_soeBuffer points
to, or memory corruption will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE after startID. If startID represent an invalid
SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
fun_LocalSoeDescending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the past. The order of the returned SOEs is the time of
their creation on the RTAC, not the time of the actual event. The local RTAC generated all
returned SOEs.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE
Struct_soe_content_id data. The array provided must have at least
maxSoeCount members, or memory corruption
will occur.
startID STRING(80) The unique identifier of a local SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_-
soeBuffer. This number must exceed zero to ob-
tain a non-error result and it must not exceed the
number of Struct_soe_content_id objects that
can fit in the memory space pt_soeBuffer points
to, or memory corruption will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE before startID. If startID represent an
invalid SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
fun_RemoteSoeGetID
Use this function to request the data of a single SOE after a provided time stamp. If the
system finds no SOE after the time stamp, it provides the nearest SOE before the time
stamp. If the system finds no SOEs, then status reports an error. Any data returned are an
SOE a device other than the local RTAC generated.
Inputs
Name IEC 61131 Type Description
soeTime DT The time near which to search for an SOE. This value must be
between the years 2000 and 2037, or the call will result in an
error.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable where the state of the asynchronous task that
is obtaining the SOE id will be reported.
soeData Struct_soe_content_id The location that will be populated with the information de-
scribing the returned SOE.
Processing
ä Sets status to IN_PROGRESS.
fun_RemoteSoeAscending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the future. The order of the returned SOEs is the time of
their creation on the RTAC, not the time of the actual event. A device other than the local
RTAC generated all SOEs returned.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content_- The array provided must have at least maxSoeCount
id members, or memory corruption will occur.
startID STRING(80) The unique identifier of a remote SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the number of
Struct_soe_content_id objects that can fit in the mem-
ory space pt_soeBuffer points to, or memory corrup-
tion will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE after startID. If startID represent an invalid
SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
fun_RemoteSoeDescending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the past. The order of the returned SOEs is the time of
their creation on the RTAC, not the time of the actual event. A device other than the local
RTAC generated all SOEs returned.
Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content_- The array provided must have at least maxSoeCount
id members, or memory corruption will occur.
startID STRING(80) The unique identifier of a remote SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the number of
Struct_soe_content_id objects that can fit in the mem-
ory space pt_soeBuffer points to, or memory corrup-
tion will occur.
Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.
Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE after startID. If startID represent an invalid
SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.
Classes
This library provides the following classes as extensions of the IEC 61131 function block.
class_DirectoryListing (Class)
This class calls the sel_file.sel_open_dir() function after a new listing is requested
by the call to CreateNewList(). On the task where this class is instantiated, Run() must
be called once on every scan to handle all of the asynchronous file system interactions.
While there are still items to list, Run() will call sel_file.sel_read_dir() once each
scan until the complete directory listing is built.
Outputs
Name IEC 61131 Type Description
InProgress BOOL Stays TRUE while the Run() method constructs the list-
ing. The class ignores any calls to CreateNewList()
while this output is TRUE.
Error BOOL TRUE if the directory listing could not be created.
ErrorDesc STRING(255) The last error encountered is described here.
NewListReady BOOL Once a list has been built, this output is set to TRUE.
CreateNewList (Method)
This is one of the methods that can be called each time a new directory listing is required.
If no filter is given, it will provide a complete listing of the directory.
Inputs
Name IEC 61131 Type Description
directoryName STRING(255) The directory path to get file list from. Path separators
should be the “/” character.
filter STRING(255) If not blank, only those files that contain this substring
will be appended to the list.
Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and destroys any internal lists.
ä Initiates the enumeration of the directory, carried out by the Run() method.
CreateNewerThanList (Method)
This is one of the methods that can be called each time a new directory listing is required.
This method causes a list to be generated that contains all files with a date code equal to or
newer than the value passed in.
Inputs
Name IEC 61131 Type Description
directoryName STRING(255) The directory path to get file list from. Path separators
should be the “/” character.
filter STRING(255) If not blank, only those files that contain this substring
will be appended to the list.
mtimeSec DT Last UTC modification time (DT#yyyy-mm-dd-
00:00:00)
Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and deletes any internal lists.
ä Initiates the enumeration of the directory, carried out by the Run() method.
GetList (Method)
The call to this method must occur after the NewListReady output is TRUE to obtain the
populated class_SELStringList. There can only be one call to this method per created list.
Inputs/Outputs
Name IEC 61131 Type Description
list SELString.class_SELStringList The class_SelStringList to write the directory list-
ing to. See the SELString library for more informa-
tion about the type class_SELStringList.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the class_SELStringList provided was populated success-
fully.
Processing
ä Returns FALSE if NewListReady is not TRUE.
ä Populates list with the prepared list.
ä Sets the NewListReady class output to FALSE.
ä Destroys the internal list.
Run (Method)
Call this method on every scan. It supervises the asynchronous directory listing.
Processing
ä If a directory listing has been initiated:
â Ensure that the directory is opened, using the sel_file.sel_open_dir()
function.
â Repeatedly call the sel_file.sel_read_dir() and append a class_SEL-
String to list for each file name containing the filter substring, until no more
file names are returned.
ä Once the directory listing is complete, it closes the operation by setting NewListReady
to TRUE and calling sel_file.sel_close_dir().
ä If any error occurs, Error is set to TRUE and ErrorDesc is populated appropriately.
class_EventReportListing (Class)
This class has been completely removed from the library. If it was included in projects,
these projects will now provide compile-time errors. If you want event access, the class_-
EventListing provides access to those files along with non-obfuscated file names, the ability
to filter queries based on several criteria, and the ability to properly open COMTRADE file
collections to view individual files.
Please note that the class_EventListing class does have one limitation that this class did not.
All class_EventListing objects on a single RTAC task (e.g., Main or Automation) share an
internal iterator. It is best practice to only have one class_EventListing per task.
class_EventListing (Class)
This class calls sel_file.sel_begin_event_iterator_filtered() after a new list-
ing request activated by a call to CreateNewList() or CreateNewFilteredList(). On
the task in which this class is instantiated, Run() must be called once on every scan to han-
dle all of the asynchronous file system interactions. While there are still items to list, Run()
calls sel_file.sel_next_event() once each scan until the complete directory listing
is built.
All class_EventListing objects on a single RTAC task (e.g., Main or Automation) share an
internal iterator. It is best practice to only have one class_EventListing per task.
Outputs
Name IEC 61131 Type Description
InProgress BOOL Stays TRUE while the Run() method constructs the list-
ing. The class ignores any calls to CreateNewList()
while this output is TRUE.
Error BOOL TRUE if the directory listing could not be created.
ErrorDesc STRING(255) The last error encountered is described here.
NewListReady BOOL Once a list has been built, this output is set to TRUE.
CreateNewList (Method)
This method may be called each time a new listing of event reports is required. It filters by
device name only.
Inputs/Outputs
Name IEC 61131 Type Description
deviceName STRING(32) If not blank, only events from this device will be listed.
Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and destroys any internal lists.
ä Initiates the enumeration of the directory, carried out by the Run() method.
CreateNewFilteredList (Method)
This method may be called each time a new listing of event reports is required. It filters by
device name, time of creation, the reporting protocol, and the event type.
Inputs/Outputs
Name IEC 61131 Type Description
deviceName STRING(32) If not blank, only events from this device will be listed.
Inputs
Name IEC 61131 Type Description
startTime DT The earliest time stamp of a returned event as seconds since
epoch.
endTime DT The latest time stamp of a returned event as seconds since
epoch.
protocol Enum_protocol_id The protocol that collected the events.
eventType Enum_event_type The type of the events to be presented.
Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and destroys any internal lists.
ä Initiates the enumeration of the events, carried out by the Run() method.
ä Values of NO_PROTOCOL_SPECIFIED, NO_EVENT_TYPE, or zero for start-
Time and endTime result in the associated filter not being used.
GetList (Method)
The call to this method must occur after the NewListReady output is TRUE to obtain the
vector of event handles. There can only be one call to this method per created list.
Inputs/Outputs
Name IEC 61131 Type Description
list DynamicVectors.class_BaseVector The vector to write the directory listing to.
This vector must have been initialized with an
element size SIZEOF(struct_EventDetails).
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the class_BaseVector provided was populated success-
fully.
Processing
ä Returns FALSE if NewListReady is not TRUE.
ä Populates list with the prepared list.
ä Sets the NewListReady class output to FALSE.
ä Destroys the internal list.
Run (Method)
Call this method on every scan. It supervises the asynchronous event report listing.
Processing
ä If an event listing has been initiated:
â Ensure that the listing is opened by using sel_file.sel_begin_event_-
iterator().
â Repeatedly call sel_file.sel_next_event() and append a struct_Event-
Details to list for each of the returned files that were issued by deviceName, the
system returns no more files.
ä Once the directory listing is complete, it closes the operation by setting NewListReady
to TRUE.
ä If any error occurs, Error is set to TRUE and ErrorDesc is populated appropriately.
class_FileWriter (Class)
This class provides the ability to write files to the sequestered RTAC file system. This class
is instantiated with a specific file name. The return value of each method is based on the
success or failure of queuing the requested action. The final success or failure of each action
is not determined until processing completes after multiple calls to the Run() method,
which you must call every scan to perform whatever file-handling actions are buffered in
its internal queue.
The g_p_FileIo_MaxBufferSize parameter, detailed in Global Parameters on page 43.2,
dictates the maximum amount of data that can be buffered at one time before writing to the
specified file.
Initialization Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path of the file opened in append mode. The character
“/” delimits the folder path. This path must end with the full
file name, including extension. It may contain all printable
ASCII characters between 16#20(Space) and 16#7E(~) except
for ", ', :, <, %, >, ?, \, and |. It cannot contain any file path
manipulation variables (//, /./, /../). If the file does not exist, it
will be created.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Outputs
Name IEC 61131 Type Description
Error BOOL TRUE if the function block cannot write the contents of its
buffer to file.
ErrorDesc STRING(255) The last error encountered will be described here.
FileRename BOOL After the Filename property is set, this pin will remain
TRUE until all pending writes to the previous file name
have been completed.
AppendBytes (Method)
Call this method whenever bytes are to be appended to the write buffer. Every subsequent
call of the Run() method will write as many bytes as possible until nothing remains in the
write buffer.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the item to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, starting with pt_data.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE for successful addition of the data to the output buffer.
Processing
ä Check that numBytes exceeds 0.
ä Check that the memory region specified has read access.
ä If both previous statements are true, copy the contents of the specified region into
the output buffer.
ä If the copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.
AppendSELString (Method)
Call this method to append the content of a class_SELString to the write buffer.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.
Processing
ä Copy the content of the supplied string to the output buffer.
ä If the copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.
AppendString (Method)
Call this method to append the content of a string to the write buffer.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to append.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.
Processing
ä Copy the content of the supplied string to the output buffer.
ä If copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.
AppendVector (Method)
Call this method to append the content of a vector to the write buffer.
Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the vector was successfully added to the output buffer.
Processing
ä Check that vector passed in is valid and has contents to copy.
ä Copy the content of the dynamic vector into the output buffer.
ä If the copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.
Run (Method)
Call this method on every scan to supervise the asynchronous writing of the internal buffer
to the specified file.
Processing
ä If the file is not open, this method opens it in append mode and stores the file handle
internally.
ä If the file is open and there are data in the internal buffer, this method writes to the
opened file.
ä Monitors the asynchronous write process, clears the buffer of written data, and sub-
tracts number of bytes written from BytesLeft.
ä If any error occurs, this method sets Error to TRUE and fills ErrorDesc appropri-
ately.
class_FileReader2 (Class)
This class provides the ability to read files from the sequestered RTAC file system. Call
the Run() method every scan to perform whatever file-handling actions are buffered in the
internal queue.
The g_p_FileIo_MaxBufferSize parameter, detailed in Global Parameters on page 43.2,
dictates the maximum file size that can be read using this class.
Outputs
Name IEC 61131 Type Description
InProgress BOOL Stays TRUE while the Run() method reads a file. The
class ignores any calls to a read method while this output
is TRUE.
Error BOOL TRUE if the function block cannot read contents of the
file into buffer.
ErrorDesc STRING(255) The last error encountered is described here.
BytesInBuffer UDINT The number of bytes that were read from file. Set to 0
when a read method is called, and populated when read
is complete.
ReadFile (Method)
Call this method to read the content of a file into the internal buffer.
Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path to the file of interest within the sequestered file
system. The character “/” delimits the folder path. This path
must end with the full file name, including extension. It may
contain all printable ASCII characters between 16#20(Space)
and 16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot
contain any file path manipulation variables (//, /./, /../).
Processing
ä Checks that a read operation is not in progress.
ä Ensures that the first character of filename is “/”. This method prepends the character
if it is missing from the filename provided.
ä Initiates a read operation, which Run() performs.
ReadEventFromDB (Method)
Call this method to read the content of an event from the database into the internal buffer.
Populate inputs startByte and totalBytes to read a window of bytes from COMTRADE data
(.dat) file types into the internal buffer.
Inputs
Name IEC 61131 Type Description
handle Struct_event_handle The details required to request this event from the database.
fileType Enum_event_data The file extension to attempt to extract from this event.
startByte UDINT The starting byte position of the event to read from the
database. Optional input that defaults to 0.
totalBytes UDINT The total number of bytes to read from the database event.
Set this value to 0 to read all bytes from startByte to the end
of the file. Optional input that defaults to 0.
Processing
ä Checks that a read operation is not in progress.
ä Initiates a read operation, which Run() performs.
CopyTo (Method)
Copies the contents of the buffer to a user-accessible location.
Inputs
Name IEC 61131 Type Description
startByte UDINT Indicates the first byte to copy as an offset from the begin-
ning of the internal buffer.
pt_byte POINTER TO BYTE The destination address to where the bytes should be
copied.
numBytes UDINT The maximum number of bytes to write out, starting with
startByte.
Return Value
IEC 61131 Type Description
UDINT Returns the number of bytes copied to the destination address.
Processing
ä Checks that startByte is less than BytesInBuffer and that pt_byte is a valid pointer
with write access. If the initial checks fail, return 0.
ä Copies contents of internal buffer to destination until all remaining bytes in buffer
have been copied or numBytes specified have been copied.
ä Returns the number of bytes copied.
AppendToSELString (Method)
Copies the contents of the internal buffer to a class_SELString.
Inputs
Name IEC 61131 Type Description
startByte UDINT Indicates the first byte to copy as an offset from the beginning
of the internal buffer.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to which the contents of the internal buffer
will be appended. See the SELString library documentation for
information about the class_SELString type.
Return Value
IEC 61131 Type Description
UDINT Returns the number of characters added to the SELString.
Processing
ä Checks that startByte is less than BytesInBuffer. If the initial check fails, returns 0.
ä Beginning with startByte, appends the bytes from the internal buffer to the strSel
supplied, until one of the following occurs:
1. The class_SELString throws an internal error.
2. No bytes remain in the buffer.
ä Returns the number of characters added to strSel.
CopyToString (Method)
Copies the content of the internal buffer to a string.
NOTE: This method assumes that
the string str is of type STRING(255).
Smaller strings will cause undesired
Inputs behavior.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to which the content of the internal buffer will be
written.
Return Value
IEC 61131 Type Description
UDINT Returns the number of characters added to the string.
Processing
ä Checks that startByte is less than BytesInBuffer. If the initial check fails, returns 0.
ä Copies the bytes from the internal buffer to str until either of the following occurs:
1. Two hundred and fifty-five (255) characters have been copied.
2. No bytes remain in the buffer.
ä Appends a null terminator onto the str.
AppendToVector (Method)
Allows the content of the buffer to be copied to the end of a user-accessible vector.
Inputs
Name IEC 61131 Type Description
startByte UDINT Indicates the first byte to copy as an offset from the beginning
of the internal buffer.
vector I_Vector The vector to which the internal buffer content is appended.
See the DynamicVectors library documentation for informa-
tion about the I_Vector interface.
Return Value
IEC 61131 Type Description
UDINT Returns the number of elements added to the vector.
Processing
ä Checks that startByte is less than BytesInBuffer. If the initial check fails, return 0.
ä Pushes the contents of the buffer into the supplied vector.
ä If the number of bytes specified for the copied output (BytesInBuffer minus startByte)
is not evenly divisible by the vector ElementSize, then pads the last element appended
to vector with trailing zeros.
Run (Method)
Call this method on every scan to supervise the asynchronous reading of the specified file
into the internal buffer.
Processing
ä Waits until the initiation of a file read operation by the ReadFile() or ReadEventFromDB
methods.
ä If the file is not open, opens the file in read mode and stores the file handle internally.
ä If the file is open and a read has been signaled by the ReadFile() or ReadEventFromDB
methods, monitors the asynchronous task until complete.
ä Populates BytesInBuffer upon completion of the read.
ä If any error occurs, this method sets Error TRUE and fills ErrorDesc appropriately.
class_FileReader (Class)
This is a deprecated class that is now an exact copy of class_FileReader2. The ability to
view event files by name only has been removed from the file system. Projects that contain
the ReadEventReport method will now generate compile-time errors. Reading files should
be accomplished using full paths or Struct_event_handle objects.
The g_p_FileIo_MaxBufferSize parameter, detailed in Global Parameters on page 43.2,
dictates the maximum file size that can be read using this class.
If you use this class, consider refactoring to use class_FileReader2.
class_BasicDirectoryManager (Class)
This class manages files within a given directory by removing files based on the size of the
directory, the number of files in the directory, or the maximum number of days to hold a
file since modified.
This class does not do the following:
ä Directly write any files.
ä Modify any files.
ä Monitor files within a subdirectory.
Before you can use class_BasicDirectoryManager to manage a directory, it must be pro-
vided the folder path to monitor, a maximum size for that directory, and either a maximum
number of files to hold or a maximum number of days for which to hold files.
File Blacklisting
File blacklisting allows for files to be ignored by the class_BasicDirectoryManager. A
blacklisted file cannot be deleted, and it is not counted in the total directory size or number
of files.
A file is blacklisted by having a period (.) as the first character in the file name.
For example, a file named “.somefile.txt” is ignored by class_BasicDirectoryManager,
while a file named “MySpecialFileData.txt” is managed by class_BasicDirectoryManager.
File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If only one file exists, no files are deleted. This allows the
single file to overfill the allotted maximum until the creation of a new file. This means that
if the maximum number of files is set to one, the manager never deletes files based on the
directory size or age of the file.
Outputs
Name IEC 61131 Type Description
Directory STRING(128) The directory being managed.
Error BOOL TRUE if the class encounters any error.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileCount UDINT The maximum number of files this directory stores. A
value of zero indicates that MaxFileCount is ignored.
MaxDaysHeld UDINT The maximum number of days this directory stores files
based on the time stamp. A value of zero indicates that
MaxDaysHeld is ignored.
bootstrap_SetDirectory (Method)
This method is called once, before any other method, to configure the class_BasicDirecto-
ryManager. It provides the values the class uses to determine what directory to watch and
when to delete files.
Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to use and manage. The character “/”
delimits the folder path. It may contain all print-
able ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |.
It cannot contain any file path manipulation vari-
ables (//, /./, /../). If the folder does not exist, the
class will show an error until the directory is cre-
ated by some other mechanism.
maximumFolderSize ULINT The size, in bytes, at which the directory begins
deleting files, starting at the oldest.
maximumNumFiles UDINT The maximum number of files this directory
stores. A value of zero indicates that maximum-
NumFiles is ignored.
maximumNumDays UDINT The maximum number of days this directory
stores files based on the time stamp. A value of
zero indicates that maximumNumDays is ignored.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors occured during bootstrapping.
Run (Method)
Call this method on every scan. It supervises the asynchronous deletion of old files. Dele-
tions occur only if the number of files in the directory, the size of the directory, or the
number of days to hold a file exceeds user-set limits.
Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the directory listing is exhausted:
a. Determine the cutoff file for deletions on the next scan by performing the fol-
lowing steps:
i. Collect a running total of space moving backward in time.
ii. Find the file that causes the space to be exceeded and store its time stamp.
iii. Find the file that exceeds the file count and store its time stamp.
iv. Set the cutoff time to the newest of the two saved time stamps.
b. Restart the directory iterator.
2. If the directory listing is not exhausted, perform one of the following checks on the
next file:
class_DirectoryManager (Class)
This class allows for the creation of managed files, over time, in a controlled directory. It
provides protection for the size of the directory, the number of files in the directory, and
the size of those files.
Before you can use this class to manage a directory, you must provide it the folder path
designating to where log files are written, a maximum size for that directory, a maximum
number of files to allow in that directory, and a postfix to add to log files.
This class uses class_FileWriter objects to perform the writing of log files and event logs.
See class_FileWriter (Class) on page 16.27 for more detailed information about the limi-
tations on the maximum size of log files or maximum number of buffered log entries.
File Entries
File entries take exactly the data provided and append this information to the active file.
No additional formatting is performed.
Event Logs
In addition to log files, you may want to create a separate file that records information
corresponding to some event, with custom formatting. These are referred to as “Event
Logs,” and should not be confused with the “Event Records” relays generate, containing
high-resolution waveforms. An event file is simply a custom log file written out to the
managed directory, rotated with the files (as described in File Rotation on page 16.38),
and sent to the same FTP server (if set) for this manager object.
Event Logs are stored with the time stamp of when they were created. The format for these
files is YYYY-MM-DD-HH-MM_eventPostfix, where eventPostfix is defined in the method
call to write the file.
It is important to recognize that, because the file name does not include seconds, two events
recorded within the same minute and defined with the same eventPostfix argument will
cause the contents of the second event to be appended to the end of the first file.
File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If no other files exist except the active file, no files are deleted.
This allows the single active file to overfill the allotted maximum until the creation of a
new file.
Outputs
Name IEC 61131 Type Description
Directory STRING(127) The directory being managed.
ActiveFile STRING(128) The rotating file presently waiting for write requests.
Error BOOL TRUE if the class cannot write the contents of its buffer
to file.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileSize UDINT The size, in bytes, at which this class rotates its auto-
matically generated files.
MaxFileCount UDINT The maximum number of files this directory stores. A
value of zero indicates that MaxFileCount is ignored.
bootstrap_SetDirectory (Method)
This method is called once, before any other method, to configure the class_Directory-
Manager. It provides the values the class uses to determine where to store files, what to
call them, and when to create and delete them.
Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to use and manage. The character “/”
delimits the folder path. It may contain all print-
able ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |.
It cannot contain any file path manipulation vari-
ables (//, /./, /../). If the folder does not exist, it
will be created the first time that a file is written.
Any files in this directory that are not managed
files will be deleted.
filenamePostfix STRING(16) A string that is added to the end of the time-
stamped file name on every file.
maximumFolderSize UDINT The size, in bytes, at which the directory manager
begins deleting files, starting at the oldest.
maximumFileSize UDINT The size, in bytes, at which this class rotates its
automatically generated files.
maximumNumFiles UDINT The maximum number of files this directory
stores. A value of zero indicates that maximum-
NumFiles is ignored.
rollFileAtDay BOOL Close the working file each day at midnight and
start a new file.
SetFtpServerForArchiving (Method)
Call this method once to specify a remote FTP server to which generated files are sent and
how often the files should be sent.
Every FTP attempt generates a log file to assist with debugging (overwriting the previous
log file if it exists). The file includes success notifications as well as errors the ftp client
encounters (such as a bad username or password). View the following file, found at the
root of the sequestered file system, via a web browser after attempting an FTP file transfer:
ftplog.txt
Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
remotePath STRING(127) The folder on the FTP server to where the local files
are sent.
username STRING(32) The FTP username used to log into the server. This
must contain only alphanumeric or underscore char-
acters.
password STRING(32) The password associated with the FTP username used
to log into the server. This may contain any printable
ASCII characters, excluding the quote characters.
timeout UDINT The number of seconds for the FTP attempt to be run
before it is canceled. Must be greater than 0.
schedule enum_FtpSendSchedule Specify when local files should be sent to the remote
FTP server.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the arguments provided are within range.
Processing
ä Validates the input strings and confirms that a valid IP address is provided.
ä If the inputs provided are valid, sets internal variables so that the Run() method
attempts to send files, and returns TRUE.
ä If the inputs provided are invalid, returns FALSE.
SetFileHeaderBytes (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing header; new files will be started with the first data entry instead.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the header block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.
SetFileHeaderSELString (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A strSel
of Size zero clears any existing header; new files will be started with the first data entry
instead.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the header block.
SetFileHeaderString (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing header; new files will be started with the first data entry instead.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the header block.
SetFileHeaderVector (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A vector
of Size zero clears any existing header; new files will be started with the first data entry
instead.
Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the header block. See the DynamicVectors
library documentation for information about the I_Vector inter-
face.
SetFileFooterBytes (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing footer.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the footer block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.
SetFileFooterSELString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A strSel of Size
zero clears any existing footer.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the footer block.
SetFileFooterString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing footer.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the footer block.
SetFileFooterVector (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A vector of Size
clears any existing footer.
Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the new footer block. See the DynamicVec-
tors library documentation for information about the I_Vector
interface.
StartNewFile (Method)
Use this method to close the active file and begin a new one. Unless you call this method,
a new file starts only if the conditions provided in bootstrap_SetDirectory() are met,
(i.e., rollFileAtDay is TRUE and a new day has begun or the active file size exceeded
maximumFileSize).
Processing
ä For an active log file and a non-empty footer string, this method places that string at
the end of the active file.
ä Closes the active file.
ä Creates a new file with the present time stamp.
ä For a non-empty header string, places that string at the top of the new file.
WriteToFileBytes (Method)
Call this method to append a raw byte array to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of pt_data was successfully added to the out-
put buffer.
Processing
ä Appends numBytes characters, starting at address pt_data to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteToFileSELString (Method)
Call this method to append an SELString to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.
Processing
ä Appends the content of selStr to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteToFileString (Method)
Call this method to append a string to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to append to the file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.
Processing
ä Appends the value of str to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteToFileVector (Method)
Call this method to append a vector of data to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of vector was successfully added to the output
buffer.
Processing
ä Appends the content of vector to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
EventLogFromBytes (Method)
Call this method to write a log file with contents defined in a contiguous set of memory.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.
Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromSELString (Method)
Call this method to write a log file with contents defined in a class_SELString.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromString (Method)
Call this method to write a log file with contents defined in a string.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromVector (Method)
Call this method to write a log file with contents defined in an I_Vector.
Inputs
Name IEC 61131 Type Description
vector I_Vector The content of the event file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
Run (Method)
Call this method on every scan. It supervises the asynchronous writing of queued data to
active files and the asynchronous deletion of old files. Deletions occur only if the number
of files in the directory or size of the directory exceed user-set limits.
This method is also responsible for sending local files to a remote FTP server if the user
has configured FTP through a successful call to SetFtpServerForArchiving().
Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the system day of year has changed since the last time Run() was called and the
class is set to start a new file each day, the method starts a new log by calling the
StartNewFile() method.
2. Is this object already in one of the states described in Processing States on page 16.60?
ä Yes: Continues execution of that state.
ä No: Evaluates the job priority list described in Processing Jobs on page 16.60
and executes the next job.
3. Calls Run() on the internal class_FileWriter object that handles the writing of en-
tries.
4. Calls Run() on the internal class_FileWriter object that handles the writing of event
logs.
Processing Jobs
Only one job is performed per call to this method. The jobs are listed below in priority
order:
1. Enters the Send File state if a write operation has been completed since the last
Send File state completed (determined by looking for the falling edge of class_-
FileWriter.BytesLeft <> 0).
2. Enters the Directory Housekeeping state if there is no directory listing or the last
listing was exhausted.
3. Enters the Resend File state if there are unsent files that have not been synchronized
to the remote server .
Processing States
Some of the jobs in Processing Jobs on page 16.60 cause this object to enter a state. The
following describes these states and their exit criteria:
ä Send File: This state exits immediately if a valid FTP server was not provided using
the method SetFtpServerForArchiving().
If the FTP server was set appropriately, the behavior of this state varies depending on
the value of the schedule argument passed in using the SetFtpServerForArchiving()
method call. Enumerations on page 43.2 defines the enumeration for this argument.
â schedule = ON_CLOSE: If this write was initiated by the StartNewFile()
method, the closed file is sent to the FTP server using the sel_ftp_client.ftp_-
upload() function call.
The state is maintained until the file is sent and then successfully read back
using the sel_ftp.ftp_download() function call.
If any error occurs, this method sets Error to TRUE and fills ErrorDesc appro-
priately.
â schedule = ON_UPDATE: The active file is sent to the server using the method
call sel_ftp.ftp_upload().
ä Directory Housekeeping: The following sub-states exist in this state.
â Obtain the size of the active file.
â If the active file size is greater than maximumFileSize, start a new file.
class_TimeBasedDirectoryManager (Class)
This class allows for the creation of managed files, over time, in a controlled directory. It
provides protection for the size of the directory, the number of files in the directory, and
the size of those files.
Before you can use this class to manage a directory, you must provide it the folder path
designating to where log files are written, a maximum size for that directory, a maximum
number of days for which to hold files, and a postfix to add to log files.
This class uses class_FileWriter objects to perform the writing of log files and event logs.
See class_FileWriter (Class) on page 16.27 for more detailed information about the limi-
tations on the maximum size of log files or maximum number of buffered log entries.
File Entries
File entries take exactly the data provided and append this information to the active file.
No additional formatting is performed.
Event Logs
In addition to log files, you may want to create a separate file that records information
corresponding to some event, with custom formatting. These are referred to as “Event
Logs,” and should not be confused with the “Event Records” relays generate, containing
high-resolution waveforms. An event file is simply a custom log file written out to the
managed directory, rotated with the files (as described in File Rotation on page 16.51),
and sent to the same FTP server (if set) for this manager object.
Event Logs are stored with the time stamp of when they were created. The format for these
files is YYYY-MM-DD-HH-MM_eventPostfix, where eventPostfix is defined in the method
call to write the file.
It is important to recognize that, because the file name does not include seconds, two events
recorded within the same minute and defined with the same eventPostfix argument will
cause the contents of the second event to be appended to the end of the first file.
File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If no other files exist except the active file, no files are deleted.
This allows the single active file to overfill the allotted maximum until the creation of a
new file.
Outputs
Name IEC 61131 Type Description
Directory STRING(127) The directory being managed.
ActiveFile STRING(128) The rotating file presently waiting for write requests.
Error BOOL TRUE if the class cannot write the contents of its buffer
to file.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileSize UDINT The size, in bytes, at which this class rotates its auto-
matically generated files.
MaxDaysHeld UDINT The maximum number of days this directory stores files
based on the time stamp.
bootstrap_SetDirectory (Method)
This method is called once, before any other method, to configure the class. It provides
the values the class uses to determine where to store files, what to call them, and when to
create and delete them.
Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to use and manage. The character “/”
delimits the folder path. It may contain all print-
able ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |.
It cannot contain any file path manipulation vari-
ables (//, /./, /../). If the folder does not exist, it
will be created the first time that a file is written.
Any files in this directory that are not managed
files will be deleted.
filenamePostfix STRING(16) A string that is added to the end of the time-
stamped file name on every file.
maximumFolderSize UDINT The size, in bytes, at which the directory begins
deleting files, starting at the oldest.
maximumFileSize UDINT The size, in bytes, at which this class rotates its
automatically generated files.
maximumNumDays UDINT The maximum number of days from today this di-
rectory stores files based on the time stamp.
rollFileAtDay BOOL Close the working file each day at midnight and
start a new file.
SetFileHeaderBytes (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing header; new files will be started with the first data entry instead.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the header block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.
SetFileHeaderSELString (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A strSel
of Size zero clears any existing header; new files will be started with the first data entry
instead.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the header block.
SetFileHeaderString (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing header; new files will be started with the first data entry instead.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the header block.
SetFileHeaderVector (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A vector
of Size zero clears any existing header; new files will be started with the first data entry
instead.
Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the header block. See the DynamicVectors
library documentation for information about the I_Vector inter-
face.
SetFileFooterBytes (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing footer.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the footer block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.
SetFileFooterSELString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A strSel of Size
zero clears any existing footer.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the footer block.
SetFileFooterString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing footer.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the footer block.
SetFileFooterVector (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A vector of Size
clears any existing footer.
Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the new footer block. See the DynamicVec-
tors library documentation for information about the I_Vector
interface.
StartNewFile (Method)
Use this method to close the active file and begin a new one. Unless you call this method,
a new file starts only if the conditions provided in bootstrap_SetDirectory() are met,
(i.e., rollFileAtDay is TRUE and a new day has begun or the active file size exceeded
maximumFileSize).
Processing
ä For an active log file and a non-empty footer string, this method places that string at
the end of the active file.
ä Closes the active file.
ä Creates a new file with the present time stamp.
ä For a non-empty header string, places that string at the top of the new file.
WriteToFileBytes (Method)
Call this method to append a raw byte array to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of pt_data was successfully added to the out-
put buffer.
Processing
ä Appends numBytes characters, starting at address pt_data to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteToFileSELString (Method)
Call this method to append an SELString to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.
Processing
ä Appends the content of selStr to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteToFileString (Method)
Call this method to append a string to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to append to the file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.
Processing
ä Appends the value of str to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteToFileVector (Method)
Call this method to append a vector of data to the active file.
Inputs/Outputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of vector was successfully added to the output
buffer.
Processing
ä Appends the content of vector to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
EventLogFromBytes (Method)
Call this method to write a log file with contents defined in a contiguous set of memory.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, starting with pt_data.
Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromSELString (Method)
Call this method to write a log file with contents defined in a class_SELString.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromString (Method)
Call this method to write a log file with contents defined in a string.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromVector (Method)
Call this method to write a log file with contents defined in an I_Vector.
Inputs
Name IEC 61131 Type Description
vector I_Vector The content of the event file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
Run (Method)
Call this method on every scan. It supervises the asynchronous writing of queued data to
active files and the asynchronous deletion of old files. Deletions occur only if the number
of files in the directory or size of the directory exceed user-set limits.
This method is also responsible for sending local files to a remote FTP server if the user
has configured FTP through a successful call to SetFtpServerForArchiving().
Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the system day of year has changed since the last time Run() was called and the
class is set to start a new file each day, the method starts a new log by calling the
StartNewFile() method.
2. Is this object already in one of the states described in Processing States on page 16.60?
ä Yes: Continues execution of that state.
ä No: Evaluates the job priority list described in Processing Jobs on page 16.60
and executes the next job.
3. Calls Run() on the internal class_FileWriter object that handles the writing of en-
tries.
4. Calls Run() on the internal class_FileWriter object that handles the writing of event
logs.
Processing Jobs
Only one job is performed per call to this method. The jobs are listed below in priority
order:
1. Enters the Send File state if a write operation has been completed since the last
Send File state completed (determined by looking for the falling edge of class_-
FileWriter.BytesLeft <> 0).
2. Enters the Directory Housekeeping state if there is no directory listing or the last
listing was exhausted.
3. Enters the Resend File state if there are unsent files that have not been synchronized
to the remote server .
Processing States
Some of the jobs in Processing Jobs on page 16.60 cause this object to enter a state. The
following describes these states and their exit criteria:
ä Send File: This state exits immediately if a valid FTP server was not provided using
the method SetFtpServerForArchiving().
If the FTP server was set appropriately, the behavior of this state varies depending on
the value of the schedule argument passed in using the SetFtpServerForArchiving()
method call. Enumerations on page 43.2 defines the enumeration for this argument.
â schedule = ON_CLOSE: If this write was initiated by the StartNewFile()
method, the closed file is sent to the FTP server using the sel_ftp_client.ftp_-
upload() function call.
The state is maintained until the file is sent and then successfully read back
using the sel_ftp.ftp_download() function call.
If any error occurs, this method sets Error to TRUE and fills ErrorDesc appro-
priately.
â schedule = ON_UPDATE: The active file is sent to the server using the method
call sel_ftp.ftp_upload().
ä Directory Housekeeping: The following sub-states exist in this state.
â Obtain the size of the active file.
â If the active file size is greater than maximumFileSize, start a new file.
class_LogDirectoryManager (Class)
This class allows for the creation of managed files, over time, in a controlled directory. It
provides protection for the size of the directory, the number of files in the directory, and
the size of those files.
Before you can use this class to manage a directory, you must provide it the folder path
designating to where log files are written, a maximum size for that directory, a maximum
number of files to allow in that directory, and a postfix to add to log files.
This class uses class_FileWriter objects to perform the writing of log files and event logs.
See class_FileWriter (Class) on page 16.27 for more detailed information about the limi-
tations on the maximum size of log files or maximum number of buffered log entries.
Log Entries
Log entries are prefixed with a time stamp and added as a single-row entry to the active log
file.
The log file names are stored with the time stamp of when they were created. The format for
these files is YYYY-MM-DD-HH-MM_logPostfix, where logPostfix is set in the declaration
of the class.
Event Logs
In addition to log files, you may want to create a separate file that records information
corresponding to some event, with custom formatting. These are referred to as “Event
Logs,” and should not be confused with the “Event Records” relays generate, containing
high-resolution waveforms. An event file is simply a custom log file written out to the
managed directory, rotated with the log files (as described in File Rotation on page 16.62),
and sent to the same FTP server (if set) for this manager object.
Event Logs are stored with the time stamp of when they were created. The format for these
files is YYYY-MM-DD-HH-MM_eventPostfix, where eventPostfix is defined in the method
call to write the file.
It is important to recognize that, because the file name does not include seconds, two events
recorded within the same minute and defined with the same eventPostfix argument will
cause the contents of the second event to be appended to the end of the first file.
File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If no other files exist except the active log file, no files are
deleted. This allows the single active log file to overfill the allotted maximum until the
creation of a new log file.
Initialization Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to write logs to and manage. The
character “/” delimits the folder path. It may
contain all printable ASCII characters between
16#20(Space) and 16#7E(~) except for ", ', :, <,
%, >, ?, \, and |. It cannot contain any file path
manipulation variables (//, /./, /../). If the folder
does not exist, it will be created the first time
that a log is written. Any files in this directory
that are not log files will be deleted.
logPostfix STRING(16) A string that is added to the end of the time-
stamped file name on every log file.
maxFolderSize UDINT The size, in bytes, at which the directory begins
deleting files, starting at the oldest.
maxNumFiles UDINT The maximum number of files this directory
stores. A value of zero indicates that maxNum-
Files is ignored.
autoStartNewLogDaily BOOL If this is TRUE, a new log file is automatically
created on the first PLC scan of every day, re-
gardless of whether an entry is written that day.
If FALSE, a new log file will only be created at
the first log entry method call.
Outputs
Name IEC 61131 Type Description
Directory STRING(127) The directory being managed.
ActiveFile STRING(128) The rotating file presently waiting for write requests.
Error BOOL TRUE if the class cannot write the contents of its buffer
to file.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileSize UDINT The size, in bytes, at which this class rotates its auto-
matically generated files.
MaxFileCount UDINT The maximum number of files this directory stores. A
value of zero indicates that MaxFileCount is ignored.
SetFtpServerForArchiving (Method)
Call this method once to specify a remote FTP server to which generated files are sent and
how often the files should be sent.
Every FTP attempt generates a log file to assist with debugging (overwriting the previous
log file if it exists). The file includes success notifications as well as errors the ftp client
encounters (such as a bad username or password). View the following file, found at the
root of the sequestered file system, via a web browser after attempting an FTP file transfer:
ftplog.txt
Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
remotePath STRING(127) The folder on the FTP server to where the local files
are sent.
username STRING(32) The FTP username used to log into the server. This
must contain only alphanumeric or underscore char-
acters.
password STRING(32) The password associated with the FTP username used
to log into the server. This may contain any printable
ASCII characters, excluding the quote characters.
timeout UDINT The number of seconds for the FTP attempt to be run
before it is canceled. Must be greater than 0.
schedule enum_FtpSendSchedule Specify when local files should be sent to the remote
FTP server.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the arguments provided are within range.
Processing
ä Validates the input strings and confirms that a valid IP address is provided.
ä If the inputs provided are valid, sets internal variables so that the Run() method
attempts to send files, and returns TRUE.
ä If the inputs provided are invalid, returns FALSE.
StartNewLog (Method)
Call this method to create a new log file. All new log entries are added to this file until this
method is called again or the system day of year changes. Do not call this method if you
desire exactly one log file per day.
Processing
ä If there was an active log file, adds a log entry with the text: --End log file--
ä Updates internal retained variable storing the active log time via the SYS_TIME()
function call.
ä Adds a log to this new file with the text: --Begin log file--
WriteLogEntryBytes (Method)
Call this method to append a raw byte array to the active log file.
Inputs/Outputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of pt_data was successfully added to the out-
put buffer.
Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends numBytes characters starting at address pt_data to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteLogEntrySELString (Method)
Call this method to append an SELString to the active log file.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.
Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends the content of selStr to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteLogEntryString (Method)
Call this method to append a string to the active log file.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to add to the log.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.
Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends the value of str to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
WriteLogEntryVector (Method)
Call this method to append a vector of data to the active log file.
Inputs/Outputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of vector was successfully added to the output
buffer.
Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends the content of vector to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.
EventLogFromBytes (Method)
Call this method to write a log file with contents defined in a contiguous set of memory.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, starting with pt_data.
Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromSELString (Method)
Call this method to write a log file with contents defined in a class_SELString.
Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromString (Method)
Call this method to write a log file with contents defined in a string.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
EventLogFromVector (Method)
Call this method to write a log file with contents defined in an I_Vector.
Inputs
Name IEC 61131 Type Description
vector I_Vector The content of the event file. See the DynamicVectors library
documentation for information about the I_Vector interface.
Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.
Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.
Run (Method)
Call this method on every scan. It supervises the asynchronous writing of queued data to
active files and the asynchronous deletion of old files. Deletions occur only if the number
of files in the directory or size of the directory exceed user-set limits.
This method is also responsible for sending local files to a remote FTP server if the user
has configured FTP through a successful call to SetFtpServerForArchiving().
Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the system day of year has changed since the last time Run() was called, the
method starts a new log by calling the StartNewLog() method.
2. Is this object already in one of the states described in Processing States on page 16.70?
ä Yes: Continues execution of that state.
ä No: Evaluates the job priority list described in Processing Jobs on page 16.70
and executes the next job.
3. Calls Run() on the internal class_FileWriter object that handles the writing of en-
tries.
4. Calls Run() on the internal class_FileWriter object that handles the writing of event
logs.
Processing Jobs
Only one job is performed per call to this method. The jobs are listed below in priority
order:
1. Enters the Send File state if a write operation has been completed since the last
Send File state completed (determined by looking for the falling edge of class_-
FileWriter.BytesLeft <> 0).
2. Enters the Directory Housekeeping state if there is no directory listing or the last
listing was exhausted.
3. Enters the Resend File state if there are unsent files that have not been synchronized
to the remote server .
Processing States
Some of the jobs in Processing Jobs on page 16.70 cause this object to enter a state. The
following describes these states and their exit criteria:
ä Send File: This state exits immediately if a valid FTP server was not provided using
the method SetFtpServerForArchiving().
If the FTP server was set appropriately, the behavior of this state varies depending on
the value of the schedule argument passed in using the SetFtpServerForArchiving()
method call. Enumerations on page 43.2 defines the enumeration for this argument.
â schedule = ON_CLOSE: If this write was initiated by the StartNewLog()
method, the closed file is sent to the FTP server using the sel_ftp_client.ftp_-
upload() function call.
The state is maintained until the file is sent and then successfully read back
using the sel_ftp.ftp_download() function call.
If any error occurs, this method sets Error to TRUE and fills ErrorDesc appro-
priately.
â schedule = ON_UPDATE: The active file is sent to the server using the method
call sel_ftp.ftp_upload().
ä Directory Housekeeping: The following sub-states exist in this state.
â Obtain the size of the active file.
â If the active file size is greater than 1/3 of the maxFolderSize, start a new file.
class_ComtradeParser(Class)
This class provides the necessary functionality to read COMTRADE .dat and .cfg event
files from the RTAC’s database into the logic engine. The class automatically parses the
COMTRADE file using information from the .cfg file. The initial release of this class only
supports SEL Axion COMTRADE event files.
Because this class manages asynchronous file operations, call the Run() method of the
instantiated class on every scan to ensure that all queued work is correctly performed and
monitored after calling the ReadEventFromDB() method.
This class is compatible with the following COMTRADE standards:
ä IEEE C37.111-1999
ä IEEE C37.111-2013
Outputs
Name IEC 61131 Type Description
InProgress BOOL Remains TRUE while the Run() method reads an
event. The class ignores any calls to read methods
while this output is TRUE.
Error BOOL TRUE if the function block is unable to read or parse
a COMTRADE event file.
ErrorDesc STRING(255) The last error encountered is described here.
CfgBytes UDINT The number of bytes read from the .cfg file.
DatBytes UDINT The number of bytes read from the .dat file.
NewEventReady BOOL Asserts TRUE for one processing interval after event
is successfully retrieved from database.
ReadEventFromDB (Method)
Call this method to initiate reading an event from the RTAC’s database. After calling this
method, Run() reads the event that matches the device identification and has a trigger time
that is within TimeVar. If the file cannot be found, Run() continues looking for the event
for the duration of WaitTime. When Run() finds an event that matches the input criteria,
it reads the contents of the event into internal data buffers for later use.
The optional StartSample and TotalSamples inputs provide the ability to read a window of
samples from the COMTRADE data (.dat) file only. Setting a value of 0 to StartSample
and TotalSamples results in reading all contents contained in the COMTRADE data file.
Calling this method more than once every logic processing interval results in the last call
overwriting previous calls. If more than one call per processing interval is expected, in-
stantiate multiple instances of class_ComtradeParser for each call.
Inputs
Name IEC 61131 Type Description
DeviceId STRING(255) The name of the device that generates the COMTRADE
event. Must be equivalent to the .cfg DeviceID field.
TriggerTime dateTime_t The event’s trigger time. If exact match does not exist,
this method reads an event within TimeVar milliseconds
of TriggerTime.
TimeVar UINT The time variance in milliseconds allowed between Trig-
gerTime and the event’s actual trigger time (0 - 1000 mil-
liseconds).
WaitTime UINT The amount of time that ReadEventFromDB() waits until
the event is available in the database (1 - 60 minutes).
This method keeps looking for the event until WaitTime
transpires.
StartSample UDINT The starting sample to read from the COMTRADE file.
Optional input that defaults to 0.
TotalSamples UDINT The total number of samples, beginning from StartSam-
ple, in the COMTRADE data file to read into the RTAC’s
internal buffers. A value of 0 results in reading all sam-
ples from StartSample to the end of the of the file. Op-
tional input that defaults to 0.
Processing
ä ReadEventFromDB() call sets InProgess to TRUE and Error to FALSE.
ä ReadEventFromDB() configures parameters for the event to be read.
ReadEventFromDBDirect (Method)
Call this method to retrieve a COMTRADE event from the database using the event handle.
After calling this method, Run() reads the event into internal data buffers for later use.
The event handle is an attribute of the struct_EventDetails structure. See class_EventList-
ing for details on populating an instance of struct_EventDetails.
Inputs
Name IEC 61131 Type Description
EventHandle sel_file.Struct_event_handle The details required to request an event from the
database.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the read request was successfully processed.
Processing
ä If EventID is null, or InProgress is TRUE, does no work and returns FALSE. Else,
does the following.
ä Sets InProgess to TRUE and Error to FALSE and ErrorDesc to a null string.
ä Passes the EventID to Run() which initiates a database read operation for the event.
ReadEventFromFS (Method)
Call this method to initiate a search of the RTAC’s file system for a set of files that define
a COMTRADE event (.cfg , .dat). After calling this method, Run() reads the event into
internal data buffers for later use.
Inputs
Name IEC 61131 Type Description
CfgFileName STRING(255) The full path to the .cfg file. The character / delimits the
folder path.
DatFileName STRING(255) The full path to the .dat file. The character / delimits the
folder path.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the read request was successfully processed.
Processing
ä If InProgress is TRUE, or either file name does not conform to the requirements of
the fileIO.class_FileReader2.ReadFile method, does no work and returns FALSE.
Else, does the following.
ä Sets InProgess to TRUE and Error to FALSE and ErrorDesc to a null string.
ä Passes the file names to Run() which initiates a file system read operation for the
event.
GetComtradeInfo (Method)
Call this method to read the COMTRADE event information from the .cfg file and output
the data to a struct_ComtradeInfo variable.
Outputs
Name IEC 61131 Type Description
ComtradeInfo struct_ComtradeInfo The COMTRADE event information.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if event information is found.
Processing
If Error and InProgress are FALSE:
ä GetComtradeInfo() method scans event information and outputs the COMTRADE
event details to ComtradeInfo.
ä GetComtradeInfo() returns TRUE after event information is collected.
GetComtradeInfo() call is ignored if Error or InProgress is TRUE.
GetAnalogChannelInfo (Method)
Call this method to read an analog channel’s information from the .cfg file and output the
data to a struct_AnalogChannelInfo variable.
Inputs
Name IEC 61131 Type Description
ChannelNumber UDINT The analog channel number for which the method col-
lects information.
Outputs
Name IEC 61131 Type Description
ChannelInfo struct_AnalogChannelInfo The analog channel information.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if channel information is found.
Processing
If Error and InProgress are FALSE:
ä GetAnalogChannelInfo() checks that channelNumber exists in the .cfg file and out-
puts the analog channel’s information.
ä GetAnalogChannelInfo() returns TRUE after channel information is collected.
GetAnalogChannelInfo() call is ignored if Error or InProgress is TRUE.
GetDigitalChannelInfo (Method)
Call this method to read a digital channel’s information from the .cfg file and output the
data to a struct_digitalChannelInfo variable.
Inputs
Name IEC 61131 Type Description
ChannelNumber UDINT The digital channel number for which the method col-
lects information.
Outputs
Name IEC 61131 Type Description
ChannelInfo struct_DigitalChannelInfo The digital channel information.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if channel information is found.
Processing
If Error and InProgress are FALSE:
ä GetDigitalChannelInfo() checks that channelNumber exists in the .cfg file and output
the digital channel’s information.
ä GetDigitalChannelInfo() returns TRUE after channel information is collected.
GetDigitalChannelInfo() call is ignored if Error or InProgress is TRUE.
GetAnalogChannelNumber (Method)
Call this method to retrieve the channel number of the analog channel specified by the input
channel name. This method is useful in conjunction with the GetAnalogChannelInfo()
method when only the channel name is known.
Inputs
Name IEC 61131 Type Description
ChannelName STRING(128) The channel name string of the analog channel.
Return Value
IEC 61131 Type Description
UDINT Returns the analog channel number of the first found channel whose chan-
nel ID matches the input ChannelName (case insensitive). Returns zero if
no match is found.
GetDigitalChannelNumber (Method)
Call this method to retrieve the channel number of the digital channel specified by the input
channel name. This method is useful in conjunction with the GetDigitalChannelInfo()
method when only the channel name is known.
Inputs
Name IEC 61131 Type Description
ChannelName STRING(128) The channel name string of the digital channel.
Return Value
IEC 61131 Type Description
UDINT Returns the digital channel number of the first found channel whose chan-
nel ID matches the input ChannelName (case insensitive). Returns zero if
no match is found.
ConvertComtradeTStoUTC (Method)
Call this method to convert a class_ComtradeParser-calculated timestamp to a UTC times-
tamp, based on the Local Code offset denoted in the .cfg file.
Inputs
Name IEC 61131 Type Description
TimeStamp dateTime_t Timestamp returned from GetDigitalSample(),
GetAnalogSample() or struct_ComtradeInfo.
Return Value
IEC 61131 Type Description
dateTime_t Returns the UTC representation of the TimeStamp input.
GetRealVector (Method)
Call this method to parse samples contained in the range of FirstSample to LastSample of
an analog channel and write it to a REAL vector. This method scales the data using the
channel’s information from the .cfg file.
Inputs
Name IEC 61131 Type Description
ChannelInfo struct_AnalogChannelInfo The analog channel information to parse.
FirstSample UDINT The first sample to read.
LastSample UDINT The last sample to read.
Inputs/Outputs
Name IEC 61131 Type Description
SampleVector DynamicVectors.class_RealVector The REAL vector to which the method
writes the analog samples.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if channel information is found.
Processing
If Error and InProgress are FALSE:
ä GetRealVector() checks that ChannelInfo and analog samples within the provided
sample range from FirstSample to LastSample exist.
ä Parses the .dat file for ChannelName and write the samples to SampleVector.
ä GetRealVector() returns TRUE after real vector is written.
GetRealVector() call is ignored if Error or InProgress is TRUE.
GetAnalogSample (Method)
Call this method to get a single sample of an analog channel and output the sample as a
REAL value. This method scales the sample using the channel’s information from the .cfg
file. The method also outputs the sample’s absolute timestamp with respect to the event
trigger time.
Inputs
Name IEC 61131 Type Description
ChannelInfo struct_AnalogChannelInfo The analog channel information to parse.
SampleNumber UDINT The sample to read.
Outputs
Name IEC 61131 Type Description
Sample REAL The analog sample’s value.
SampleTime dateTime_t The sample’s date and timestamp.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if sample is found.
Processing
If Error and InProgress are FALSE:
ä GetAnalogSample() checks that channelName and the sampleNumber exist.
ä Parses the .dat file for ChannelName and outputs the analog sample information for
SampleNumber.
ä GetAnalogSample() returns TRUE after sample information is written.
GetAnalogSample() call is ignored if Error or InProgress is TRUE.
GetBoolVector (Method)
Call this method to parse samples contained in the range of FirstSample to LastSample of
a digital channel and write it to a vector.
Inputs
Name IEC 61131 Type Description
ChannelInfo struct_DigitalChannelInfo The digital channel information to parse.
FirstSample UDINT The first sample to read.
LastSample UDINT The last sample to read.
Inputs/Outputs
Name IEC 61131 Type Description
SampleVector DynamicVectors.class_BaseVector The vector to which the method writes
the boolean samples. Vector must
be declared with elementSize :=
SIZEOF(BOOL).
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if channel information is found.
Processing
If Error and InProgress are FALSE:
ä Checks that ChannelInfo and digital samples within the provided sample range from
FirstSample to LastSample exist.
ä Calls .clear() on SampleVector if not already cleared.
ä Parses the .dat file for struct_DigitalChannelInfo.ChannelId and write the samples
to SampleVector.
ä Returns TRUE if all samples in the specified range were successfully written to Sam-
pleVector. Otherwise, returns FALSE.
GetBoolVector() call is ignored if Error or InProgress is TRUE.
GetDigitalSample (Method)
Call this method to get a single sample of a digital channel and output the sample as a
BOOL value.
Inputs
Name IEC 61131 Type Description
ChannelInfo struct_DigitalChannelInfo The digital channel information to parse.
SampleNumber UDINT The sample to read.
Outputs
Name IEC 61131 Type Description
Sample BOOL The digital sample’s state.
SampleTime dateTime_t The digital sample’s date and timestamp.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if sample is found.
Processing
If Error and InProgress are FALSE:
ä GetDigitalSample() checks that ChannelName and the SampleNumber exist.
ä Parse the .dat file for ChannelName and output the digital sample information for
SampleNumber.
ä GetDigitalSample() returns TRUE after sample information is written.
GetDigitalSample() call is ignored if Error or InProgress is TRUE.
GetSamplingInfo (Method)
Call this method to get a sample rate and corresponding last sample number from the .cfg
file. When the number of samples read from the database is less than the number of samples
indicated in the .cfg file, the last sample number displays the quantity of samples stored in
the internal buffer.
Inputs
Name IEC 61131 Type Description
SampleRateNumber UDINT The .cfg file sample rate to collect sampling infor-
mation from.
Outputs
Name IEC 61131 Type Description
SamplingInfo Struct_SamplingInfo The sample rate and corresponding last sample number.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if sample rate and last sample number are found.
Processing
If Error and InProgress are FALSE:
ä GetSamplingInfo() checks that SampleRateNumber exists in the .cfg file and outputs
information to SamplingInfo.
ä GetSamplingInfo() returns TRUE after sampling information is collected.
GetSamplingInfo() call is ignored if Error or InProgress is TRUE.
Run (Method)
Call this method on every scan. It supervises all asynchronous operations.
Processing
ä If a ReadEventFromDB() or ReadEventFromDBDirect()method has been initi-
ated:
â Set InProgress to TRUE.
â Set Error to FALSE.
â Clear ErrorDesc.
ä ReadEventFromDB() invokes the following behavior
â Begin searching for a COMTRADE event that matches DeviceID and has as
trigger time that is within ±TimeVar of TriggerTime.
â Continue searching for event until one is found or WaitTime expires.
â If a COMTRADE event is found, read the .cfg file into internal buffers.
ã If StartSample and TotalSamples are 0, all contents from the .dat file are
asynchronously read into internal buffers.
ã If StartSample is non-zero and less then the number of samples contained
in the .dat file, the run method reads TotalSamples samples from the .dat
file with an offset starting sample of StartSample into internal buffers. If
TotalSamples is zero, the run method reads all contents from the .dat file
with an offset starting sample of StartSample into internal buffers.
ã When the .dat file read is complete, the run method sets InProgress to
FALSE and NewEventReady to TRUE for one processing cycle.
â If a COMTRADE event is not found before WaitTime expires, perform the fol-
lowing actions:
ã Set InProgess to FALSE.
ã Populate ErrorDesc with "Event Not Found".
ä ReadEventFromDBDirect() invokes the following behavior
â Read the .cfg and then the .dat file into internal buffers for later use.
â When the .dat file read is complete, set InProgress to FALSE, and set New-
EventReady to TRUE for one processing cycle.
ä If any error occurs, set Error to TRUE and populate ErrorDesc appropriately.
class_PersistentData(Class)
This class provides the necessary functionality to monitor the present values of a config-
urable collection of variables of any data type or custom structure; periodically write the
values of those variables to a managed JSON data file; and, upon the next restart of the
RTAC, automatically apply the variable values found in the managed file to the original
logic engine variables.
The functionality offered by this class is similar to that offered by retained global variable
lists (GVLs) in the user logic engine with the following major differences:
ä Retained GVLs are limited to approximately 28 kB of dedicated nonvolatile memory,
whereas the JSON data files created by this class are limited by the free space in the
RTAC’s file system.
ä The first time a project file containing a retained GVL is sent to an RTAC, the ‘Re-
initialize Retain Variables’ option in the project send dialog must be selected to apply
default values to these variables. A subsequent change in the structure of the variable
layout (additions, removals, relocations, etc.) contained within the retained GVL ne-
cessitates that the re-initialization option be selected again to ensure that predictable
defaults are loaded to the variables. Similar changes to the list of variables monitored
by class_PersistentData require no manual re-initialization steps during subsequent
project send operations and variables not found in the managed JSON file at startup
are automatically initialized to their bootstrapped default values.
ä Values contained within retained GVLs can be a challenge to apply back to tag val-
ues owned by other devices or tag lists (e.g., applying a raw retained BOOL value
back to the .stVal component of an SPS tag contained in a DNP tag list), requiring
custom user logic. Variables monitored by class_PersistentData are automatically
re-assigned to their intended location on startup and then monitored and stored pe-
riodically during runtime.
This class is compatible with all IEC 61131 data types, including custom structures. When
the managed JSON data file is created, the raw data representing the value of a variable are
encoded into an ASCII string and stored as a value associated with a specified key in the
JSON structure.
The persistent JSON data file written to the RTAC’s file system will contain content similar
to the following:
"aSPSTag":"0100000001000000000000000000000000000000000000003D32 /
95611C9B0900000001001F00000001003C00000000000400000000000000",
"aString":"77686F612E2E2E206973207468697320776F726B696E673F0000 /
0000000000000000000000000000000000000000000000000000 /
0000000000000000000000000000000000000000000000000000000000"}
The most accurate way store the values of variables of any type in the JSON file is an ASCII-
encoded equivalent of the raw hex data bytes that represent the entire variable contents.
This ASCII-encoded data is not human-readable, but it can be easily converted back to a
raw byte format and used to restore a the value of a variable upon restart.
During runtime, if the values of any monitored variables change and the RTAC is restarted,
the last known values of those variables written to the JSON data file are automatically
restored to the appropriate variables at startup.
Initialization Inputs
Name IEC 61131 Type Description
PersistentPath STRING(255) The fully qualified directory path to the managed
JSON data file on the RTAC’s file system. This path
must comply with the allowable characters specified
by enum_FilenameScheme.SEL_FILEIO_LOCAL
contained in the SELUtils library.
WriteInterval TIME The interval in which the class will periodically gen-
erate the managed JSON data file containing the
present values of all monitored variables.
LogRuntimeErrors BOOL Set to TRUE to log runtime errors to the SOE log.
Outputs
Name IEC 61131 Type Description
Error BOOL TRUE when class_PersistentData encounters an error.
ErrorDesc STRING(255) Errors encountered will be described here and will only be
displayed when Error is TRUE.
Initialized BOOL Asserts once the class has completed its first executions of
the Run() method on startup and restored any variable values
stored in the persistent JSON file.
bootstrap_Variable (Method)
Call this method to monitor a specified variable as part of the persistent JSON data file.
Only call this method once per monitored variable and before the first call to the Run() NOTE: Other applications within
the RTAC project that are referring to
method. Calls to this method after the first call to Run() are ignored. variables bootstrapped by this class
should wait until Initialized is asserted
before operating on those variables.
Inputs
Name IEC 61131 Type Description
pt_Variable POINTER TO BYTE Pointer to the variable to be persistently maintained as
evaluated by the ADR() function.
NumBytes UDINT Number of bytes required to store the variable as evalu-
ated by the SIZEOF() function.
DataName STRING(255) The unique name with which to identify this variable
value in the managed JSON data file. This name becomes
the ‘key’ in a collection of key-value pairs.
pt_Default POINTER TO BYTE Pointer to a variable containing the default state which
the data at pt_Variable are initialized to in the event that
DataName is not found in the persistent file at startup.
Must be the same variable type/size as that specified by
pt_Variable and NumBytes.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the variable was successfully added to persistent data
tracking.
Processing
If Error and Initialized are FALSE:
ä Checks that the pointer address specified by pt_Variable is a valid unique memory
address amongst all prior calls to bootstrap_Variable(). Returns FALSE if otherwise.
ä Checks that NumBytes is non-zero.
ä Checks that the string value specified by DataName is not empty and is unique
amongst all prior calls to all bootstrap methods. Returns FALSE if otherwise.
ä Checks that the pointer address specified by pt_Default is a valid memory address.
Returns FALSE if otherwise.
ä Stores the criteria specified by the four inputs into an internal dictionary structure
that is used to later parse and create the managed JSON data file.
ä bootstrap_Variable() returns TRUE after successfully adding the variable to its mon-
itored data points.
bootstrap_Variable() call returns FALSE if Error or Initialized is TRUE.
Run (Method)
Call the Run() method of the instantiated class on every scan to ensure that all variables are
correctly monitored and periodically written to the managed JSON data file. This method
should only be called after initially calling the bootstrap_Variable() method on startup to
define the monitored variables.
Processing
ä On calls to Run() until the Initialized output is asserted:
â Initiates a file read operation of the persistent JSON data file on the RTAC’s
file system.
â Passes through any Errors encountered by the file read operation to the Error
and ErrorDesc outputs.
â Waits for the file read operation to successfully complete and attempts to per-
form a JSON parse operation on the file content.
â Passes through any Errors encountered by the JSON parse operation to the
Error and ErrorDesc outputs.
â Iterates through the internal dictionary populated by the calls to the bootstrap_-
Variable() method and attempts to locate the keys found in this dictionary in
the parsed JSON content:
ã If a matching key is found, the data located at the memory address specified
by pt_Variable in the original bootstrap call is overwritten with the value
located in the parsed JSON data. The number of bytes that are overwrit-
ten at pt_Variable are determined by the NumBytes value in the original
bootstrap call.
ã If a matching key is not found, the data located at the memory address
specified by pt_Variable in the original bootstrap call are overwritten with
the data located at the address specified by pt_Default in the original boot-
strap call. The number of bytes that are overwritten at pt_Variable are
determined by the NumBytes value in the original bootstrap call.
â If no errors have been encountered, sets Initialized to TRUE.
ä On subsequent calls to Run():
â At a cyclic interval specified by WriteInterval:
ã Iterates through the internal dictionary populated by the calls to the boot-
strap_Variable() method and uses the DataName and raw byte data from
the content located at pt_Variable to create an internal JSON structure
represented by keys and ASCII-encoded values, respectively.
ã Once the internal JSON structure is successfully created, initializes a se-
quence to:
· Open the managed file contained on the RTAC’s file system.
· Serialize the internal JSON structure.
· Using Over-Write mode, write the serialized JSON content to the data
file.
· Close the managed data file.
ã Passes through any errors encountered by the JSON creation or file open/write/-
close operations to the Error and ErrorDesc outputs.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R136-V0 firmware
ä SEL-3530
â R136-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R136-V0 firmware
class_DirectoryListing
CreateNewList
The time necessary to request a new list when provided a 255-character path.
GetList
The time necessary to copy a list containing 10 file names.
Run
The time necessary to call Run() on each scan when there is directory work pending.
Idle
The time necessary to call Run() on each scan when there is no directory work pending.
class_EventListing
CreateNewList
The time necessary to request a new list when provided a 255-character path.
GetList
The time necessary to copy a list containing 10 file names.
Run
The time necessary to call Run() on each scan when there is directory work pending.
Run (Idle)
The time necessary to call Run() on each scan when there is no directory work pending.
class_FileWriter
AppendBytes
The time necessary to request 255 bytes be written via AppendBytes().
AppendVector
The time necessary to request 255 bytes be written via AppendVector().
AppendString
The time necessary to request 255 bytes be written via AppendString().
AppendSELString
The time necessary to request 255 bytes be written via AppendSELString().
Run
The time necessary to call Run() on the scan it switches from idle to work pending. This
tests how long it takes to request a copy of 255 characters when switching from idle state.
Run (Idle)
The time necessary to call Run() on each scan when there is no work pending.
class_FileReader2
ReadFile
The time necessary to request that a file with a 255-byte-long file name be opened via
ReadFile().
CopyTo
The time necessary to copy 255 bytes from the internal buffer via CopyTo().
AppendToVector
The time necessary to append 255 bytes from the internal buffer by using AppendToVector().
CopyToString
The time necessary to copy 255 bytes from the internal buffer via CopyToString().
AppendToSELString
The time necessary to append 255 bytes from the internal buffer by using AppendToSELString().
Run
The time necessary to call Run() on a class_FileReader2 on the scan it switches from work
pending to idle. This tests how long it takes to request a copy of 255 characters into the
internal buffer when switching to idle state.
Run (Idle)
The time necessary to call Run() on a class_FileReader each scan when there is no work
pending.
class_LogDirectoryManager
StartNewLog
The time necessary to call StartNewLog().
WriteLogEntryBytes
The time necessary to call WriteLogEntryBytes() with 255 bytes of input.
WriteLogEntryVector
The time necessary to call WriteLogEntryVector() with 255 bytes of content.
WriteLogEntryString
The time necessary to call WriteLogEntryString() with 255 characters of content.
WriteLogEntrySELString
The time necessary to call WriteLogEntrySELString() with 255 characters of content.
EventLogFromBytes
The time necessary to call EventLogFromBytes() with 255 bytes of input.
EventLogFromVector
The time necessary to call EventLogFromVector() with 255 bytes of input.
EventLogFromString
The time necessary to call EventLogFromString() with 255 bytes of input.
EventLogFromSELString
The time necessary to call EventLogFromSELString() with 255 bytes of input.
Run
The time necessary to call Run() with FTP configured.
class_DirectoryManager
StartNewFile
The time necessary to call StartNewLog().
WriteLogEntryBytes
The time necessary to call WriteLogEntryBytes() with 255 bytes of input.
WriteLogEntryVector
The time necessary to call WriteLogEntryVector() with 255 bytes of content.
WriteLogEntryString
The time necessary to call WriteLogEntryString() with 255 characters of content.
WriteLogEntrySELString
The time necessary to call WriteLogEntrySELString() with 255 characters of content.
EventLogFromBytes
The time necessary to call EventLogFromBytes() with 255 bytes of input.
EventLogFromVector
The time necessary to call EventLogFromVector() with 255 bytes of input.
EventLogFromString
The time necessary to call EventLogFromString() with 255 bytes of input.
EventLogFromSELString
The time necessary to call EventLogFromSELString() with 255 bytes of input.
Run
The time necessary to call Run() with FTP configured.
class_TimeBasedDirectoryManager
StartNewFile
The time necessary to call StartNewLog().
WriteLogEntryBytes
The time necessary to call WriteLogEntryBytes() with 255 bytes of input.
WriteLogEntryVector
The time necessary to call WriteLogEntryVector() with 255 bytes of content.
WriteLogEntryString
The time necessary to call WriteLogEntryString() with 255 characters of content.
WriteLogEntrySELString
The time necessary to call WriteLogEntrySELString() with 255 characters of content.
EventLogFromBytes
The time necessary to call EventLogFromBytes() with 255 bytes of input.
EventLogFromVector
The time necessary to call EventLogFromVector() with 255 bytes of input.
EventLogFromString
The time necessary to call EventLogFromString() with 255 bytes of input.
EventLogFromSELString
The time necessary to call EventLogFromSELString() with 255 bytes of input.
Run
The time necessary to call Run() with FTP configured.
fun_FtpDownload
The time necessary to request a file download when provided a 255-character path.
fun_FtpEventUpload
The time necessary to request an event upload when provided a 255-character path.
fun_FtpUpload
The time necessary to request a file upload when provided a 255-character path.
fun_DeleteFile
The time necessary to request a file delete when provided a 255-character path.
fun_FileSize
The time necessary to request a file size when provided a 255-character path.
fun_FilesystemFreeSpace
The time necessary to request the available free space on the system.
fun_SoeAscending
The time necessary to request a list of 10 SOE reports without a filter.
fun_SoeDescending
The time necessary to request a list of 10 SOE reports without a filter.
fun_SoeWindow
The time necessary to request a list of 10 SOE reports without a filter.
fun_LocalSoeGetID
The time necessary to request a list of 10 SOE reports without a filter.
fun_LocalSoeAscending
The time necessary to request a list of 10 SOE reports without a filter.
fun_LocalSoeDescending
The time necessary to request a list of 10 SOE reports without a filter.
fun_RemoteSoeGetID
The time necessary to request a list of 10 SOE reports without a filter.
fun_RemoteSoeAscending
The time necessary to request a list of 10 SOE reports without a filter.
fun_RemoteSoeDescending
The time necessary to request a list of 10 SOE reports without a filter.
Benchmark Results
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that a user-specified IEC 61131 function called fun_StringDifferent
provides functionality similar to that in Code Snippet 16.2.
FOR i := 0 TO c_maxStringSize - 1 DO
IF (0 = str1[i]) AND (0 = str2[i]) THEN
// Found null terminator on both strings at the same time.
EXIT;
ELSIF str1[i] <> str2[i] THEN
differenceFound := TRUE;
EXIT;
END_IF
END_FOR
(* Return True if difference found *)
fun_StringsDifferent := differenceFound;
Solution
Because we assume that a simple string comparison function exists, we can write out the
contents of a string to a file every time it changes by using just a few lines of code, as in
Code Snippet 16.3.
Assumptions
The file “/FileToRead.txt” exists in the root of the RTAC public file system.
Solution
The file is read into an internal buffer and then copied into an empty user-supplied byte
array using the program in Code Snippet 16.4.
IF FirstScan THEN
//Initiate the File Read.
FileReader.ReadFile(Filename);
FirstScan := FALSE;
ELSIF 0 < FileReader.BytesInBuffer AND NOT Copied THEN
FileReader.CopyTo(startByte := 0,
pt_byte := ADR(TheByteArray),
numBytes := c_ByteArraySize);
Copied := TRUE;
END_IF
FileReader.Run(); // Run this every scan regardless.
Assumptions
1. You have included the DynamicVectors library in your project.
2. The file “/FileToRead.txt” exists in the root of the RTAC public file system.
Solution
The file will first be read into an internal buffer and then copied into an empty user-supplied
class_ByteVector using the program in Code Snippet 16.5.
IF FirstScan THEN
//Initiate the File Read.
FileReader.ReadFile(Filename);
FirstScan := FALSE;
ELSIF 0 < FileReader.BytesInBuffer AND NOT Copied THEN
FileReader.AppendToVector(startByte := 0, vector := TheByteVector);
Copied := TRUE;
END_IF
FileReader.Run(); // Run this every scan regardless.
Assumptions
The file “/FileToRead.txt” exists in the root of the RTAC File Manager.
Solution
The file will first be read into an internal buffer and then it will be copied into an empty
user-supplied strings using the program in Code Snippet 16.6.
IF FirstScan THEN
//Initiate the File Read.
FileReader.ReadFile(Filename);
FirstScan := FALSE;
ELSIF 0 < FileReader.BytesInBuffer AND NOT Copied THEN
FOR stringIter := 1 TO c_NumStringsInArray DO
IF bufferTracker <= FileReader.BytesInBuffer THEN
FileReader.CopyToString(startByte := bufferTracker,
str := TheStringArray[stringIter]);
ELSE
// All of the file contents has been copied into strings.
EXIT;
END_IF
bufferTracker := bufferTracker + c_StringSize;
END_FOR
Copied := TRUE;
END_IF
FileReader.Run(); // Run this every scan regardless.
Assumptions
1. You have included the SELString and DynamicVectors libraries in your project.
NOTE: See the SELString library
2. The RTAC database contains events collected from the desired relays. documentation for more information
about class_SELStrings and
class_SELStringLists.
Solution
You can locate qualifying files using a class_EventListing. Then you can select one as in
Code Snippet 16.7.
Assumptions
1. You have included the SELString and DynamicVectors libraries in your project.
NOTE: See the SELString library
2. Collected events from the desired relays exist in the RTAC database. documentation for more information
about class_SELStrings and
class_SELStringLists.
Solution
You can locate qualifying files using a class_EventListing. Then you can select one as in
Code Snippet 16.8.
Assumptions
1. An FTP server is set up, configured, and accessible by the RTAC over the network.
2. The FTP server configuration is as follows:
ä IP address: 192.168.0.2
ä Username: FTPUSER
ä Password: TAIL
3. The file “FileToFtp.csv” exists in the root of the FTP server file system.
Solution
First, you must get the file from the remote server by performing an FTP download using
code similar to that shown in Code Snippet 16.9.
Then you can manipulate the file at will. For example, you could read the file into an
internal buffer, then copy it into an empty user-supplied class_ByteVector by using the
program shown previously in Code Snippet 16.5.
Assumptions
1. An FTP server is set up, configured, and accessible by the RTAC over the network.
2. The FTP server configuration is as follows:
ä IP address: 192.168.0.2
ä Username: FTPUSER
ä Password: TAIL
3. The file “FileToSend.csv” exists in the root of the RTAC File Manager.
Solution
Get the file onto the remote server by performing an FTP upload.
CurrentStatus := UploadStatus;
IF FirstScan THEN
//Initiate the FTP write.
FileIo.sel_ftp_client.ftp_upload(
ftp_server := FtpServerIP,
local_path := LocalFileToSend,
remote_path := FileNameForFtpServer,
username := FtpServerUsername,
password := FtpServerPassword,
timeout := Timeout,
status := UploadStatus); // This is passed in as a VAR_IN_OUT
(* Note, making this call will cause the upload status to be initialized
to 'IN_PROGRESS'*)
FirstScan := FALSE;
Assumptions
1. A user-programmed application is writing files to a designated folder, Dir1, on the
RTAC file system by using FileIO class_FileWriter.
2. A Global Variable List, GVL1, has been defined to contain variables pertinent to
error tracking activities for the application. This example GVL is shown in Code
Snippet 16.11.
3. The user-programmed application populates the variables in GVL1.
Solution
Instantiate a class_BasicDirectoryManager to fulfill the stated directory management ob-
jectives. Also use class_FileWriter to generate a persistent error log file. Recall that class_-
BasicDirectoryManager ignores files with file names beginning with a period (.).
Assumptions
There exist some set of inputs and outputs to the work being done. Here these are delineated
by adding the prefix g_, indicating that they exist in a GVL as shown in Code Snippet 16.13.
g_OutputOne : BOOL;
g_OutputTwo : BOOL;
END_VAR
Solution
You can instantiate a class_LogDirectoryManager to manage rotation of the logs you want.
IF g_TriggerOne THEN
WorkspaceString := CONCAT( 'Trigger One received with a input voltage
of ',
REAL_TO_STRING(g_workingVoltage));
LogManager.WriteLogEntryString(WorkspaceString);
END_IF
IF g_TriggerTwo THEN
WorkspaceString := CONCAT( 'Trigger Two received with a input current
of ',
REAL_TO_STRING(g_workingCurrent));
LogManager.WriteLogEntryString(WorkspaceString);
END_IF
(*At this point the user calls the application doing work so the outputs
update.*)
IF g_OutputOne THEN
LogManager.WriteLogEntryString('Action One requested');
END_IF
IF g_OutputTwo THEN
LogManager.WriteLogEntryString('Action Two requested');
END_IF
LogManager.Run();
Solution
You can instantiate a class_LogDirectoryManager to manage rotation of the logs you want.
To do this, you must track the time and issue StartNewLog() on the eight-hour shift
boundaries.
PresentTime : timestamp_t;
TimeOfDay : TIME_OF_DAY;
PreviousHours : UDINT;
PresentHours : UDINT;
END_VAR
PreviousHours := PresentHours;
//Divide by 1000 to remove milliseconds and 3600 to remove seconds and
minutes.
PresentHours := TOD_TO_UDINT(TimeOfDay)/3600000;
IF FirstScan THEN
PreviousHours := PresentHours;
FirstScan := FALSE;
END_IF
LogManager.Run();
Assumptions
1. An FTP server is set up, configured, and accessible by the RTAC over the network.
2. The FTP server configuration is as follows:
ä IP address: 192.168.0.2
ä Username: FTPUSER
ä Password: TAIL
3. There are external variables g_EventOccurred and g_EventDescription, driven by
other code, that cause an event to be populated and sent.
4. There exists some set of inputs and outputs for the work being done. Here these are
delineated by adding the prefix g_, indicating that they exist in a GVL as shown in
Code Snippet 16.16.
Solution
You can instantiate a class_LogDirectoryManager to accept the data for transmission and
to manage the storage required to facilitate the transaction.
IF FirstScan THEN
LogManager.SetFtpServerForArchiving( ftpServer := ServerIP,
remotePath := RemotePath,
username := FtpUser,
password := FtpPassword,
timeout := 5,
schedule := ON_UPDATE);
FirstScan := FALSE;
END_IF
IF g_EventOccurred THEN
LogManager.EventLogFromString( str := g_EventDescription,
eventPostfix := EventPostfix);
g_EventOccurred := FALSE;
END_IF
LogManager.Run();
Assumptions
Your workload requires assurances that every SOE is seen and that duplication of responses
to SOEs is unacceptable. In this use case, the order of the events matters less than ensuring
that each event is seen and addressed. For this method to work, the SOEs must either be
all from the local RTAC or from external devices being logged on the RTAC. If both types
of SOEs exist, they would need to be handled independently.
Solution
You periodically query the system for the next c_MaxSoeCount SOEs that have not yet
been addressed.
// Input Filters
StartTime : DT := DT#2000-1-1-0:0:0;
Filters : FileIo.sel_file.Struct_soe_filter;
IF GetFirstSOE THEN
// We need to get a starting SOE.
IF NOT SoeQueried THEN
FileIo.fun_LocalSoeGetID(StartTime, Filters, Status, Content[1]);
SoeQueried := TRUE;
ELSE
IF Status = FileIo.sel_file.SYSTEM_BUSY THEN
// The system was too busy try again.
SoeQueried := FALSE;
ELSIF Status = FileIo.sel_file.NO_ERROR THEN
// We got a result, switch to group queries
GetFirstSoe := FALSE;
SoeQueried := FALSE;
LastOutput := Content[1];
StartTime := Content[1].TimeStamp;
// This function only ever returns one result.
Count := 1;
// Trigger processing for the SOE data returned
DoWork := TRUE;
ELSIF Status = FileIo.sel_file.OPERATION_FAILED THEN
;(* The database was unable to find any SOEs matching the
filters provided. *)
ELSIF Status <> FileIo.sel_file.IN_PROGRESS THEN
;(* If we arrive here configuration is bad and needs to be
manually adjusted to continue. *)
END_IF
END_IF
ELSE
IF NOT SoeQueried THEN
// Beginning from the last SOE received, query for the next set of
SOEs.
FileIo.fun_LocalSoeAscending( ADR(content[1]), LastOutput.ID,
c_MaxSoeCount,
Filters, Status, Count);
SoeQueried := TRUE;
ELSE
IF Status = FileIo.sel_file.SYSTEM_BUSY THEN
// The system was too busy try again.
SoeQueried := FALSE;
ELSIF Status = FileIo.sel_file.NO_ERROR THEN
DoWork := Count > 0;
SoeQueried := FALSE;
IF DoWork THEN
// Store next lookup information if there is any.
LastOutput := Content[Count];
StartTime := Content[Count].TimeStamp;
END_IF
ELSIF Status <> FileIo.sel_file.IN_PROGRESS THEN
(* If we arrive here configuration is probably OK, as we got
results above.
Something probably affected the ID we were using. Start
over. *)
SoeQueried := FALSE;
GetFirstSOE := TRUE;
END_IF
END_IF
END_IF
IF DoWork THEN
// Process any new data.
FOR i := 1 TO Count DO
;(* Insert your code here to do work on the SOEs encountered. *)
END_FOR
DoWork := FALSE;
END_IF
Assumptions
You have some code for presenting or communicating the SOE content at some other loca-
tion. In this use case, the order of events is more important than hard guarantees of seeing
each event occur.
Solution
You periodically query the system for the most recent SOE data.
Timestamp : timestamp_t;
Now : DT;
Last : DT;
// Flag indicating that SOE data has been requested and not copied.
Running : BOOL := FALSE;
i : UDINT;
END_VAR
Timestamp := Sys_Time();
Now := Timestamp.value.dateTime;
Assumptions
The directory content to be listed is uploaded.
Solution
Create the file list using the FileIo.class_DirectoryListing, and write that content into an
array to make it easier to see.
CASE Stage OF
1: // Clear from last run, and request a new list
DirList.Clear();
FOR i := 1 TO c_MaxFilesToList DO
ArrayList[i] := ''; // Empty the array
END_FOR
Lister.CreateNewList(directoryName := '/TestDirectory',
filter := '');
Stage := Stage + 1;
2: // Wait until done
IF Lister.NewListReady THEN
Lister.GetList(DirList);
// Read the list into the array
DirList.Begin(); // Start at the beginning of the list
FOR i := 1 TO DirList.Size DO
IF (i > c_MaxFilesToList) THEN
EXIT; // No more room in the array
END_IF
pt_SelStr := DirList.Next();
IF 0 <> pt_SelStr THEN // Always check pointers aren't 0
ArrayList[i] := pt_SelStr^.ToString();
END_IF
END_FOR
Stage := 0; // Reset to start
END_IF
ELSE
; // Do nothing
END_CASE
Lister.Run(); // Always run the worker method
Assumptions
An SEL-2245-42 with device name of CTPTModule is included in the Axion backplane.
Solution
Read event data into the RTAC’s logic engine using the FileIo.class_ComtradeReader, and
write one channel’s content into an array.
Error : BOOL;
ErrorMessage : STRING := '';
END_VAR
END_IF
EVENT1.Run();
Solution
Use FileIo.class_PersistentData, to monitor and restore a collection of user logic variables.
MyStoredData.Run();
Upon initial loading of this program onto an RTAC, the values of the 3 simple variable types
specified as aBoolVariable, aRealVariable and aStringVariable are "FALSE", "1.234" and
"default string contents" respectively. The aSPSVariable contains a default SPS structure
with a timestamp initialized to the RTAC startup time. If the values in those variables later
update and the RTAC is subsequently restarted, the updated values stored in the managed
JSON file will be restored.
GridConnect
Introduction
The GridConnect library is designed for use with the SEL Real-Time Automation Con-
troller (RTAC) family of products. It contains ready-to-use function blocks for controlling
the point of common coupling (PCC) between the utility grid and a solar power generation
resource. The GridConnect library uses proportional integral (PI) controllers when in a
closed-loop mode to regulate output set points.
Overview
The GridConnect library contains the following four function blocks:
ä fb_MasterPlantController: Regulates PCC between the utility and the solar facility.
ä fb_PvInverter: Interfaces with a photovoltaic inverter.
ä fb_StorageInverter: Interfaces with a battery storage inverter.
ä fb_Capacitor: Interfaces with a capacitor.
The user must map all necessary input/output (I/O) signals to interface the function blocks
to their various pieces of external equipment, but the GridConnect library automates all
data exchange between the function blocks themselves.
Feature Summary
This library contains the following features for PCC of a solar facility to the utility grid.
Additional Features
ä PCC voltage limit override when in power factor or reactive power control or com-
pensation modes
ä PCC power factor limit override when in voltage control or compensation modes
ä Integrated control of PV inverters, storage inverters, and capacitors to provide precise
control at the PCC
ä Solar Smoothing integrates storage assets with PV assets to maintain ramp rates for
increasing or decreasing PV power output.
ä Automated charging of storage assets.
Licensing
GridConnect versions 3.5.3.X and later support two license tiers. The two licenses will
show up on the RTACs web interface with the following strings.
ä GridConnect_5MW: This license supports managing systems up to 5MW. This is
determined by adding up the PRating input of each manager asset. This includes
all inverter and storage function blocks. If the total capacity of power system assets
starts below 5MW, then increases above 5MW GridConnect will disable and will not
re-enable until the RTAC has been power cycled. All features are supported with this
license.
ä GridConnect: This license has no restrictions on features or power managed.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myGridConnectObjectObject.value;
// As is this
pt_myGridConnectObjectObject := ADR(myGridConnectObjectObject);
Operational Modes
Overview
The master plant controller (hereafter referred to as the Controller) is operated in several
different control modes, each having the objective of controlling or compensating power
factor, reactive power, or voltage. The desired mode is provided as an input on the fb_-
MasterPlantController function block. The controller is enabled by asserting the Enable
input and is disabled by deasserting the Enable input. Top-level mode and enable/disable
control inputs are described in Table 17.1.
When the controller is in open-loop power factor control mode it passes the power factor
set point to the power factor reference for all inverters in the facility. This mode is used as
a fall-back mode (when PCC measurements are not reliable).
In closed-loop mode, the controller automatically adjusts either the power, power factor, or
VAR reference signal of the inverter to perform control or compensation at the PCC.
The controller automatically adjusts the power limit reference signal of the inverters to limit
the cumulative power output of the plant.
ä PlantLowPowerCutoff
The following settings tell GridConnect the mode in which it will operate for four primary
categories: real power management, reactive power management, coordination with any
configured storage assets, and frequency regulation. GridConnect can operate in one real
power mode and one reactive power mode at a time. Please note that some real power
management modes are not compatible with all StorageOperationMode inputs and will
override StorageOperationMode. Frequency regulation is supported for the following real
power modes:
ä PLimitMode
ä ControlMode
ä StorageOperationMode
ä FrequencyRegulationMode
The following inputs are used to manage the operation of GridConnect to drive the set
points configured by the user in the active control modes. All of these settings must be set
to appropriate values during the operation of the system.
ä Enable
ä PlantP
ä PlantQ
ä PlantPF
ä PlantV
ä PlantF
ä PlantMeasurementsGood
ä EvaluationPeriod
ä ControlRetryPeriod
ä InverterModeChangeControlDelay
Evaluation Period
The EvaluationPeriod setting manages how often GridConnect generates new set points
for inverters to implement. SEL recommends that this be set to a minimum value of 105
percent of the update rate from the PCC. If inverters do not respond quickly to set points,
a larger evaluation period may be necessary. Many of the modes in GridConnect use a PI
controller to calculate set points. Just like any PI controller, if it runs more frequently than
the data update or faster than the system can respond, the controller will accumulate errors,
which is likely to generate undesirable set points.
For an EvaluationPeriod of one second, this would translate to multiplying the error by
one in calculating the IntegralTerm. Tuning of the PI controller is the responsibility of the
end user. Starting in GridConnect version 3.5.4.3, there are POU output pins on the fb_-
masterPlantController that show the error and integral terms for each PI controller that is
active in GridConnect.
The feedback signal, which is used in all PI controllers, comes from the PCC measurements
(i.e., PlantP, PlantQ, PlantV, PlantPF, or PlantF).
If PlantP is outside the deadband of Psetpoint then all inverters are driven proportionally
as quickly as possible to the deadband of Psetpoint. This may cause some over or under-
shoot during this transition. Ensuring that PowerClampMarginPercent is configured such
that the difference between PLimitSetMag and InverterP is less than the deadband around
PSetpoint will ensure a smooth transition after an inverter leaves power clamp mode. For
example if PowerClampMarginPercent is 3 percent, an inverter has PRating of 1000 and
current inverterP is 100, and Pdeadband is 50. These settings would mean the single in-
verter would have a PLimitSetmag of 130 when InverterP is 100 during power clamp. This
is less than the Pdeadband of 50 making it likely that as that inverter leaves power clamp
mode initially it will keep the system within the deadband of PlantP. Ultimately, this will
allow GridConnect’s smoothing function to return all inverters to a proportional setpoint.
If there are multiple inverters which may be in power clamp mode in this example scenario
it is important to consider the probability of all power clamped inverters returning to nor-
mal operation simultaneously. The inverter makes small adjustments in order to return to a
proportional deadband, the adjustment amount can be configured per inverter by the setting
ContinuityAdjustment. This setting adjusts the PlimitSetmag of the inverter by a percent-
age of the inverters PRating. By default this is set to 0.25 percent, for most systems this
will be a slow rate of change, but will help ensure a smooth transition. This value can be
configured to increase the rate at which the inverter returns to a proportional PLimitSetMag
but should not be increased such that it causes PlantP to exceed Pdeadband of Psetpoint.
Control Modes
The GridConnect library supports a variety of control modes. This section provides details
about the following modes: no reactive control, power factor, voltage, VAR, and open-
loop power factor. The remaining two modes are compensation modes and are detailed in
Compensation Modes on page 17.11.
No Reactive Control
When the controller is in no reactive control mode, it will not send any VAR or power factor
set points to the inverter. In addition, it will not change the operating mode of the inverter.
Any current set points on the inverter function block outputs will be left as is. The trigger
bits for VAR or power factor set points will not assert while this mode is active.
ä PFRampSetpoint
Once PlantPF is within the range of PFSetpoint +/- PFDeadband, the error and integral of
the closed control loop managing power factor will be set to zero. Inverter set points for
power factor will remain steady until PlantPF is outside the deadband around PFSetpoint.
See the following model diagram for operation of power factor control in the time and
frequency domains.
VAR Control
When the controller is in VAR control mode, it adjusts the VAR reference of the inverter to
provide precise adjustment of VAR flow at the PCC. The controller uses a PI controller for
these adjustments. For this mode to function properly, the inverter must be in VAR control
mode (as opposed to power factor control mode). If the inverter is not in VAR control
mode, the controller will periodically attempt to send a mode change control. The inverter
is considered unavailable to the master controller if it is unable to change modes.
See the following model diagram for operation of VAR control in the time and frequency
domains.
Voltage Control
When the controller is in voltage control mode, it adjusts the VAR reference of the inverter
to provide precise adjustment of the voltage magnitude at the PCC. The controller uses
a PI controller for these adjustments, and separate tuning parameters (VKp and VKi) are
provided for this mode. For this mode to function properly, the inverter must be in VAR
control mode (as opposed to power factor control mode). If the inverter is not in VAR
control mode, the controller will periodically attempt to send a mode change control. The
inverter will be considered unavailable to the master controller if it is unable to change
modes.
It is important that PlantV is within the range of VLimitHigh and VLimitLow. If it is
not, the max and min Q at the voltage limits will be significantly distorted, causing non-
functional set points. The min and max Q values at the voltage limits are identified on
output pins CalculatedQAtVHighLimit and CalculatedQAtVLowLimit. These Q limits
are defined by the following equations.
CalculatedQAtVHighLimit := PlantQ + ((VLimitHigh - PlantV) / ConditionedDVDQ);
CalculatedQAtVLowLimit := PlantQ - ((PlantV - VLimitLow) / ConditionedDVDQ);
GridConnect also checks that QSetpoint calculated for voltage control does not exceed the
ranges of Q at the PCC at the defined lead and lag limits for power factor. This is reflected
in the output pins CalculatedQAtPFLeadLimit and CalculatedQAtPFLagLimit.
The input setting dV_dQ is the relationship between voltage and reactive power. It is the
ratio of one voltage change over the number of VARs needed to cause that voltage change.
Voltage set points at the PCC given to GridConnect are translated to VAR set points dis-
tributed to inverters. Because the control loop is driving VARs to a target value to achieve
a voltage set point, the voltage deadband is converted to a VAR deadband. The QDeadband
in Voltage control mode is VDeadband/dV_dQ.
The QSetpoint achieved at the PCC is determined by the following equation:
Voltage QSetpoint := PlantQ + (VSetpoint - PlantV) / dV_dQ;
The input dV_dQ heavily influences the voltage control management. Having this input
match system performance allows the voltage set point to be reached faster with a smoother
response. If this input does not match the voltage-to-reactive-power-change ratio, the PI
controller in most cases correctly drives the system to the voltage set point. If the configured
dV_dQ is significantly different than the actual volt/VAR relationship in this system, the
resulting plant voltage may be outside of the configured voltage deadband. This is because
the voltage deadband is translated to a QDeadband in which dV_dQ is an important factor.
The following logic diagram shows the process for generating a QSetpoint from a VSetpoint
input modeled in both the time and frequency domains.
Settings on the fb_masterplantcontroller that affect voltage control are the following:
ä VSetpoint
ä VDeadband
ä VKp
ä VKi
ä dV_dQ
ä QRampSetpoint
Compensation Modes
The GridConnect library supports both power factor and voltage compensation. These
modes regulate the controlled value (power factor or voltage) in a response proportional to
the percentage of plant output power or voltage.
Voltage Compensation
When the controller is in voltage compensation mode, it regulates VAR flow at the PCC
based on voltage at the PCC. This mode uses the same PI controller tuning parameters as
the Voltage Control mode. In this mode the plant can provide VAR support for grid voltage,
even at night or when real power output is otherwise very low. The relationship between
VAR output and voltage magnitude follows a curve defined by voltage and VAR set points
(as illustrated in Figure 17.4. These inputs can be adjusted at any time, which will change
the curve being used by the controller for voltage compensation. If these inputs are made
variable, it is important to ensure that they have correct and intended values at all times,
including at controller startup.
V1,Q1
V3,Q3
V
V2,Q2
V4,Q4
This mode requires that the inverters be in VAR control mode. Any inverter not in VAR
control mode is flagged as unavailable to the master controller and is periodically sent a
mode change control signal.
The following settings are used to manage Voltage Compensation Mode:
ä VCompensationV1
ä VCompensationV2
ä VCompensationV3
ä VCompensationV4
ä VCompensationQ1
ä VCompensationQ2
ä VCompensationQ3
ä VCompensationQ4
ä VKp
ä VKi
ä QRampSetpoint
ä VDeadband
The following logic diagram shows the process for generating a QSetpoint from the voltage
compensation mode modeled in both the time and frequency domains.
Capacitor Control
The master controller calculates the reactive power required to achieve the active control
objective (i.e., VAR, voltage, or power factor at the PCC). Additionally, the master con-
troller calculates the reactive power available to be added or removed using inverters and
capacitors. Generally, the capacitors will operate to improve the power factor of the in-
verters that GridConnect manages. If inverters collectively output more than the setting,
CapacitorOperatePercent(default is 75), which is a percentage of the next capacitor rating
selected to operate for a time duration that exceeds the setting CapacitorPickUpTime, the
capacitor will close (as long as the CapacitorOperationPeriod interval is not violated). In
this manner, the master controller will attempt to use capacitors to make coarse control ad-
justments at the PCC, and use the inverters to reach and maintain fine control at the PCC.
This functionality is demonstrated by the equation below.
Total Inverter Q >= Next Capacitor Q Rating * CapacitorOperationPeriod
Capacitor banks will open when collective inverter Q output is less than Q’s to be removed
by the next capacitor block. This functionality is demonstrated by the equation below.
Total Inverter Q <= Next Capacitor Q Rating * CapacitorOperationPeriod
Capacitors will turn close in on the sequence defined by the input pin SequenceNumber of
each capacitor. The last capacitor to close in will be the first capacitor to open.
The following settings are used to manage capacitor operation on the fb_masterplantCon-
troller:
ä CapacitorOperationPeriod
ä CapacitorOperatePercent
ä CapacitorPickUpTime
ä CapacitorDropOutTime
function block. Once a storage inverter has reached this value, the charging power for
that storage inverter will be allocated to other storage inverters that have not reached
their MaxStateOfCharge. While this value is non-zero value all storage assets will
be unavailable for participation in GridConnect operations.
ä AutomaticStorageCharging on the master plant controller is a Boolean input that will
tell GridConnect to manage charging storage assets. When this Boolean is true, Grid-
Connect will charge storage assets up to the ReferenceSOC with the defined PVOut-
putChargeMargin, which takes a percentage of current PV power output and charge
storage assets. Once the storage asset SOC reaches the ReferenceSOC the storage
asset will be returned to GridConnect for control again. Storage inverter charging
will not occur until storage asset SOC is a certain percentage below ReferenceSOC.
This percentage is defined by the setting ReferenceSOCRange. Once this condition
occurs GridConnect will charge the storage asset to ReferenceSOC. If GridConnect
encounters a situation that requires downramp control all storage inverters will stop
charging and then participate in downramp control. If GridConnect was charging
storage assets, and then needs to suspend charging due to another system condition
then charging storage assets will resume after SOC falls below ReferenceSOCRange
of ReferenceSOC again.
The master plant controller function block has an input pin called StorageOperationMode.
This input pin has several modes that define how storage inverters will participate in power
plant control. The following modes are supported.
ä Manual Storage Operation: Storage assets will not participate in aggregate control
via PCC power set points. Storage assets will receive one power set point per storage
inverter function block. The storage asset will receive the set point configured on
the input pin provided it is within the bounds of SOC management and the storage
asset has the SOC level to provide the amount of power dictated by the set point.
In NoLimitPower and SimplePowerMode real power modes, the power the storage
asset produces will be in addition to the power set point on the master plant controller.
The total real power output of GridConnect at the PCC will be master plant controller
power set point + each storage inverter PstorageSetpoint. In advanced power mode,
the PI controller will adjust the PV inverter output so that the combination of the PV
and storage inverter outputs matches the master plant controller power set point.
ä Downramp Control: Storage assets will only be used to discharge energy to the PCC
in order to maintain the PCC real power ramp rate as photovoltaic (PV) power output
decreases.
ä Storage Generation: Storage assets will be included to meet the PCC set point. Each
storage inverter will receive a proportional set point to meet the PCC set point. SEL
recommends using this mode when the system only contains storage assets.
do so until the PCC is able to achieve the PCC PSetpoint without storage asset assistance
for the time period defined by ConstantPowerDropOutTime, or until there is insufficient
charge in the storage assets to maintain PSetpoint. If storage asset assistance is no longer
needed but not maintained for the duration of ConstantPowerDropOutTime, storage asset
assistance will begin without waiting for the duration of ConstantPowerPickupTime. Once
storage asset assistance is no longer needed and the duration of ConstantPowerDropOut-
Time occurs, the input condition to start storage asset assistance will need to wait for the
time defined by ConstantPowerPickupTime.
When GridConnect is in Constant PCC Power Limit mode, the StorageOperationMode
input will be ignored. The output pin ConditionedStorageOperationMode will be set to
ManagedByGridConnect, indicating that PStorageSetPoint on the storage inverter will not
be processed. Additional power can be drawn from all storage assets proportionally using
AdditionalStorageDischargeSetPoint pin on the master plant controller. If StorageCharge-
Setpoint is used on the master plant controller to charge storage assets, storage assets will
not be available to discharge while charging is occurring.
If the real power mode(PLimitMode) is changed to another value, any active storage dis-
charge for constant power mode will be set to zero. When real power mode is changed back
to Consant PCC Power limit mode the duration of ConstantPowerPickupTime will need to
occur before power is discharged from storage assets again.
A logic diagram for the constant power limit mode is shown below.
The following settings are used to manage Constant PCC Power mode:
ä PSetpoint
ä PDeadband
ä PKp
ä PKi
ä PLimitRampSetpoint
ä PLimitDelay
ä PowerClampMarginPercent
ä AdditionalStorageDischargeSetPoint
ä ConstantPowerPickupTime
ä ConstantPowerDropOutTime
Frequency Regulation
The following settings determine how the controller performs frequency regulation. It is
able to do so using either the non-storage generation assets (general PV plant output) or
by using storage devices. Frequency regulation is performed according to a curve defined
by inputs on the Master Plant Controller. These inputs can be adjusted at any time, which
will change the curve being used by the controller for frequency regulation. If these inputs
are made variable, it is important to ensure that they have correct and intended values at
all times, including at controller startup. These inputs are described in Table 17.2 and
Figure 17.8.
F1, P1
F3, P3
F
F2, P2
F4, Q4
Disabled
When Frequency Regulation is disabled, the controller does not perform any adjustment
of real power set points in response to frequency input.
Plant
When Frequency Regulation is in Plant mode, the controller uses any available capacity
in configured non-storage generation devices to perform frequency regulation. The output
adjustment of these non-storage devices is changed at a rate according to the EvaluationIn-
terval setting on the controller in accordance with the PLimitRampSetpoint setting. This
mode uses the plant’s non-storage generation devices. If an increase in power output is
desired in response to a frequency event, some margin must be left (the plant needs to be
run at less than maximum capacity) proportional to the slope of the frequency regulation
curve and the expected severity of frequency events.
HighSpeedStorage
When Frequency Regulation is in HighSpeedStorage mode, the controller uses any avail-
able capacity in configured storage devices to perform frequency regulation. The output
of these storage devices is adjusted every RTAC task cycle, which allows this feature to
quickly react to changes in frequency using stored energy. This mode does not apply any
ramp rate control to the set point delivered to storage devices.
Enumerations
Enumerations make code more readable by allowing a specific number to have a text equiv-
alent. Either the raw integer value can be assigned to a value that requires an enumeration
or the text of the enumeration itself can be assigned. When viewing the values online, the
enumeration text is displayed instead of the integer value.
enum_ReactiveControlMode
This enumeration is used to set and indicate the desired reactive power control mode of the
Master Plant Controller.
enum_PLimitMode
This enumeration is used to set and indicate the real power control mode of the Master
Plant Controller.
enum_FrequencyRegulationMode
This enumeration is used to set and indicate the frequency regulation mode of the Master
Plant Controller.
Function Blocks
The library contains the function blocks required to build a GridConnect control system.
Inputs
Name IEC 61131 Type Description
ControlMode enum_ReactiveControlMode PCC control mode. Default is OpenLoopPFCon-
trol. For more information see Enumerations on
page 17.21.
StorageOperationMode enum_StorageOperation Operation mode storage inverters will operate in. De-
fault is ManualStorage. For more information see
Enumerations on page 17.21.
Frequency- enum_FrequencyRegulationMode Frequency Regulation mode. Default is Disabled. For
RegulationMode more information see Enumerations on page 17.21.
Enable BOOL PCC control enable. Default is FALSE.
QuickStop BOOL Stop signal. Sets power and Q output set points to
zero, disregarding ramp rates on all inverters. Dis-
ables master controller. This signal will go through
to connected inverters even if the master controller is
already disabled.
PlantP REAL PCC real power measurement. Units are kW. Default
is 0. (Positive values = flow from plant to grid.)
PlantQ REAL PCC reactive power measurement. Units are kVAR.
Default is 0. (Positive values = flow from plant to grid)
PlantPF REAL PCC power factor measurement. Default is 1. Units
are PF. (Positive values = lagging, negative values =
leading.)
PlantV REAL PCC voltage measurement. Units are kV. Default is 1.
PlantF REAL PCC frequency. Units are in Hz. Default is 60.
PlantMeasurementsGood BOOL PCC measurement quality indication. Default is
FALSE.
QSetpoint REAL PCC reactive power control set point. Units are kVAR.
Default is 0.
QDeadband REAL PCC reactive power control deadband. Units are
kVAR. Default is 250.
QKp REAL Proportional tuning parameter for VAR control. De-
fault is 1.
QKi REAL Integral tuning parameter for VAR control. Default is
0.
QLimitHigh REAL Reactive power high limit
QLimitLow REAL Reactive power low limit
PFSetpoint REAL PCC power factor control set point. Units are PF. De-
fault is 1. (Positive values = lagging, negative values
= leading)
PFDeadband REAL PCC power factor control deadband. Units are PF. De-
fault is 0.0002.
PFKp REAL Proportional tuning parameter for power factor con-
trol. Default is 1.
PFKi REAL Integral tuning parameter for power factor control.
Default is 0.
Outputs
Name IEC 61131 Type Description
ConnectToPlantDevices POINTER Connect to all plant devices.
Enabled BOOL Master controller is enabled.
QuickStopAsserted BOOL QuickStop input pin is asserted.
PFControlMode BOOL Master controller is in power factor control mode.
QControlMode BOOL Master controller is in reactive power control mode.
PFCompensationMode BOOL Master controller is in power factor compensation mode.
VCompensationMode BOOL Master controller is in voltage compensation mode.
VControlMode BOOL Master controller is in voltage control mode.
OpenLoopPFCon- BOOL Master controller is in open-loop power factor control
trolMode mode.
NoLimitPControl BOOL Master controller is in NoLimit power control mode.
SimplePControl BOOL Master controller is in Simple power control mode.
AdvancedPControl BOOL Master controller is in Advanced power control mode.
PlantFRegulationEnabled BOOL Plant frequency regulation mode is enabled.
StorageFRegulationEn- BOOL High-speed storage frequency regulation mode is en-
abled abled.
PFOutOfBand BOOL Power factor at the PCC is outside the deadband.
QOutOfBand BOOL VAR flow at the PCC is outside the deadband.
VOutOfBand BOOL Voltage at the PCC is outside the deadband.
PFLagAlarm BOOL Power factor lagging beyond the limit at the PCC (gener-
ating more kVAR).
PFLeadAlarm BOOL Power factor leading beyond the limit at the PCC (con-
suming more kVAR).
VHighAlarm BOOL Voltage above the high limit at the PCC.
Inputs
Name IEC 61131 Type Description
ConnectToMasterController POINTER Connect this input to a master controller instance.
Offline BOOL Communications channel to the inverter control device is offline (1
= Offline). Default is FALSE.
RemoteEnabled BOOL Inverter control device is available to remote master control. Default
is FALSE.
Fault BOOL Inverter control device is reporting a fault. Default is FALSE.
OnStatus BOOL On/off status of the inverter. Default is FALSE.
OnCommandInput BOOL Command to turn on the inverter control device. Default is FALSE.
OffCommandInput BOOL Command to turn off the inverter control device. Default is FALSE.
Include BOOL Latch to include inverter in the master control. Default is FALSE.
Exclude BOOL Latch to remove inverter from the control. Default is FALSE.
PFModeEnabled BOOL Inverter is in power factor control mode.
QModeEnabled BOOL Inverter is in reactive power control mode.
InverterP REAL Real power output from inverter. Units are kW.
InverterQ REAL Reactive power output from inverter. Units are kVAR.
InverterPF REAL Power factor at inverter (generative +, consumptive –). Units are PF.
InverterPFLagLimit REAL Inverter lagging power factor limit (positive). Default is 0.8. Units
are PF.
InverterPFLeadLimit REAL Inverter leading power factor limit (negative). Default is –0.8. Units
are PF.
PFSetpointFeedback REAL Power factor set point feedback. Units are PF.
QSetpointFeedback REAL Reactive power set point feedback. Units are kVAR.
PLimitSetpointFeedback REAL Power limit set point feedback. Units are kW.
PFRampFeedback REAL Power factor ramp feedback. Units are PF/sec.
QRampFeedback REAL Reactive power ramp feedback. Units are kVAR/sec.
PLimitRampFeedback REAL Power limit ramp feedback. Units are kW/sec.
ContinuityAdjustment REAL The percentage amount to adjust PV setpoints by, when returning
to a proportional setpoint after system conditions have caused set-
points to be non-proportional. Units are in percentage. Range is 0 -
3. Default is 0.25 percent.
PRating REAL Power rating for the inverter. Units are kW. Default is 0.
QRating REAL Reactive power rating for the inverter. Units are kVAR. Default is 0.
Outputs
Inputs
Name IEC 61131 Type Description
ConnectToMasterCon- POINTER Connect this input to a master controller instance.
troller
Offline BOOL Communications channel to the inverter control device is offline (1 =
Offline). Default is FALSE.
RemoteEnabled BOOL Inverter control device is available to remote master control. Default
is FALSE.
Fault BOOL Inverter control device is reporting a fault. Default is FALSE.
OnStatus BOOL On/off status of the inverter. Default is FALSE.
OnCommandInput BOOL Command to turn on the inverter control device. Default is FALSE.
OffCommandInput BOOL Command to turn off the inverter control device. Default is FALSE.
IncludeCommand BOOL Command to include inverter in the master control. Default is
FALSE.
ExcludeCommand BOOL Command to remove inverter from the control. Default is FALSE.
PFModeEnabled BOOL Inverter is in power factor control mode.
Outputs
Name IEC 61131 Type Description
IncludedInMasterControl BOOL Inverter is included in master control. Will assert when inverter is on,
included, and not excluded.
OnCommand BOOL Pulse to turn on inverter.
OffCommand BOOL Pulse to turn off inverter.
QuickStop BOOL Asserts to send stop signal to inverter. This output can assert when
required even if the master controller is not enabled.
PFModeCommand BOOL Command to put inverter in power factor mode.
QModeCommand BOOL Command to put inverter in reactive power mode.
PFSetMag REAL Power factor output. Units are PF.
PFTrigger BOOL Power factor trigger (1 = Write).
QSetMag REAL Reactive power output. Units are kVAR.
QTrigger BOOL Reactive power trigger (1 = Write).
Inputs
Name IEC 61131 Type Description
ConnectToMasterCon- POINTER Connect this input to a master controller instance.
troller
Offline BOOL Communications channel to the capacitor control device is offline (1
= Offline). Default is FALSE.
RemoteEnabled BOOL Capacitor control device is available to remote master control (1 =
Remote). Default is FALSE.
Fault BOOL Capacitor control device is reporting a fault (1 = Fault). Default is
FALSE.
OnStatus BOOL On/off status of the capacitor. Default is FALSE.
OnCommandInput BOOL Command to turn on the capacitor. Default is FALSE.
OffCommandInput BOOL Command to turn off the capacitor. Default is FALSE.
IncludeCommand BOOL Command to include capacitor in the master control. Default is
FALSE.
ExcludeCommand BOOL Command to remove capacitor from the master control. Default is
FALSE.
CapacitorV REAL Voltage at the capacitor terminals. Units are kV. Default is 0.
QRating REAL Reactive power rating of the capacitor. Units are kVAR. Default is 0.
VRating REAL Voltage rating of the capacitor. Units are kV. Default is 0.
Outputs
Name IEC 61131 Type Description
IncludedInMasterControl BOOL Capacitor is included in master control. Will assert when capacitor
is included and not excluded.
OnCommand BOOL Pulse to turn on capacitor.
OffCommand BOOL Pulse to turn off capacitor.
Simulator
Function Blocks
The GridConnect library contains a built-in set of Simulator function blocks to support
learning, testing, and tuning of GridConnect integration. These constructs are intended to
be used to simulate the various inverter-based devices that GridConnect would normally
interact with and control. Therefore, the GridConnect Simulator function blocks should
take input from the outputs of GridConnect POUs and should provide feedback as input to
GridConnect objects, as shown in Figure 17.9 below.
Noise inputs all have units of percent between 0 and 100, meaning it will affect that pa-
rameter output by the percent defined. For example, if PNoise is 3, then a PlantP output
value of 100 would fluctuate between 97 and 103. Noise is applied at the level of individual
assets and accumulated at the PCC simulator block.
Inputs
Name IEC 61131 Type Description
RealPowerLosses REAL Losses of real power behind the PCC. Units
are kW.
ReactivePowerLosses REAL Losses of reactive power behind the PCC.
Units are kVAR.
ForceUniversalIrradiance BOOL Enable/disable for the PCC to manage the ca-
pability output of all inverters’ maximum ca-
pability.
UniversalIrradiance REAL Percentage between 0 to 100 that tells the
inverter its maximum power output based
upon its rating. For example, if UniversalIr-
radiance is 75 and the inverter’s rating is
100 kW, the max output of the inverter would
be 75 kW.
dVdQ REAL The relationship between voltage and VAR,
or how many VARs it takes to create a 1-
volt change. Units are volts/VAR; default is
0.002.
NominalVoltage REAL Nominal voltage at PCC if reactive power
flow is 0. Units are kV.
IrradianceNoise REAL Noise experienced in irradiance at PCC.
Units are percentage.
PNoise REAL Noise experienced in real power flow at PCC.
Units are percentage.
QNoise REAL Noise experienced in reactive power flow at
PCC. Units are percentage.
NoiseTimePeriod TIME Time interval to adjust the noise output. De-
fault is 0.
TimeScaleMultiplier REAL Time multiplier used to speed up behavior for
testing purposes. A value of 1 operates in real
time, a value 2 means 1 second is equivalent
to 2 seconds. A value of 60 means 1 second
equates to 1 minute.
Outputs
Name IEC 61131 Type Description
ConnectToPlantSimulators POINTER TO fb_PCCSim Connection point at which all plant
simulators attach.
PlantP REAL Real power flow at PCC. Units are
kW.
PlantQ REAL Reactive power flow at PCC. Units
are kVAR.
PlantV REAL Voltage at PCC that accounts for
VAR flow at PCC. Units are kV.
Inputs
Name IEC 61131 Type Description
ConnectToPCCSim POINTER TO fb_PCCSim Connection to the Point of Common Cou-
pling Simulator Object.
On BOOL Control to turn the inverter on/off; when
FALSE, the inverter outputs 0. TRUE: ON.
RemoteEnabled BOOL When TRUE, the inverter takes set points
and processes them. When FALSE, the in-
verter output remains frozen at current val-
ues.
PSetpoint REAL Real power set point for the inverter to is-
sue. Units are kW.
QSetpoint REAL Reactive power set point for inverter to is-
sue. Units are kVAR.
PFSetpoint REAL PF relationship between P and Q. Q output
is calculated based upon this relationship.
PRamprate REAL Ramp rate per second at which real power
is allowed to change. A value of 0 does not
restrict changes. Units are kW/second.
QRamprate REAL Ramp rate per second at which reactive
power is allowed to change. A value of 0
does not restrict changes. Only enforced
when in Qmode. Units are kVAR/second.
PFRamprate REAL Ramp rate per second at which reactive
power is allowed to change according to the
PF relationship between P and Q. A value
of 0 does not restrict changes. Only en-
forced when in PFmode.
QModeInput BOOL When TRUE, the inverter operates in Q
mode. The rising edge of this input will
set the inverter to operate in Qmode.
PFModeInput BOOL When TRUE, the inverter operates in PF
mode. The rising edge of this input will
set the inverter to operate in PFmode.
Outputs
Name IEC 61131 Type Description
POutput REAL Real power output of the inverter. Units are kW.
QOutput REAL Reactive power output of the inverter. Units are kVAR.
PFOutput REAL Power factor output of the inverter.
QMode BOOL Indicator that device is operating in Q mode. PF- and
Qmode outputs are exclusive, and only one may be true at
any point in time.
PFMode BOOL Indicator that device is operating in PFmode. PF- and
Qmode outputs are exclusive, and only one may be true at
any point in time.
Connected BOOL Diagnostic output to indicate whether the connection to the
PCC simulator was established successfully.
For example, a discharge set point of 100 kW of 1 minute is 1.67 kWh; similarly, a charge
value would add this amount of capability back to the battery. In this simulator, Q discharge
does not affect state of charge (SOC).
Inverter should output the given input unless it violates the following:
ä ramp rate of the inverter
ä power factor limit of the device
Inputs
Name IEC 61131 Type Description
ConnectToPCCSim POINTER TO fb_PCCSim Connection to the Point of Common Cou-
pling Simulator object.
On BOOL Control to turn the inverter on/off; when
FALSE, inverter outputs 0.
RemoteEnabled BOOL When TRUE, the inverter takes set points
and processes them. When FALSE, the in-
verter output remains frozen at current val-
ues.
PSetpoint REAL Real power set point for the inverter to is-
sue. Units are kW.
QSetpoint REAL Reactive power set point for the inverter to
issue. Units are kVAR.
PFSetpoint REAL PF relationship between P and Q. Q output
is calculated based upon this relationship.
PRamprate REAL Ramp rate per second at which real power
is allowed to change. A value of 0 does not
restrict changes. Units are kW/second.
QRamprate REAL Ramp rate per second at which reactive
power is allowed to change. A value of 0
does not restrict changes. Only enforced
when in Qmode. Units are kVAR/second.
PFRamprate REAL Ramp rate per second at which reactive
power is allowed to change according to the
PF relationship between P and Q. A value
of 0 does not restrict changes. Only en-
forced when in PFmode.
QModeInput BOOL When TRUE, the inverter operates in
Qmode. The rising edge of this input will
set the inverter to operate in Qmode.
PFModeInput BOOL When TRUE, the inverter operates in PF
mode. The rising edge of this input will
set the inverter to operate in PFmode.
Outputs
Name IEC 61131 Type Description
POutput REAL Real power output of the inverter. Units are in kW.
QOutput REAL Reactive power output of the inverter. Units are in
kVAR.
PFOutput REAL Power factor output of the inverter.
QMode BOOL Indicator that device is operating in Q mode. PF- and
Qmode outputs are exclusive, and only one may be true
at any point in time.
PFMode BOOL Indicator that device is operating in PF mode. PF- and
Qmode outputs are exclusive, and only one may be true
at any point in time.
StateOfCharge REAL Present SOC of battery. Units are in percent.
Connected BOOL Diagnostic output to indicate whether connection to
PCC simulator was established successfully.
Inputs
Name IEC 61131 Type Description
ConnectToPCCSim POINTER TO fb_PCCSim Connection to the Point of Common Cou-
pling Simulator object.
CapOn BOOL Control to engage capacitor or to logically
disconnect it. TRUE: ON
CapQRating REAL Reactive power rating of capacitor. Units
are in kVAR.
Outputs
Name IEC 61131 Type Description
Connected BOOL Diagnostic output to indicate whether connection to PCC
simulator was established successfully.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Utility
POI
inverter 1
storage 1
storage 2
Figure 17.15 Solar Facility One-Line Diagram
Solution
Once the user has identified all the elements of the model and decided the source for all
required data, the only work remaining is to construct the model in a program as shown in
Code Snippet 17.1.
MasterController.PFDeadband := 0.001; // PF
MasterController.PFKp := 0.2;
MasterController.PFKi := 0;
MasterController.PFLagLimit := 0.8; // PF
MasterController.PFLeadLimit := -0.8; // PF
MasterController.PFCompensationSetpoint := 1.0; // Unity PF
MasterController.PFCompensationLowPowerCutoff := 15; // 15%
MasterController.PFCompensationGradient := -0.002; // PF / %kW
MasterController.PFCompensationLowPFLimit := 0.8; // +- 0.8 PF
MasterController.VDeadband := 0.05; // kV
MasterController.VKp := 0.3;
MasterController.VKi := 0.03;
MasterController.VLimitHigh := 42; // kV
MasterController.VLimitLow := 38; // kV
MasterController.dV_dQ := 0.0002; // kW/kVAR
MasterController.VCompensationV1 := 38; // kV
MasterController.VCompensationV2 := 40;
MasterController.VCompensationV3 := 40;
MasterController.VCompensationV4 := 41;
MasterController.VCompensationQ1 := 2000; // kVAR
MasterController.VCompensationQ2 := 0;
MasterController.VCompensationQ3 := 0;
MasterController.VCompensationQ4 := -2000;
MasterController.FRegulationF1 := 59; // Hz
MasterController.FRegulationF2 := 59.7;
MasterController.FRegulationF3 := 60.3;
MasterController.FRegulationF4 := 61;
MasterController.FRegulationP1 := 10; // % of plant rated kW
MasterController.FRegulationP2 := 0;
MasterController.FRegulationP3 := 0;
MasterController.FRegulationP4 := -10;
MasterController.PDeadband := 2; // kW
MasterController.PKp := 0.4;
MasterController.PKi := 0.04;
// Inverter 1 Settings
Inverter1.IncludeCommand := TRUE;
Inverter1.ExcludeCommand := FALSE;
Inverter1.InverterPFLagLimit := 0.8;
Inverter1.InverterPFLeadLimit := -0.8;
Inverter1.PRating := 500; // kW
// Inverter 2 Settings
Inverter2.IncludeCommand := TRUE;
Inverter2.ExcludeCommand := FALSE;
Inverter2.InverterPFLagLimit := 0.8;
Inverter2.InverterPFLeadLimit := -0.8;
Inverter2.PRating := 500; // kW
Inverter2.QRating := 450; // kVAR
// Battery 1 settings
Storage1.IncludeCommand := TRUE;
Storage1.ExcludeCommand := FALSE;
Storage1.InverterPFLagLimit := 0.8;
Storage1.InverterPFLeadLimit := -0.8;
Storage1.PRating := 200; // kW
Storage1.QRating := 150; // kVAR
// Battery 2 settings
Storage2.IncludeCommand := TRUE;
Storage2.ExcludeCommand := FALSE;
Storage2.InverterPFLagLimit := 0.8;
Storage2.InverterPFLeadLimit := -0.8;
Storage2.PRating := 200; // kW
Storage2.QRating := 150; // kVAR
// Capacitor 1 Settings
Capacitor1.IncludeCommand := TRUE;
Capacitor1.ExcludeCommand := FALSE;
Capacitor1.QRating := 200; // kVAR
Capacitor1.VRating := 7.2; // kW
Capacitor1.SequenceNumber := 0; // First to turn on
// Capacitor 2 Settings
Capacitor2.IncludeCommand := TRUE;
Capacitor2.ExcludeCommand := FALSE;
Capacitor2.QRating := 200; // kVAR
Capacitor2.VRating := 7.2; // kW
Capacitor2.SequenceNumber := 0; // First to turn on
hasRunOnce := TRUE;
END_IF
MasterController.QSetpoint := vtl_PlantControls.QSetpoint.instMag;
MasterController.PFSetpoint := vtl_PlantControls.PFSetpoint.instMag;
MasterController.VSetpoint := vtl_PlantControls.VSetpoint.instMag;
MasterController.PSetpoint := vtl_PlantControls.PSetpoint.instMag;
MasterController.StoragePSetpoint := vtl_PlantControls.StoragePSetpoint.instMag;
// Inverter 1 I/O
Inverter1.Offline := vtl_InverterData.IsInverter1Offline.stVal;
Inverter1.RemoteEnabled := vtl_InverterData.IsInverter1RemoteEnabled.stVal;
Inverter1.Fault := vtl_InverterData.IsInverter1InFaultedState.stVal;
Inverter1.OnStatus := vtl_InverterData.IsInverter1On.stVal;
Inverter1.PFModeEnabled := vtl_InverterData.IsInverter1InPFMode.stVal;
Inverter1.QModeEnabled := vtl_InverterData.IsInverter1InQMode.stVal;
Inverter1.InverterP := DINT_TO_REAL(vtl_InverterData.Inverter1P.stVal);
Inverter1.InverterQ := DINT_TO_REAL(vtl_InverterData.Inverter1Q.stVal);
Inverter1.InverterPF := DINT_TO_REAL(vtl_InverterData.Inverter1PF.stVal)/1000;
Inverter1.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter1PFSetpointFeedback.stVal)/1000;
Inverter1.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter1QSetpointFeedback.stVal);
Inverter1.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter1PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Inverter1PackedControls.stVal.0 := Inverter1.OnCommand;
vtl_InverterData.Inverter1PackedControls.stVal.1 := Inverter1.OffCommand;
vtl_InverterData.Inverter1PackedControls.stVal.2 := Inverter1.EmergencyStop;
vtl_InverterData.Inverter1PackedControls.stVal.3 := Inverter1.PFModeCommand;
vtl_InverterData.Inverter1PackedControls.stVal.4 := Inverter1.QModeCommand;
vtl_InverterData.Inverter1PFSetpoint.oper.setMag := Inverter1.PFSetMag*1000; // Move significant
figures left of decimal
vtl_InverterData.Inverter1PFSetpoint.oper.trigger := Inverter1.PFTrigger;
vtl_InverterData.Inverter1QSetpoint.oper.setMag := Inverter1.QSetMag;
vtl_InverterData.Inverter1QSetpoint.oper.trigger := Inverter1.QTrigger;
vtl_InverterData.Inverter1PSetpoint.oper.setMag := Inverter1.PLimitSetMag;
vtl_InverterData.Inverter1PSetpoint.oper.trigger := Inverter1.PLimitTrigger;
vtl_InverterData.Inverter1PFRampSetpoint.oper.setMag := Inverter1.PFRampSetMag;
vtl_InverterData.Inverter1PFRampSetpoint.oper.trigger := Inverter1.PFRampTrigger;
vtl_InverterData.Inverter1QRampSetpoint.oper.setMag := Inverter1.QRampSetMag;
vtl_InverterData.Inverter1QRampSetpoint.oper.trigger := Inverter1.QRampTrigger;
vtl_InverterData.Inverter1PRampSetpoint.oper.setMag := Inverter1.PLimitRampSetMag;
vtl_InverterData.Inverter1PRampSetpoint.oper.trigger := Inverter1.PLimitRampTrigger;
// Inverter 2 I/O
Inverter2.Offline := vtl_InverterData.IsInverter2Offline.stVal;
Inverter2.RemoteEnabled := vtl_InverterData.IsInverter2RemoteEnabled.stVal;
Inverter2.Fault := vtl_InverterData.IsInverter2InFaultedState.stVal;
Inverter2.OnStatus := vtl_InverterData.IsInverter2On.stVal;
Inverter2.PFModeEnabled := vtl_InverterData.IsInverter2InPFMode.stVal;
Inverter2.QModeEnabled := vtl_InverterData.IsInverter2InQMode.stVal;
Inverter2.InverterP := DINT_TO_REAL(vtl_InverterData.Inverter2P.stVal);
Inverter2.InverterQ := DINT_TO_REAL(vtl_InverterData.Inverter2Q.stVal);
Inverter2.InverterPF := DINT_TO_REAL(vtl_InverterData.Inverter2PF.stVal)/1000;
Inverter2.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter2PFSetpointFeedback.stVal)/1000;
Inverter2.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter2QSetpointFeedback.stVal);
Inverter2.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter2PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Inverter2PackedControls.stVal.0 := Inverter2.OnCommand;
vtl_InverterData.Inverter2PackedControls.stVal.1 := Inverter2.OffCommand;
vtl_InverterData.Inverter2PackedControls.stVal.2 := Inverter2.EmergencyStop;
vtl_InverterData.Inverter2PackedControls.stVal.3 := Inverter2.PFModeCommand;
vtl_InverterData.Inverter2PackedControls.stVal.4 := Inverter2.QModeCommand;
vtl_InverterData.Inverter2PFSetpoint.oper.setMag := Inverter2.PFSetMag * 1000; // Move significant
figures left of decimal
vtl_InverterData.Inverter2PFSetpoint.oper.trigger := Inverter2.PFTrigger;
vtl_InverterData.Inverter2QSetpoint.oper.setMag := Inverter2.QSetMag;
vtl_InverterData.Inverter2QSetpoint.oper.trigger := Inverter2.QTrigger;
vtl_InverterData.Inverter2PSetpoint.oper.setMag := Inverter2.PLimitSetMag;
vtl_InverterData.Inverter2PSetpoint.oper.trigger := Inverter2.PLimitTrigger;
vtl_InverterData.Inverter2PFRampSetpoint.oper.setMag := Inverter2.PFRampSetMag;
vtl_InverterData.Inverter2PFRampSetpoint.oper.trigger := Inverter2.PFRampTrigger;
vtl_InverterData.Inverter2QRampSetpoint.oper.setMag := Inverter2.QRampSetMag;
vtl_InverterData.Inverter2QRampSetpoint.oper.trigger := Inverter2.QRampTrigger;
vtl_InverterData.Inverter2PRampSetpoint.oper.setMag := Inverter2.PLimitRampSetMag;
vtl_InverterData.Inverter2PRampSetpoint.oper.trigger := Inverter2.PLimitRampTrigger;
// Battery 1 I/O
Storage1.Offline := vtl_InverterData.IsStorage1Offline.stVal;
Storage1.RemoteEnabled := vtl_InverterData.IsStorage1RemoteEnabled.stVal;
Storage1.Fault := vtl_InverterData.IsStorage1InFaultedState.stVal;
Storage1.OnStatus := vtl_InverterData.IsStorage1On.stVal;
Storage1.PFModeEnabled := vtl_InverterData.IsStorage1InPFMode.stVal;
Storage1.QModeEnabled := vtl_InverterData.IsStorage1InQMode.stVal;
Storage1.InverterP := DINT_TO_REAL(vtl_InverterData.Storage1P.stVal);
Storage1.InverterQ := DINT_TO_REAL(vtl_InverterData.Storage1Q.stVal);
Storage1.InverterPF := DINT_TO_REAL(vtl_InverterData.Storage1PF.stVal)/1000;
Storage1.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage1PFSetpointFeedback.stVal)/1000;
Storage1.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage1QSetpointFeedback.stVal);
Storage1.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage1PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Storage1PackedControls.stVal.0 := Storage1.OnCommand;
vtl_InverterData.Storage1PackedControls.stVal.1 := Storage1.OffCommand;
vtl_InverterData.Storage1PackedControls.stVal.2 := Storage1.EmergencyStop;
vtl_InverterData.Storage1PackedControls.stVal.3 := Storage1.PFModeCommand;
vtl_InverterData.Storage1PackedControls.stVal.4 := Storage1.QModeCommand;
vtl_InverterData.Storage1PFSetpoint.oper.setMag := Storage1.PFSetMag * 1000; // Move significant
figures left of decimal
vtl_InverterData.Storage1PFSetpoint.oper.trigger := Storage1.PFTrigger;
vtl_InverterData.Storage1QSetpoint.oper.setMag := Storage1.QSetMag;
vtl_InverterData.Storage1QSetpoint.oper.trigger := Storage1.QTrigger;
vtl_InverterData.Storage1PSetpoint.oper.setMag := Storage1.PLimitSetMag;
vtl_InverterData.Storage1PSetpoint.oper.trigger := Storage1.PLimitTrigger;
vtl_InverterData.Storage1PFRampSetpoint.oper.setMag := Storage1.PFRampSetMag;
vtl_InverterData.Storage1PFRampSetpoint.oper.trigger := Storage1.PFRampTrigger;
vtl_InverterData.Storage1QRampSetpoint.oper.setMag := Storage1.QRampSetMag;
vtl_InverterData.Storage1QRampSetpoint.oper.trigger := Storage1.QRampTrigger;
vtl_InverterData.Storage1PRampSetpoint.oper.setMag := Storage1.PLimitRampSetMag;
vtl_InverterData.Storage1PRampSetpoint.oper.trigger := Storage1.PLimitRampTrigger;
// Battery 2 I/O
Storage2.Offline := vtl_InverterData.IsStorage2Offline.stVal;
Storage2.RemoteEnabled := vtl_InverterData.IsStorage2RemoteEnabled.stVal;
Storage2.Fault := vtl_InverterData.IsStorage2InFaultedState.stVal;
Storage2.OnStatus := vtl_InverterData.IsStorage2On.stVal;
Storage2.PFModeEnabled := vtl_InverterData.IsStorage2InPFMode.stVal;
Storage2.QModeEnabled := vtl_InverterData.IsStorage2InQMode.stVal;
Storage2.InverterP := DINT_TO_REAL(vtl_InverterData.Storage2P.stVal);
Storage2.InverterQ := DINT_TO_REAL(vtl_InverterData.Storage2Q.stVal);
Storage2.InverterPF := DINT_TO_REAL(vtl_InverterData.Storage2PF.stVal)/1000;
Storage2.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage2PFSetpointFeedback.stVal)/1000;
Storage2.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage2QSetpointFeedback.stVal);
Storage2.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage2PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Storage2PackedControls.stVal.0 := Storage2.OnCommand;
vtl_InverterData.Storage2PackedControls.stVal.1 := Storage2.OffCommand;
vtl_InverterData.Storage2PackedControls.stVal.2 := Storage2.EmergencyStop;
vtl_InverterData.Storage2PackedControls.stVal.3 := Storage2.PFModeCommand;
vtl_InverterData.Storage2PackedControls.stVal.4 := Storage2.QModeCommand;
vtl_InverterData.Storage2PFSetpoint.oper.setMag := Storage2.PFSetMag * 1000; // Move significant
figures left of decimal
vtl_InverterData.Storage2PFSetpoint.oper.trigger := Storage2.PFTrigger;
vtl_InverterData.Storage2QSetpoint.oper.setMag := Storage2.QSetMag;
vtl_InverterData.Storage2QSetpoint.oper.trigger := Storage2.QTrigger;
vtl_InverterData.Storage2PSetpoint.oper.setMag := Storage2.PLimitSetMag;
vtl_InverterData.Storage2PSetpoint.oper.trigger := Storage2.PLimitTrigger;
vtl_InverterData.Storage2PFRampSetpoint.oper.setMag := Storage2.PFRampSetMag;
vtl_InverterData.Storage2PFRampSetpoint.oper.trigger := Storage2.PFRampTrigger;
vtl_InverterData.Storage2QRampSetpoint.oper.setMag := Storage2.QRampSetMag;
vtl_InverterData.Storage2QRampSetpoint.oper.trigger := Storage2.QRampTrigger;
vtl_InverterData.Storage2PRampSetpoint.oper.setMag := Storage2.PLimitRampSetMag;
vtl_InverterData.Storage2PRampSetpoint.oper.trigger := Storage2.PLimitRampTrigger;
// Capacitor 1 I/O
Capacitor1.Offline := vtl_CapacitorData.IsCapacitor1Offline.stVal;
Capacitor1.RemoteEnabled := vtl_CapacitorData.IsCapacitor1RemoteEnabled.stVal;
Capacitor1.Fault := vtl_CapacitorData.IsCapacitor1InFaultedState.stVal;
Capacitor1.OnStatus := vtl_CapacitorData.IsCapacitor1On.stVal;
Capacitor1.CapacitorV :=
DINT_TO_REAL(vtl_CapacitorData.Capacitor1Voltage.stVal);
vtl_CapacitorData.Capacitor1On.operPulse.ctlVal := Capacitor1.OnCommand;
vtl_CapacitorData.Capacitor1Off.operPulse.ctlVal := Capacitor1.OffCommand;
// Capacitor 2 I/O
Capacitor2.Offline := vtl_CapacitorData.IsCapacitor2Offline.stVal;
Capacitor2.RemoteEnabled := vtl_CapacitorData.IsCapacitor2RemoteEnabled.stVal;
Capacitor2.Fault := vtl_CapacitorData.IsCapacitor2InFaultedState.stVal;
Capacitor2.OnStatus := vtl_CapacitorData.IsCapacitor2On.stVal;
Capacitor2.CapacitorV :=
DINT_TO_REAL(vtl_CapacitorData.Capacitor2Voltage.stVal);
vtl_CapacitorData.Capacitor2On.operPulse.ctlVal := Capacitor2.OnCommand;
vtl_CapacitorData.Capacitor2Off.operPulse.ctlVal := Capacitor2.OffCommand;
IPAliasRedundancy
Introduction
This library provides functionality to manage an additional IP alias (a second IP address)
added to a specified interface on an SEL Real-Time Automation Controller (RTAC). The
function blocks in this library are designed to work in a redundancy scheme by using an IP
alias to be shared between two RTAC units. The two RTAC units will communicate with
each other via the logic in this library to decide when the IP alias should and should not be
active on the specified interface. The primary IP address for interfaces on the RTAC are
still configured via the web interface.
The two RTACs managing the IP alias communicate via an Ethernet or serial connection.
The library only supports the use of one or the other connection type (do not use both si-
multaneously). If the RTACs communicate via Ethernet, it is recommended that a separate
interface than the managed interface is used for communications. (This is not an absolute
requirement—the two RTACs can communicate via the same interface that is being man-
aged—see Frequently Asked Questions on page 18.2 for details.) Information between the
two RTACs is updated at least once a second regardless of which connection is used.
The redundancy logic operates in two modes. The first is a primary-primary mode, in which
the detection of a failover condition causes the IP alias to activate on the inactive unit. In this
mode, the previously inactive unit will become the primary unit. If the previous primary
unit becomes available again, it will be the inactive unit and must wait for a condition to
occur in which the IP alias will become active. The second mode is a primary-backup
mode, in which the backup unit is designated on the function block. In this mode, if the
primary unit is no longer available, the backup unit will activate the IP alias. When the
primary unit is available again and reestablishes communication to the backup unit, the IP
alias on the backup unit will be deactivated and that IP alias will be returned to the primary
unit.
The function blocks in this library offer a maintenance mode in which the unit will no longer
participate in the IP alias redundancy logic. If the IP alias is currently active on the unit
when maintenance mode is activated, it will be transferred to the other unit. Maintenance
mode persists through project settings changes and power cycles. This mode allows for
configuration changes or testing to be performed without affecting communication on the
other unit participating in the redundancy scheme.
The following conditions will cause the IP address to activate on the standby unit:
ä Managed Ethernet interface loss of link
ä Loss of communication between RTACs (note that a unit with a broken communi-
cations cable looks the same to the standby unit as a unit that has lost power)
ä Maintenance mode is activated
Can the IP alias logic work with different RTAC hardware variants
such as the SEL-3530 and SEL-3555?
Yes, the interface control logic will work between any two RTACs of any hardware combi-
nations. This includes any combination of RTAC hardware variants including the SEL-2240
Axion.
Special Considerations
ä Copying function blocks from this library causes unwanted behavior. This means
the following:
1. The assignment operator “:=” must not be used on any function block from
this library; consider assigning pointers to the objects instead.
// This is fine
someVariable := myIpAliasRedundancyObject.value;
// As is this
pt_myIpAliasRedundancyObject :=
ADR(myIpAliasRedundancyObject);
Function Blocks
This library provides two function blocks. Both function blocks provide the same redun-
dancy functionality. The InterfaceControlWithSerialCheck function block allows for the
same redundancy configuration to be applied to two RTACs, and the logic will identify
which IP address and behavior should be associated with which RTAC based upon the
supplied RTAC serial numbers.
Inputs
Name IEC 61131 Type Description
ControlledInterface enum_interface_ID Interface that will be managed with Con-
trolledIPAlias.
ControlledIPAlias STRING(18) IP address and CIDR value that will be man-
aged on the ControlledInterface pin.
Backup BOOL If TRUE, the unit will operate in backup mode.
If FALSE, the unit will operate in primary
mode.
RemoteRtacIP STRING(15) IP address of remote RTAC.
RemoteRtacPort UINT Port number of the other RTAC. This setting
needs to match the LocalAPPort setting on the
remote RTAC.
LocalAPPort UINT Port number for RTAC-to-RTAC communica-
tions on the unit. This setting needs to match
the listening access point that is configured.
LocalClientConnectPort UINT Port number for the RTAC to use to create a
TCP connection to the remote RTAC (29459
by default).
LocalSerialPort UINT The communications port that will be used to
communicate with the other RTAC.
CommStatusTimeout TIME The amount of time for which the RTAC will
activate the IP alias when RTAC-to-RTAC
communications is lost. This setting has a
range of 500 ms to 1 hour.
EnterMaintenanceMode BOOL This pin on a rising edge will activate main-
tenance mode. When the unit is in mainte-
nance mode, it will not participate in redun-
dancy logic.
ExitMaintenanceMode BOOL This pin on a rising edge will remove the unit
from maintenance mode and allow the unit to
participate in managing the IP alias.
InterfaceLinkStatus SPS Connect to the system tags Ethernet link sta-
tus, which shows the current value of the man-
aged interface.
Outputs
Name IEC 61131 Type Description
IPAliasActive BOOL This pin shows if the IP address that
is assigned on “ControlledIPAlias”
is active on the RTAC unit.
MaintenanceMode BOOL This pin shows if the unit is cur-
rently in maintenance mode. If the
unit is in maintenance mode, the
RTAC will not participate in redun-
dancy logic. Maintenance mode
persists through power cycle and
settings changes on the unit. Once
the unit is set to exit maintenance
mode it will participate in the redun-
dancy scheme of the “ControlledIn-
terfaceIP”.
RtacEthernetCommsGood BOOL If both RTAC connections are com-
municating via the Ethernet connec-
tion, this pin will be set to TRUE.
RtacSerialCommsGood BOOL If both RTAC connections are com-
municating via the serial connec-
tion, this pin will be set to TRUE.
InvalidInputPin STRING Lists an incorrectly configured input
pin.
CommunicationDataResetCounter WORD Lists the number of times inter-
nal data has been reset due to de-
layed responses or corrupted re-
ceived data.
Inputs
Name IEC 61131 Type Description
ControlledInterface enum_interface_ID The interface that will be managed with the
ControlledIPAlias.
ControlledIPAlias String(18) The IP address and CIDR value that will be
managed by the Controlled_Interface pin.
SerialNumber String(80) The serial number of the unit on which redun-
dancy logic will operate.
Outputs
Name IEC 61131 Type Description
IPAliasActive BOOL This pin shows if the IP address that
is assigned on “ControlledIPAlias”
is active on the RTAC unit.
MaintenanceMode BOOL This pin shows if the unit is cur-
rently in maintenance mode. If
the unit is in maintenance mode,
the RTAC will not participate in
redundancy logic. Maintenance
mode persists through power cy-
cle and settings change on the unit.
Once the unit is set to exit main-
tenance mode, it will participate in
the redundancy scheme of the “Con-
trolledInterfaceIP”.
RtacEthernetCommsGood BOOL If both RTAC connections are com-
municating via the Ethernet connec-
tion, this pin will be set to TRUE.
RtacSerialCommsGood BOOL If both RTAC connections are com-
municating via the serial connec-
tion, this pin will be set to TRUE.
SerialNumberMismatch BOOL If the assigned and actual serial
numbers do not match, this pin will
be TRUE. Redundancy logic will
only function if this value is FALSE.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes the following:
ä The IP alias and its associated subnet do not overlap with any other configured sub-
nets on any Ethernet interface or other IP aliases.
ä The client will communicate with the RTAC on Ethernet Port 2.
ä Both RTACs will communicate with each other on Ethernet Port 1.
ä Both RTACs have IP addresses in the same subnet on Ethernet Port 1.
ä Ethernet Port 1 on each RTAC will be connected directly to the other RTAC or
through a switch.
ä Each RTAC configuration includes an Ethernet Listening, Raw TCP access point that
matches the LocalAPPort setting on the interface control function block.
ä Each RTAC collects data from the other RTAC through serial ports or an Ethernet
port.
ä Any supported server protocol can be used to send data to the client via the IP alias.
ä If a serial connection is used, an RS-232 compatible cable that matches the wiring
diagram according to each connected serial port (as listed in the specific RTAC hard-
ware instruction manual) is used.
Solution
RTAC Project 1
The user creates an Ethernet listening access point as shown in Figure 18.1.
Port1Control(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
Backup := FALSE,
RemoteRtacIP := '192.168.25.8',
RemoteRTACPort := 3000,
LocalAPPort := 7500,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);
Figure 18.2 presents the same logic as Code Snippet 18.1 shown in CFC rather than an ST
program.
RTAC Project 2
The user creates an Ethernet listening access point as shown in Figure 18.3.
Port1Control(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
Backup := FALSE,
RemoteRtacIP := '192.168.25.7',
RemoteRTACPort := 7500,
LocalAPPort := 3000,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);
Figure 18.4 presents the same logic as Code Snippet 18.2 shown in CFC rather than an ST
program.
Assumptions
This example assumes the following:
ä The IP alias and its associated subnet mask do not overlap with any other configured
subnets on any Ethernet interface or other IP aliases.
ä The client will communicate with the RTAC on Ethernet Port 2.
ä Both RTACs will communicate with each other on Ethernet Port 1.
ä Both RTACs have IP addresses in the same subnet on Ethernet Port 1.
ä Ethernet port 1 on each RTAC will be connected directly to the other RTAC or
through a switch.
ä Each RTAC configuration includes an Ethernet Listening of Raw TCP access point
that matches the LocalAPPort setting on the interface control function block.
ä Each RTAC collects data from the other RTAC through serial ports or an Ethernet
port.
ä Any supported server protocol can be used to send data to the client via the IP alias.
ä If a serial connection is used, then an RS-232 compatible cable that matches the
wiring diagram according to each connected serial port (as listed in the specific
RTAC hardware instruction manual) is used.
Solution
In each RTAC configuration, create one access point of type Ethernet incoming listening
that matches the settings of the LocalAPPort setting on each function block.
PortControlRTAC2(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
SerialNumber := '1122680283',
Backup := FALSE,
RemoteRtacIP := '192.168.25.7',
RemoteRTACPort := 7500,
LocalAPPort := 3000,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);
Figure 18.7 presents the same logic as Code Snippet 18.3 shown in CFC rather than an ST
program.
JSON_Utilities_SL
Introduction
The JSON_Utilities_SL library provides mechanisms to generate and parse JSON (JavaScript
Object Notation) data structures from any structure whose characters are accessible by
byte-wise operations (example structures include Dynamic Vectors, STRINGs, and arrays
of BYTEs). The JSON standard is fully described at json.org.
Implementation Note
This library is provided as a member of the CODESYS® IIoT package as a special offer-
ing available in the SEL RTAC. The functionality provided by this resource is generally
intended to operate in generic CODESYS® environments. As such, some limitations may
be encountered when implementing these resources in the SEL RTAC. Any POUs or POU
inputs that may be subject to these limitations are marked accordingly in this document.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
Enumerations defined in this, the JSON Utilities SL library, provide control of the various
JSON parser/serializer mechanisms.
ERROR
Enumeration Description
NO_ERROR No error.
INDEX_OUT_OF_BOUNDS Array index was out of bounds.
NOT_FOUND The requested element cannot be found.
NULL_POINTER Null pointer.
MAX_STRING_SIZE_EXCEEDED Max size of Strings exceeded.
READ_ERROR Read error.
INVALID_HANDLE Invalid file handle.
FILE_OPEN_ERROR File open error.
INVALID_ENCODING Invalid encoding.
WRITE_ERROR Write error.
UNKNOWN_JSON_TYPE Unknown JSON type.
MAX_FILE_SIZE_EXCEEDED Max size of file exceeded.
INVALID_DECIMAL_PLACE Decimal place is < 0.
MAX_OBJECT_DEPTH_EXCEEDED Maximum object depth g_diMaxDepth exceeded.
INVALID_KEY_PARENT Parent of a key must be an object.
INVALID_VALUE_PARENT Parent of a value must be an array or a key.
INVALID_LICENSE RTAC firmware does not adequately provide IIoT in-
formation.
INVALID_STRUCTURE Invalid JSON structure.
Encoding
Enumeration Description
UTF_8 UTF-8 encoding.
UTF_16 UTF-16 encoding.
JSONType
Enumeration Description
KEY The element is a key which is stored as WSTRING.
WSTRING_VALUE Element is a WSTRING value.
LINT_VALUE Element is a LINT value.
LREAL_VALUE Element is a LREAL value.
BOOL_VALUE Element is a BOOL value.
NULL Element is NULL.
JSON_ARRAY Element is an array.
JSON_OBJECT Element is an object.
NONE NO JSON type.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Structures defined in this, the JSON Utilities SL library, are positioned to be provide func-
tional access to JSON data.
JSONElement
Name IEC 61131 Type Description
value JSONValue Value of the element.
eType JSONType Type of the value.
diIndex DINT Index of this element in the data array.
diParentIndex DINT Index of the parent JSONElement, -1 for top-level ele-
ments.
Unions
Unions provide a means to interchange datatypes sharing the same memory space to facil-
itate accessing data commonalities in a functional manner.
Unions defined in this, the JSON Utilities SL library, are positioned to be provide functional
access to JSON data.
JSONElement
Name IEC 61131 Type Description
wsValue WSTRING(GParams.g_diMaxStringSize) Value as WSTRING.
xValue BOOL Value as BOOL.
lrValue LREAL Value as LREAL.
liValue LINT Value as LINT.
Functions
JSONElementToString (Function)
Converts a JSON element to WSTRING.
Inputs
Name IEC 61131 Type Description
element JSONElement The element to convert.
wsResult WSTRING(GParams.g_diMaxStringSize) The string representation of an ele-
ment.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
Interfaces
This library provides the following interfaces.
IJSONData
Interface for JSONData.
Clear (Method)
Clears the underlying data array.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
FindAllElementsByKey (Method)
Find all elements by key.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING(GParams.g_diMaxStringSize) The key to search.
diStartIndex DINT Index of the array to start the
search.
pResult POINTER TO JSONElement Pointer to the result array.
udiMaxSize UDINT Maximum size of pResult.
Outputs
Name IEC 61131 Type Description
udiResultSize UDINT The size of the result array.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
FindFirstElementByKey (Method)
Find the first element in the data array by key.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING(GParams.g_diMaxStringSize) The key to search.
diStartIndex DINT Index of the array to start the
search.
Outputs
Name IEC 61131 Type Description
jsonElement JSONElement The first element in the array with the requested key.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
FindFirstValueByKey (Method)
Find the first value of the requested key.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING(GParams.g_diMaxStringSize) The key to search.
diStartIndex DINT Index of the array to start the
search.
Outputs
Name IEC 61131 Type Description
jsonElement JSONElement The first element in the array with the requested key.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
GetChildren (Method)
Get all children of an element.
Inputs
Name IEC 61131 Type Description
diIndex UDINT Index of the parent element.
pResult POINTER TO JSONElement Children of the parent element index.
udiMaxSize UDINT Maximum number of children.
Outputs
Name IEC 61131 Type Description
udiResultSize UDINT The size of the result array.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
GetElementByIndex (Method)
Get an element by index.
Inputs
Name IEC 61131 Type Description
diIndex UDINT Index of the element.
Outputs
Name IEC 61131 Type Description
jsonElement JSONElement The element with the requested index.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetArray (Method)
Method to set an object.
Inputs
Name IEC 61131 Type Description
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetBool (Method)
Method to set BOOL values.
Inputs
Name IEC 61131 Type Description
bValue BOOL Value to be set.
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetKey (Method)
Method to set a key.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING(GParams.g_diMaxStringSize) Value to be set.
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetLReal (Method)
Method to set LREAL values.
Inputs
Name IEC 61131 Type Description
lrValue LREAL Value to be set.
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetLRealRounded (Method)
Method to set rounded LREAL values. Rounding mode: Round halfway from zero.
Inputs
Name IEC 61131 Type Description
lrValue LREAL Value to be set.
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
iDecimalPlaces INT Number of decimal places.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetLint (Method)
Method to set LINT values.
Inputs
Name IEC 61131 Type Description
liValue LREAL Value to be set.
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetNull (Method)
Method to set NULL values.
Inputs
Name IEC 61131 Type Description
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetObject (Method)
Method to set an object.
Inputs
Name IEC 61131 Type Description
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
SetString (Method)
Method to set WSTRING values.
Inputs
Name IEC 61131 Type Description
wsValue WSTRING(GParams.g_diMaxStringSize) Value to be set.
diIndex DINT Index of the element.
diParentIndex DINT Parent index, -1 if top level.
Return Value
IEC 61131 Type Description
ERROR Resulting status of operation.
Function Blocks
The JSON Utilities SL library provides various function block to construct and parse data
into respective structures.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä IJSONData
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the func-
tion block has completed its action, the
outputs operate in the usual manner and
are only reset if either the action is com-
pleted or in the event of an error. In
this case, the corresponding output val-
ues (xDone, xError) are present at the
outputs for exactly one cycle.
pwData POINTER TO WORD Pointer to the data array with JSON data.
xIgnoreValueStringLength BOOL If True, the error is ignored and the value
is shortened and xValueTrunked will be
TRUE.
Inputs/Outputs
Name IEC 61131 Type Description
jsonData JSONDataInternal JSONData object.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
xValueTruncated BOOL Minimum one String value was > GParams.g_di-
MaxStringSize.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the function block has com-
pleted its action, the outputs operate in the usual manner
and are only reset if either the action is completed or in
the event of an error. In this case, the corresponding out-
put values (xDone, xError) are present at the outputs for
exactly one cycle.
pwData POINTER TO WORD Pointer to the target array.
udiSize UDINT Size of target array.
Inputs/Outputs
Name IEC 61131 Type Description
jsonData JSONDataInternal JSONData object.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the function block has com-
pleted its action, the outputs operate in the usual manner
and are only reset if either the action is completed or in
the event of an error. In this case, the corresponding out-
put values (xDone, xError) are present at the outputs for
exactly one cycle.
wsKey WSTRING The key to search.
diStartIndex DINT Start index.
Inputs/Outputs
Name IEC 61131 Type Description
jsonData JSONDataInternal JSONData object.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
jsonElement BOOL The corresponding value of the key.
eError ERROR Output error.
Classes
The JSON Utilities SL library provides the following classes.
JSONData (Class)
This class contains the JSON data and provides methods to access and set data.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä IJSONData
JSONBuilder (Class)
Class to support constructing a JSON structure.
Inputs/Outputs
Name IEC 61131 Type Description
pJsonData POINTER TO JSONData Pointer to the JSON data.
Outputs
Name IEC 61131 Type Description
diRootObj DINT Root of the JSON structure.
SetKey (Method)
Method to set key in a JSON data.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING Key to be set.
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
SetKeyWithArray (Method)
Method to set key with an array in a JSON data.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING Key to be set.
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
SetKeyWithObject (Method)
Method to set key and object in a JSON data.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING Key to be set.
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
SetKeyWithValue (Method)
Method to set key and value in a JSON data.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING Key to be set.
Value __SYSTEM.AnyType Value to be set.
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
SetKeyWithValueNull (Method)
Method to set key and null value in a JSON data.
Inputs
Name IEC 61131 Type Description
wsKey WSTRING Key to be set.
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
SetObject (Method)
Method to set an object value in a JSON data.
Inputs
Name IEC 61131 Type Description
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
SetKeyWithValue (Method)
Method to set value in a JSON data.
Inputs
Name IEC 61131 Type Description
Value __SYSTEM.AnyType Value to be set.
diParentIndex DINT Index of parent for the new key.
Return Value
IEC 61131 Type Description
DINT Size of key added.
JSONDataFactory (Class)
Factory with a heap based extendable memory pool.
Inputs
Name IEC 61131 Type Description
uxiInstCount CAA.COUNT Factor for the size of the initial memory pool of JSON-
Data objects. Should be equal to the maximum number
of created JSONData objects. Set to 1 and use a single
instance of JSONData to reduce memory usage.
Create (Method)
Method to create an instance of the function block JSONData.
Outputs
Name IEC 61131 Type Description
eError FBF.ERROR Output error.
Return Value
IEC 61131 Type Description
POINTER TO JSONDataInternal Pointer to the generated JSONData function block.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that a JSON data structure defined by the user is to be parsed. This
JSON structure is to be defined as follows, with three keys in the outermost MAP of the
structure.
1 {
2 "fid": "SEL-3530-R146-V0-Z000002-D20200224",
3 "licensed features": {
4 "features": [
5 {"hmi": true},
6 {"library": "fileio"}
7 ]
8 },
9 "device name": "SEL-RTAC"
10 }
11
Solution
In order to appropriately extract the keys from this JSON structure, the string must first
be parsed, and because the exact number of key-strings in the JSON structure is known,
the keys can be loaded into an array of STRING(255)s with that exact number of elements.
Note, however, this is not an advisable operation when the number of keys is either unknown
or could change.
MQTT_Client_SL
Introduction
The MQTT_Client_SL library provides mechanisms to publish and subscribe to topics
managed by an external MQTT broker.
Implementation Note
This library is provided as a member of the CODESYS® IIoT package as a special offer-
ing available in the SEL RTAC. The functionality provided by this resource is generally
intended to operate in generic CODESYS® environments. As such, some limitations may
be encountered when implementing these resources in the SEL RTAC. Any POUs or POU
inputs that may be subject to these limitations are marked accordingly in this document.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
Enumerations defined in this, the MQTT Client library, are positioned to be accessed by
various external libraries in order to reduce redundant enumeration descriptions.
COMMUNICATION_MODE
Enumeration Description
TCP Standard TCP/IP communication.
WEB_SOCKET TCP/IP communication via WebSocket (MQTT over WebSocket).
FILTER_MODE
Enumeration Description
FILTER_ON Filters the telegrams by topics.
FILTER_OFF Turns the filter off and receives ALL subscribed telegrams.
FILTER_NONE Receives no telegrams. In this mode you can only subscribe or unsubscribe
topics.
MQTT_ERROR
Enumeration Description
NO_ERROR No error.
TCP_INIT_ERROR Unable to initialize the TCP socket.
TCP_READ_ERROR Error while reading response.
TCP_WRITE_ERROR Error while sending the request.
MAX_RESPONSE_SIZE_EXCEEDED Size of incoming packet exceeds the
maximum packet size.
DECODE_REMAINING_LENGTH_MALFORMED Malformation during Decoding of Re-
maining Length of Packet.
RESPONSE_PACKET_EMPTY The Response Packet is empty.
INVALID_PACKET_TYPE Invalid Packet Type in first byte of
Fixed Header.
INVALID_PACKET_BIT_FLAGS Invalid Packet Bit Flags in first byte of
Fixed Header.
INVALID_PACKET Invalid Packet.
KEEP_ALIVE_TIME_EXCEEDED Keep Alive Time is too much.
WRONG_SESSION_PRESENT_CONNACK Wrong Session Present in CONNACK
packet.
UNACCEPTABLE_PROTOCOL_VERION Connection to Broker is Refused, be-
cause of Unacceptable Protocol Ver-
sion.
IDENTIFIER_REJECTED Connection to Broker is Refused, be-
cause of Rejection of Client Identifier.
SERVER_UNAVAILABLE Connection to Broker is Refused, be-
cause the Server Broker is not avail-
able.
BAD_USER_NAME_PASSWORD Connection to Broker is Refused, be-
cause of Bad User name or Bad Pass-
word.
NOT_AUTHORIZED Connection to Broker is Refused, be-
cause of Not Authorized access.
TOPIC_FILTER_EMPTY Topic Filter is empty (e.g., “remove-
me”), MUST be at least one character
long.
TOPIC_NAME_NOT_ALLOWED_WILDCARD Topic Name contains Wildcards, which
is not allowed. Only Topic Filter can
contain these.
TOPIC_INVALID_LENGTH Topic Length out of valid range.
TOPIC_IS_EMPTY Topic name is empty.
SUBSCRIBE_FAILURE Subscription Failure.
ADD_MQTT_PACKET_COLLECTION_ERROR Collection Error while trying to add an
MQTT packet to the stack.
ADD_SUBSCRIBER_COLLECTION_ERROR Collection Error while trying to add a
subscriber to the stack.
REMOVE_SUBSCRIBER_COLLECTION_ERROR Collection Error while trying to remove
a subscriber from the stack.
ACKNOWLEDGE_TIMEOUT Client waits for ping response from
Server, but Server does not response
within a given time interval (2 * ping
interval).
MQTT_QOS
Enumeration Description
QoS0 Send Message 1x, if disconnected from server then send can fail.
QoS1 Send Message Nx, until Receive is acknowledged.
QoS2 Send Message 1x, if disconnected from server then send is always successfully.
Functions
This library provides functions to perform UTF conversions, intended to allow converting
of UTF16 to UTF8 and vice-versa.
ConvertUTF16toUTF8 (Function)
This function converts a WSTRING (UTF16) to a STRING (UTF8).
Inputs
Name IEC 61131 Type Description
sourceStart POINTER TO WORD Pointer to WSTRING.
targetStart POINTER TO BYTE Pointer to STRING.
dwTargetBufferSize DWORD Size of STRING.
bStrictConversion BOOL Require strict conversion technique.
Return Value
IEC 61131 Type Description
UDINT Number of WORD characters converted.
ConvertUTF8toUTF16 (Function)
This function converts a STRING (UTF8) to a WSTRING (UTF16).
Inputs
Name IEC 61131 Type Description
sourceStart POINTER TO BYTE Pointer to STRING.
targetStart POINTER TO WORD Pointer to WSTRING.
dwTargetBufferSize DWORD Size of WSTRING.
bStrictConversion BOOL Require strict conversion technique.
Return Value
IEC 61131 Type Description
UDINT Number of BYTE characters converted.
Classes
The MQTT Client SL library provides classes designed to be implemented to provide a
connection to the respective MQTT broker.
MQTTClient (Class)
Function block to connect with an MQTT broker.
Inputs
Name IEC 61131 Type Description
xEnable BOOL TRUE: Activates the defined
operation.
FALSE: Aborts/resets the de-
fined operation.
uiPort UINT Port of MQTT Broker Server.
xUseTLS BOOL TRUE: Encrypted Connection.
FALSE: Unencrypted Connec-
tion.
uiKeepAlive UINT Keep Alive Time in Seconds
(optional).
pbWillMessage POINTER TO BYTE Pointer to the “Last Will” mes-
sage (optional).
uiWillMessageSize UINT Size of “Last Will” message
(optional).
xWillRetain BOOL TRUE: Saves the “Last Will”
message on server. If Client
subscribes later, then it receives
the last stack message from
server.
eWillQoS MQTT_QOS QoS Level of “Last Will” mes-
sage.
xCleanSession BOOL TRUE: Creates a new session.
FALSE: Uses already existing
session if available.
wsUsername WSTRING(255) User Name (optional).
wsPassword WSTRING(1024) User Password (optional).
wsWillTopic WSTRING(1024) Will Topic (optional).
sClientId STRING(255) Client ID, if empty then
new ID is generated, al-
lowed are only these charac-
ters 0123456789abcdefghi-
jklmnopqrstuvwxyzABCDE-
FGHIJKLMNOPQRSTU-
VWXYZ (optional).
tPingInterval TIME Interval time in seconds how of-
ten should be pinged, if Time <=
0 then no pings.
hCert RTS_IEC_HANDLE Handle to the client certificate
(optional).
itfTLSContext NBS.ITLSContext Encapsulates all the data neces-
sary to handle encrypted TCP
connections.
itfAsyncProperty NBS.IAsyncProperty Runs the connect process in a
own background task. Use this
property if the connection setup
takes longer than one task cycle
(e.g., TLS connections)
Inputs/Outputs
Name IEC 61131 Type Description
sHostname STRING(80) Host name of Broker MQTT Server (is IPAddress).
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eMQTTError MQTT_ERROR MQTT Error Type.
xConnectedToBroker BOOL FALSE when there is no Connection to MQTT
Broker Server, otherwise TRUE.
SetWebSocketOptions (Method)
Method to set additional websocket options if eCommunicationMode = COMMUNICA-
TION_MODE.WEB_SOCKET
Inputs
Name IEC 61131 Type Description
tPingInterval TIME Ping interval, T#0s: no ping.
httpProxySettings WEB_SOCKET.HttpProxySettings Optional HTTP proxy settings.
Return Value
IEC 61131 Type Description
BOOL Web socket options were set successfully.
Function Blocks
The MQTT Client SL library provides function blocks designed to be implemented to pro-
vide unique subscription and publisher functionality.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Publish message.
udiTimeOut UDINT Timeout in microseconds, default: 10s.
eQoS MQTT_QOS QoS Level of message.
xReDelivery BOOL TRUE: When packet got already send and now
should got resend. FALSE: First time.
xRetain BOOL TRUE: Stores the message on server.
pbPayload POINTER TO BYTE Pointer to the message.
udiPayloadSize UDINT Size of message.
Inputs/Outputs
Name IEC 61131 Type Description
mqttClient MQTTClient Function block MQTTClient.
wsTopicName WSTRING(1024) Topic Name of message.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eMQTTError MQTT_ERROR MQTT Error Type.
Inputs
Name IEC 61131 Type Description
xEnable BOOL TRUE: Subscribes the topic filter wsTopicFilter.
FALSE: Unsubscribe topic filter.
eSubscribeQoS MQTT_QOS TRUE: QoS-Level for Subscribe.
pbPayload POINTER TO BYTE Pointer to memory for incoming payload.
udiMaxPayloadSize UDINT Maximum Size of incoming payload.
eFilterMode FILTER_MODE Filter mode for incoming telegrams. Default:
FILTER_MODE.FILTER_ON.
Inputs/Outputs
Name IEC 61131 Type Description
mqttClient MQTTClient Function block MQTTClient.
wsTopicName WSTRING(1024) Topic Filter.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eMQTTError MQTT_ERROR MQTT Error Type.
xReceived BOOL FALSE as long as there is no message, TRUE if
a message got received, in new cycles then again
FALSE.
udiPayloadSize UDINT Size of the received message.
xSubscribeActive BOOL FALSE: When there is no active subscription.
TRUE: Subscriber is listening.
wsLastTopic WSTRING(1024) The real topic value from the publish packet that is
corresponding to this topic filter.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
The following assumptions are made:
1. MQTT Broker is hosted with an IPv4 address of 192.168.1.10.
2. MQTT Broker is hosted with a TCP listening port of 1883.
3. No MQTT usernames or passwords are in use.
4. A common topic of rtac/data/topic-name shall be used.
5. For simplicity, the message will be published every ten (10) seconds.
Solution
Code Snippet 20.1 prg_MqttLoopback
PROGRAM prg_MqttLoopback
VAR CONSTANT
c_BrokerHostname : STRING(80) := '192.168.1.10';
c_BrokerTcpPort : UINT := 1883;
c_ExchangedTopic : WSTRING(1024) := 'rtac/data/topic-name';
END_VAR
VAR
// Function block to establish a connection to an MQTT broker.
mqttClient : MQTT.MQTTClient;
// Function block to subscribe MQTT topics.
mqttSubscriber : MQTT.MQTTSubscribe;
// Function block to publish MQTT topics.
mqttPublisher : MQTT.MQTTPublish;
// Run the MQTT Subscriber - This will listen for any new messages
// associated with the subscribed topic.
mqttSubscriber(
xEnable := TRUE,
pbPayload := ADR(subscriptionPayload),
udiMaxPayloadSize := SIZEOF(subscriptionPayload),
mqttClient := mqttClient,
wsTopicFilter := c_ExchangedTopic
);
MathComplex
Introduction
The MathComplex library allows the storage of complex numbers as well as basic manip-
ulations that can be performed on them.
All numbers in polar notation are expected to be in units of degrees and not radians.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_ComplexRect
This structure represents a complex number in rectangular coordinates.
Functions
fun_ComplexAbs (Function)
This function returns the absolute value, or magnitude, of the provided complex number.
Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number from which the absolute value is calculated.
Return Value
IEC 61131 Type Description
LREAL The absolute value of num.
Processing
p
This function returns a value equal to (num.Re)2 + (num.Im)2 .
fun_ComplexAdd (Function)
This function returns the sum of two complex numbers.
Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The first addend.
num2 struct_ComplexRect The second addend.
Return Value
IEC 61131 Type Description
struct_ComplexRect The result of num1 + num2.
fun_ComplexCmp (Function)
This function compares two complex values based on magnitude.
Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The first value to compare.
num2 struct_ComplexRect The second value to compare.
Return Value
IEC 61131 Type Description
INT Returns –1 if the magnitude of num2 is larger than num1, 0 if the magni-
tudes are equal, and 1 if the magnitude of num1 is larger than num2.
Processing
This function calculates the absolute value of both provided inputs and then provides its
return based on which one is larger.
fun_ComplexConjugate (Function)
This function returns the conjugate of the provided complex number.
Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number from which the conjugate is derived.
Return Value
IEC 61131 Type Description
struct_ComplexRect The complex conjugate of num.
Processing
This function returns a struct_ComplexRect with a negated imaginary component.
fun_ComplexDivide (Function)
This function returns the quotient of num1 / num2.
Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The dividend.
num2 struct_ComplexRect The divisor.
Return Value
IEC 61131 Type Description
struct_ComplexRect The quotient of num1 / num2.
Processing
num1 × num2∗
This function performs the equivalent of providing a result formatted as
num2 × num2∗
a single complex number.
fun_ComplexExp (Function)
Compute enum .
Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number e will be raised to.
Return Value
IEC 61131 Type Description
struct_ComplexRect The result of enum .
Processing
Performs the calculation ea+bi = ea (cos b + i sin b).
fun_ComplexLn (Function)
Compute the natural logarithm of num.
Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number from which the natural log is calculated.
Return Value
IEC 61131 Type Description
struct_ComplexRect The natural log of num.
Processing
This function returns an Re component of the natural log of the magnitude of num and an
Im component of the angle defined by the arctangent of num.Im and num.Re.
fun_ComplexMultiply (Function)
This function returns the product of multiplying two complex numbers.
Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The first factor.
num2 struct_ComplexRect The second factor.
Return Value
IEC 61131 Type Description
struct_ComplexRect The product of num1 and num2.
fun_ComplexScale (Function)
This function multiplies a complex number by a scalar.
Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number to scale.
scalar LREAL The scalar.
Return Value
IEC 61131 Type Description
struct_ComplexRect The product of num and scalar.
fun_ComplexSubtract (Function)
This function returns the difference of two complex numbers.
Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The minuend.
num2 struct_ComplexRect The subtrahend.
Return Value
IEC 61131 Type Description
struct_ComplexRect The difference of num1 – num2.
fun_ComplexZero (Function)
This function zeros the provided struct_ComplexRect.
Inputs/Outputs
Name IEC 61131 Type Description
num struct_ComplexRect The struct to be zeroed.
struct_ComplexRect_TO_vector_t (Function)
This function converts a complex number stored as rectangular coordinates to a complex
number stored as polar coordinates. The angle returned by this function will be between
–180 and 180 degrees.
Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The rectangular coordinates to be converted.
Return Value
IEC 61131 Type Description
vector_t num represented as polar coordinates.
vector_t_TO_struct_ComplexRect (Function)
This function converts a complex number stored as polar coordinates to a complex number
stored as rectangular coordinates.
Inputs
Name IEC 61131 Type Description
num vector_t The polar coordinates to be converted.
Return Value
IEC 61131 Type Description
struct_ComplexRect num represented as rectangular coordinates.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R135-V0 firmware
ä SEL-3530
â R135-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V0 firmware
AlgebraicOps Performance
The times fun_ComplexAdd, fun_ComplexSubtract, fun_ComplexDivide, fun_ComplexS-
cale, and fun_ComplexMultiply require to run, averaged over 1000 calls.
Exponential Performance
The times fun_ComplexExp and fun_ComplexLn require to run, averaged over 1000 calls.
Conversion Performance
The times struct_ComplexRect_TO_vector_t and vector_t_TO_struct_ComplexRect require
to run, averaged over 1000 calls.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_ComplexAbs 10 7 1
fun_ComplexConjugate 5 4 1
fun_ComplexZero 1 1 1
fun_ComplexAdd 2 2 1
fun_ComplexSubtract 2 2 1
fun_ComplexMultiply 2 2 1
fun_ComplexDivision 3 2 1
fun_ComplexScale 1 1 1
fun_ComplexExp 36 15 1
fun_ComplexLn 50 13 1
vector_t_TO_struct_ComplexRect 19 6 1
struct_ComplexRect_TO_vector_t 23 12 1
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
The usage shown in Code Snippet 21.1 would be the same for any other operation as well.
Solution
Code Snippet 21.2 prg_ComplexConvert
PROGRAM prg_ComplexConvert
VAR
DatumOne : vector_t := (ang := 36.87, mag := 35_614);
DatumTwo : vector_t := (ang := 53.13, mag := 17_735);
ComplexNumOne : struct_ComplexRect;
ComplexNumTwo : struct_ComplexRect;
ComplexResult : struct_ComplexRect;
DatumResult : vector_t;
END_VAR
ComplexNumOne := vector_t_TO_struct_ComplexRect(DatumOne);
ComplexNumTwo := vector_t_TO_struct_ComplexRect(DatumTwo);
ComplexResult := fun_ComplexAdd(ComplexNumOne, ComplexNumTwo);
//Scale from Kilovolts to Volts.
ComplexResult := fun_ComplexScale(ComplexResult, 1000);
DatumResult := struct_ComplexRect_TO_vector_t(ComplexResult);
MathMatrix
Introduction
The MathMatrix library allows for the creation of matrices of complex numbers. There are
multiple desired workflows that exist when working with matrices and the library provides
several options for working with them.
The library is designed to facilitate two basic types of matrix operations: operations that
modify an existing matrix and operations that take one or more matrices as arguments
and place the result in a different matrix. Operations that affect only the active matrix are
completed using the methods on class_Matrix objects. Operations that affect two or more
matrices are performed by external functions or special matrix manipulation classes.
The library also allows for operations of varying levels of required immediacy. For work
on large or highly variant sized matrices that can be completed over multiple task cycles, NOTE: Because of the cost of
checking the system time, the time is
it provides matrix manipulation classes that are loaded with operator and result matrices, not validated at each step in the
stimulated to run to completion, and given a fixed number of steps or a fixed time slice. algorithm but rather after multiple
steps have been completed.
For operations that must complete immediately, ideally on fixed sized matrices so the com-
putation time can be evaluated to validate timing requirements, functions provided by the
library accomplish the same work while guaranteeing the completion of the algorithm be-
fore returning.
This library is dependent on the capabilities defined in the MathComplex library for all
operations (see the MathComplex library documentation for more information on the op-
eration of this library).
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myMathMatrixObject.value;
// As is this
pt_myMathMatrixObject := ADR(myMathMatrixObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_MatrixState
Enumeration Description
NOT_INITIALIZED This matrix has no memory assigned to it, call SetSize() to
initialize.
NO_OPERATION The matrix is not locked to any operation.
MATRIX_SCALE The matrix is being scaled by one value.
EXTERNAL_OPERATION The matrix is being operated on by an external class.
MATRIX_ROW_STEP_MULT The matrix is multiplying a row by a scalar.
MATRIX_ROW_STEP_DIV The matrix is dividing a row by a scalar.
MATRIX_ROW_STEP_ADD The matrix is adding two rows together.
MATRIX_ROW_STEP_SUB The matrix is subtracting one row from another.
Functions
fun_DeleteMatrix (Function)
The user should call this after completing work on a matrix received through fun_NewMatrix()
before the matrix goes out of scope. It releases all system resources.
Inputs/Outputs
Name IEC 61131 Type Description
pt_matrix POINTER TO class_Matrix The matrix to be deleted. This pointer must be re-
ceived through fun_NewMatrix.
Return Value
IEC 61131 Type Description
BOOL TRUE if the memory is successfully deallocated.
Processing
This function frees all system resources owned by this matrix. After completion of the
function, pt_matrix is NULL(0).
fun_MatrixAdd (Function)
This function adds two matrices and places the result in a third. The entire operation will
complete before the function returns.
Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The first addend.
matrix2 class_Matrix The second addend.
result class_Matrix The sum of the two matrices.
Return Value
IEC 61131 Type Description
BOOL The matrix addition completed successfully.
Processing
This function sets the return value to TRUE if all conditions for performing the addition
are met as follows:
ä matrix1 and matrix2 are initialized.
ä All three matrices are not busy performing a stepwise operation.
ä result is a separate matrix from both matrix1 and matrix2.
ä matrix1 and matrix2 have the same dimensions.
ä If necessary, result is successfully resized.
It then performs the addition.
fun_MatrixCopyColumn (Function)
This function copies one column from one matrix to a column in a second matrix. The
entire operation will complete before the function returns.
Inputs
Name IEC 61131 Type Description
fromColumn UINT The column index of the column being copied from.
toColumn UINT The column index of the column being copied to.
Inputs/Outputs
Name IEC 61131 Type Description
fromMatrix class_Matrix The matrix being copied from.
toMatrix class_Matrix The matrix being copied to.
Return Value
IEC 61131 Type Description
BOOL The column copy completed successfully.
Processing
This function sets the return value to TRUE if all conditions for performing the copy are
met as follows:
ä Both matrices are initialized.
ä Both matrices are not busy performing a stepwise operation.
ä Both matrices have the same number of rows.
ä The column indices provided are within the size of the matrices referenced.
It then performs the copy.
fun_MatrixDeterminant (Function)
This function calculates the determinant of a square matrix. The entire operation will
complete before the function returns.
If the purpose behind calculating the determinant is a check before inverting a matrix or
as part of the process of solving a system of equations this class is not the most optimal to
use. In these cases it is better to use the fun_MatrixInvert or the fun_MatrixGaussianElim
object instead as the overhead for all three is similar.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to calculate the determinant of. This matrix is
left unchanged.
workspace class_Matrix Memory to do the calculation in. If this is the same size
as original, no memory allocation will occur in finding the
determinant.
Outputs
Name IEC 61131 Type Description
determinant struct_ComplexRect The determinant of the matrix. Zero if the matrix is not
invertible.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation was attempted.
Processing
1. This function sets the return value to TRUE if all conditions for performing the
calculation are met as follows:
ä original is initialized.
ä original is a square matrix.
ä workspace is a separate matrix from original.
ä Neither matrix is busy performing some other operation.
ä If necessary, workspace is successfully resized.
2. Copies the contents of original into workspace.
3. Reduces workspace to an identity matrix using elementary row operations.
4. Calculates the determinant from the row operations performed.
5. If at any time the row operations cannot reduce workspace further and it is still not
an identity matrix, the operation is terminated and determinant is set to zero.
fun_MatrixGaussianElim (Function)
This function simplifies a matrix to a diagonal ones matrix with trailing columns using
Gaussian elimination. The contents of coefficients are destroyed and the contents of solu-
tions are modified by this function. The entire operation will complete before the function
returns.
Inputs/Outputs
Name IEC 61131 Type Description
coefficients class_Matrix The coefficients of the variables being solved for.
solutions class_Matrix The right hand side of the system of equations.
Outputs
Name IEC 61131 Type Description
error BOOL This algorithm cannot solve this system of equations.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination was attempted and the matrices
could have been modified.
Processing
ä This function sets the return value to TRUE if all conditions for performing the cal-
culation are met as follows:
â Both matrices are initialized.
â Both matrices are not busy performing a stepwise operation.
â coefficients is a separate matrix from solutions.
â coefficients has at least as many columns as rows.
â solutions has the same number of rows as coefficients.
ä Reduces the first Rows • Rows of coefficients to an identity matrix using elementary
row operations.
ä Performs the same row operations on solutions.
ä If at any time the row operations cannot reduce coefficients further and there is still
not an identity matrix on the left the operation is terminated and error is set.
ä The contents of coefficients are destroyed and the contents of solutions are modified
by this method.
fun_MatrixInvert (Function)
This function creates the inverse of a square matrix. original is destroyed in the process
so if the data are still desired, they must be copied before the function is called. The entire
operation will complete before the function returns.
One common use case for inverting a matrix is to solve a system of equations. In this library
that use case is discouraged unless solving the same system for many solutions as Gaussian
elimination performs the same functionality with less overhead.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to invert.
result class_Matrix The inverted matrix.
Outputs
Name IEC 61131 Type Description
error BOOL The inversion could not be attempted or original cannot be in-
verted.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if inversion was attempted and the matrices could have been
modified.
Processing
1. This function sets the return value to TRUE if all conditions for performing the
calculation are met as follows:
ä original is initialized.
ä Both matrices are not busy performing a stepwise operation.
ä result is a separate matrix from original.
fun_MatrixMultiply (Function)
This function multiplies two matrices and places the result in a third. The entire operation
will complete before the function returns.
Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The multiplier.
matrix2 class_Matrix The multiplicand.
result class_Matrix The product of the two matrices.
Return Value
IEC 61131 Type Description
BOOL The matrix multiplication completed successfully.
Processing
This function sets the return value to TRUE if all conditions for performing the calculation
are met as follows:
ä matrix1 and matrix2 are initialized.
ä All three matrices are not busy performing a stepwise operation.
ä result is a separate matrix from both matrix1 and matrix2.
ä The column count of matrix1 equals the row count of matrix2.
If necessary, it sets the size of result. It then performs the multiplication.
fun_MatrixSubtract (Function)
This function subtracts one matrix from another and places the result in a third. The entire
operation will complete before the function returns.
Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The minuend.
matrix2 class_Matrix The subtrahend.
result class_Matrix The difference of the two matrices.
Return Value
IEC 61131 Type Description
BOOL The matrix subtraction completed successfully.
Processing
This function verifies that the subtraction can be performed:
1. matrix1 and matrix2 are initialized.
2. All three matrices are not busy performing a stepwise operation.
3. result is a separate matrix from both matrix1 and matrix2.
4. matrix1 and matrix2 have the same dimensions.
If necessary, the function resizes result. It then performs the subtraction.
fun_MatrixTranspose (Function)
This function places the transpose of a matrix into a result. The entire operation will com-
plete before the function returns.
Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be the Hermitian Transpose.
Before each element is placed in result, it will be conjugated.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix whose transpose is calculated.
result class_Matrix The transpose of the original matrix.
Return Value
IEC 61131 Type Description
BOOL The matrix transpose completed successfully.
Processing
This function verifies that the transpose can be performed:
1. original is initialized.
2. Both matrices are not busy performing a stepwise operation.
3. result is a separate matrix from original.
If necessary the function resizes result. It then performs the transpose. If conjugate is
TRUE, conjugate each element in result.
fun_Matrix_ATA (Function)
This function performs an optimization of the operation (AT A) transposing an input matrix
and multiplying it by itself. The entire operation will complete before the function returns.
Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be calculated using the Her-
mitian Transpose. Before the transpose step is complete, each
element will be conjugated.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix A.
result class_Matrix The matrix for the result.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed successfully.
Processing
This function verifies that the operation can be performed:
1. original is initialized.
2. Both matrices are not busy performing a stepwise operation.
3. result is a separate matrix from original.
If necessary, the function resizes result. It then performs the operation AT A. If conjugate
is TRUE, conjugate each element in the transpose before using it in the multiply.
fun_NewMatrix (Function)
Request a new matrix from the system with all required resources. Matrices received
through this function must be freed through the fun_DeleteMatrix() function before
they leave scope.
Inputs
Name IEC 61131 Type Description
rows UINT The number of rows in the new matrix.
cols UINT The number of columns in the new matrix.
Return Value
IEC 61131 Type Description
POINTER TO class_Matrix The address of the new class_Matrix.
Processing
This function allocates system resources for a rows by cols matrix of struct_ComplexRect
objects.
Classes
This library provides the following classes as extensions of the IEC 61131 function block.
class_Matrix (Class)
This is the fundamental class for this library. It allows for the storage of struct_Com-
plexRect objects ordered by row and column. It manages all required system resources
internally.
Initialization Inputs
Name IEC 61131 Type Description
rowCount UINT The number of rows this matrix begins with.
colCount UINT The number of columns this matrix begins with.
Outputs
Name IEC 61131 Type Description
pt_Data POINTER TO POINTER TO Pointer to an array of pointers (one for each
struct_ComplexRect row). Allows accessing the matrix with [row][col]
syntax. Indexing starts at zero. This pointer should
be re-read before access after any resize operation.
Rows UINT The number of rows in the matrix.
Cols UINT The number of columns in the matrix.
State enum_MatrixState The active matrix operation.
Clear (Method)
This method returns all system resources internal to this matrix and sets its size to zero
rows by zero columns. In addition it clears all locks on the matrix and resets all internal
state machines.
This should typically be used only to free the system resources held by this matrix before
it goes out of scope.
MatrixRowAdd (Method)
This method adds one row to another inside this matrix, replacing the content of the second
row (Matrix[toRow] = Matrix[toRow] + Matrix[fromRow] • scalar). The entire operation
will complete before the method returns.
Inputs
Name IEC 61131 Type Description
fromRow UINT The first addend.
toRow UINT The second addend and the location of the result.
scalar struct_ComplexRect A constant that is multiplied against the value of each entry
in fromRow before adding it to the entry in toRow.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the addition.
Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates that the provided row indices exist.
3. If the checks pass, multiplies fromRow by scalar and adds the result to toRow.
4. fromRow remains unchanged.
MatrixRowDivide (Method)
This method divides each element in rowIndex by scalar and stores the results back in
rowIndex (Matrix[rowIndex] = Matrix[rowIndex] / scalar). The entire operation will com-
plete before the method returns.
Inputs
Name IEC 61131 Type Description
rowIndex UINT The row to be modified.
scalar struct_ComplexRect A constant used as the divisor against the value of each entry
in rowIndex.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the division.
Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates the row index provided exists.
3. If the checks pass, divides each entry in rowIndex by scalar.
MatrixRowMultiply (Method)
This method multiplies each element in rowIndex by scalar and stores the results back
in rowIndex (Matrix[rowIndex] = Matrix[rowIndex] • scalar). The entire operation will
complete before the method returns.
Inputs
Name IEC 61131 Type Description
rowIndex UINT The row to be modified.
scalar struct_ComplexRect A constant used as the multiplier against the value of each
entry in rowIndex.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the multiplication.
Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates the row index provided exists.
3. If the checks pass, multiplies each entry in rowIndex by scalar.
MatrixRowSubtract (Method)
This method subtracts one row from another inside this matrix, replacing the content of
the second row (Matrix[toRow] = Matrix[toRow] – Matrix[fromRow] • scalar). The entire
operation will complete before the method returns.
Inputs
Name IEC 61131 Type Description
fromRow UINT The subtrahend.
toRow UINT The minuend and the location of the result.
scalar struct_ComplexRect A constant that is multiplied against the value of each entry
in fromRow before subtracting it from the entry in toRow.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the subtraction.
Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates the row indices provided exist.
3. If the checks pass, multiplies fromRow by scalar and subtracts the result from
toRow.
MatrixScale (Method)
Multiplies each element in this matrix by a scalar. The entire operation will complete before
the method returns.
Inputs
Name IEC 61131 Type Description
scalar struct_ComplexRect A constant that is multiplied against the value of each entry this
matrix.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method scaled the matrix.
Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. If the checks pass, multiplies each element in the matrix by scalar, placing the result
in the same location.
MatrixStepRowAdd (Method)
This method adds one row to another inside this matrix, replacing the content of the second
row (Matrix[toRow] = Matrix[toRow] + Matrix[fromRow] • scalar).
The operation will perform the next steps operations of the complete addition. This de-
sign allows for the completion of the algorithm over the course of multiple task cycles for
matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the addition.
Processing
1. Validates that the matrix is initialized and has begun a stepwise addition.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and add the result to toRow.
3. fromRow remains unchanged.
4. Performs, at most, the next steps operations toward completing the addition algo-
rithm.
5. Decrements steps by the number of operations consumed.
6. Returns TRUE and unlocks the matrix if the addition completed.
7. Returns FALSE if the addition was not attempted or steps was exhausted before the
algorithm completed.
MatrixStepRowDivide (Method)
This method divides each element in toRow by scalar and stores the results back in toRow
(Matrix[toRow] = Matrix[toRow] / scalar).
The operation will perform the next steps operations of the complete division. This de-
sign allows for the completion of the algorithm over the course of multiple task cycles for
matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the division.
Processing
1. Validates that the matrix is initialized and has begun a stepwise division.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to divide each element in toRow by scalar.
3. Performs, at most, the next steps operations toward completing the division algo-
rithm.
4. Decrements steps by the number of operations consumed.
5. Returns TRUE and unlocks the matrix if the division completed.
6. Returns FALSE if the division was not attempted or steps was exhausted before the
algorithm completed.
MatrixStepRowMultiply (Method)
This method multiplies each element in toRow by scalar and stores the results back in
toRow (Matrix[toRow] = Matrix[toRow] • scalar).
The operation will perform the next steps operations of the complete multiplication. This
design allows for the completion of the algorithm over the course of multiple task cycles
for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the multiplication.
Processing
1. Validates that the matrix is initialized and has begun a stepwise multiplication.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each entry in toRow by scalar.
3. Performs, at most, the next steps operations toward completing the multiplication
algorithm.
4. Decrements steps by the number of operations consumed.
5. Returns TRUE and unlocks the matrix if the multiplication completed.
6. Returns FALSE if the multiplication was not attempted or steps was exhausted be-
fore the algorithm completed.
MatrixStepRowSubtract (Method)
This method subtracts one row from another inside this matrix, replacing the content of the
second row (Matrix[toRow] = Matrix[toRow] – Matrix[fromRow] • scalar).
The operation will perform the next steps operations of the complete subtraction. This
design allows for the completion of the algorithm over the course of multiple task cycles
for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the subtraction.
Processing
1. Validates that the matrix is initialized and has begun a stepwise subtraction.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and subtract the result from toRow.
3. fromRow remains unchanged.
4. Performs, at most, the next steps operations toward completing the subtraction al-
gorithm.
5. Decrements steps by the number of operations consumed.
6. Returns TRUE and unlocks the matrix if the subtraction completed.
7. Returns FALSE if the subtraction was not attempted or steps was exhausted before
the algorithm completed.
MatrixStepScale (Method)
Multiplies each element in this matrix by a scalar.
The operation will perform the next steps operations of the complete scaling operation.
This design allows for the completion of the algorithm over the course of multiple task
cycles for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the scaling operation.
Processing
1. Validates that the matrix is initialized and has begun a stepwise scaling operation.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each element in the matrix by scalar.
3. Performs, at most, the next steps operations toward completing the scaling algo-
rithm.
MatrixTimedRowAdd (Method)
This method adds one row to another inside this matrix, replacing the content of the second
row (Matrix[toRow] = Matrix[toRow] + Matrix[fromRow] • scalar).
The operation will perform work for the next duration microseconds toward completion
of the addition. This design allows for the completion of the algorithm over the course of
multiple task cycles for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the addition.
Processing
1. Validates that the matrix is initialized and has begun a stepwise addition.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and add the result to toRow.
3. fromRow remains unchanged.
4. Performs work toward completing the addition algorithm, in groups of steps, until
duration microseconds is exceeded.
5. Decrements duration by the microseconds consumed.
6. Returns TRUE and unlocks the matrix if the addition completed.
7. Returns FALSE if the addition was not attempted or duration was exhausted before
the algorithm completed.
MatrixTimedRowDivide (Method)
This method divides each element in toRow by scalar and stores the results back in toRow
(Matrix[toRow] = Matrix[toRow] / scalar).
The operation will perform work for the next duration microseconds toward the complete
division. This design allows for the completion of the algorithm over the course of multiple
task cycles for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the division.
Processing
1. Validates that the matrix is initialized and has begun a stepwise division.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to divide each element in toRow by scalar.
3. Performs work toward completing the division algorithm, in groups of steps, until
duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE and unlocks the matrix if the division completed.
6. Returns FALSE if the division was not attempted or duration was exhausted before
the algorithm completed.
MatrixTimedRowMultiply (Method)
This method multiplies each element in toRow by scalar and stores the results back in
toRow (Matrix[toRow] = Matrix[toRow] • scalar).
The operation will perform work for the next duration microseconds toward the complete
multiplication. This design allows for the completion of the algorithm over the course of
multiple task cycles for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the multiplication.
Processing
1. Validates that the matrix is initialized and has begun a stepwise multiplication.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each entry in toRow by scalar.
3. Performs work toward completing the multiplication algorithm, in groups of steps,
until duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE and unlocks the matrix if the multiplication completed.
6. Returns FALSE if the multiplication was not attempted or duration was exhausted
before the algorithm completed.
MatrixTimedRowSubtract (Method)
This method subtracts one row from another inside this matrix, replacing the content of the
second row (Matrix[toRow] = Matrix[toRow] – Matrix[fromRow] • scalar).
The operation will perform work for the next duration microseconds toward the complete
subtraction. This design allows for the completion of the algorithm over the course of
multiple task cycles for matrices large enough for completion time to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the subtraction.
Processing
1. Validates that the matrix is initialized and has begun a stepwise subtraction.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and subtract the result from toRow.
3. fromRow remains unchanged.
4. Performs work toward completing the subtraction algorithm, in groups of steps,
until duration microseconds is exceeded.
5. Decrements duration by the microseconds consumed.
6. Returns TRUE and unlocks the matrix if the subtraction completed.
7. Returns FALSE if the subtraction was not attempted or duration was exhausted
before the algorithm completed.
MatrixTimedScale (Method)
Multiplies each element in this matrix by a scalar.
The operation will perform work for the next duration microseconds toward the complete
scaling operation. This design allows for the completion of the algorithm over the course
of multiple task cycles for matrices large enough for completion duration to be a concern.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the scaling operation.
Processing
1. Validates that the matrix is initialized and has begun a stepwise scaling operation.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each element in the matrix by scalar.
3. Performs work toward completing the scaling algorithm, in groups of steps, until
duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE and unlocks the matrix if the scaling operation completed.
6. Returns FALSE if the scaling operation was not attempted or duration was ex-
hausted before the algorithm completed.
RowSwap (Method)
This method exchanges the position of two rows in a given matrix.
Inputs
Name IEC 61131 Type Description
row1 UINT The first row to swap.
row2 UINT The second row to swap.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the row swap.
Processing
1. Validates that the matrix is initialized and not performing any stepwise operation.
2. If the checks pass, swaps the positions of row1 and row2.
3. Returns TRUE if the swap succeeded.
4. Returns FALSE if the swap failed.
SetSize (Method)
This method changes the storage capacity of the matrix modifying Rows and Cols.
Inputs
Name IEC 61131 Type Description
rowCount UINT The new number of rows.
colCount UINT The new number of columns.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method resized the matrix.
Processing
1. Validates that the matrix is not performing any stepwise operation.
2. If either rowCount or colCount is zero, sets Rows and Cols to zero and frees all
system resources.
3. If both rowCount equals Rows and colCount equals Cols, leaves the matrix un-
changed.
4. If rowCount is greater than Rows, adds zeroed rows to the bottom of the matrix.
5. If rowCount is less than Rows, removes rows from the bottom of the matrix.
6. If colCount is greater than Cols, adds zeros to the end of each row.
7. If colCount is less than Cols, truncates each row to the new count.
8. Returns TRUE if the matrix is the newly requested size.
9. Returns FALSE if the matrix is not the newly requested size.
10. If the resize fails, the matrix retains all old values.
StartMatrixOperation (Method)
This method must be called to configure any stepwise or timed operation on only this ma-
trix. It accepts and stores the values used during the operation.
Inputs
Name IEC 61131 Type Description
operation enum_MatrixState The stepwise operation to begin.
fromRow UINT The row to use in the modification. Used only in addition
and subtraction.
toRow UINT The row to be modified.
scalar struct_ComplexRect The constant value to be used during the operation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method locked the matrix to the requested operation.
Processing
1. Validates that the matrix is initialized and not performing any stepwise operation.
2. Validates row indices required for the operation requested. For addition and sub-
traction, both indices must be within the matrix. For multiplication and division,
only toRow is validated. For scaling operations, no row index is validated
3. Stores scalar for use during the operation.
4. Locks the matrix to prevent other operations from occurring.
5. Returns TRUE if the operation is primed.
6. Returns FALSE if anything prevents the operation from being primed.
class_MatrixAdd (Class)
This class handles the locking handshakes and the state required to add two class_Matrix
objects over the course of multiple scans.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform a new addition (result = matrix1 + matrix2). It
must be called before each addition of two matrices to be performed.
Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The first addend.
matrix2 class_Matrix The second addend.
result class_Matrix The sum of matrix1 and matrix2.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the addition operation is now ready.
Processing
1. Returns FALSE if either matrix1 or matrix2 is not initialized.
2. Returns FALSE if result is not a separate matrix from both matrix1 and matrix2.
3. Returns FALSE if any of the three matrices is busy doing any stepwise operation.
4. Returns FALSE if the dimensions of matrix1 do not match those of matrix2.
5. Returns FALSE if result cannot be made to be the same dimensions as the other
two matrices.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of result are destroyed by this method.
ProcessSteps (Method)
This method performs the addition algorithm on three already locked-in matrices.
The operation will perform the next steps sub-operations of the complete addition algo-
rithm.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the addition completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Adds each element in matrix1 to its corresponding element in matrix2 and stores
the sum in result.
3. Decrements steps by the number of operations performed.
4. Returns TRUE if the addition algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
ProcessTimed (Method)
This method performs the addition algorithm on three already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
addition algorithm.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the addition completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Adds each element in matrix1 to its corresponding element in matrix2 and stores
the sum in result.
3. Performs work toward completing the addition algorithm, in groups of steps, until
duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the addition algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixCopyColumn (Class)
This class handles the locking handshakes and the state required to copy a column from
one class_Matrix object to another over the course of multiple scans.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform a new column copy. It must be called before each
column copy to be performed.
Inputs
Name IEC 61131 Type Description
fromColumn UINT The index of the column to copy from.
toColumn UINT The index of the column to copy to.
Inputs/Outputs
Name IEC 61131 Type Description
fromMatrix class_Matrix The matrix to be copied from.
toMatrix class_Matrix The matrix to be copied to.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the copy operation is now ready.
Processing
1. Returns FALSE if either fromMatrix or toMatrix is not initialized.
2. Returns FALSE if either of the matrices is busy doing any stepwise operation.
3. Returns FALSE if Rows of matrix1 does not match Rows of matrix2.
4. Returns FALSE if either index provided is outside of the corresponding matrix.
5. Returns FALSE if it cannot lock all matrices involved in the operation.
6. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
ProcessSteps (Method)
This method performs the copy algorithm on two already locked-in matrices.
The operation will perform the next steps sub-operations of the complete copy.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the copy completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Copies each element in column fromColumn of fromMatrix to its corresponding
element in column toColumn of toMatrix.
3. Decrements steps by the number of sub-operations performed.
4. Returns TRUE if the copy algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
ProcessTimed (Method)
This method performs the copy algorithm on two already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
copy.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the copy completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Copies each element in column fromColumn of fromMatrix to its corresponding
element in column toColumn of toMatrix.
3. Performs work toward completing the copy algorithm, in groups of steps, until du-
ration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the copy algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixDeterminant (Class)
This class handles the locking handshakes and the state required to calculate the determi-
nant of a matrix over the course of multiple scans.
If the purpose behind calculating the determinant is a check before inverting a matrix or as
part of the process of solving a system of equations this class is not the most optimal to use.
In these cases it is better to use the class_MatrixInvert or the class_MatrixGaussianElim
object instead as the overhead for all three is similar.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to calculate the determinant of a new matrix. It must be called
before each operation to be performed.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to calculate the determinant of. This matrix is
left unchanged.
workspace class_Matrix Memory to do the calculation in. If this is the same size
as original, no memory allocation will occur in finding the
determinant.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation is now ready.
Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if workspace is not a separate matrix from original.
3. Returns FALSE if either of the matrices is busy doing any stepwise operation.
4. Returns FALSE if original is not a square matrix.
5. Returns FALSE if workspace cannot be resized to the correct dimensions.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of workspace are destroyed by this method.
ProcessSteps (Method)
This method computes the determinant of an already locked-in matrix.
The operation will perform the next steps sub-operations of the complete task.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Outputs
Name IEC 61131 Type Description
determinant struct_ComplexRect The determinant of the matrix. Zero if the calculation is
incomplete or the matrix is not invertible.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Decrements steps by the number of sub-operations performed.
3. Returns TRUE and outputs the calculated determinant if the algorithm completed
before steps was exhausted.
4. Returns FALSE and outputs a determinant of zero if LockMatrices() has not
been called or steps was exhausted before completing the algorithm.
5. In the case that the matrix is not invertible, outputs a determinant of zero.
ProcessTimed (Method)
This method computes the determinant of an already locked-in matrix.
The operation will perform work for the next duration microseconds toward the complete
matrix operation.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Outputs
Name IEC 61131 Type Description
determinant struct_ComplexRect The determinant of the matrix. Zero if the calculation is
incomplete or the matrix is not invertible.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
3. Decrements duration by the microseconds consumed.
4. Returns TRUE and outputs the calculated determinant if the operation completed
before duration was exhausted.
5. Returns FALSE and outputs a determinant of zero if LockMatrices() has not
been called or duration was exhausted before completing the algorithm.
6. In the case that the matrix is not invertible, outputs a determinant of zero.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixGaussianElim (Class)
This class handles the locking handshakes and the state required to simplify the matrix to
a diagonal ones matrix with trailing columns using Gaussian elimination over the course
of multiple scans. The contents of coefficients are destroyed and the contents of solutions
are modified by this class.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform the Gaussian elimination. It must be called before
each calculation to be performed.
Inputs/Outputs
Name IEC 61131 Type Description
coefficients class_Matrix The coefficients of the variables being solved for.
solutions class_Matrix The right hand side of the system of equations.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination is now ready.
Processing
1. Returns FALSE if either matrix is not initialized.
2. Returns FALSE if coefficients is not a separate matrix from solutions.
3. Returns FALSE if either matrix is busy doing any stepwise operation.
4. Returns FALSE if coefficients has fewer columns than rows.
5. Returns FALSE if solutions is not one column with the same number of rows as
coefficients.
6. Returns FALSE if it cannot lock both matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
ProcessSteps (Method)
This method performs Gaussian elimination on two already locked-in matrices.
The operation will perform the next steps sub-operations of the complete calculation.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Outputs
Name IEC 61131 Type Description
error BOOL This algorithm cannot solve this system of equations.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Reduces the first Rows • Rows of coefficients to an identity matrix using elementary
row operations.
3. Performs the same row operations on solutions.
4. If at any time the row operations cannot reduce coefficients further and there is still
not an identity matrix on the left, the operation is terminated and error is set.
5. Decrements steps by the number of operations performed.
6. Returns TRUE if the Gaussian elimination completed before steps was exhausted.
7. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
8. The contents of coefficients are destroyed and the contents of solutions are modified
by this method.
ProcessTimed (Method)
This method performs Gaussian elimination on two already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
inversion algorithm.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Outputs
Name IEC 61131 Type Description
error BOOL This algorithm cannot solve this system of equations.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Reduces the first Rows • Rows of coefficients to an identity matrix using elementary
row operations.
3. Performs the same row operations on solutions.
4. If at any time the row operations cannot reduce coefficients further and there is still
not an identity matrix on the left, the operation is terminated and error is set.
5. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
6. Decrements duration by the microseconds consumed.
7. Returns TRUE if the Gaussian elimination completed before duration was exhausted.
8. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
9. The contents of coefficients are destroyed and the contents of solutions are modified
by this method.
The table, listed for the previous method, is provided as reference for interpreting output
combinations.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixInvert (Class)
This class handles the locking handshakes and the state required to create the inverse of a
square matrix over the course of multiple scans. The contents of original are destroyed in
the process so if the data are still desired, they must be copied before this class is used. The
entire operation will complete before the function returns.
One common use case for inverting a matrix is to solve a system of equations. In this library
that use case is discouraged unless solving the same system for many solutions as Gaussian
elimination performs the same functionality with less overhead.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to invert a matrix. (result = original-1 ). It must be called
before each inversion to be performed.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to invert.
result class_Matrix The inverted matrix.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the inversion operation is now ready.
Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if result is not a separate matrix from original.
3. Returns FALSE if any of the matrices is busy doing any stepwise operation.
4. Returns FALSE if original is not a square matrix.
5. Returns FALSE if result cannot be sized correctly to store the product.
ProcessSteps (Method)
This method performs the inversion algorithm on two already locked-in matrices.
The operation will perform the next steps sub-operations of the complete inversion algo-
rithm.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Outputs
Name IEC 61131 Type Description
error BOOL The matrix is not invertible.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the inversion completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Sets result to an identity matrix.
3. Reduces original to an identity matrix using elementary row operations.
4. Performs the same row operations on result to create the inverse.
5. If at any time the row operations cannot reduce original further and it is still not an
identity matrix, the operation is terminated and error is set.
6. Decrements steps by the number of operations performed.
7. Returns TRUE if the inversion algorithm completed before steps was exhausted.
8. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
9. The contents of original are destroyed by this method.
ProcessTimed (Method)
This method performs the inversion algorithm on two already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
inversion algorithm.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Outputs
Name IEC 61131 Type Description
error BOOL The matrix is not invertible.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the inversion completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Sets result to an identity matrix.
3. Reduces original to an identity matrix using elementary row operations.
4. Performs the same row operations on result to create the inverse.
5. If at any time the row operations cannot reduce original further and it is still not an
identity matrix, the operation is terminated and error is set.
6. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
7. Decrements duration by the microseconds consumed.
8. Returns TRUE if the inversion algorithm completed before duration was exhausted.
9. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
10. The contents of original are destroyed by this method.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixMultiply (Class)
This class handles the locking handshakes and the state required to multiply two class_-
Matrix objects over the course of multiple scans.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform a new multiply (result = matrix1 • matrix2). It
must be called before each multiply to be performed.
Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The multiplicand.
matrix2 class_Matrix The multiplier.
result class_Matrix The matrix to store the product.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the multiply operation is now ready.
Processing
1. Returns FALSE if either matrix1 or matrix2 is not initialized.
2. Returns FALSE if result is not a separate matrix from both matrix1 and matrix2.
3. Returns FALSE if any of the matrices are busy doing any stepwise operation.
4. Returns FALSE if Cols of matrix1 does not match Rows of matrix2.
5. Returns FALSE if result cannot be sized correctly to store the product.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
ProcessSteps (Method)
This method performs the multiplication algorithm on three already locked-in matrices.
The operation will perform the next steps sub-operations of the complete multiplication
algorithm.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the multiplication completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Multiplies matrix1 by matrix2.
3. Decrements steps by the number of operations performed.
4. Returns TRUE if the multiply algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
ProcessTimed (Method)
This method performs the multiplication algorithm on three already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
multiplication algorithm.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the multiplication completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Multiplies matrix1 by matrix2.
3. Performs work toward completing the multiplication algorithm, in groups of steps,
until duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the multiply algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixSubtract (Class)
This class handles the locking handshakes and the state required to subtract one class_-
Matrix object from another over the course of multiple scans.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform a new subtraction (result = matrix1 – matrix2). It
must be called before each subtraction to be performed.
Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The minuend.
matrix2 class_Matrix The subtrahend.
result class_Matrix The difference of matrix1 – matrix2.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the subtraction operation is now ready.
Processing
1. Returns FALSE if either matrix1 or matrix2 is not initialized.
2. Returns FALSE if result is not a separate matrix from both matrix1 and matrix2.
3. Returns FALSE any of the matrices are busy doing any stepwise operation.
4. Returns FALSE if the dimensions of matrix1 do not match those of matrix2.
5. Returns FALSE if result cannot be resized to match the dimensions of the other two
matrices.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of result are destroyed by this method.
ProcessSteps (Method)
This method performs the subtraction algorithm on three already locked-in matrices.
The operation will perform the next steps sub-operations of the complete subtraction algo-
rithm.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the subtraction completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Subtracts each element in matrix2 from its corresponding element in matrix1 and
the difference in result.
3. Decrements steps by the number of sub-operations performed.
4. Returns TRUE if the subtraction algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
ProcessTimed (Method)
This method performs the subtraction algorithm on three already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
subtraction algorithm.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the subtraction completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Subtracts each element in matrix2 from its corresponding element in matrix1 and
stores the difference in result.
3. Performs work toward completing the subtraction algorithm, in groups of steps,
until duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the subtraction algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_MatrixTranspose (Class)
This class handles the locking handshakes and the state required to transpose a class_Matrix
object over the course of multiple scans.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform a new matrix transpose. It must be called before
each transpose to be performed.
Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be the Hermitian Transpose.
Before each element is placed in result, it will be conjugated.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to copy from.
result class_Matrix The matrix to copy to.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the transpose operation is now ready.
Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if result is not a separate matrix from original.
3. Returns FALSE if either of the matrices is busy doing any stepwise operation.
4. Returns FALSE if result cannot be resized to the correct dimensions.
5. Returns FALSE if it cannot lock all matrices involved in the operation.
6. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
7. The contents of result are destroyed by this method.
ProcessSteps (Method)
This method transposes an already locked-in matrix.
The operation will perform the next steps sub-operations of the complete matrix transpose.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the transpose completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Copies each element (i, j) from original to element (j, i) of result.
3. If conjugate was TRUE, conjugate each element in result.
4. Decrements steps by the number of sub-operations performed.
5. Returns TRUE if the transpose algorithm completed before steps was exhausted.
6. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
ProcessTimed (Method)
This method transposes an already locked-in matrix.
The operation will perform work for the next duration microseconds toward the complete
matrix transpose.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the transpose completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Copies each element (i, j) from original to element (j, i) of result.
3. If conjugate was TRUE, conjugate each element in result.
4. Performs work toward completing the transpose, in groups of steps, until duration
microseconds is exceeded.
5. Decrements duration by the microseconds consumed.
6. Returns TRUE if the transpose algorithm completed before duration was exhausted.
7. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
class_Matrix_ATA (Class)
This class handles the locking handshakes and the state required for an optimization of the
operation (AT A) transposing the input matrix and multiplying it by the original matrix over
the course of multiple scans.
Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.
LockMatrices (Method)
This method primes the class to perform a new matrix operation AT A. It must be called
before each operation to be performed.
Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be calculated using the Her-
mitian Transpose. Before the transpose step is complete, each
element will be conjugated.
Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix A.
result class_Matrix The matrix for the result.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation is now ready.
Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if result is not a separate matrix from original.
3. Returns FALSE if either of the matrices is busy doing any stepwise operation.
4. Returns FALSE if result cannot be resized to the correct dimensions.
5. Returns FALSE if it cannot lock all matrices involved in the operation.
6. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
7. The contents of result are destroyed by this method.
ProcessSteps (Method)
This method computes AT A of an already locked-in matrix.
The operation will perform the next steps sub-operations of the complete task.
Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Decrements steps by the number of sub-operations performed.
3. Returns TRUE if the algorithm completed before steps was exhausted.
4. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
ProcessTimed (Method)
This method computes AT A of an already locked-in matrix.
The operation will perform work for the next duration microseconds toward the complete
matrix operation.
Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.
Processing
1. Validates that LockMatrices() has been successfully called.
2. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
3. Decrements duration by the microseconds consumed.
4. Returns TRUE if the operation completed before duration was exhausted.
5. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.
Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware
fun_DeleteMatrix
The posted time is the average execution time of 100 consecutive calls when deleting a
matrix.
fun_MatrixAdd
The posted time is the average execution time of 100 consecutive calls when adding two
matrices.
fun_MatrixCopyColumn
The posted time is the average execution time of 100 consecutive calls when copying a
column from one matrix to another.
fun_MatrixDeterminant
The posted time is the average execution time of 100 consecutive calls when operating on
a valid invertable matrix.
fun_MatrixGaussianElim
The posted time is the average execution time of 100 consecutive calls when operating on
a valid matrix that allows the algorithm to run to completion.
fun_MatrixInvert
The posted time is the average execution time of 100 consecutive calls when inverting a
matrix.
fun_MatrixMultiply
The posted time is the average execution time of 100 consecutive calls when multiplying
two matrices.
fun_MatrixSubtract
The posted time is the average execution time of 100 consecutive calls when subtracting
two matrices.
fun_MatrixTranspose
The posted time is the average execution time of 100 consecutive calls when transposing a
matrix.
fun_MatrixTranspose (Hermitian)
The posted time is the average execution time of 100 consecutive calls when calculating
the Hermitian transpose of a matrix.
fun_Matrix_ATA
The posted time is the average execution time of 100 consecutive calls when calculating
AT A.
fun_Matrix_ATA (Hermitian)
The posted time is the average execution time of 100 consecutive calls when calculating
AT A when using the Hermitian transpose.
fun_NewMatrix
The posted time is the average execution time of 100 consecutive calls when allocating a
new matrix.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_DeleteMatrix - 2x2 118 54 6
fun_DeleteMatrix - 8x8 105 49 4
fun_DeleteMatrix - 64x64 119 57 4
fun_MatrixAdd - 2x2 17 7 1
fun_MatrixAdd - 8x8 66 46 4
fun_MatrixAdd - 64x64 5 408 3 299 244
fun_MatrixCopyColumn - 2x2 7 2 1
fun_MatrixCopyColumn - 8x8 10 3 1
fun_MatrixCopyColumn - 64x64 61 36 1
fun_MatrixDeterminant - 2x2 69 41 3
fun_MatrixDeterminant - 8x8 1 118 665 53
fun_MatrixDeterminant - 64x64 515 458 292 846 26 267
fun_MatrixGaussianElim - 2x2 76 39 2
fun_MatrixGaussianElim - 8x8 1 392 731 61
fun_MatrixGaussianElim - 64x64 516 370 296 721 26 789
fun_MatrixInvert - 2x2 74 48 3
fun_MatrixInvert - 8x8 2 092 1 243 105
fun_MatrixInvert - 64x64 1 034 455 581 496 52 648
fun_MatrixMultiply - 2x2 26 15 2
fun_MatrixMultiply - 8x8 1 002 626 51
fun_MatrixMultiply - 64x64 554 947 325 479 26 534
fun_MatrixSubtract - 2x2 13 6 1
fun_MatrixSubtract - 8x8 90 41 4
fun_MatrixSubtract - 64x64 5 341 3 066 242
fun_MatrixTranspose - 2x2 8 4 1
fun_MatrixTranspose - 8x8 29 12 1
fun_MatrixTranspose - 64x64 2 447 1 731 71
fun_MatrixTranspose (Hermitian) - 2x2 14 7 1
fun_MatrixTranspose (Hermitian) - 8x8 97 48 3
fun_MatrixTranspose (Hermitian) - 64x64 6 071 3 699 192
fun_Matrix_ATA - 2x2 26 15 1
fun_Matrix_ATA - 8x8 563 318 29
fun_Matrix_ATA - 64x64 308 482 179 945 13 186
fun_Matrix_ATA (Hermitian) - 2x2 34 19 1
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
This becomes a 3x4 matrix which, after Gaussian elimination, appears as follows:
1 2 3 2 1 0 0 5
2 3 1 2 => 0 1 0 −3
3 2 1 10 0 0 1 1
Assumptions
Each scan the user has placed the values to use into a pair of arrays of struct_ComplexRect
objects, Values and Answers, before this program is called.
Solution
The user can call this program each scan to receive a solution for the provided inputs, as
shown in Code Snippet 22.1.
Row : UINT;
Col : UINT;
END_VAR
Assumptions
The user has created an enumeration to assist in managing the data flow to the desired
outcome.
Solution
The user can call this program each scan, as shown in Code Snippet 22.3, to receive a
solution for the provided inputs. When Begin is set to true, the calculation will commence.
When the program has copied the answer into Solution, the program sets the Complete flag
to true.
Row : UINT;
Col : UINT;
Steps : UDINT;
Scans : UDINT;
Begin : BOOL;
Complete : BOOL;
END_VAR
Troubleshooting a Matrix
Objective
The user has designed a solution with matrices to perform some set of calculations and
something is not going as desired. The user would like to have additional insight into the
matrix element values for online troubleshooting.
Assumptions
This solution assumes a static matrix size. This is not required but if the Rows and Cols
variables of the matrix do not match the sizes provided for the troubleshooting variable,
the user must realize that only data up to the size of the matrix are valid.
Solution
The user can add an additional pointer variable to provide additional insight during runtime.
The syntax for this pointer is shown in Code Snippet 22.4.
PacketEncoding
Introduction
The PacketEncoding library provides functions and classes to decode from and encode to
common data representations.
Various functions translate bytes of data to and from classes that facilitate storing informa-
tion in an easy-to-use manner.
Special Considerations
Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.
// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_VectorObject"
myVectorObject := otherVectorObject;
// This is fine
someVariable := myVectorObject.value;
// As is this
pt_myVectorObject := ADR(myVectorObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_Asn1ClassType
Enumeration Value Description
UNIVERSAL 0 The type is native to ASN.1.
APPLICATION 1 The type is only valid for one specific application.
CONTEXT_SPECIFIC 2 The meaning of this type depends on the context.
SPECIAL_PRIVATE 3 This type is defined in private specifications.
enum_Asn1UniversalClassTags
Enumeration Value
EOC 00
BOOLEAN 01
INTEGER 02
BIT_STRING 03
OCTET_STRING 04
NULL 05
OBJECT_IDENTIFIER 06
OBJECT_DESCRIPTOR 07
EXTERNAL 08
REAL_FLOAT 09
ENUMERATED 10
EMBEDDED_PDV 11
UTF8_STRING 12
RELATIVE_OID 13
RESERVED_1 14
RESERVED_2 15
SEQUENCE 16
SET 17
NUMERIC_STRING 18
PRINTABLE_STRING 19
T61_STRING 20
VIDEOTEX_STRING 21
IA5_STRING 22
UTC_TIME 23
GENERALIZED_TIME 24
GRAPHIC_STRING 25
VISIBLE_STRING 26
GENERAL_STRING 27
UNIVERSAL_STRING 28
CHARACTER_STRING 29
BMP_STRING 30
LONG_FORM 31
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_Asn1Index
Name IEC 61131 Type Description
Class enum_Asn1ClassType The class as defined by the first two Identifier
bits.
Constructed BOOL True for constructed entries, False for prim-
itive entries.
TagNumber enum_Asn1UniversalClassTags The type of the entry.
BytesInValue UDINT The number of content bytes.
Index UDINT The starting location of the content bytes as a
byte offset from the beginning of the parsed
byte array.
Functions
This library provides the following functions.
fun_IndexAsn1Packet
Walk the provided byte array and populate a class_Asn1IndexVector with the size, starting
index, and type of each first level entry in an ASN.1 packet as defined by the “Basic Encod-
ing Rules” (BER), the superset of encoding algorithms explained in the ASN.1 standard.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The packet to parse.
numBytes UDINT The number of bytes in the provided packet.
Inputs/Outputs
Name IEC 61131 Type Description
parsedData class_Asn1IndexVector The vector for storing the list of data types and indices.
Return Value
IEC 61131 Type Description
BOOL TRUE if all data objects were indexed successfully.
Processing
The fun_IndexAsn1Packet() function does the following:
ä Validates pt_data for readability.
ä Clears all data from parsedData.
ä Locates the beginning of each first-level data entry in the packet.
ä Stores the class, tag number, and length in bytes of each entry found as well as
whether the entry is primitive or constructed.
ä Stores the index zero for any objects of length zero.
ä Stores the index of the first content byte of the entry as a byte offset from pt_data for
all other data types.
This is accomplished by traversing the entire byte array from the beginning to the end.
Any failure in parsing data results in an error and the function stops attempting to parse
the provided data. The algorithm in use takes the first byte and interprets it to find the
type of data being encoded. If the function finds a tag type of 0b11111 the next bytes are
interpreted as the type of the data. If more than 32 bits of data are used to encode the type,
then this method will return an error. The function interprets the next bytes as the length
of the data.
Three length definitions are allowed:
1. A value less than 0x80 is a direct reference to the length. The function tags the next
byte as the index and skips to the end of the object as defined by its length.
2. A value of 0x80 indicates that the length is not predefined. This value is only al-
lowed for constructed types. The function tags the next byte as the index and im-
mediately terminates the object. The function parses subsequent objects for length
and ignores the content until it finds one End-of-Content object for each previously
recorded length 0x80. The length becomes the accumulation of all the sizes of the
child objects, including their headers.
3. A value between 0x81 and 0x84 indicates that one to four subsequent bytes define
the length of the object as an unsigned integer. The function stores those bytes as
the length and places the index directly after them. It then skips to the end of the
object as defined by its length and the next object begins.
Though values larger than 0x84 are legal, they define numbers of bytes larger than this
library can index and result in an error.
This process repeats for each object found until the end of the provided data. If the final
length sends the function beyond the end of the array or unclosed length 0x80 objects
remain, the function returns an error.
0101FF02038765430904A73546FF048180<128 Octets>
Becomes
0101FF BOOLEAN length 1 index 2
0203876543 INTEGER length 3 index 5
0904A73546FF REAL_FLOAT length 4 index 10
fun_DecodeAsn1_Boolean
Decode a Boolean encoded in ASN.1 following the Basic Encoding Rules.
Inputs
Name IEC 61131 Type Description
data BYTE The byte to parse. This should be the byte at the index returned
by fun_IndexAsn1Packet().
Inputs/Outputs
Name IEC 61131 Type Description
value BOOL The result of parsing the data.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the Boolean.
Processing
The fun_DecodeAsn1_Boolean() function does the following:
1. Parses the provided byte into a Boolean.
2. Returns TRUE if the function encountered no errors during parsing.
This function recognizes any non-zero value as TRUE and only the value of zero as FALSE.
0b11001100 = TRUE
0b00000001 = TRUE
0b00000000 = FALSE
fun_DecodeAsn1_Integer
Decode an integer encoded in ASN.1 following the “Basic Encoding Rules.”
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of the
Index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This
should be the BytesInValue returned by fun_-
IndexAsn1Packet().
Inputs/Outputs
Name IEC 61131 Type Description
value DINT The result of parsing the data.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the integer.
Processing
The fun_DecodeAsn1_Integer() function does the following:
1. Validates pt_data for readability.
2. Parses the bytes provided into an integer.
3. Returns FALSE if rollover prevents the function from returning the exact value.
4. Returns TRUE if the function encounters no errors during parsing.
This function expects the provided bytes to be an integer represented in two’s complement
notation using the least number of bytes possible. It only parses numbers represented by
four or fewer bytes.
0x80 = -128
0xFF80 results in an error because it uses more bytes than necessary.
0x7F7F = 32639
0x007F7F results in an error because it uses more bytes than necessary.
fun_DecodeAsn1_Enumerated
Decode an enumeration encoded in ASN.1 following the “Basic Encoding Rules.”
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of then
Index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This
should be the BytesInValue returned by fun_-
IndexAsn1Packet().
Inputs/Outputs
Name IEC 61131 Type Description
value DINT The result of parsing the data.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the enumeration.
Processing
The fun_DecodeAsn1_Enumerated() function does the following:
1. Validates pt_data for readability.
2. Parses the bytes provided into an integer.
3. Returns FALSE if rollover prevents returning the exact value.
4. Returns TRUE if the function encountered no errors during parsing.
This function expects the provided bytes to be an integer represented in two’s complement
notation using the least number of bytes possible. It only parses numbers represented by
four or fewer bytes.
0x80 = -128
0xFF80 results in an error because it uses more bytes than necessary.
0x7F7F = 32639
0x007F7F results in an error because it uses more bytes than necessary.
fun_DecodeAsn1_Object_Identifier
Decode an Object Identifier (OID) encoded in ASN.1 following the “Basic Encoding Rules”
to a list of UDINTs.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of the
index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This
should be the BytesInValue returned by fun_-
IndexAsn1Packet().
Inputs/Outputs
Name IEC 61131 Type Description
value class_DwordVector The vector for storing the list of OID entries.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the OID.
Processing
The fun_DecodeAsn1_Object_Identifier() function does the following:
1. Validates pt_data for readability.
2. Clears all data from value.
3. Parses the bytes provided into an OID.
4. Returns FALSE if rollover prevents the function from returning exact values.
5. Returns TRUE if the function encountered no errors during parsing.
This function expects the provided bytes to appear as a sequence of unsigned integers rep-
resented in the fewest bytes possible. Any byte with the value 1 as its most significant bit
indicates that the next byte is part of the same integer value. A value of one in the most sig-
nificant bit of the final byte of the referenced data indicates the OID would extend beyond
numBytes and the function returns FALSE. If any unsigned integer begins with 0x80, the
number is represented by more bytes than required and the function returns FALSE. The
function also returns FALSE if any unsigned integer requires more than 32 bits to contain
its value.
After finding the first unsigned integer, the function parses it into two distinct values. For
this example, consider val to be the first unsigned integer found. If val is between 0 and
39, the OID begins with 0.val. If val is between 40 and 79, the OID begins with 1.(val-40).
Finally, if val is greater than 79 the OID begins with 2.(val-80).
0x2B0601040181F84F01952A0D040100
Broken into parts
0x2B 0x06 0x01 0x04 0x01 0x81F84F 0x01 0x952A 0x0D 0x04
0x01 0x00
Extra formatting stripped
0x2B => 40 & 3 => 1.3
fun_DecodeAsn1_Real
Decode a floating point number encoded as ASN.1 in base 2, 8, or 16 according to the
“Basic Encoding Rules.”
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of the
index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This should be
the BytesInValue returned by fun_IndexAsn1Packet().
Inputs/Outputs
Name IEC 61131 Type Description
value REAL The decoded floating point number.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the number.
Processing
The fun_DecodeAsn1_Real() function does the following:
1. Validates pt_data for readability.
2. Validates the format and base found in pt_data.
3. Parses the bytes provided into a real.
4. Returns TRUE if the function encounters no errors during parsing.
The ASN.1 standard allows reals to be encoded through the use of both binary values and
character-based encodings. This function only decodes reals that are encoded as binary
values in base 2, 8, or 16.
The decoding of a real happens in eight steps:
1. This function checks for any special values (see Special Bit Patterns for Reals for
details).
2. If numBytes is two, this function returns FALSE because there are no valid real
encodings of length two.
3. This function checks the first byte to ensure it can be parsed. Bit 8 must be one. Bit
7 stores the sign of the value. Bits 6–5 represent the base of the number (B): 0b00 is
base 2, 0b01 is base 8, 0b10 is base 16, and 0b11 is invalid. Bits 4–3 are interpreted
as an unsigned number defining a power of two by which to shift the result (F). Bits
2–1 help delineate the length of the exponent in bytes. A value of 0b00 means one
byte of exponent, 0b01 two bytes, 0b10 three bytes, and 0b11 means the next byte
defines the length as a value from 0–255.
4. Because ASN.1 states the exponent must be represented in the fewest bytes pos-
sible, this function rounds any value with an exponent of three or more bytes to
positive/negative zero or infinity because it cannot represent numbers that large or
small.
5. The exponent is parsed as a two’s complement number (E) and saved.
6. The function interprets as many as the first four of the remaining bytes as an un-
signed integer.
7. Each byte greater than four results in the addition of eight to F, truncating the man-
tissa (M) to a size this function can handle.
8. Finally, the function calculates the result as (M • 2F • BE ), then adds the appropriate
sign.
0xD40C4567 M = 17767 E = 12 B = 8 F = 1
0x8DFF7F01030307 M = 16974599 E = -129 B = 2 F = 3
0x8DFF7F01030307AD M = 16974599 E = -129 B = 2 F = 11
fun_SerializeAsn1_Boolean
Place the provided Boolean value as the next entry in an ASN.1 BER message.
Inputs
Name IEC 61131 Type Description
value BOOL The value to use as the payload of this Boolean.
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the Boolean.
Processing
The fun_SerializeAsn1_Boolean() function does the following:
1. Serializes value and appends it as the next entry in message.
2. Returns TRUE if value was added to message.
This function appends 0x010100 for false and 0x010101 for true.
fun_SerializeAsn1_Integer
Place the integer value provided as the next entry in an ASN.1 BER message.
Inputs
Name IEC 61131 Type Description
value DINT The value to use as the payload of this integer.
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the integer.
Processing
The fun_SerializeAsn1_Integer() function does the following:
1. Serializes value and appends it as the next entry in message.
2. Returns TRUE if value was added to message.
This function determines the fewest number of bytes necessary to encode the provided
integer by checking the most significant byte and the next bit for all ones or all zeros and
dropping the byte from the number. This process can be repeated as many as three times.
After this process completes, it appends the following to the message: 0x02, the number
of significant bytes, and the bytes themselves.
-1 0x0201FF
1 0x020101
134217728 0x02040F000000
-134217728 0x0204F8000000
fun_SerializeAsn1_Enumerated
Place the integer value provided as the next entry in an ASN.1 BER message.
Inputs
Name IEC 61131 Type Description
value DINT The value to use as the payload of this enumeration.
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the enumeration.
Processing
The fun_SerializeAsn1_Enumerated() function does the following:
1. Serializes value and appends it as the next entry in message.
2. Returns TRUE if value was added to message.
This function determines the fewest number of bytes necessary to encode the provided
integer by checking the most significant byte and the next bit for all ones or all zeros and
dropping the byte from the number. This process can be repeated as many as three times.
After this process completes, it appends the following to the message: 0x02, the number
of significant bytes, and the bytes themselves.
-1 0x0201FF
1 0x020101
134217728 0x02040F000000
-134217728 0x0204F8000000
fun_SerializeAsn1_Real
Place the real provided as the next entry in an ASN.1 BER message.
Inputs
Name IEC 61131 Type Description
value REAL The value to use as the payload of this real.
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the real.
Processing
The fun_SerializeAsn1_Real() function does the following:
1. Serializes value as a base 2 floating point number and appends it as the next entry
in message.
2. Returns true if value was added to message.
This function serializes every real as a base 2 binary encoded real. First, it checks for any
special value encodings as listed in Special Bit Patterns for Reals. If this real is not a special
case, this method breaks the real into its constituent parts. This process consists of four
steps:
1. The sign is pulled from Bit 32, the exponent from Bits 31 to 24, and the mantissa
from Bits 23 to 1.
2. If the exponent is zero, the mantissa is saved as is. Otherwise the function prepends
a one to the mantissa as the 24th bit.
3. If the exponent is zero, a value of one is added to it. Then the function subtracts 127
subtracted from the exponent to turn it into a two’s complement, signed number; the
function also subtracts 23 from it to remove the decimal point from the mantissa.
4. The function generates a descriptive byte where Bit 8 is one, Bit 7 is one for negative
and zero for positive, Bits 6–2 are zero, and Bit 1 is one for an exponent requiring
a two byte representation and zero for an exponent requiring one byte.
This function then appends 0x09; a length of 0x00, 0x01, 0x05 or 0x06; the descriptive
byte; the exponent; and the mantissa to message.
2.25 0x090580EA900000
-2.25 0x0905C0EA900000
1.25E-38 0x090681FF6B881CEA
1.25E-41 0x090681FF6B0022D8
fun_SerializeAsn1_Object_Identifier
Place the OID provided as the next entry in an ASN.1 BER message.
Inputs/Outputs
Name IEC 61131 Type Description
value class_DwordVector The OID to append to message.
message class_ByteVector The message to which value is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the OID.
Processing
The fun_SerializeAsn1_Object_Identifier() function does the following:
1. Serializes all dwords in value to construct the next entry in message.
2. Returns FALSE if value cannot be serialized.
3. Returns TRUE if value was added to message.
This function starts by adding the first two OID sub entries together ((40 • OID1) + OID2).
Using that result as the first sub entry, it builds a list where each OID sub entry is reduced
to the minimum number of seven-bit segments needed to represent it as an unsigned value.
The function prepends a one to each seven-bit segment except the least significant seven-bit
segment of every sub entry, which the function prepends with a zero. Once all sub entries
have been encoded, the function appends the following to message: 0x06, the number of
bytes representing the sub entries encoded in the same manner as the sub entries themselves,
and the sub entry list.
1.3.6.1.4.1.31823.1.2730.13.4.4.213268340
Insert Extra formatting
OID Enumeration => 0x06
1.3 => 40 & 3 => 0x2B
.6.1.4.1 => 0x06010401
.31823 => 0x7C4F => 0x81F84F
.1 => 0x01
.2730 => 0x0AAA => 0x952A
.13.4.4 => 0x0D0404
.213268340 => 0xCB63774 => 0xE5D8EE74
length => 18 => 0x12
Construct as Enumeration, Length, SubEntry list
0x06122B0601040181F84F01952A0D0404E5D8EE74
fun_SerializeAsn1_Bit_String
Place the bit string provided as the next entry in an ASN.1 BER message.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The bit string to insert.
numBytes UDINT The number of bytes in the string.
ignoreBits USINT The number of bits of invalid data terminating the string.
(Range: 0–7)
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which the bit string is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the bit string.
Processing
The fun_SerializeAsn1_Bit_String() function does the following:
1. Validates pt_data for read access.
2. Limits ignoreBits to a maximum of seven.
3. Appends an entry containing all bytes prescribed to message, masking the last ig-
noreBits bits of the last byte by replacing then with zero.
4. Returns true if the entire bit string was added to message.
This function appends 0x03, numBytes plus one for the ignoreBits information as the length,
ignoreBits, and the data found at pt_data to message, zeroing the final ignoreBits bits.
fun_BeginAsn1Constructed_Bit_String
Place the codes necessary to begin a constructed bit string in an ASN.1 BER message.
For each call to this method the user must call fun_AppendAsn1_Eoc() before the mes-
sage can be considered complete. Only bit strings should be appended to message until the
call to fun_AppendAsn1_Eoc().
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which the entry is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the entry.
Processing
The fun_BeginAsn1Constructed_Bit_String() function:
1. Appends the beginning of a constructed bit string to message, (0x2380).
2. Returns TRUE if the entry was added to message.
fun_AppendAsn1_Eoc
Place the codes necessary to end a variable length entry in an ASN.1 BER message.
To ensure proper packet construction, the user must call this function once for each variable
length entry begun.
Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which the entry is appended.
Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the EOC.
Processing
The fun_AppendAsn1_Eoc() function does the following:
1. Appends the End-of-Content entry to message, 0x0000).
2. Returns TRUE if the EOC was added to message.
fun_EncodeBase64_MIME
Encodes a byte vector into base64-MIME format. See base64 and MIME descriptions in
RFC 2045 for complete definition of these encodings and their usage. A common example
is encoding the bytes of a file to be sent as email attachments.
Inputs/Outputs
Name IEC 61131 Type Description
source class_ByteVector The raw byte data to encode.
encoded class_ByteVector The encoded output of source.
Return Value
IEC 61131 Type Description
BOOL TRUE if data was successfully encoded; returns FALSE only if source was
empty.
Processing
The fun_EncodeBase64_MIME() function does the following:
1. Encodes the raw-bytes of source, writing the base64-MIME encoded output to en-
coded. Note that source will not be modified as a result of calling this function.
2. Returns TRUE if input was encoded successfully; returns FALSE only if source
was empty.
This function encodes a raw byte vector in base64-MIME. The output encoded will be
approximately 133% the size of source.
fun_DecodeBase64_MIME
Decodes a byte vector encoded in base64-MIME format. See base64 and MIME descrip-
tions in RFC 2045 for complete definition of these encodings and their usage.
Inputs/Outputs
Name IEC 61131 Type Description
source class_ByteVector The base64-MIME encoded data to decode.
decoded class_ByteVector The decoded output of source.
Return Value
IEC 61131 Type Description
BOOL TRUE if data was successfully decoded without any corruption detected.
Returns FALSE if source contains only invalid characters or if the number
of valid characters in source is not a multiple of four.
Processing
The fun_DecodeBase64_MIME() function does the following:
1. Decodes the base64-MIME encoded input of source, placing output in decoded.
Invalid, non-base64 characters in source are ignored. Note that source will not be
modified as a result of calling this function.
2. Processes valid base64 characters in groups of four. It fails only if terminal charac-
ters are incorrectly placed or if the number of valid characters is not a multiple of
four.
3. Stops processing after the first group of four characters containing a terminal char-
acter.
4. If source is empty, then the function will return TRUE.
This function decodes a base64-MIME encoded string. The size of decoded will be ap-
proximately 75% of source.
source := RHJpbmsgcGxlbnR5IG9mIE92YWx0aW5l
decoded := Drink plenty of Ovaltine
Classes
Classes are a particular implementation of a Function Block(FB). They provide Methods
and Properties, which a normal FB does not provide.
class_Asn1IndexVector (Class)
This class provides a DynamicVector structured specifically to store indexing information
about a byte array encoded in ASN.1. NOTE: For more information on the
I_Vector interface, see the
DynamicVectors library
documentation.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector
GetAt (Method)
Provides a copy of the element at the specified index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.
Outputs
Name IEC 61131 Type Description
element struct_Asn1Index The element at the specified index. If the return value is
FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.
SetAt (Method)
This method provides write access to any element within the vector.
Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value struct_Asn1Index The new element value.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and the method returns FALSE.
Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.
Outputs
Name IEC 61131 Type Description
element struct_Asn1Index A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.
Push (Method)
This method appends a copy of the provided element to the end of the vector.
Inputs
Name IEC 61131 Type Description
element struct_Asn1Index The element to copy to the end of the vector.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the vector. FALSE if an error
occurs.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware
fun_DecodeAsn1_Boolean
The posted time is the average execution time of 100 consecutive calls.
fun_DecodeAsn1_Integer
The posted time is the average execution time of 100 consecutive calls.
fun_DecodeAsn1_Enumerated
The posted time is the average execution time of 100 consecutive calls.
fun_DecodeAsn1_Object_Identifier
The posted time is the average execution time of 100 consecutive calls. The encoded object
identifier that is decoded has a value of (1, 17, 19).
fun_DecodeAsn1_Real
The posted time is the average execution time of 100 consecutive calls.
fun_SerializeAsn1_Boolean
The posted time is the average execution time of 100 consecutive calls.
fun_SerializeAsn1_Integer
The posted time is the average execution time of 100 consecutive calls.
fun_SerializeAsn1_Enumerated
The posted time is the average execution time of 100 consecutive calls.
fun_SerializeAsn1_Real
The posted time is the average execution time of 100 consecutive calls.
fun_SerializeAsn1_Object_Identifier
The posted time is the average execution time of 100 consecutive calls. The object identifier
encoded has a value of (1, 17, 19).
fun_SerializeAsn1_Bit_String
The posted time is the average execution time of 100 consecutive calls. The bit string
encoded has a ASCII value of “Hello World”.
fun_BeginAsn1Constructed_Bit_String
The posted time is the average execution time of 100 consecutive calls.
fun_AppendAsn1_Eoc
The posted time is the average execution time of 100 consecutive calls.
Benchmark Results
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example shows the parsing of a static byte array. To truly use this functionality, the
user would need to populate that array after collecting the data from the network.
Solution
The user can create the program found in Code Snippet 23.1 to parse the byte array.
// Iterator counts.
ListPosition : UDINT;
ObjectCount : UDINT;
Assumptions
This example shows the parsing of a static byte array. To truly use this functionality the
user would need to populate that array after collecting the data from the network.
Solution
The user can create the program found in Code Snippet 23.2 to parse the byte array.
Assumptions
The RTAC also has access to the SELEthernetControllers library. The listening server must
know the format of the incoming data.
Solution
The user can create the program found in Code Snippet 23.3 to build the data package.
// Counting variable.
i : UDINT;
END_VAR
Assumptions
The RTAC has access to the DynamicVectors and FileIo libraries and has a file called
binaryData.data in the /FILES folder of the virtual file system.
Solution
The user can create the program found in Code Snippet 23.4 to encode their data in base64-
MIME and store the encoded data to the local file system.
IF alarm THEN
IF NOT complete THEN
IF firstRead THEN
fileReader.ReadFile(dataFile);
firstRead := FALSE;
ELSIF fileReader.BytesInBuffer > 0 THEN
rawData.Recycle();
fileReader.AppendToVector(0,rawData);
//encode the raw data in base64-MIME
PacketEncodings.fun_EncodeBase64_MIME(source := rawData,
encoded := encodedData);
writeFile := TRUE;
END_IF
IF writeFile THEN
fileWriter.AppendVector(encodedData);
writeFile := FALSE;
complete := TRUE;
END_IF
PowerMetering
Introduction
This library provides objects for performing common power metering functions. These
functions provide event times for minimum and maximum thresholds, accumulated energy
over time, demand over a configurable length of time, and KYZ/KY accumulators. Exam-
ple applications include use of these function blocks with Axion analog input, digital input,
and/or CT/PT (current transformer/potential transformer) modules.
Function Blocks
fb_Maximum
Compare input value to stored maximum value, update output if greater, and record the
date/time of occurrence.
Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided initial
values; a value of TRUE results in setting Maximum to
zero and the time stamp to the present time.
initialValue REAL Maximum value to use for initialization if set-
tingsChange is FALSE.
initialTime timestamp_t Time stamp value to use for initialization if set-
tingsChange is FALSE.
Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable maximum comparison.
AnalogQuantity REAL Value to check against Maximum.
Reset BOOL Flag to reset Maximum and time stamp.
Outputs
Name IEC 61131 Type Description
Maximum REAL Maximum value.
EventTime timestamp_t The moment at which Maximum was last updated.
Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, Maximum is set to zero and
will take on the next AnalogQuantity received.
ä Compare the input AnalogQuantity to the stored Maximum value.
ä If the input is greater than the stored value for two or more samples, update Maximum
and record the date and time of occurrence.
fb_Minimum
Compare input real value to stored minimum value, update output if greater, and record the
date/time of occurrence.
Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided
initial values; a value of TRUE results in setting
Minimum to zero and the time stamp to the present
time.
initialValue REAL Minimum value to use for initialization, if set-
tingsChange is FALSE.
initialTime timestamp_t Time stamp value to use for initialization, if set-
tingsChange is FALSE.
minimumThreshold REAL Lowest value this function block will record.
Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable minimum comparison.
AnalogQuantity REAL Value to check against Minimum.
Reset BOOL Flag to reset Minimum and time stamp.
Outputs
Name IEC 61131 Type Description
Minimum REAL Minimum value.
EventTime timestamp_t The date and time which Minimum was last updated.
Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, Minimum is set to zero and
will take on the next AnalogQuantity received.
ä Compare the input AnalogQuantity to the stored Minimum value.
ä If the input is less than the stored value and greater than minimumThreshold for two
or more samples, update Minimum and record the date and time of occurrence.
ä This function block will work with any values but is designed for use alongside fb_-
Maximum with positive numbers.
fb_Energy
Collect energy input over time, accumulating positive and negative values in separate reg-
isters.
Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided ini-
tial values; a value of TRUE results in setting Ener-
gyIn and EnergyOut to zero.
initialValueIn REAL EnergyIn value to use for initialization, if set-
tingsChange is FALSE.
initialValueOut REAL EnergyOut value to use for initialization, if set-
tingsChange is FALSE.
rolloverThreshold REAL Rollover value for this function block.
Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable energy accumulation.
AnalogQuantity REAL Value to use for accumulating energy.
Reset BOOL Flag to reset EnergyIn and EnergyOut.
Outputs
Name IEC 61131 Type Description
EnergyIn REAL Accumulated energy in.
EnergyOut REAL Accumulated energy out.
Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, EnergyIn and EnergyOut are
set to zero.
ä Maintain the accumulated IN/OUT energy. A negative power value is considered IN
energy while a positive power value is considered OUT energy. Receiving a positive
power value (OUT) will not affect the accumulated IN value and vice versa.
ä Update no more frequently than once a second regardless of the RTE cycle time.
ä Restart either output to zero when it exceeds rolloverThreshold.
fb_Demand
Calculates demand.
Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided
initial values; a value of TRUE results in setting De-
mand to zero.
initialValue REAL Demand value to use for initialization, if set-
tingsChange is FALSE.
demandType Demand_Enum The calculation method this function block will use;
either ROLLING or THERMAL.
timeConstant Time_Constant_Enum The time constant this function block will use dur-
ing demand calculations, MIN5, MIN10, MIN15,
MIN20, MIN30, MIN60.
Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable demand calculation.
AnalogQuantity REAL Value to use for calculating demand.
Reset BOOL Flag to reset Demand.
Outputs
Name IEC 61131 Type Description
Demand REAL Demand value.
Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, Demand is set to zero.
ä Update no more frequently than once a second regardless of the RTE cycle time.
ä Thermal demand output updates with each call to the function block.
ä Thermal demand is a logarithmic average of the power used, with more-recent load
weighted more heavily than less-recent load. For a steady state transition, this block
outputs Demand of 90% of the change after timeConstant has passed.
ä Rolling demand output only updates once every 5 minutes.
ä Rolling demand averages input over periods of 5 minutes and outputs Demand as an
average of enough 5 minute averages to equal timeConstant.
fb_KYZ
Accumulate a count of transitions from only a Y of true to only a Z of true or back again.
Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided initial
values; a value of TRUE results in setting CV and ROV
to zero.
initialCV BCR Initial accumulator state, if settingsChange is FALSE.
initialROV UDINT Initial roll over value, if settingsChange is FALSE.
maxValue UDINT The value of the accumulator at which roll over occurs
Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable the KYZ accumulator.
Y SPS Terminal Y.
Z SPS Terminal Z.
Reset BOOL Flag to reset the state of the KYZ block.
Outputs
Name IEC 61131 Type Description
CV BCR The number of transitions from Y to Z or Z to Y.
ROV UDINT The number of times CV has reset to zero.
Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, CV is set to the default state
and ROV is set to zero.
ä Monitor Y and Z when EN is TRUE and Reset is FALSE.
ä Define a countable state as Y and Z being in opposite states with qualities of good.
ä Define a countable transition as the present inputs being in a countable state and the
present state of the inputs is opposite to the previous counted state of the inputs.
ä Count only at times when both Y and Z report good quality (i.e., q.validity = good).
ä Set the CV quality attribute based on the input with the least quality (i.e., if input
Y.q.validity is invalid and Z.q.validity is good, then CV.q.validity is invalid).
ä Override the quality of CV to invalid if the block is disabled or being reset.
ä Increment ROV and the accumulator to zero when the accumulator equals maxValue.
The practical implication is that maxValue declared at initialization is never reported,
but instead the accumulator rolls over to zero allowing the total count to be calculated
as CV + ROV • maxValue.
fb_KY
Accumulate a count of transitions of a single variable Y.
Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided initial
values; a value of TRUE results in setting CV and ROV
to zero.
initialCV BCR Initial accumulator state, if settingsChange is FALSE.
Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable the KY accumulator.
Y SPS Terminal Y.
Reset BOOL Flag to reset the state of the KY block.
Outputs
Name IEC 61131 Type Description
CV BCR The number of transitions of Y.
ROV UDINT The number of times CV has reset to zero.
Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, CV is set to the default state
and ROV is set to zero.
ä Monitor Y when EN is TRUE and Reset is FALSE.
ä Define a countable transition as the present input being opposite its previous value.
ä Count only at times when Y reports good quality (i.e., q.validity = good).
ä Set the CV quality attribute as the quality of the input.
ä Override the quality of CV to invalid if the block is disabled or being reset.
ä Increment ROV and the accumulator to zero when the accumulator equals maxValue.
The practical implication is that maxValue declared at initialization is never reported,
but instead the accumulator rolls over to zero allowing the total count to be calculated
as CV + ROV • maxValue.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R135-V1 firmware
ä SEL-3530
â R135-V2 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V0 firmware
fb_Minimum
The posted time is the average execution time of 100 calls in which a new minimum value
was observed. This constitutes the longest running time for this call.
fb_Energy
The posted time is the average execution time of 100 calls at the top of the second. This
constitutes the longest running time for this call.
fb_Demand (Thermal)
The posted time is the average execution time of 100 calls at the top of the second. This
constitutes the longest running time for this call.
fb_Demand (Rolling)
The posted time is the average execution time of 100 calls at a 5-minute boundary. This
constitutes the longest running time for this call.
fb_KYZ
The posted time is the average execution time of 100 calls where the block incremented.
This constitutes the longest running time for this call.
fb_KY
The posted time is the average execution time of 100 calls where the block incremented.
This constitutes the longest running time for this call.
Benchmark Results
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Maximum
Objective
A user has an analog variable and wants to determine the greatest observed value of the
analog.
Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for non-volatile variables while the second program assumes
there is a requirement that variables are retained through power loss.
Solution
The user can create a program as shown in Code Snippet 24.1. Note that this example does
not use retain variables.
PROGRAM prg_Maximum_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;
Minimum
Objective
A user has an analog variable and wants to determine the smallest observed value of the
analog.
Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables, and the second program assumes
there is a requirement that variables are retained through power loss.
Solution
The user can create a program as shown in Code Snippet 24.3. Note that this example does
not use retain variables.
PROGRAM prg_Minimum_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;
MinThreshold : REAL := 50000;
Energy
Objective
A user has a power quantity and wants to keep track of energy flow. Positive power value
is considered to be “out” and negative power is considered to be “in.”
Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.
Solution
The user can create a program as shown in Code Snippet 24.5. Note that this example does
not use retain variables.
EnergyIn : REAL;
EnergyOut : REAL;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD := 1;
END_VAR
PROGRAM prg_Energy_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;
Threshold : REAL;
Demand
Objective
A user wants to calculate demand on an analog quantity.
Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.
Solution
The user can create a program as shown in Code Snippet 24.7. Note that this example does
not use retain variables.
KYZ
Objective
A user has two inputs connected to the Y and Z terminal of a meter and wants to count the
number of transitions.
Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.
Solution
The user can create a program as shown in Code Snippet 24.9. Note that this example does
not use retain variables.
PROGRAM prg_KYZ_Example
VAR
//Terminal for Y and Z pulses
DI_Y_Terminal : SPS;
DI_Z_Terminal : SPS;
//Enabling and Rest Conditions
Enable : BOOL;
Reset : BOOL;
KY
Objective
A user has one input connected to the Y terminal of a meter and wants to count the number
of transitions.
Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.
Solution
The user can create a program as shown in Code Snippet 24.11. Note that this example
does not use retain variables.
Retain Variables
Note on Usage
Retain variables allow values to persist through removal and restoration of power, a reboot,
and some program downloads. To accomplish this, retain variables point to a specific
location in nonvolatile memory. This results in a situation where changing the definition
of any retain variable (e.g., creating or deleting variables or changing variable order), can
result in the variables pointing to a different location in memory, meaning an incorrect
value would be used in logic. Therefore, you should initialize all retain variables when you
change or add any retain variable declarations. Furthermore, it is best practice to keep all
retain variables in the same global variable list to avoid the opportunity of the lists being
reordered.
PowerSystemAutomation
Introduction
The PowerSystemAutomation library includes function blocks that can be used for bay
control applications and other power system automation applications.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := mySynchronismCheckObject.value;
// As is this
pt_mySynchronismCheckObject := ADR(mySynchronismCheckObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_SlipFreqStatus
This enumeration defines the status of the slip frequency.
Enumeration Description
UnderSlipFreqMin Absolute value of the slip frequency is less than the minimum allowed slip
frequency set by the user.
PositiveSlipFreq The slip frequency is in the range between the minimum and maximum
slip frequency settings set by the user, and the synchronizing frequency is
higher than the reference frequency.
NegativeSlipFreq The slip frequency is in the range between the minimum and maximum
slip frequency settings set by the user, and the synchronizing frequency is
lower than the reference frequency.
OverSlipFreqMax Absolute value of the slip frequency is greater than the maximum allowed
slip frequency set by the user.
Function Blocks
fb_SynchronismCheck (Function Block)
The SynchronismCheck function block provides functionality to indicate synchrony be-
tween two voltage sources. To appropriately determine synchronism, each voltage source
must provide simultaneous magnitudes and angles. Thus, this function block requires
time stamps with each measurement to validate time-alignment. Additionally, this func-
tion block assumes that voltage magnitudes are represented on the same scale (primary or
secondary).
The Synchronized Boolean output is set to TRUE when the synchronizing voltage is within
the allowed phase and magnitude with the reference voltage. The following describes how
the CircuitBreakerCloseTimeMs setting value dictates the behavior of the Synchronized
output:
ä No-compensation mode (CircuitBreakerCloseTimeMs = 0): The Synchronized out-
put is set to TRUE if the absolute value of the angle between the synchronizing
voltage and the reference voltage is lower than the maximum angle difference set by
the user, and voltage magnitudes, time stamps, and the slip frequency are within ac-
ceptable range (see Processing section below). Figure 25.1 illustrates the operation
of the Synchronized output in no-compensation mode. The gray triangle indicates
the area where the Synchronized output is set to TRUE.
ä When using C37.118 Synchrophasor data for the voltage and frequency measure-
ments, ensure the data rate is at least 30 messages per second for 60 Hz systems or
25 messages per second for 50 Hz systems.
ä When Fundamental tags from two different Axion AC analog input modules sup-
ply the reference voltage and synchronizing voltage inputs, set the Reference Angle
setting on both modules to No Reference. Selecting No Reference prevents the
module from applying self-reference offsets to their angle measurements, allowing
for appropriate angle comparison between modules.
Inputs
Name IEC 61131 Type Description
EN BOOL Enables the function block.
VRef Vector_t Reference voltage.
VRefTime Timestamp_t Reference voltage time stamp.
FreqRef REAL Reference frequency.
VSynch Vector_t Synchronizing voltage.
VSynchTime Timestamp_t Synchronizing voltage time stamp.
FreqSynch REAL Synchronizing frequency.
VSynchMagComp REAL Adjust VSynch magnitude to VRef mag-
nitude to account for differences in po-
tential transformer connections. Range is
all positive real numbers, including zero.
Default value is 1.0.
VSynchAngComp REAL Adjust VSynch angle to be in phase with
VRef angle. Default value is 0.
BlockSynchCheck BOOL Set to TRUE to block synchronism check.
VoltageMax REAL Voltage window high limit.
VoltageMin REAL Voltage window low limit.
VoltageDiffMax REAL Maximum absolute value of the differ-
ence between synchronizing and refer-
ence voltage magnitudes.
MaxSynchAngle REAL Maximum angle (degrees) for synchro-
nism check.
CircuitBreakerCloseTimeMs REAL Circuit breaker close time, in millisec-
onds. Range is all positive real numbers,
including zero.
MinimumSlipFreq REAL Minimum value allowed for the slip fre-
quency (Hz). Default value is 0.005 Hz.
Range is from 0 to MaximumSlipFreq.
MaximumSlipFreq REAL Maximum value allowed for the slip fre-
quency (Hz). Range is from 0.005 Hz to
0.5 Hz. Default value is 0.1 Hz.
Outputs
Name IEC 61131 Type Description
ENO BOOL TRUE when the function block is en-
abled.
SynchCheckLogicEnabled BOOL The synchronism-check logic is enabled.
For more details, refer to the Processing
section below.
SlipStatus enum_SlipFreqStatus Shows the status of the slip frequency.
AngleDiff REAL Angle difference between the synchroniz-
ing and reference voltages.
SlipFrequency REAL Absolute value of the slip frequency. The
slip frequency is the difference between
FreqRef and FreqSynch.
VSynchCompensated Vector_t The compensated synchronizing voltage.
VSynchAdv Vector_t The synchronizing voltage compensated
for the circuit breaker close time. If
a close command is sent to the breaker
in the present processing interval, VSyn-
chAdv is the position in which VSynch-
Compensated will be when the breaker
actually closes.
Synchronized BOOL TRUE when the synchronizing voltage
and the reference voltage are synchro-
nized.
SynchTimeRemaining TIME When Synchronized is TRUE, this output
shows an estimation of the remaining time
that the system will remain synchronized.
Processing
1. When the following conditions are met, ENO output is set to TRUE:
ä MaximumSlipFrequency, MinimumSlipFrequency, VSynchMagComp, and Cir-
cuitBreakerCloseTimeMs inputs are within range requirements.
ä VoltageMax > VoltageMin
ä MaximumSlipFreq > MinimumSlipFreq
ä EN = TRUE.
2. When ENO is TRUE, the compensated synchronizing voltage VSynchCompensated
is calculated as follows:
ä VSynchCompensated.MAG = VSynch.MAG ×VSynchMAGcomp
ä VSynchCompensated.ANG = VSynch.ANG − VSynchAngComp
3. When BlockSynchCheck is set to FALSE and the following conditions are met for at
least 200 ms plus one RTAC processing interval, SynchCheckLogicEnabled output
is set to TRUE:
ä VoltageMin ≤ VRef.MAG ≤ VoltageMax.
ä VoltageMin ≤ VSynchCompensated.MAG ≤ VoltageMax.
ä |VRef.MAG − VSynchCompensated.MAG| ≤ VoltageDiffMax.
Inputs
Name IEC 61131 Type Description
EN BOOL Enables the function block.
CloseSignalLocal BOOL Close command signal issued locally
(e.g., via the SEL Touchscreen).
CloseSignalRemote BOOL Close command signal issued remotely
(e.g., via communication protocol).
LocalMode BOOL When TRUE, this function block does not
process remote close commands. When
FALSE, this function block does not pro-
cess local open commands.
BlockCloseControl BOOL When TRUE, close control commands
are blocked.
CloseLatchReset BOOL When TRUE, the CloseSignal output is
reset. This input is typically set to
CloseSealInTimeout OR SwitchIsClosed
to ensure that CloseSignal remains as-
serted for the duration of the expected
disconnect switch operate time, or if an
alarm is detected.
CloseImmobilityPickupTime TIME Maximum time to wait for the discon-
nect close operation to initiate. If the dis-
connect close operation does not initiate
within this time, an alarm condition is de-
clared. Default value is 300 milliseconds.
For more information on how to set this
value, refer to the Disconnect Switch Op-
eration section in page 25.12 of this doc-
ument.
CloseImmobilityReset BOOL When TRUE, the close immobility timer
resets. This signal indicates that the
switch has moved from its initial posi-
tion and is in progress to complete the
close operation. This input is typically as-
signed to NOT SwitchIsOpen.
CloseSealInPickupTime TIME Set longer than the highest expected close
operate time of the disconnect switch.
This timer starts when the CloseSignal
output asserts. Default value is 4 seconds.
For more information on how to set this
value, refer to the Disconnect Switch Op-
eration section in page 25.12 of this doc-
ument.
Outputs
Name IEC 61131 Type Description
ENO BOOL TRUE when the function block is en-
abled.
CloseSignal BOOL Successful close signal. Once this out-
put asserts, it latches until a rising edge
is detected in the CloseLatchReset in-
put.
ClosePulseStart BOOL Asserts for one processing interval
when CloseSignal transitions to TRUE.
This output may be mapped to the ctl-
Val member of the OperSPC tag struc-
ture of the operSet element of the dig-
ital output controlling the disconnect
switch close operation.
ClosePulseEnd BOOL Asserts for one processing inter-
val when CloseSignal transitions to
FALSE. This output may be mapped
to the ctlVal member of the OperSPC
tag structure of the operClear element
of the digital output controlling the
disconnect switch close operation.
CloseImmobilityTimeOut BOOL Asserts for one second when Clo-
seImmobilityReset input does not assert
within CloseImmobilityPickupTime af-
ter asserting the CloseSignal output.
This indicates that the switch has not
moved the minimum distance to tran-
sition from the open state to the in-
progress state.
CloseSealInTimeOut BOOL Asserts for one processing interval af-
ter the CloseSealInPickupTime expires
following the assertion of CloseSig-
nal. This signal may be assigned to
the CloseLatchReset input to reset the
CloseSignal output.
RemoteCloseControlIsBlocked BOOL Asserts for one processing interval
when a remote close command is
blocked by the BlockCloseControl in-
put.
OpenSignal BOOL Successful open signal. Once this out-
put asserts, it latches until a rising edge
is detected in the OpenLatchReset input
signal.
OpenPulseStart BOOL Asserts for one processing interval
when OpenSignal transitions to TRUE.
This output may be mapped to the ctl-
Val member of the OperSPC tag struc-
ture of the operSet element of the dig-
ital output controlling the disconnect
switch open operation.
Processing
When configuring the DisconnectSwitchControl, take the following considerations into ac-
count:
ä Set CloseSealInPickupTime to a value 10 to 15 percent longer than the maximum
Expected Disconnect Operate Time shown in Figure 25.6. Proceed similarly with
OpenSealInPickupTime.
ä Set CloseImmobilityPickupTime to a value 10 to 15 percent longer than the T1 time
shown in Figure 25.6. Proceed similarly with OpenImmobilityPickupTime.
Inputs
Name IEC 61131 Type Description
EN BOOL Enables the function block.
OpenSignalLocal BOOL Open command signal issued locally (e.g., via the
SEL Touchscreen).
OpenSignalRemote BOOL Breaker open command issued remotely (e.g., via
communication protocol).
LocalMode BOOL When TRUE, this function block does not pro-
cess remote open commands. When FALSE, this
function block does not process local open com-
mands.
BlockOpenControl BOOL When TRUE, breaker open commands are
blocked.
OpenLatchReset BOOL When TRUE, the OpenSignal output signal is re-
set. The feedback from the circuit breaker 52A
and 52B contacts is typically used to unlatch the
open signal.
OpenFailPickupTime TIME Maximum time to wait for the circuit breaker to
open. Default value is 500 milliseconds.
Outputs
Name IEC 61131 Type Description
ENO BOOL TRUE when the function block is en-
abled.
OpenSignal BOOL Successful open signal. Once this out-
put asserts, it latches until the rising
edge of the OpenLatchReset or Block-
OpenControl input is detected.
OpenPulseStart BOOL Asserts for one processing interval
when OpenSignal transitions to TRUE.
This output may be mapped to the ctl-
Val member of the OperSPC tag struc-
ture of the operSet element of the digi-
tal output controlling the circuit breaker
open operation.
OpenPulseEnd BOOL Asserts for one processing inter-
val when OpenSignal transitions to
FALSE. This output may be mapped to
the ctlVal member of the OperSPC tag
structure of the operClear element of
the digital output controlling the circuit
breaker open operation.
RemoteOpenControlIsBlocked BOOL Asserts for one processing interval
when a remote circuit breaker open op-
eration is blocked by the BlockOpen-
Control input.
OpenFailTimeout BOOL Asserts if OpenSignal remains asserted
longer than the amount of time speci-
fied in OpenFailPickupTime. This sig-
nal may be assigned to OpenLatchReset
to reset OpenSignal.
Processing
Inputs
Name IEC 61131 Type Description
EN BOOL Enables the function block.
CloseSignalLocal BOOL Close command signal issued locally (e.g., via
the SEL Touchscreen).
CloseSignalRemote BOOL Breaker close command issued remotely (e.g.,
via communication protocol).
LocalMode BOOL When TRUE, this function block does not pro-
cess remote close commands. When FALSE, this
function block does not process local close com-
mands.
BlockCloseControl BOOL When TRUE, breaker close commands are
blocked.
CloseLatchReset BOOL When TRUE, the CloseSignal output signal is re-
set. The feedback from the circuit breaker 52A
and 52B contacts is typically used to unlatch the
close signal.
CloseFailPickupTime TIME Maximum time to wait for the circuit breaker to
close. Default value is 1 second.
Outputs
Name IEC 61131 Type Description
ENO BOOL TRUE when the function block is en-
abled.
CloseSignal BOOL Successful close signal. Once this out-
put asserts, it latches until the rising
edge of the CloseLatchReset or Block-
CloseControl input is detected.
ClosePulseStart BOOL Asserts for one processing interval
when CloseSignal transitions to TRUE.
This output may be mapped to the ctl-
Val member of the OperSPC tag struc-
ture of the operSet element of the digi-
tal output controlling the circuit breaker
close operation.
Processing
Timer Symbols
The timer symbols used in the logic diagrams follow the conventions shown below:
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
The user wants to block the synchronism-check function if any of the following conditions
are true:
ä The system is unbalanced (negative-sequence voltage or zero-sequence voltage is
greater than 5 percent of the positive-sequence voltage).
ä The breaker is closed.
ä The EtherCAT network disables.
Assumptions
This example assumes the following:
ä An SEL-2245-41 Metering module, an SEL-2244-2 Digital Input module, and an
SEL-2244-3 Digital Output module are contained in the EtherCAT I/O network.
Those modules have default names.
ä The Phase A potential transformer on the line side of the circuit breaker is connected
to the VA input of the AC metering module.
ä The Phase A potential transformer of the bus side of the circuit breaker is connected
to the VS input of the AC metering module.
ä A 52A auxiliary contact of the circuit breaker is wired to the first digital input channel
of the SEL-2244-2.
ä Voltages are represented in secondary scale of the potential transformers.
ä Potential transformers on the bus side and the line side of the circuit breaker are
wired in wye configuration.
Solution
Code Snippet 25.1 prg_Synchronism Check — Axion
PROGRAM prg_SynchCheck
VAR
SynchCheckBreaker1 : fb_SynchronismCheck;
BlockingLogic : BOOL;
VNominalSecondary : SINT := 68;
END_VAR
Assumptions
This example assumes the following:
ä An IEEE C37.118 Synchrophasor client named SynchMeasurements is added into
the RTAC project. The RTAC receives synchrophasor data from PMU1 and PMU2.
PMU1 contains the reference voltage measurements, and PMU2 contains the syn-
chronizing voltage measurements.
ä A DNP client exists in the project. The DNP client is used to send the synchronized
signal to an external device.
ä Voltages are represented in secondary scale of the potential transformers.
ä Potential transformers on the bus side and the line side of the circuit breaker are
wired in wye configuration.
Solution
Code Snippet 25.2 prg_Synchronism Check — Synchrophasors
PROGRAM prg_SynchCheck
VAR
SynchCheckBreaker1 : fb_SynchronismCheck;
BlockingLogic : BOOL;
VNominalSecondary : SINT := 68;
END_VAR
ä An alarm shall be sent back to the touchscreen if the disconnect switch fails to initiate
the open or close operation, or if it remains in the in-progress state longer than 4
seconds.
ä Two Boolean Global variables called InterlockOpen and InterlockClose are used to
block the open and close control commands, respectively.
Solution
Code Snippet 25.3 prg_DisconnectSwitch NOTE: To support control of the
disconnect switch from the SEL
PROGRAM prg_DisconnectSwitch Touchscreen in the Bay Controller,
VAR the disconnect switch mode must be
Switch1_Control : fb_DisconnectSwitchControl; changed from its default of
"MONITOR" to "CONTROL." This
END_VAR change can be made in the Disconnect
Switches tab of the Bay Configuration
1 page under the SEL_Touchscreen.
// Instantiate the Disconnect Switch Control function block
Switch1_Control(
EN := TRUE,
CloseSignalLocal :=
SEL_Touchscreen.
Bay_Configuration_1_Two_Position_Disconnect_1_Close_Command.stVal,
CloseSignalRemote := DNPclient_DNP.BO_00000.operClose.ctlVal,
LocalMode := SEL_24DI_1_ECAT.INPUT_001.stVal,
BlockCloseControl := InterlockClose,
CloseLatchReset := Switch1_Control.CloseSealInTimeout OR
Switch1_Control.SwitchIsClosed,
CloseImmobilityPickupTime := T#1S,
CloseImmobilityReset := NOT Switch1_Control.SwitchIsOpen,
CloseSealInPickupTime := T#4.5S,
OpenSignalLocal :=
SEL_Touchscreen.
Bay_Configuration_1_Two_Position_Disconnect_1_Open_Command.stVal,
OpenSignalRemote := DNPclient_DNP.BO_00000.operTrip.ctlVal,
BlockOpenControl := InterlockOpen,
OpenLatchReset := Switch1_Control.OpenSealInTimeout OR
Switch1_Control.SwitchIsOpen,
OpenImmobilityPickupTime := T#1S,
OpenImmobilityReset := NOT Switch1_Control.SwitchIsClosed,
OpenSealInPickupTime := T#4.5S,
AlarmPickupTime := T#4S,
Auxiliary89A := SEL_24DI_1_ECAT.INPUT_002.stVal,
Auxiliary89B := SEL_24DI_1_ECAT.INPUT_003.stVal
);
Solution
Code Snippet 25.4 prg_CircuitBreaker
PROGRAM prg_CircuitBreaker
VAR
CB_Open_Control : fb_BreakerOpenControl;
CB_Close_Control : fb_BreakerCloseControl;
END_VAR
PowerSystemModel
Introduction
The PowerSystemModel library provides the ability to instantiate, describe, and connect
different power system elements. With each scan of the logic engine task, it will collect
the available measured information and determine which nodes are connected. The model
provides a single voltage quantity for all devices connected without impedance (an elec-
trical node) and a current for each branch that can be directly calculated using Kirchhoff’s
current law.
The PowerSystemModel library works with the C37.118 synchrophasor stream to provide a
more detailed snapshot of the system than can be provided by the raw data alone. Internally
the model treats all data and parameters as three-phase data at base units (e.g., ohms and
amperes) and it uses those three-phase data to perform its calculations. Each monitored
input contains a quality_t structure. If validity inside this structure is set to anything other
than GOOD, that measured value is not used in the calculations during this scan. Once all
inputs have been validated, the model expands existing current and voltage data to as many
nodes and branches as possible, and where sufficient data is available, provides a sanity
check on the measured values and breaker states.
The PowerSystemModel library is primarily designed to support the following two use
cases: extending system observability given a sparsely metered system and validating mea-
surements and topology given a densely metered system. The breaker-and-a-half configu-
ration, shown in Figure 26.1, is used to illustrate the different use cases.
A A A A A
A A
A A A A A
Observability Extension: Figure 26.1a shows current meters installed on all three breakers.
By combining these measurements and the topology information, the power system model
can calculate the current injected into both of the unmetered lines.
Error Detection: Figure 26.1b shows current meters installed on two of the three breakers
and both lines. By combining these measurements and the topology information, the power
system model can calculate the current flow through the unmetered breaker and detect if a
metering error has likely occurred.
Error Detection and Identification: Figure 26.1c shows fully redundant current. By com-
bining these measurements and the topology information, the power system model can
validate each of the redundant measurements, detect any inconsistencies, and provide an
indicator that one of the meters within the collection is providing incorrect data.
Glossary
These terms are used throughout this document to describe the functionality provided by
this library.
Conducting Equipment Any piece of electrical equipment that is designed to carry cur-
rent or that is conductively connected to the network. This does not include containers
that hold this equipment. For example, a power transformer is not conducting equipment
even though it can hold multiple power transformer ends which are themselves conducting
equipment.
Connectivity Node A representation of the connecting point for two or more terminals.
The model will create these anywhere two or more terminals are connected via the bootstrap
methods. At no time should the user ever instantiate a connectivity node.
Model In this library, the model is a collection of conducting equipment that is connected
and the data that describes that equipment.
Power Transformer End A transformer winding. A given transformer may have two or
more windings.
Terminal The part of a piece of electrical equipment that is meant to connect it to other
equipment. Every piece of conducting equipment has at least one terminal and all terminals
should be attached to at least one other terminal at a connectivity node. These also serve
as anchoring points for various measurement devices.
To begin with, the user must identify the individual pieces of conducting equipment rep-
resented by this diagram. This defines what objects must be created within the library to
model this system, as seen in Figure 26.3. Note that every piece of conducting equipment
in the model has one or more terminals that are implicitly created with the object—the bus
can be represented as only a single terminal.
Energy Source
Breaker Bus
Switch
Switch Switch
Transformer End
Breaker Breaker
Switch
Energy Source
To tie each of the pieces of equipment together, we introduce the idea of a connectivity
node. These nodes provide a location to tie together as many terminals as desired. In the
library the user does not need to create these nodes. They are created automatically when
two or more terminals are connected. Figure 26.4 shows how this might be conveyed. As
before, there is a connectivity node where the terminals of the three lines join the terminal
of the bus.
Figure 26.5 shows the user indicating where data are fed into (classes named as Measure-
ments) and read out of (classes named as Report) the model. Each of these I/O points is
tied to a terminal that it monitors. The direction of current flow is standardized as being
positive when flow is moving through the terminal from the conducting equipment into the
connectivity node. For example; if current was flowing from left-to-right through a breaker,
a measurement point on the left terminal would read as a negative value flowing into the
conducting equipment, away from the connectivity node; and a measurement point on the
right terminal would read as a positive value flowing away from the conducting equipment,
into the connectivity node.
Though current and voltage values may be read in from measurements in whatever units
desired, they must be scaled to volts or amperes with the correct sign for use in the model.
Measurement classes provide a scalar that must be correctly populated to translate the units
and directionality being fed into the model from the synchrophasor stream into the required
magnitudes and directions.
A A
Finally, some objects need to be part of a container to define their interaction with other
objects. For example, all conducting equipment must be placed in a nominal voltage and
transformer ends must be placed in a transformer with other transformer ends, as shown in
Figure 26.6.
V
230,000 V
A High
to
Low
A A
Figure 26.6 All Objects Defined for One Side of the Substation
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_ValueSource
Enumeration Description
UNAVAILABLE The value is not measured and cannot be calculated by the installed
system.
MEASURED The value is reported exactly as measured.
DIRECT_ASSOCIATION The value was achieved through comparing like values connected
without impedance.
CALCULATED The value was achieved through linear extrapolation based on pro-
vided parameters.
UNTRUSTED The value measured here conflicts with other measured values or
the provided parameters. This can be set if a measured value is too
different from a calculated value or switch that reports open has a
calculated current.
enum_WindingConnection
Enumeration Description
DELTA A Delta winding.
WYE A Wye winding.
ZIGZAG A ZigZag winding.
WYE_NEUTRAL A Wye winding with neutral brought out for grounding.
ZIGZAG_NEUTRAL A ZigZag winding with neutral brought out for grounding.
AUTO An Autotransformer common winding.
INDEPENDENT An independent winding for single-phase connections.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
This library makes use of several ACSELERATOR RTAC Data Types for data input, output,
and storage. The layout of these structures can be found in the ACSELERATOR RTAC SEL-
5033 Software Instruction Manual.
CMV A communications structure for moving phasors.
MV A communications structure for moving analog values.
quality_t A communications structure for indicating data health.
SPS A communications structure for moving binary points.
vector_t A structure for storing phasors as an angle and a magnitude.
Classes
Classes are a particular implementation of a function block. They are generally initial-
ized using bootstrap methods and provide methods and properties, which normal function
blocks do not provide.
class_PowerSystemModel (Class)
This class contains the working algorithms for the model. It stores the connections of
objects to each other, controls the order of operations each scan, and provides a centralizing
point for all other features.
For the model to do its work, all elements must be tied to it before calling run. In general,
this means that all terminals must be tied first using bootstrap_ConnectTerminals().
Then individual objects should be configured using their assorted bootstrap_Set and boot-
strap_Configure methods. Finally, objects can be grouped in containers and transformers
and meters can be added using bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
Filename STRING The name of the log file for this model’s initialization.
ABCRotation BOOL The rotation of the phases in this model. True indicates
that after the A-phase current crosses a reference angle,
B-phase current will cross it next.
bootstrap_ConnectTerminals (Method)
Call this method to connect two terminals to each other. A terminal can be used as an
argument to this method more than once to connect more than two terminals to each other.
If Terminal A is connected to Terminal B and then Terminal A is connected to Terminal C,
Terminal B is implicitly connected to Terminal C and the two do not need to be connected
by an explicit call to this method.
This is the first bootstrap method to be called. It must be called after all objects are instan-
tiated and before any other bootstrap method and before Run().
Inputs
Name IEC 61131 Type Description
pt_terminal1 POINTER TO class_Terminal The first terminal to connect.
pt_terminal2 POINTER TO class_Terminal The second terminal to connect.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the terminals are connected together and added to the
model.
Processing
This method is intended to be called before processing to link objects together in the model.
It performs the following actions:
ä Stores a reference to the model in both objects.
ä Connects the two terminals together at a connectivity node.
ä Connects both terminals to any other terminals already attached to the connectivity
node.
ä Returns FALSE if the references are not stored, either because the objects are no
longer in the initialization phase or a terminal is already attached to another model.
bootstrap_FinalizeConnections (Method)
To ensure proper tying of all model objects, this method must be called after all terminals
have been connected by bootstrap_ConnectTerminals and before calling any other
bootstrap methods or Run(). It switches the model out of the terminal connection state in
preparation for all other work.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the model has been successfully tied together.
Processing
This method prompts the model to perform the following actions:
ä Disable the connection of additional terminals.
ä Enable the insertion of objects (e.g., class_Breakers, class_ACLineSegments, and
others) into containers (i.e., class_VoltageLevels and class_PowerTransformers).
ä Build internal linking structures required for additional processing.
ä Return FALSE if bootstrap_ConnectTerminals() has not been successfully called
or if the system state prevented the final connections.
bootstrap_ValidateModel (Method)
This verifies the state of all objects and that the model itself can operate without error. Until
this method is called, no work is done by the Run() method.
Upon completion of this method, the model is ready to write out a log file summarizing
the configuration of the model. This file will be completed during the first few iterations of
the calls to the Run() method. Its format can be seen in Log File Format on page 26.70.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the model is ready to monitor inputs and update outputs.
Processing
This method is intended to be called before ever calling Run() to finalize all model con-
figuration. It prompts the model to perform the following actions:
ä Disable the attachment of any additional containers.
ä Check that all model objects have every reference required for calculations.
ä Return FALSE if the model is unable to calculate model state due to a configuration
error. Any such error will be described in the file filename.
Run (Method)
This method drives all work done by the model. It should be called once per task scan after
all configuration information has been processed.
Processing
Each time Run() is called, it performs the following tasks:
ä Checks that the model has been validated and deemed healthy.
ä Updates the measurements from all inputs configured during bootstrap.
ä Determines the observability of the system. This decides which current values can
be calculated and which cannot based on the switch states and valid measurement
values available.
ä Calculates the current through all observable pieces of conducting equipment and the
voltage at all observable terminals. If measurements beyond the minimum required
for observability are available, the method uses all available information to generate
a minimum mean squared error estimate.
ä If measurements are deemed to be too far from calculated values, the resulting output
will be flagged as UNTRUSTED. Likewise, any switch reporting as open with more
than minimal current running through it will be reported as UNTRUSTED.
ä Once all measurements are calculated and outputs are flagged, the time-aligned val-
ues will be placed in the outputs of all user-provided measurement points and all
switches and breakers.
class_ConductingEquipment
This class is never instantiated by the user. This is a category of object that is extended
to allow objects of multiple types to be treated as if they are the same for the purpose of
grouping and analysis. Classes that extend this class can be added to class_VoltageLevels.
class_Measurement
This class is never instantiated by the user. This is a category of object that is extended
to allow objects of multiple types to be treated as if they are the same for the purpose of
grouping and analysis. Classes that extend this class can be added to terminals for both
input and output of measurement values.
class_Terminal
The point on a piece of conducting equipment that connects to other conducting equipment.
Terminals are used to join all objects together and provide explicit points of contact for
measurement units.
This class is never instantiated by the user. All instantiated conducting equipment already
have terminals as member objects. The user must be aware that terminals exist to facilitate
calling bootstrap methods to ty the model together and to attach measurement points.
bootstrap_AddMeasurement (Method)
Call this method to tie a measurement point to a specific terminal.
This is the last type of bootstrap method to be called. It must be called after all terminals
are connected and all configure and set bootstrap methods have been completed.
Inputs/Outputs
Name IEC 61131 Type Description
measurement class_Measurement The measurement to be applied to this terminal.
Return Value
IEC 61131 Type Description
BOOL The measurement was successfully added to the terminal.
Processing
This method stores a reference to the provided measurement at this terminal unless the ob-
jects are no longer in the initialization phase or the terminal is attached to a bus or junction
and the measurement is a current measurement. After being attached, these measurement
inputs and outputs will be used with all operations acting on the model.
class_Switch
Instantiate one instance of this class for any non-load breaking switch in the model. The
instance tracks the open-close state of that device. Before this class can be used, one or
both of its bootstrap methods must be called.
If none of the variables being monitored are healthy on a given scan, the switch will be
analyzed per its TypicallyClosed value and the StO_Quality will be set to UNAVAILABLE.
If only one value is available, because only one bootstrap method is called or only one
monitored value is healthy, that value will be used as the open-close state. If both values
are bootstrapped and healthy and the two values conflict, the switch will be analyzed per
its TypicallyClosed value and the StO_Quality will be set to UNTRUSTED.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
TypicallyClosed BOOL This switch is closed under normal operating condi-
tions. This is the value that will be used if there is no
communication with the switch.
Inputs/Outputs
Name IEC 61131 Type Description
pt_TerminalA POINTER TO class_Terminal The first terminal of this switch, used to
attach it inside the model.
pt_TerminalB POINTER TO class_Terminal The second terminal of this switch, used
to attach it inside the model.
StIn_IsClosed BOOL The switch is reporting as closed.
StIn_IsClosedQOk BOOL The channel communicating switch state
is healthy.
StO_IsClosed BOOL The state the model calculates the switch
to be in. The model may override an
open condition if current is still detected
across the link.
StO_Quality enum_ValueSource The confidence level in the StO_Is-
Closed flag.
bootstrap_ConfigureIsOpenInput (Method)
Call this method to provide a reference to the value the switch should monitor to detect an
open condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsOpen SPS The variable that will be monitored to determine the open
status of this switch.
Return Value
IEC 61131 Type Description
BOOL The switch was successfully configured.
Processing
This method is intended to be called before processing to associate a data location with the
switch. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the switch already had this
bootstrap method called.
bootstrap_ConfigureIsClosedInput (Method)
Call this method to provide a reference to the value the switch should monitor to detect a
closed condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsClosed SPS The variable that will be monitored to determine the
closed status of this switch.
Return Value
IEC 61131 Type Description
BOOL The switch was successfully configured.
Processing
This method is intended to be called before processing to associate a data location with the
switch. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the switch already had this
bootstrap method called.
class_Breaker
Instantiate one instance of this class for any load breaking device in the model. The instance
tracks open-close state of that device. Before this class can be used, one or both of its
bootstrap methods must be called.
If none of the variables being monitored are healthy on a given scan, the breaker will be
analyzed per its TypicallyClosed value and the StO_Quality will be set to UNAVAILABLE.
If only one value is available, because only one bootstrap method is called or only one
monitored value is healthy, that value will be used as the open-close state. If both values
are bootstrapped and healthy and the two values conflict, the breaker will be analyzed per
its TypicallyClosed value and the StO_Quality will be set to UNTRUSTED.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
ä class_Switch
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
TypicallyClosed BOOL This breaker is closed under normal operating condi-
tions. This is the value that will be used if there is no
communication with the breaker.
Outputs
Name IEC 61131 Type Description
pt_TerminalA POINTER TO class_Terminal The first terminal of this breaker, used to
attach it inside the model.
pt_TerminalB POINTER TO class_Terminal The second terminal of this breaker, used
to attach it inside the model.
StIn_IsClosed BOOL The breaker is reporting as closed.
StIn_IsClosedQOk BOOL The channel communicating breaker
state is healthy.
StO_IsClosed BOOL The state the model calculates the
breaker to be in. The model may over-
ride an open condition if current is still
detected across the link.
StO_Quality enum_ValueSource The confidence level in the StO_Is-
Closed flag.
bootstrap_ConfigureIsOpenInput (Method)
Call this method to provide a reference to the value the breaker should monitor to detect an
open condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsOpen SPS The variable that will be monitored to determine the open
status of this breaker.
Return Value
IEC 61131 Type Description
BOOL The breaker was successfully configured.
Processing
This method is intended to be called before processing to associate a data location with the
breaker. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the breaker already had this
bootstrap method called.
bootstrap_ConfigureIsClosedInput (Method)
Call this method to provide a reference to the value the breaker should monitor to detect a
closed condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsClosed SPS The variable that will be monitored to determine the
closed status of this breaker.
Return Value
IEC 61131 Type Description
BOOL The breaker was successfully configured.
Processing
This method is intended to be called before processing to associate a data location with the
breaker. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the breaker already had this
bootstrap method called.
class_EnergySource
This class is a terminating element. It represents an edge of the model being worked on.
Instantiate one instance of this class anywhere it is desired to model all elements beyond
this point as a metered source of electrical power.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this source, used to attach it in-
side the model.
class_EnergyConsumer
This class is a terminating element. It represents an edge of the model being worked on.
Instantiate one instance of this class anywhere it is desired to model all elements beyond
this point as a metered electrical load.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this load, used to attach it inside
the model.
class_ShuntCompensator
This class is a terminating element. It represents an edge of the model being worked on.
Instantiate one instance of this class anywhere it is desired to model a shunt capacitor,
inductor, or resistor. The provided values are used during all operations on the model.
Inputs to this class must be in units of siemens.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
conductanceAPhase LREAL The real part of the shunt admittance of the
A-phase.
susceptanceAPhase LREAL The reactive part of the shunt admittance of the
A-phase.
conductanceBPhase LREAL The real part of the shunt admittance of the
B-phase.
susceptanceBPhase LREAL The reactive part of the shunt admittance of the
B-phase.
Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this compensator, used to attach
it inside the model.
class_ACLineSegment
Instantiate one instance of this class at each location where it is desired to model the con-
nection between two points as having impedance. Each instance defaults to zero impedance
and zero shunt admittance unless an appropriate bootstrapping method is called.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
Outputs
Name IEC 61131 Type Description
pt_TerminalA POINTER TO class_Terminal The first terminal of this line, used to attach it
inside the model.
pt_TerminalB POINTER TO class_Terminal The second terminal of this line, used to at-
tach it inside the model.
bootstrap_SetNominalLineImpedance1Line (Method)
Call this method to set the line impedance using a 1-line model. Arguments of this method
must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
resistance LREAL The real part of the positive-sequence series impedance.
reactance LREAL The reactive part of the positive-sequence series impedance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.
Processing
This method sets the impedance of the line based on the provided values and returns TRUE,
unless the impedance of the line was set previously or the model is no longer in the initial-
ization phase.
bootstrap_SetNominalLineImpedance3Phase (Method)
Call this method to set the line impedance using three-phase data. Arguments of this
method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
resistanceAPhase LREAL The real part of the series impedance of the
A-phase.
reactanceAPhase LREAL The reactive part of the series impedance of the
A-phase.
resistanceBPhase LREAL The real part of the series impedance of the
B-phase.
reactanceBPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceCPhase LREAL The real part of the series impedance of the
B-phase.
reactanceCPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceABPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the B-phase.
reactanceABPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the B-phase.
resistanceACPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the C-phase.
reactanceACPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the C-phase.
resistanceBCPhase LREAL The real part of the series impedance due to mutual
coupling between the B-phase and the C-phase.
reactanceBCPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the B-phase and the C-phase.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.
Processing
This method sets the impedance of the line based on the provided values and returns TRUE,
unless the impedance of the line was set previously or the model is no longer in the initial-
ization phase.
bootstrap_SetNominalLineImpedanceWZeroSequence (Method)
Call this method to set the line impedance using a positive- and zero-sequence data model.
Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
resistancePosSequence LREAL The real part of the positive-sequence series
impedance.
reactancePosSequence LREAL The reactive part of the positive-sequence se-
ries impedance.
resistanceZeroSequence LREAL The real part of the zero-sequence series
impedance.
reactanceZeroSequence LREAL The reactive part of the zero-sequence series
impedance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.
Processing
This method sets the impedance of the line based on the provided values and returns TRUE,
unless the impedance of the line was set previously or the model is no longer in the initial-
ization phase.
bootstrap_SetNominalShuntAdmittance1Line (Method)
Call this method to set the shunt admittance of the line using a one-line model. Arguments
of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
conductance LREAL The real part of the positive-sequence shunt admittance.
susceptance LREAL The reactive part of the positive-sequence shunt admit-
tance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.
Processing
This method sets the admittance of the line based on the provided values and returns TRUE,
unless the admittance of the line was set previously or the model is no longer in the initial-
ization phase.
bootstrap_SetNominalShuntAdmittance3Phase (Method)
Call this method to set the line’s shunt admittance using three-phase data. Arguments of
this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
conductanceAPhase LREAL The real part of the shunt admittance of the
A-phase.
susceptanceAPhase LREAL The reactive part of the shunt admittance of the
A-phase.
conductanceBPhase LREAL The real part of the shunt admittance of the
B-phase.
susceptanceBPhase LREAL The reactive part of the shunt admittance of the
B-phase.
conductanceCPhase LREAL The real part of the shunt admittance of the
C-phase.
susceptanceCPhase LREAL The reactive part of the shunt admittance of the
C-phase.
conductanceABPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
susceptanceABPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
conductanceACPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
susceptanceACPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
conductanceBCPhase LREAL The real part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
susceptanceBCPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
Return Value
IEC 61131 Type Description
BOOL Returns true if the admittance was set based on the provided values.
Processing
This method sets the admittance of the line based on the provided values and returns TRUE,
unless the admittance of the line was set previously or the model is no longer in the initial-
ization phase.
bootstrap_SetNominalShuntAdmittanceWZeroSequence (Method)
Call this method to set the line’s shunt admittance using a positive- and zero-sequence data
model. Arguments of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
conductancePosSequence LREAL The real part of the positive-sequence shunt
admittance.
susceptancePosSequence LREAL The reactive part of the positive-sequence
shunt admittance.
conductanceZeroSeqeunce LREAL The real part of the zero-sequence shunt ad-
mittance.
susceptanceZeroSequence LREAL The reactive part of the zero-sequence shunt
admittance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.
Processing
This method sets the admittance of the line based on the provided values and returns TRUE,
unless the admittance of the line was set previously or the model is no longer in the initial-
ization phase.
class_PowerTransformerEnd
Instantiate one instance of this class for each transformer winding desired in the model.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
NominalRatio REAL The modifier to use as the expected change be-
tween this winding and others in the system.
ConnectionType enum_WindingConnection The wiring configuration of the winding.
Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this transformer winding, used
to attach it into the model.
bootstrap_AddTapChanger (Method)
Call this method to add a tap changer that will modify the NominalRatio of this transformer
end.
This is the last type of bootstrap method to be called. It must be called after all terminals
are connected and all configure and set bootstrap methods have been completed.
Inputs/Outputs
Name IEC 61131 Type Description
tapChanger class_TapChanger The tap changer that will modify this winding.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the tap changer is added to this winding.
Processing
This method links the provided tap changer to this winding and returns true, unless another
tap changer has already been set, the tap changer is already modifying another transformer
end, or the model is no longer in the initialization phase.
bootstrap_SetNominalEndImpedance1Line (Method)
Call this method to set the impedance of the transformer winding from a 1-line model.
Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
resistance LREAL The real part of the positive-sequence series impedance.
reactance LREAL The reactive part of the positive-sequence series impedance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.
Processing
This method sets the impedance of the transformer end based on the provided values and
returns TRUE, unless the impedance of the transformer end was set previously or the model
is no longer in the initialization phase.
bootstrap_SetNominalEndImpedance3Phase (Method)
Call this method to set the impedance of the transformer winding from three-phase data.
Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
resistanceAPhase LREAL The real part of the series impedance of the
A-phase.
reactanceAPhase LREAL The reactive part of the series impedance of the
A-phase.
resistanceBPhase LREAL The real part of the series impedance of the
B-phase.
reactanceBPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceCPhase LREAL The real part of the series impedance of the
B-phase.
reactanceCPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceABPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the B-phase.
reactanceABPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the B-phase.
resistanceACPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the C-phase.
reactanceACPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the C-phase.
resistanceBCPhase LREAL The real part of the series impedance due to mutual
coupling between the B-phase and the C-phase.
reactanceBCPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the B-phase and the C-phase.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.
Processing
This method sets the impedance of the transformer end based on the provided values and
returns TRUE, unless the impedance of the transformer end was set previously or the model
is no longer in the initialization phase.
bootstrap_SetNominalEndImpedanceWZeroSequence (Method)
Call this method to set the impedance of the transformer winding from a positive- and
zero-sequence data model. Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
resistancePosSequence LREAL The real part of the positive-sequence series
impedance.
reactancePosSequence LREAL The reactive part of the positive-sequence se-
ries impedance.
resistanceZeroSequence LREAL The real part of the zero-sequence series
impedance.
reactanceZeroSequence LREAL The reactive part of the zero-sequence series
impedance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.
Processing
This method sets the impedance of the transformer end based on the provided values and
returns TRUE, unless the impedance of the transformer end was set previously or the model
is no longer in the initialization phase.
bootstrap_SetNominalShuntAdmittance1Line (Method)
Call this method to set the shunt admittance of the transformer end from a 1-line model.
Arguments of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
conductance LREAL The real part of the positive-sequence shunt admittance.
susceptance LREAL The reactive part of the positive-sequence shunt admit-
tance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.
Processing
This method sets the admittance of the transformer end based on the provided values and
returns TRUE, unless the admittance of the transformer end was set previously or the model
is no longer in the initialization phase.
bootstrap_SetNominalShuntAdmittance3Phase (Method)
Call this method to set the shunt admittance of the transformer winding from three-phase
data. Arguments of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs
Name IEC 61131 Type Description
conductanceAPhase LREAL The real part of the shunt admittance of the
A-phase.
susceptanceAPhase LREAL The reactive part of the shunt admittance of the
A-phase.
conductanceBPhase LREAL The real part of the shunt admittance of the
B-phase.
susceptanceBPhase LREAL The reactive part of the shunt admittance of the
B-phase.
conductanceCPhase LREAL The real part of the shunt admittance of the
C-phase.
susceptanceCPhase LREAL The reactive part of the shunt admittance of the
C-phase.
conductanceABPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
susceptanceABPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
conductanceACPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
susceptanceACPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
conductanceBCPhase LREAL The real part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
susceptanceBCPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.
Processing
This method sets the admittance of the transformer end based on the provided values and
returns TRUE, unless the admittance of the transformer end was set previously or the model
is no longer in the initialization phase.
bootstrap_SetNominalShuntAdmittanceWZeroSequence (Method)
Call this method to set the shunt admittance of the transformer end from a positive- and
zero-sequence data model. Arguments of this method must be in units of siemens.
Inputs
Name IEC 61131 Type Description
conductancePosSequence LREAL The real part of the positive-sequence shunt
admittance.
susceptancePosSequence LREAL The reactive part of the positive-sequence
shunt admittance.
conductanceZeroSeqeunce LREAL The real part of the zero-sequence shunt ad-
mittance.
susceptanceZeroSequence LREAL The reactive part of the zero-sequence shunt
admittance.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.
Processing
This method sets the admittance of the transformer end based on the provided values and
returns TRUE, unless the admittance of the transformer end was set previously or the model
is no longer in the initialization phase.
class_BusbarSection
Instantiate one instance of this class for each location of a bus desired to be modeled.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this bus, used to attach it into
the model.
class_Junction
Instantiate one instance of this class for each location of a non-bus intersection of three or
more terminals that requires a name.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this junction, used to attach it
into the model.
class_TapChanger
Instantiate one instance of this class for each class_PowerTransformerEnd requiring a dy-
namic transformer ratio.
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
DefaultStep INT The step value this tap changer will use if communica-
tion with the device is unhealthy. A value of zero leaves
the PowerTransformer winding at its default Nominal-
Ratio.
Outputs
Name IEC 61131 Type Description
StIn_RatioModifier REAL The measured value of the tap changer as a
percentage.
StIn_RatioModifierQOk BOOL The health of the communications channel
providing the ratio modifier. This will be
FALSE if the value is out of bounds or the
communication is flagged as invalid.
bootstrap_ConfigureInputs (Method)
Call this method to provide a reference to all required variables the tap changer should
monitor for its state.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
ratioModifier INS The variable that will report the step position of the tap
changer.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the variables are successfully tied to the tap changer.
Processing
This method stores references to the provided variables and returns true, unless it has al-
ready been called for this tap changer.
class_PowerTransformer
Instantiate one instance of this class for each set of correlated windings to be modeled.
This class acts as a container for class_PowerTransformerEnd objects and relates them to
each other.
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
PowerFactorRating REAL The information required to derive the maximum
angle from real power this transformer allows be-
fore its behavior becomes non-linear.
RealPowerRating REAL The maximum real power this transformer can han-
dle.
bootstrap_AddWinding (Method)
Call this method to attach a class_PowerTransformerEnd to this transformer as one of mul-
tiple windings.
This is the last type of bootstrap method to be called. It must be called after all terminals
are connected and all configure and set bootstrap methods have been completed.
Inputs/Outputs
Name IEC 61131 Type Description
winding class_PowerTransformerEnd The winding to add to this transformer.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the winding was added successfully.
Processing
This method attaches the transformer end to this transformer and returns true, unless the
transformer end is already attached to a transformer, the transformer has ends attached to
a different model, or the model is no longer in the initialization stage.
class_VoltageLevel
Instantiate one voltage level for each nominal voltage desired in the model. The model uses
values provided here in per-unit calculations.
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
NominalVoltage REAL The voltage value to be used in per-unit calculations
for all equipment added to this voltage level.
bootstrap_AddEquipment (Method)
Call this method for each piece of equipment that should be associated with this container.
Inputs/Outputs
Name IEC 61131 Type Description
equipment class_ConductingEquipment The equipment to add to the container.
Return Value
IEC 61131 Type Description
BOOL The equipment was successfully added to the container.
Processing
This method is intended to be called before processing to associate equipment with this
container. It performs the following actions:
ä Stores a reference to the object so that it can be accessed as part of the container later.
ä If the equipment can be stored in only one of this container type, prompts the equip-
ment to store a reference to the container as well.
ä Returns FALSE if the object cannot be added to the container because either the
objects are no longer in the initialization phase or the equipment was already added
to a conflicting container.
class_CurrentMeasurement
Current measurement objects can be added to any class_Terminal except one correlating
to a bus or junction. Measurements are complex phasors that must be scaled to present the
current injection from the equipment out, in amperes. Instantiate one instance of this class
for each set of current meter data that the model needs to account for.
class_CurrentMeasurement objects also reports three-phase current values after data ma-
nipulation.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
ScaleFactor REAL A multiplier applied as values enter the model.
MaxError REAL The maximum error percentage allowed on this meter
before it is flagged as UNTRUSTED. Default is 1%.
MinimumValue REAL The minimum value in amperes that will be used as the
denominator in calculating percentage error. Default is
1 ampere.
Outputs
Name IEC 61131 Type Description
StIn_IsEnabled BOOL The values read by this measurement are allowed
by the operator to be used in model calculations.
StIn_QOk BOOL The values provided to this measurement object
are healthy.
StIn_PhaseA vector_t A-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseB vector_t B-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseC vector_t C-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PosSequence vector_t PosSequence is calculated for three-phase inputs,
or as a measured PosSequence input.
StIn_ZeroSequence vector_t ZeroSequence is calculated for three-phase inputs,
or as a measured ZeroSequence input.
StIn_NegSequence vector_t NegSequence is calculated for three-phase inputs,
or as a measured NegSequence input.
StO_PhaseAQuality enum_ValueSource The confidence level in the reported A-phase
value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported B-phase
value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported C-phase
value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.
bootstrap_ConfigureInputsPosSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from a
single value, positive-sequence. It ensures that values read will be converted from positive-
sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.
Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.
bootstrap_ConfigureInputsSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three values: positive-, negative-, and zero-sequence. It ensures that values read will be
converted from sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.
zeroSequence CMV The variable that will be monitored to determine the
zero-sequence value of this measurement.
negSequence CMV The variable that will be monitored to determine the
negative-sequence value of this measurement.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.
Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.
bootstrap_ConfigureInputsThreePhase (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three-phase values. It ensures that values read will be used directly in later calculations by
the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual override of
this measurement.
phaseA CMV The variable that will be monitored to determine the A-phase
value of this measurement.
phaseB CMV The variable that will be monitored to determine the B-phase
value of this measurement.
phaseC CMV The variable that will be monitored to determine the C-phase
value of this measurement.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.
Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.
class_VoltageMeasurement
Voltage measurement objects can be added to any class_Terminal. Measurements are com-
plex phasors that must be scaled to present the voltage in volts. Instantiate one instance of
this class for each set of voltage meter data that the model needs to account for.
class_VoltageMeasurement objects also reports three-phase voltage values after data ma-
nipulation.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
ScaleFactor REAL A multiplier applied as values enter the model.
MaxError REAL The maximum error percentage allowed on this meter
before it is flagged as UNTRUSTED. Default is 1%.
MinimumValue REAL The minimum value in volts that will be used as the
denominator in calculating percentage error. Default is
1 volt.
Outputs
Name IEC 61131 Type Description
StIn_IsEnabled BOOL The values read by this measurement are allowed
by the operator to be used in model calculations.
StIn_QOk BOOL The values provided to this measurement object
are healthy.
StIn_PhaseA vector_t A-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseB vector_t B-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseC vector_t C-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PosSequence vector_t PosSequence is calculated for three-phase inputs,
or as a measured PosSequence input.
StIn_ZeroSequence vector_t ZeroSequence is calculated for three-phase inputs,
or as a measured ZeroSequence input.
StIn_NegSequence vector_t NegSequence is calculated for three-phase inputs,
or as a measured NegSequence input.
StO_PhaseAQuality enum_ValueSource The confidence level in the reported A-phase
value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported B-phase
value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported C-phase
value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.
bootstrap_ConfigureInputsPosSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from a
single value, positive-sequence. It ensures that values read will be converted from positive-
sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.
Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.
bootstrap_ConfigureInputsSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three values: positive-, negative-, and zero-sequence. It ensures that values read will be
converted from sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.
zeroSequence CMV The variable that will be monitored to determine the
zero-sequence value of this measurement.
negSequence CMV The variable that will be monitored to determine the
negative-sequence value of this measurement.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.
Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.
bootstrap_ConfigureInputsThreePhase (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three-phase values. It ensures that values read will be used directly in later calculations by
the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.
Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual override of
this measurement.
phaseA CMV The variable that will be monitored to determine the A-phase
value of this measurement.
phaseB CMV The variable that will be monitored to determine the B-phase
value of this measurement.
phaseC CMV The variable that will be monitored to determine the C-phase
value of this measurement.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.
Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.
class_ReportedCurrent3Phase
Reported current objects can be added to any class_Terminal except one correlating to a
bus or junction. Reports are complex phasors that present the current injection from the
equipment out, in amperes. Instantiate one instance of this class for each unmonitored
location where knowledge of the current is desired.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
PerPhaseMaxThreshold REAL The value that, if exceeded by the results of any
phase, will flag a possible error condition. This
value is compared directly against the final un-
scaled output.
Outputs
Name IEC 61131 Type Description
StO_PhaseAQuality enum_ValueSource The confidence level in the reported
A-phase value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported
B-phase value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported
C-phase value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.
PhaseAThresholdExceeded BOOL The magnitude of the A-phase value re-
ported exceeds the provided threshold.
PhaseBThresholdExceeded BOOL The magnitude of the B-phase value re-
ported exceeds the provided threshold.
PhaseCThresholdExceeded BOOL The magnitude of the C-phase value re-
ported exceeds the provided threshold.
class_ReportedCurrentSequence
Reported current objects can be added to any class_Terminal except one correlating to a
bus or junction. Reports are complex phasors that present the current injection from the
equipment out, in amperes. Instantiate one instance of this class for each unmonitored
location where knowledge of the current is desired.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power sys-
tem.
Description STRING A human-readable description of this ob-
ject.
positiveSeqMaxThreshold REAL The value that, if exceeded by the
positive-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.
zeroSeqMaxThreshold REAL The value that, if exceeded by the
zero-sequence results, will flag a possible
error condition. This value is compared
directly against the final unscaled output.
negativeSeqMaxThreshold REAL The value that, if exceeded by the
negative-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.
Outputs
Name IEC 61131 Type Description
StO_Quality enum_ValueSource The confidence level in the reported
sequence values.
StO_PosSequence vector_t The calculated positive-sequence
value.
StO_ZeroSequence vector_t The calculated negative-sequence
value.
StO_NegSequence vector_t The calculated zero-sequence value.
positiveSeqThresholdExceeded BOOL The magnitude of the
positive-sequence value reported
exceeds the provided threshold.
zeroSeqThresholdExceeded BOOL The magnitude of the zero-sequence
value reported exceeds the provided
threshold.
negativeSeqThresholdExceeded BOOL The magnitude of the
negative-sequence value reported
exceeds the provided threshold.
class_ReportedVoltage3Phase
Voltage report objects can be added to any class_Terminal. Reports are complex phasors
that present voltage in volts. Instantiate one instance of this class for each unmonitored
location where knowledge of the voltage is desired.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
PerPhaseMaxThreshold REAL The value that, if exceeded by the results of any
phase, will flag a possible error condition. This
value is compared directly against the final un-
scaled output.
Outputs
Name IEC 61131 Type Description
StO_PhaseAQuality enum_ValueSource The confidence level in the reported
A-phase value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported
B-phase value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported
C-phase value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.
PhaseAThresholdExceeded BOOL The magnitude of the A-phase value re-
ported exceeds the provided threshold.
PhaseBThresholdExceeded BOOL The magnitude of the B-phase value re-
ported exceeds the provided threshold.
PhaseCThresholdExceeded BOOL The magnitude of the C-phase value re-
ported exceeds the provided threshold.
class_ReportedVoltageSequence
Voltage report objects can be added to any class_Terminal. Reports are complex phasors
that present voltage in volts. Instantiate one instance of this class for each unmonitored
location where knowledge of the voltage is desired. All values presented are in the base
units used by the library.
Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement
Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power sys-
tem.
Description STRING A human-readable description of this ob-
ject.
positiveSeqMaxThreshold REAL The value that, if exceeded by the
positive-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.
zeroSeqMaxThreshold REAL The value that, if exceeded by the
zero-sequence results, will flag a possible
error condition. This value is compared
directly against the final unscaled output.
negativeSeqMaxThreshold REAL The value that, if exceeded by the
negative-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.
Outputs
Name IEC 61131 Type Description
StO_Quality enum_ValueSource The confidence level in the reported
sequence values.
StO_PosSequence vector_t The calculated positive-sequence
value.
StO_ZeroSequence vector_t The calculated negative-sequence
value.
StO_NegSequence vector_t The calculated zero-sequence value.
positiveSeqThresholdExceeded BOOL The magnitude of the
positive-sequence value reported
exceeds the provided threshold.
zeroSeqThresholdExceeded BOOL The magnitude of the zero-sequence
value reported exceeds the provided
threshold.
negativeSeqThresholdExceeded BOOL The magnitude of the
negative-sequence value reported
exceeds the provided threshold.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R135-V0 firmware
ä SEL-3530
â R135-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V0 firmware
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
Substation Example Run() Time 327,803 198,856 12,858
Distribution Example Run() Time 266,256 161,899 9,550
Ring Network Example Run() Time 164,639 97,313 6,689
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Modeling a Substation
Objective
A user has a substation that needs to be monitored. The substation is laid out as seen in
Figure 26.7.
V V
230,000 V 115,000 V A
A High
to A
A A Low A A
A
A
A
Assumptions
Typically all inputs to a model would be assigned directly from a communications channel,
however for ease in compilation for this example all inputs are pulled from a GVL shown
below in Code Snippet 26.1:
Solution
Once the user has identified all the elements of the model and decided the source for all
required data there are only two other elements the user must create for the model to do its
work. First, all configuration and bootstrap methods must be called before calling Run().
In this example this is shown as completed in a GVL, Code Snippet 26.3, which allows
the configuration to complete before any task cycles begin. Second, the user must create a
program that calls the model instance’s Run() method, as shown in Code Snippet 26.2.
IF FirstRun THEN
FirstRun := FALSE;
FOR i := 1 TO g_c_NumSwitches DO
g_Switches[i].Name := g_c_SwitchNames[i];
g_Switches[i].TypicallyClosed :=
g_c_SwitchTypicallyClosedValues[i];
END_FOR
FOR i := 1 TO g_c_NumBreakers DO
g_Breakers[i].Name := g_c_BreakerNames[i];
g_Breakers[i].TypicallyClosed :=
g_c_BreakerTypicallyClosedValues[i];
END_FOR
FOR i := 1 TO g_c_NumVoltageMeters DO
g_VoltageMeters[i].Name := g_c_VoltageMeterNames[i];
g_VoltageMeters[i].ScaleFactor := g_c_VoltageMeterScaleFactors[i];
END_FOR
FOR i := 1 TO g_c_NumCurrentMeters DO
g_CurrentMeters[i].Name := g_c_CurrentMeterNames[i];
g_VoltageMeters[i].ScaleFactor := g_c_CurrentMeterScaleFactors[i];
END_FOR
END_IF
g_Model1.Run();
g_Source2.pt_Terminal,
g_Source2Line.pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Source2Line.pt_TerminalB,
g_Switches[2].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[1].pt_TerminalB,
g_Breakers[1].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[2].pt_TerminalB,
g_Breakers[2].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Bus1.pt_Terminal,
g_Breakers[1].pt_TerminalB),
g_Model1.bootstrap_ConnectTerminals(
g_Bus1.pt_Terminal,
g_Breakers[2].pt_TerminalB),
g_Model1.bootstrap_ConnectTerminals(
g_Bus1.pt_Terminal,
g_Switches[3].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[3].pt_TerminalB,
g_Breakers[3].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Breakers[3].pt_TerminalB,
g_Switches[4].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[4].pt_TerminalB,
g_TransformerAHighVoltage.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals(
g_TransformerALowVoltage.pt_Terminal,
g_Switches[5].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[5].pt_TerminalB,
g_Breakers[4].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Breakers[4].pt_TerminalB,
g_Switches[6].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Bus2.pt_Terminal,
g_Switches[6].pt_TerminalB),
g_Model1.bootstrap_ConnectTerminals(
g_Bus2.pt_Terminal,
g_Breakers[5].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Bus2.pt_Terminal,
g_Breakers[6].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Bus2.pt_Terminal,
g_Breakers[7].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Bus2.pt_Terminal,
g_Breakers[8].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Breakers[5].pt_TerminalB,
g_Switches[7].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Breakers[6].pt_TerminalB,
g_Switches[8].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Breakers[7].pt_TerminalB,
g_Switches[9].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Breakers[8].pt_TerminalB,
g_Switches[10].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[7].pt_TerminalB,
g_Load1.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[8].pt_TerminalB,
g_Load2.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[9].pt_TerminalB,
g_Load3.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals(
g_Switches[10].pt_TerminalB,
g_Load4.pt_Terminal)
];
// Finish connecting terminals and enable population of containers.
g_TerminalsComplete : BOOL := g_Model1.bootstrap_FinalizeConnections();
// Set object configuration:
g_ConfigsSet : ARRAY [1 .. g_c_ConfigurationCount] OF BOOL := [
g_Switches[1].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[1]),
g_Switches[2].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[2]),
g_Switches[3].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[3]),
g_Switches[4].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[4]),
g_Switches[5].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[5]),
g_Switches[6].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[6]),
g_Switches[7].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[7]),
g_Switches[8].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[8]),
g_Switches[9].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[9]),
g_Switches[10].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[10]),
g_Breakers[1].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[11]),
g_Breakers[2].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[12]),
g_Breakers[3].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[13]),
g_Breakers[4].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[14]),
g_Breakers[5].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[15]),
g_Breakers[6].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[16]),
g_Breakers[7].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[17]),
g_Breakers[8].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[18]),
g_CurrentMeters[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[1], phaseA := PhaseAValues[1],
phaseB := PhaseBValues[1], phaseC := PhaseCValues[1]),
g_CurrentMeters[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[2], phaseA := PhaseAValues[2],
phaseB := PhaseBValues[2], phaseC := PhaseCValues[2]),
g_CurrentMeters[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[3], phaseA := PhaseAValues[3],
phaseB := PhaseBValues[3], phaseC := PhaseCValues[3]),
g_CurrentMeters[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[4], phaseA := PhaseAValues[4],
phaseB := PhaseBValues[4], phaseC := PhaseCValues[4]),
g_CurrentMeters[5].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[5], phaseA := PhaseAValues[5],
phaseB := PhaseBValues[5], phaseC := PhaseCValues[5]),
g_CurrentMeters[6].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[6], phaseA := PhaseAValues[6],
phaseB := PhaseBValues[6], phaseC := PhaseCValues[6]),
g_CurrentMeters[7].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[7], phaseA := PhaseAValues[7],
phaseB := PhaseBValues[7], phaseC := PhaseCValues[7]),
g_CurrentMeters[8].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[8], phaseA := PhaseAValues[8],
phaseB := PhaseBValues[8], phaseC := PhaseCValues[8]),
g_CurrentMeters[9].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[9], phaseA := PhaseAValues[9],
phaseB := PhaseBValues[9], phaseC := PhaseCValues[9]),
g_CurrentMeters[10].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[10], phaseA := PhaseAValues[10],
phaseB := PhaseBValues[10], phaseC := PhaseCValues[10]),
g_VoltageMeters[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[11], phaseA := PhaseAValues[11],
phaseB := PhaseBValues[11], phaseC := PhaseCValues[11]),
g_VoltageMeters[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[12], phaseA := PhaseAValues[12],
phaseB := PhaseBValues[12], phaseC := PhaseCValues[12]),
g_Source1Line.bootstrap_SetNominalLineImpedance1Line
(resistance := 1.2, reactance := 12),
g_Source1Line.bootstrap_SetNominalShuntAdmittance1Line
(conductance := 12, susceptance := 1.2),
g_Source2Line.bootstrap_SetNominalLineImpedance1Line
(resistance := 1.2, reactance := 12),
g_Source2Line.bootstrap_SetNominalShuntAdmittance1Line
(conductance := 12, susceptance := 1.2),
g_TransformerAHighVoltage.bootstrap_SetNominalEndImpedance3Phase(
reactanceAPhase := 10, resistanceAPhase := 1,
reactanceBPhase := 10, resistanceBPhase := 1,
reactanceCPhase := 10, resistanceCPhase := 1,
reactanceABPhase := 1, resistanceABPhase := 0.1,
reactanceACPhase := 1, resistanceACPhase := 0.1,
reactanceBCPhase := 1, resistanceBCPhase := 0.1),
g_TransformerAHighVoltage.bootstrap_SetNominalShuntAdmittance3Phase(
conductanceAPhase := 10, susceptanceAPhase := 1,
conductanceBPhase := 10, susceptanceBPhase := 1,
conductanceCPhase := 10, susceptanceCPhase := 1,
conductanceABPhase := 1, susceptanceABPhase := 0.1,
conductanceACPhase := 1, susceptanceACPhase := 0.1,
conductanceBCPhase := 1, susceptanceBCPhase := 0.1),
g_TransformerALowVoltage.bootstrap_SetNominalEndImpedance3Phase(
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[9]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[10]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[4]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[5]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[6]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[7]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[8]),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load1),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load2),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load3),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load4),
g_Breakers[1].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[1]),
g_Breakers[2].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[2]),
g_Breakers[3].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[3]),
g_TransformerAHighVoltage.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[4]),
g_TransformerALowVoltage.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[5]),
g_Breakers[4].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[6]),
g_Breakers[5].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[7]),
g_Breakers[6].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[8]),
g_Breakers[7].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[9]),
g_Breakers[8].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[10]),
g_Bus1.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters[1]),
g_Bus2.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters[2])
];
// Finalize all model configuration.
g_ModelValidated : BOOL := g_Model1.bootstrap_ValidateModel();
END_VAR
AB
V
23 kV
115 kV 5 kV
BC
A
CA
A AG
A V
A BG
V
A CG
V
Assumptions
Typically all inputs to a model would be assigned directly from a communication channel,
however for ease in compilation for this example all inputs are pulled from a GVL shown
in Code Snippet 26.4. Because the user needs to add single-phase monitoring, they must
create dummy inputs for the non-existent phases as the input sources for both voltage and
current.
Solution
Once the user has identified all the elements of the model and decided the source for all
required data there are only two other elements the user must create for the model to do its
work. First, all configuration and bootstrap methods must be called before calling Run().
In this example this is shown as completed in a GVL, Code Snippet 26.6, which allows
the configuration to complete before any task cycles begin. Second, the user must create a
program that calls the model instance’s Run() method, Code Snippet 26.5:
IF FirstRun THEN
FirstRun := FALSE;
FOR i := 1 TO g_c_NumSwitches2 DO
g_Switches2[i].Name := g_c_Switches2Names[i];
g_Switches2[i].TypicallyClosed :=
g_c_Switches2TypicallyClosedValues[i];
END_FOR
FOR i := 1 TO g_c_NumBreakers2 DO
g_Breakers2[i].Name := g_c_Breakers2Names[i];
g_Breakers2[i].TypicallyClosed :=
g_c_Breakers2TypicallyClosedValues[i];
END_FOR
FOR i := 1 TO g_c_NumVoltageMeters2 DO
g_VoltageMeters2[i].Name := g_c_VoltageMeters2Names[i];
g_VoltageMeters2[i].ScaleFactor :=
g_c_VoltageMeters2ScaleFactors[i];
END_FOR
FOR i := 1 TO g_c_NumCurrentMeters2 DO
g_CurrentMeters2[i].Name := g_c_CurrentMeters2Names[i];
g_CurrentMeters2[i].ScaleFactor :=
g_c_CurrentMeters2ScaleFactors[i];
END_FOR
END_IF
g_Model2.Run();
:= ['Bkr_LineN', 'Bkr_LineS'];
g_c_Breakers2TypicallyClosedValues : ARRAY [1..g_c_NumBreakers2] OF
BOOL := [2(TRUE)];
g_c_VoltageMeters2Names : ARRAY [1..g_c_NumVoltageMeters2] OF STRING
:= ['TransformerOutVolts', 'ALineVoltage', 'BLineVoltage',
'CLineVoltage'];
g_c_VoltageMeters2ScaleFactors : ARRAY [1..g_c_NumVoltageMeters2] OF
REAL := [3(1000)];
g_c_CurrentMeters2Names : ARRAY [1..g_c_NumCurrentMeters2] OF STRING
:= ['CurrentN', 'CurrentS', 'CurrentA', 'CurrentB', 'CurrentC'];
g_c_CurrentMeters2ScaleFactors : ARRAY [1..g_c_NumCurrentMeters2] OF
REAL
:= [1, 4(-1)];
END_VAR
VAR_GLOBAL
// Instantiate any desired models here:
g_Model2 : class_PowerSystemModel :=
(Filename := 'GlobalModel2.log', ABCRotation := TRUE);
// Instantiate all other components:
g_SourceN : class_EnergySource :=
(Name := 'Source1', Description := 'North Line');
g_SourceS : class_EnergySource :=
(Name := 'Source2', Description := 'South Line');
g_LoadAB : class_EnergyConsumer := (Name := 'LoadAB');
g_LoadBC : class_EnergyConsumer := (Name := 'LoadBC');
g_LoadCA : class_EnergyConsumer := (Name := 'LoadCA');
g_LoadA : class_EnergyConsumer := (Name := 'LoadA');
g_LoadB : class_EnergyConsumer := (Name := 'LoadB');
g_LoadC : class_EnergyConsumer := (Name := 'LoadC');
g_Bus : class_BusbarSection := (Name := 'Bus');
g_Junction1 : class_Junction := (Name := 'Source Line Junction');
g_Junction2 : class_Junction := (Name := 'Junction N Shunt');
g_Junction3 : class_Junction := (Name := 'Junction S Shunt');
g_Junction4 : class_Junction := (Name := 'Junction two phase split');
g_Junction5 : class_Junction := (Name := 'Junction one phase split');
g_Switches2 : ARRAY [1..g_c_NumSwitches2] OF class_Switch;
g_Breakers2 : ARRAY [1..g_c_NumBreakers2] OF class_Breaker;
g_VoltageMeters2 : ARRAY [1..g_c_NumVoltageMeters2] OF
class_VoltageMeasurement;
g_CurrentMeters2 : ARRAY [1..g_c_NumCurrentMeters2] OF
class_CurrentMeasurement;
g_LineN1 : class_ACLineSegment := (Name := 'LineN1');
g_LineN2 : class_ACLineSegment := (Name := 'LineN2');
g_LineS1 : class_ACLineSegment := (Name := 'LineS1');
g_LineS2 : class_ACLineSegment := (Name := 'LineS2');
g_TransformerIn : class_PowerTransformer := (Name :=
'InboundTransformer');
g_TransformerN : class_PowerTransformer := (Name :=
'LineNTransformer');
g_TransformerS : class_PowerTransformer := (Name :=
'LineSTransformer');
g_TransformerInHigh : class_PowerTransformerEnd :=
(Name := 'InHighVolts', ConnectionType := WYE, NominalRatio :=
1.0);
g_TransformerInLow : class_PowerTransformerEnd :=
(Name := 'InLowVolts', ConnectionType := WYE, NominalRatio := 0.2);
g_TransformerNHigh : class_PowerTransformerEnd :=
(Name := 'LineNHighVolts', ConnectionType := WYE, NominalRatio :=
1.0);
g_TransformerNLow : class_PowerTransformerEnd :=
(Name := 'LineNLowVolts', ConnectionType := WYE, NominalRatio :=
0.21739);
g_TransformerNTap : class_TapChanger := (DefaultStep := 0,
StepSize := 0.05, StepHighLimit := 16, StepLowLimit := -16);
g_TransformerSHigh : class_PowerTransformerEnd :=
(Name := 'LineSHighVolts', ConnectionType := WYE, NominalRatio :=
1.0);
g_TransformerSLow : class_PowerTransformerEnd :=
(Name := 'LineSLowVolts', ConnectionType := WYE, NominalRatio :=
0.21739);
g_TransformerSTap : class_TapChanger := (DefaultStep := 0,
StepSize := 0.05, StepHighLimit := 16, StepLowLimit := -16);
g_HighVoltage2 : class_VoltageLevel;
g_MidVoltage2 : class_VoltageLevel;
g_LowVoltage2 : class_VoltageLevel;
g_NorthShunt : class_ShuntCompensator
:= ( Name := 'North Line Shunt Cap',
conductanceAPhase := 0,
susceptanceAPhase := 25,
conductanceBPhase := 0,
susceptanceBPhase := 25,
conductanceCPhase := 0,
susceptanceCPhase := 25
);
g_SouthShunt : class_ShuntCompensator
:= ( Name := 'South Line Shunt Cap',
conductanceAPhase := 0,
susceptanceAPhase := 25,
conductanceBPhase := 0,
susceptanceBPhase := 25,
conductanceCPhase := 0,
susceptanceCPhase := 25
);
(* Tie object terminals together.
** This should be done immediately after instantiating objects.
** This must be done before adding objects to containers. *)
g_ObjectsTied2 : ARRAY [1 .. g_c_ConnectionCount2] OF BOOL
:= [ g_Model2.bootstrap_ConnectTerminals
(g_Junction1.pt_Terminal, g_SourceN.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction1.pt_Terminal, g_Switches2[1].pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals
(g_SourceS.pt_Terminal, g_Switches2[1].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Junction1.pt_Terminal, g_Switches2[2].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Switches2[2].pt_TerminalB,
g_TransformerInHigh.pt_Terminal),
//The equipment between the transformers
g_Model2.bootstrap_ConnectTerminals(
g_Bus.pt_Terminal,
g_TransformerInLow.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Bus.pt_Terminal,
g_Switches2[3].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Switches2[3].pt_TerminalB,
g_Breakers2[1].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Breakers2[1].pt_TerminalB,
g_TransformerNHigh.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Bus.pt_Terminal,
g_Switches2[4].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Switches2[4].pt_TerminalB,
g_Breakers2[2].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Breakers2[2].pt_TerminalB,
g_TransformerSHigh.pt_Terminal),
//The equipment on the north line after the transformer
g_Model2.bootstrap_ConnectTerminals(
g_TransformerNLow.pt_Terminal,
g_LineN1.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Junction2.pt_Terminal,
g_LineN1.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals(
g_Junction2.pt_Terminal,
g_NorthShunt.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Junction2.pt_Terminal,
g_LineN2.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Junction4.pt_Terminal,
g_LineN2.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals(
g_Junction4.pt_Terminal,
g_LoadAB.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Junction4.pt_Terminal,
g_LoadBC.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Junction4.pt_Terminal,
g_LoadCA.pt_Terminal),
// The equipment on the south line after the transformer
g_Model2.bootstrap_ConnectTerminals(
g_TransformerSLow.pt_Terminal,
g_LineS1.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Junction3.pt_Terminal,
g_LineS1.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals(
g_Junction3.pt_Terminal,
g_SouthShunt.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Junction3.pt_Terminal,
g_LineS2.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals(
g_Junction5.pt_Terminal,
g_LineS2.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals(
g_Junction5.pt_Terminal,
g_LoadA.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Junction5.pt_Terminal,
g_LoadB.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals(
g_Junction5.pt_Terminal,
g_LoadC.pt_Terminal)
];
// Finish connecting terminals and enable population of conatiners.
g_TerminalsComplete2 : BOOL :=
g_Model2.bootstrap_FinalizeConnections();
// Set object configuration:
g_ConfigsSet2 : ARRAY [1 .. g_c_ConfigurationCount2] OF BOOL
:= [ g_Switches2[1].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues2[1]),
g_Switches2[2].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues2[2]),
g_Switches2[3].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues2[3]),
g_Switches2[4].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues2[4]),
g_Breakers2[1].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues2[5]),
g_Breakers2[2].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues2[6]),
g_CurrentMeters2[1].bootstrap_ConfigureInputsThreePhase(
enable := EnableBits2[1], phaseA := PhaseAValues2[1],
phaseB := PhaseBValues2[1], phaseC := PhaseCValues2[1]),
g_CurrentMeters2[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[2], phaseA := PhaseAValues2[2],
phaseB := PhaseBValues2[2], phaseC := PhaseCValues2[2]),
g_CurrentMeters2[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[3], phaseA := PhaseAValues2[3],
phaseB := g_DummyCurrent, phaseC := g_DummyCurrent),
g_CurrentMeters2[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[4], phaseA := g_DummyCurrent,
phaseB := PhaseBValues2[4], phaseC := g_DummyCurrent),
g_CurrentMeters2[5].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[5], phaseA := g_DummyCurrent,
phaseB := g_DummyCurrent, phaseC := PhaseCValues2[5]),
g_VoltageMeters2[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[6], phaseA := PhaseAValues2[6],
phaseB := PhaseBValues2[6], phaseC := PhaseCValues2[6]),
g_VoltageMeters2[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[7], phaseA := PhaseAValues2[7],
phaseB := g_DummyVoltage, phaseC := g_DummyVoltage),
g_VoltageMeters2[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[8], phaseA := g_DummyVoltage,
phaseB := PhaseBValues2[8], phaseC := g_DummyVoltage),
g_VoltageMeters2[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[9], phaseA := g_DummyVoltage,
phaseB := g_DummyVoltage, phaseC := PhaseCValues2[9]),
g_LineN1.bootstrap_SetNominalLineImpedance1Line
(resistance := g_c_SeriesRealImpedancePerMile * 45,
reactance := g_c_SeriesReactiveImpedancePerMile * 45),
g_LineN1.bootstrap_SetNominalShuntAdmittance1Line
(conductance := g_c_ShuntRealAdmittancePerMile * 45,
susceptance := g_c_ShuntReactiveAdmittancePerMile * 45),
g_LineN2.bootstrap_SetNominalLineImpedance1Line
(resistance := g_c_SeriesRealImpedancePerMile * 2,
reactance := g_c_SeriesReactiveImpedancePerMile * 2),
g_LineN2.bootstrap_SetNominalShuntAdmittance1Line
(conductance := g_c_ShuntRealAdmittancePerMile * 2,
g_TransformerSLow.bootstrap_AddTapChanger
(tapChanger := g_TransformerSTap),
g_HighVoltage2.bootstrap_AddEquipment(
equipment := g_TransformerInHigh),
g_HighVoltage2.bootstrap_AddEquipment(equipment := g_SourceN),
g_HighVoltage2.bootstrap_AddEquipment(equipment := g_SourceS),
g_HighVoltage2.bootstrap_AddEquipment(
equipment := g_Junction1),
g_HighVoltage2.bootstrap_AddEquipment(
equipment := g_Switches2[1]),
g_HighVoltage2.bootstrap_AddEquipment(
equipment := g_Switches2[2]),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_TransformerInLow),
g_MidVoltage2.bootstrap_AddEquipment(equipment := g_Bus),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_Switches2[3]),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_Switches2[4]),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_Breakers2[1]),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_Breakers2[2]),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_TransformerNHigh),
g_MidVoltage2.bootstrap_AddEquipment(
equipment := g_TransformerSHigh),
g_LowVoltage2.bootstrap_AddEquipment(
equipment := g_TransformerNLow),
g_LowVoltage2.bootstrap_AddEquipment(
equipment := g_TransformerSLow),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineN1),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineN2),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineS1),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineS2),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction2),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction3),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction4),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction5),
g_LowVoltage2.bootstrap_AddEquipment(equipment :=
g_NorthShunt),
g_LowVoltage2.bootstrap_AddEquipment(equipment :=
g_SouthShunt),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadAB),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadBC),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadCA),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadA),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadB),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadC),
g_Breakers2[1].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[1]),
g_Breakers2[2].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[2]),
g_LoadA.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[3]),
g_LoadB.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[4]),
g_LoadC.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[5]),
g_Bus.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[1]),
g_LoadA.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[2]),
g_LoadB.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[3]),
g_LoadC.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[4])
];
// Finalize all model configuration.
g_ModelValidated2 : BOOL := g_Model2.bootstrap_ValidateModel();
END_VAR
120 V
A 600 V
A
12 kV
A A
V V
A
A A
240 V
Assumptions
Typically all inputs to a model would be assigned directly from a communication channel,
however for ease in compilation for this example all inputs are pulled from a GVL shown
in Code Snippet 26.7.
(stVal:=FALSE, q:=(validity:=good)),
(stVal:=FALSE, q:=(validity:=good)),
(stVal:=FALSE, q:=(validity:=good)),
(stVal:=FALSE, q:=(validity:=good)),
(stVal:=FALSE, q:=(validity:=good)),
(stVal:=FALSE, q:=(validity:=good))
];
EnableBits3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]
OF BOOL := [g_c_NumVoltageMeters3(TRUE),
g_c_NumCurrentMeters3(TRUE)];
PhaseAValues3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]
OF CMV
:= [(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=10)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=1)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=4)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=2)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=1)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=4)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=2))
];
PhaseBValues3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]
OF CMV
:= [(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=10)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=1)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=4)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=2)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=1)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=4)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=2))
];
PhaseCValues3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]
OF CMV
:= [(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=600)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=10)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=1)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=4)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=2)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=1)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=4)),
(q:=(validity:=good), instCVal:=(ang:=0, mag:=2))
];
END_VAR
Solution
Once the user has identified all the elements of the model and decided the source for all
required data there are only two other elements the user must create for the model to do
its work. First, the user must call all configuration and bootstrap methods before calling
Run(). In this example, this is shown as completed in a GVL, Code Snippet 26.9, which
allows the configuration to complete before any task cycles begin. Second, the user must
create a program that calls the model instance’s Run() method, Code Snippet 26.8:
IF FirstRun THEN
FirstRun := FALSE;
FOR i := 1 TO g_c_NumBreakers3 DO
g_Breakers3[i].Name := g_c_Breakers3Names[i];
g_Breakers3[i].TypicallyClosed :=
g_c_Breakers3TypicallyClosedValues[i];
END_FOR
FOR i := 1 TO g_c_NumVoltageMeters3 DO
g_VoltageMeters3[i].Name := g_c_VoltageMeters3Names[i];
g_VoltageMeters3[i].ScaleFactor :=
g_c_VoltageMeters3ScaleFactors[i];
END_FOR
FOR i := 1 TO g_c_NumCurrentMeters3 DO
g_CurrentMeters3[i].Name := g_c_CurrentMeters3Names[i];
g_CurrentMeters3[i].ScaleFactor :=
g_c_CurrentMeters3ScaleFactors[i];
END_FOR
END_IF
g_Model3.Run();
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[1].pt_TerminalB,
g_12Kin600.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_JunctionW.pt_Terminal,
g_12Kout600.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_JunctionW.pt_Terminal,
g_Breakers3[2].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[2].pt_TerminalB,
g_600in120.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[2].pt_TerminalB,
g_Breakers3[3].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[3].pt_TerminalB,
g_Breakers3[4].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_JunctionE.pt_Terminal,
g_Breakers3[4].pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals(g_JunctionE.pt_Terminal,
g_Load600_1.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_JunctionE.pt_Terminal,
g_Breakers3[5].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[5].pt_TerminalB,
g_600in240.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[5].pt_TerminalB,
g_Breakers3[6].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_JunctionS.pt_Terminal,
g_Breakers3[6].pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals(g_JunctionS.pt_Terminal,
g_Switch.pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals(g_Switch.pt_TerminalA,
g_Source600.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_JunctionS.pt_Terminal,
g_Breakers3[7].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[7].pt_TerminalB,
g_Load600_2.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_Breakers3[7].pt_TerminalB,
g_Breakers3[8].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals(g_JunctionW.pt_Terminal,
g_Breakers3[8].pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals(g_600out120.pt_Terminal,
g_Load120.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals(g_600out240.pt_Terminal,
g_Load240.pt_Terminal)
];
// Finish connecting terminals and enable population of conatiners.
g_TerminalsComplete3 : BOOL :=g_Model3.bootstrap_FinalizeConnections();
// Set object configuration:
g_ConfigsSet3 : ARRAY [1 .. g_c_ConfigurationCount3] OF BOOL
:= [ g_Switch.bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[1]),
g_Breakers3[1].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[2]),
g_Breakers3[2].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[3]),
g_Breakers3[3].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[4]),
g_Breakers3[4].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[5]),
g_Breakers3[5].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[6]),
g_Breakers3[6].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[7]),
g_Breakers3[7].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[8]),
g_Breakers3[8].bootstrap_ConfigureIsOpenInput(
stIn_IsOpen := OpenStateValues3[9]),
g_CurrentMeters3[1].bootstrap_ConfigureInputsThreePhase(
enable := EnableBits3[1], phaseA := PhaseAValues3[1],
phaseB := PhaseBValues3[1], phaseC := PhaseCValues3[1]),
g_CurrentMeters3[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[2], phaseA := PhaseAValues3[2],
phaseB := PhaseBValues3[2], phaseC := PhaseCValues3[2]),
g_CurrentMeters3[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[3], phaseA := PhaseAValues3[3],
phaseB := PhaseBValues3[3], phaseC := PhaseCValues3[3]),
g_CurrentMeters3[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[4], phaseA := PhaseAValues3[4],
phaseB := PhaseBValues3[4], phaseC := PhaseCValues3[4]),
g_CurrentMeters3[5].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[5], phaseA := PhaseAValues3[5],
phaseB := PhaseBValues3[5], phaseC := PhaseCValues3[5]),
g_CurrentMeters3[6].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[6], phaseA := PhaseAValues3[6],
phaseB := PhaseBValues3[6], phaseC := PhaseCValues3[6]),
g_CurrentMeters3[7].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[7], phaseA := PhaseAValues3[7],
phaseB := PhaseBValues3[7], phaseC := PhaseCValues3[7]),
g_VoltageMeters3[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[8], phaseA := PhaseAValues3[8],
phaseB := PhaseBValues3[8], phaseC := PhaseCValues3[8]),
g_VoltageMeters3[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[9], phaseA := PhaseAValues3[9],
phaseB := PhaseBValues3[9], phaseC := PhaseCValues3[9]),
g_VoltageMeters3[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[10], phaseA := PhaseAValues3[10],
phaseB := PhaseBValues3[10], phaseC := PhaseCValues3[10]),
g_12Kin600.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_12Kin600.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_12Kout600.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_12Kout600.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_600in240.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_600in240.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_600out240.bootstrap_SetNominalEndImpedance1Line(
g_600in120.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[2]),
g_Load600_1.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[3]),
g_600in240.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[4]),
g_Switch.pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[5]),
g_Load600_2.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[6]),
g_Breakers3[4].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[7])
];
// Finalize all model configuration.
g_ModelValidated3 : BOOL := g_Model3.bootstrap_ValidateModel();
END_VAR
PowerSystemProtection
Introduction
The power system protection library provides function blocks that implement various pro-
tection elements for power systems. This library is intended to be used in conjunction with
the SEL-2245-42 AC Protection Module.
Special Considerations
ä This library is not supported on the SEL-3505 class of RTACs. This is because the
SEL-3505 does not support the Axion AC Protection Module. However, this library
is not prevented from running on a SEL-3505, but is not tested and has no guarantee
on expected behavior.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_LineBusStates
Given the voltage levels on the bus side and line side of a breaker, the line side and bus
side can each be either live or dead. This enumeration represents the four permutations
that result from the two monitored locations, each in one of two states. There are also per-
mutations provided for when one of the states can be confirmed, but not the other.
Enumeration Description
Function Blocks
fb_DefiniteTime (Function Block)
This function block implements instantaneous and definite-time overcurrent protection
functionality.
The settings inputs (starting with Set) are read on the first call to the function block after
EN becomes TRUE or on the first call to the function block. All changes to the settings
inputs during runtime are ignored until the next rising edge of EN is detected.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetPickupSetting REAL Pickup current of the protection element. This is the
minimum current required to initiate the operation
of the protection element.
SetDelayTime TIME Time delay for definite-time overcurrent protection
element. This should be set to a multiple of the
RTAC processing scan time on which this object is
instantiated and represents the amount of time Op-
eratingQuantity must exceed PickupSetting prior to
asserting the protection element output.
OperatingQuantity REAL The fundamental magnitude of the current. This
quantity may be phase (A, B, or C), ground, or
negative-sequence current measurement.
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
PickupSetting REAL Pickup current value used in the protection element,
read from SetPickupSetting.
DelayTime TIME Definite-time overcurrent time delay value used in the
protection element, read from SetDelayTime.
ElementPickup BOOL Instantaneous overcurrent protection element has op-
erated. Set to TRUE when OperatingQuantity >= Pick-
upSetting.
PickupTimeOut BOOL Definite-time overcurrent protection element has op-
erated. Set to TRUE when OperatingQuantity > Pick-
upSetting for a time longer than DelayTime.
Processing
ä If OperatingQuantity >= PickupSetting, then set ElementPickup to TRUE.
ä If ElementPickup has been TRUE for longer than DelayTime, then set PickupTimeOut
TRUE.
ä When OperatingQuantity < PickupSetting, reset the elapsed time in the timer to 0
and set the ElementPickup to FALSE.
Equations
B
OperatingT ime = T imeDial ∗ (A + ) (Equation 27.1)
MC −1
R
ResetT ime = T imeDial ∗ ( ) (Equation 27.2)
1 − M2
where:
ä M is the applied multiple of pickup current
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetPickupSetting REAL Pickup current magnitude of the protection element.
If OperatingQuantity goes above this quantity, the
protection element initiates its operation. This input
is read once on first call to the function block. All
changes to this input during runtime are ignored.
SetTimeDial REAL Time-dial setting. This input adjusts the protection
element to a predetermined trip time at a specified
current, as described in IEEE C37.112-1996, IEEE
Standard Inverse-Time Characteristic Equations for
Overcurrent Relays. This input is read once on first
call to the function block. All changes to this input
during runtime are ignored.
OperatingQuantity REAL The fundamental magnitude of the current. This
quantity may be phase (A, B, or C), ground, or
negative-sequence current measurement.
SetA REAL Sets user-defined A parameter for inverse curve cal-
culation (see Equation 27.1 ).
SetB REAL Sets user-defined B parameter for inverse curve cal-
culation (see Equation 27.1 ).
SetC REAL Sets user-defined C parameter for inverse curve cal-
culation (see Equation 27.1 ).
SetR REAL Sets user-defined R parameter for inverse curve cal-
culation (see Equation 27.2 ).
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
PickupSetting REAL Pickup current value used in the protection element.
This value is read from SetPickupSetting on first run of
the function block.
TimeDial REAL Time-dial setting value used in the protection element.
This value is read from SetTimeDial on first run of the
function block.
ElementPickup BOOL The protection element has initiated operation. Set to
TRUE if OperatingQuantity > PickupSetting.
PickupTimeOut BOOL The protection element has operated. Set to TRUE
when the operating time expires.
ElementReset BOOL The protection element has reset (refer to section 3.2
of IEEE C37.112-1996, IEEE Standard Inverse-Time
Characteristic Equations for Overcurrent Relays).
Aval REAL Value being used that was set from SetA.
Bval REAL Value being used that was set from SetB.
Cval REAL Value being used that was set from SetC.
Rval REAL Value being used that was set from SetR.
Processing
START
OperatingQuantity
M= P ickupV alue
∆T
Acck = Acck−1 + Inc
n n
Acc <= 0 Acc > 1
y y
Acc = 0 Acc = 1
PickupTimeOut= False PickupTimeOut= TRUE
ElementReset= TRUE ElementReset= FALSE
END
where:
ä TD = time-dial setting
ä M = applied multiple of pickup current
â for operating time, M > 1;
â for reset time, M < 1
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetPickupSetting REAL Pickup current magnitude of the protection element.
If OperatingQuantity goes above this quantity, the
protection element initiates its operation. This input
is read once on first call to the function block. All
changes to this input during runtime are ignored.
SetTimeDial REAL Time-dial setting. This input adjusts the protection
element to a predetermined trip time at a specified
current, as described in IEEE C37.112-1996, IEEE
Standard Inverse-Time Characteristic Equations for
Overcurrent Relays. This input is read once on first
call to the function block. All changes to this input
during runtime are ignored.
OperatingQuantity REAL The fundamental magnitude of the current. This
quantity may be phase (A, B, or C), ground, or
negative-sequence current measurement.
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
PickupSetting REAL Pickup current value used in the protection element.
This value is read from SetPickupSetting on first run of
the function block.
TimeDial REAL Time-dial setting value used in the protection element.
This value is read from SetTimeDial on first run of the
function block.
ElementPickup BOOL The protection element has initiated operation. Set to
TRUE if OperatingQuantity > PickupSetting.
PickupTimeOut BOOL The protection element has operated. Set to TRUE
when the operating time expires.
ElementReset BOOL The protection element has reset (refer to section 3.2
of IEEE C37.112-1996, IEEE Standard Inverse-Time
Characteristic Equations for Overcurrent Relays).
Processing
The calculations for these predefined curves happens exactly the same as for the fb_In-
verseTimeCurveUser (Function Block) on page 27.3, except that the coefficients used are
hard-coded instead of user-settable.
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetNominalFrequency DINT(50..60) The nominal frequency (Hz) of the power
system (50 or 60). Recommend setting
this input equal to the RTAC system tag:
SystemTags.Nominal_Frequency.stVal
SetAmpsNominal REAL The maximum nominal amperage expected
(usually 1 A or 5 A secondary).
SetVoltsNominal REAL The nominal line-to-line voltage.
VoltsPosSeq vector_t The positive-sequence fundamental voltage vec-
tor.
VoltsZeroSeq vector_t The zero-sequence voltage fundamental vector.
AmpsZeroSeq vector_t The zero-sequence current fundamental vector.
AmpsPosSeq vector_t The positive-sequence current fundamental vec-
tor.
AmpsNegSeq vector_t The negative-sequence current fundamental
vector.
AmpsPhaseA vector_t The fundamental Phase A current.
AmpsPhaseB vector_t The fundamental Phase B current.
AmpsPhaseC vector_t The fundamental Phase C current.
FundQok BOOL The fundamental quantities above are report-
ing good quality. If values are being read
from the SEL-2245-42 module, then enable the
QUALITY_FUND tag on the module and assign
that tag to this input.
FundTimeStamp timestamp_t The time stamp of the fundamental quantity
measurements. Assign the TIMESTAMP_FUND.
tag on the SEL-2245-42 module to this input.
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled
ErrorDesc STRING(80) Displays an error description if one exists
NominalFrequency DINT[50,60] The nominal frequency of the power system (Hz).
AmpsNominal REAL The magnitude of the maximum nominal amperage
expected, read once from SetAmpsNominal.
VoltsNominal REAL The magnitude of the nominal line-to-line voltage.
This value is read once from SetVoltsNominal.
LossOfPotential BOOL Loss-of-potential condition detected. If ENO is
FALSE, then this value returns to the default TRUE
state. Use this output to disable protection elements
that use voltage to trip.
Processing
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block. This should be set to
FALSE if the quantity being measured is bad qual-
ity or a loss-of-potential condition is detected.
ThresholdVoltage REAL The voltage to compare the magnitude against.
MeasuredVoltage REAL The magnitude of the voltage to measure.
Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is enabled.
OverVoltage BOOL The MeasuredVoltage is exceeding the voltage threshold.
Processing
The OverVoltage and ENO outputs are computed based on the input states according to the
following logic diagram:
MeasuredVoltage +
ThresholdVoltage −
OverVoltage
EN ENO
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block. This should be set to
FALSE if the quantity being measured is bad qual-
ity or a loss-of-potential condition is detected.
ThresholdVoltage REAL The voltage to compare the magnitude against.
MeasuredVoltage REAL The magnitude of the voltage to measure.
Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is enabled.
UnderVoltage BOOL The MeasuredVoltage is presently less than the threshold
voltage.
Processing
The UnderVoltage and ENO outputs are computed based on the input states according to
the following logic diagram:
MeasuredVoltage −
ThresholdVoltage +
UnderVoltage
EN ENO
Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block. Set this to FALSE if the
quantity being measured is bad quality or a loss-of-
potential condition is detected.
LineDeadThreshold REAL The voltage at which to declare the line dead.
LineLiveThreshold REAL The voltage at which to declare the line live.
BusDeadThreshold REAL The voltage at which to declare the bus dead.
BusLiveThreshold REAL The voltage at which to declare the bus live.
LineVoltage REAL The measured voltage of the line.
BusVoltage REAL The measured voltage of the bus.
Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is enabled.
ErrorDesc STRING(80) Displays an error description, if one exists.
LineBusState enum_LineBusStates The decided permutation.
Processing
ä If LineDeadThreshold > LineLiveThreshold, then an error is displayed in ErrorDesc.
ä If BusDeadThreshold > BusLiveThreshold, then an error is displayed in ErrorDesc.
ä When the following conditions are met, ENO is set to TRUE:
â LineDeadThreshold ≤ LineLiveThreshold.
â BusDeadThreshold ≤ BusLiveThreshold.
â EN = TRUE.
ä If ENO = TRUE, then the bus and line states are computed independently using this
logic:
â If the voltage is below the associated dead threshold, declare it dead.
â If the voltage is above the associated live threshold, declare it live.
â If neither of the above conditions are TRUE, declare it dead.
ä If ENO = FALSE, then the LineBusState is set to ULUB (undefined bus, undefined
line).
Inputs
Name IEC 61131 Type Description
EN BOOL Enables the computations of this function
block.
SetInitialTemp REAL Given in ℃; the assumed initial tempera-
ture of the line. This initializes the output
CalculatedTemp on the first scan that EN is
set to TRUE.
SetTimeConstant TIME The time constant (T ) which represents the
heating/cooling constant of the conductor
associated with the thermal capacity of the
line.
SetRatedCurrent REAL The amount of current which the conductor
is rated to carry continuously. Units must
match with the MeasuredCurrent.
SetReferenceAmbientTemp REAL The ambient temperature in ℃ at which
MaxConductorTemp was measured.
SetMaxConductorTemp REAL Given in ℃; the steady state temperature if
rated current flows continuously.
MeasuredCurrent REAL The rms current presently measured flow-
ing in the conductor. Units must match the
RatedCurrent value provided.
AmbientTemp REAL The ambient dry-bulb temperature in ℃.
The highest measured air temperature ex-
perienced by the conductor over its span.
Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is active.
TimeConstant TIME The value (T ) read from SetTimeConstant.
RatedCurrent REAL The value read from SetRatedCurrent.
ReferenceAmbientTemp REAL The value read from SetReferenceAmbient-
Temp.
MaxConductorTemp REAL The value read from SetMaxConductorTemp.
CalculatedTemp REAL Based on the parameters provided, this is the
calculated temperature of the conductor, given
in ℃. Initialized by SetInitialTemp.
TimeToOverload TIME Assuming the inputs MeasuredCurrent and
AmbientTemp remain at their present value,
this is the amount of time remaining until an
overload condition is declared.
Overloaded BOOL MaxConductorTemperature has been reached.
Processing
This section describes the formulas used by this function block to calculate the outputs.
Temperature Calculation
An internal model is employed which assumes that the thermal dissipation capacity of
the conductor varies only with environmental temperature, which can either be entered
manually, or a temperature sensor can be used to measure the actual environmental air
temperature.
In the following, the uppercase Latin character T is used for temperature (℃) and the
uppercase Greek T for time constant. Lowercase t is used to represent time.
Most of the internal temperatures used in the equations are relative to ambient temperature.
These relative temperatures are represented by T∆ .
The temperature rise beyond ambient that is experienced by the conductor at steady-state
when carrying the maximum rated current is given by Equation 27.3 .
Equation 27.5 shows the thermal differential equation, where h is the heat transfer coeffi-
cient of the conductor surface and A is the area of the surface of the conductor.
I 2R
dT 1
= −T (Equation 27.5)
dt T hA
Equation 27.6 and Equation 27.7 show the solution of Equation 27.5 in time-domain and
discrete domain, respectively.
I 2R t
t
T∆ = 1 − e− T + T∆Initial e− T (Equation 27.6)
hA
∆t R
T T hA I 2 + T∆k−1
T∆k = ∆t
(Equation 27.7)
1+ T
We can use a particular solution to find the relation between the coefficients R, h, and A: if
rated current In flows for a long amount of time (infinite), the steady state temperature of
the conductor is T∆n . Substituting these values in Equation 27.6 , the following equation
can be obtained:
R T∆n
= 2 (Equation 27.8)
hA In
2
∆t I
T In T∆n + T∆k−1
T∆k = ∆t
(Equation 27.9)
1+ T
Substituting Equation 27.10 , Equation 27.11 , and Equation 27.12 in Equation 27.9 ,
we get the equation that is used by this function block to calculate the temperature of the
conductor:
2
I T
In (TM axConductor − TRef erence ) + ∆t Tk−1 + TAmbient
TCalculatedk = T
1 + ∆t
(Equation 27.13)
where:
TCalculatedk ≡ CalculatedT emp
TM axConductor ≡ M axConductorT emp
TRef erence ≡ Ref erenceAmbientT emp
TAmbient ≡ AmbientT emp
I ≡ M easuredCurrent
In ≡ RatedCurrent
I 2 T∆n
Tss = + TAmbient (Equation 27.14)
In2
While the steady-state temperature Tss > TM axConductor and TCalculatedk < TM axConductor
then there is an imminent overload condition. The time to the overload is calculated using
Equation 27.15 :
Tss − TCalculatedk
T imeT oOverload = T × ln (Equation 27.15)
Tss − TM axConductor
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530 / SEL-2241
â R136 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R136 firmware
Benchmark Results
Platform (time in µs)
Operation Tested SEL-3530 SEL-3555
SEL-2241
fb_DefiniteTime 3.1 0.5
fb_InverseTimeCurveUser 12.6 0.9
fb_LossOfPotential 10.8 0.4
fb_BusLineVoltageCheck 5.2 0.3
fb_OverVoltage 0.9 0.1
fb_UnderVoltage 1.1 0.1
fb_ConductorThermalOverload 15.0 0.8
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes the user has an AC Protection Module setup to get current input
measurements.
Solution
The user can create a program shown in Code Snippet 27.1:
//Program Outputs
O50PT : BOOL;
END_VAR
AProtection(OperatingQuantity := SEL_prCTPT_1_ECAT.IA_FUND.mag,
SetPickupSetting := SET50P,
SetDelayTime := SET50PTD);
BProtection(OperatingQuantity := SEL_prCTPT_1_ECAT.IB_FUND.mag,
SetPickupSetting := SET50P,
SetDelayTime := SET50PTD);
CProtection(OperatingQuantity := SEL_prCTPT_1_ECAT.IC_FUND.mag,
SetPickupSetting := SET50P,
SetDelayTime := SET50PTD);
O50PT := AProtection.PickupTimeout
OR BProtection.PickupTimeout
OR CProtection.PickupTimeout;
Assumptions
This example assumes the user has a SEL-2245-42 AC Protection Module configured in
the RTAC project to obtain fundamental measurements. NOTE: The module is assumed to
have the name:
"SEL_prCTPT_1_ECAT".
Solution
The user can create a program shown in Code Snippet 27.2:
O51P := Aphase.ElementPickup
AND Bphase.ElementPickup
AND Cphase.ElementPickup;
O51PT := Aphase.PickupTimeOut
AND Bphase.PickupTimeOut
AND Cphase.PickupTimeOut;
O51PR := Aphase.ElementReset
AND Bphase.ElementReset
AND Cphase.ElementReset;
Assumptions
This example assumes the user has a SEL-2245-42 AC Protection Module configured in
the RTAC project to obtain fundamental measurements.
For voltage Phase A overvoltage detection, the current and voltage phasors are assumed to
be: NOTE: The module is assumed to
have the name:
"SEL_prCTPT_1_ECAT".
Current Phase A: 4 A ∠ 0
Current Phase B: 4 A ∠ -120
Current Phase C: 4 A ∠ 120
Voltage Phase A: 70 V ∠ 0
Voltage Phase B: 67 V ∠ -120
Voltage Phase C: 67 V ∠ 120
A loss-of-potential condition can be triggered by using the following values and the LED
1 will turn off:
Current Phase A: 4 A ∠ 0
Current Phase B: 4 A ∠ -120
Current Phase C: 4 A ∠ 120
Voltage Phase A: 70 V ∠ 0
Voltage Phase B: 0 V ∠ -120
Voltage Phase C: 67 V ∠ 120
Solution
The user can create a program shown in Code Snippet 27.3:
Initalized : BOOL;
END_VAR
PhaseAOverVoltage.ThresholdVoltage := 69;
END_IF
LossOfPotential.FundQok := SEL_prCTPT_1_ECAT.QUALITY_FUND;
LossOfPotential.FundTimeStamp := SEL_prCTPT_1_ECAT.TIMESTAMP_FUND;
LossOfPotential.AmpsNegSeq := SEL_prCTPT_1_ECAT.I2_FUND;
LossOfPotential.AmpsPosSeq := SEL_prCTPT_1_ECAT.I1_FUND;
LossOfPotential.AmpsZeroSeq := SEL_prCTPT_1_ECAT.I0_FUND;
LossOfPotential.AmpsPhaseA := SEL_prCTPT_1_ECAT.IA_FUND;
LossOfPotential.AmpsPhaseB := SEL_prCTPT_1_ECAT.IB_FUND;
LossOfPotential.AmpsPhaseC := SEL_prCTPT_1_ECAT.IC_FUND;
LossOfPotential.VoltsPosSeq := SEL_prCTPT_1_ECAT.V1_FUND;
LossOfPotential.VoltsZeroSeq := SEL_prCTPT_1_ECAT.V0_FUND;
LossOfPotential();
IF PhaseAOverVoltage.OverVoltage THEN
SystemTags.Aux_LED_01.operSet.ctlVal := TRUE;
SystemTags.Aux_LED_01.operClear.ctlVal := FALSE;
ELSE
SystemTags.Aux_LED_01.operSet.ctlVal := FALSE;
SystemTags.Aux_LED_01.operClear.ctlVal := TRUE;
END_IF
Assumptions
This example assumes the user has a SEL-2245-42 AC Protection Module configured in
the RTAC project to obtain rms measurements.
The AmbientTemperature pin values can be forced by the user to observe functionality. Val-
ues greater than 20.3℃ will cause a thermal overload condition when the MeasuredCurrent NOTE: The module is assumed to
have the name:
is set to 100 A. "SEL_prCTPT_1_ECAT".
Solution
The user can create a program shown in Code Snippet 27.4:
ThermalOverload.AmbientTemperature := AmbientTemp;
ThermalOverload.MeasuredCurrent := SEL_prCTPT_1_ECAT.IA_RMS;
ThermalOverload();
IF ThermalOverload.Overloaded THEN
SystemTags.Aux_LED_01.operSet.ctlVal := TRUE;
SystemTags.Aux_LED_01.operClear.ctlVal := FALSE;
ELSE
SystemTags.Aux_LED_01.operSet.ctlVal := FALSE;
SystemTags.Aux_LED_01.operClear.ctlVal := TRUE;
END_IF
Queue
Introduction
The purpose of this library is to implement the data structure queue, and a double-ended
queue (a deque).
Queues
A queue is a fundamental data structure in computer science, and is implemented within
this library as an object.
The term “queue” is often used interchangeably with the term “First-In-First-Out” (FIFO),
which is a more descriptive name. The queue is often used as a buffer, allowing information
to be queued up to be processed in the same order that it was received in, but at a different
rate. This library defines the front of a queue as the oldest element pushed into the queue
and the back of the queue is the newest element pushed into the queue.
This is easily visualized and remembered by using the common image of customers stand-
ing in a line, also known as a queue. The customer that has been in line the longest is at
the front of the queue, and people awaiting service are added to the back of the queue.
All queues in this library assume that all elements within the queue are the same size.
Special Considerations
Classes in this library have memory allocated inside them. As such, they should only be
created in environments of permanent scope (e.g., Programs, Global Variable Lists, or
VAR_STAT sections).
Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.
// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_QueueObject"
myQueueObject := otherQueueObject;
// This is fine
someVariable := myQueueObject.value;
// As is this
pt_myQueueObject := ADR(myQueueObject);
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_DequeType
This enumeration is used for specifying the desired type of deque to the fun_NewTypeDeque()
function.
Enumeration Description
Functions
fun_NewDeque (Function)
This function creates a new class_BaseDeque and returns a pointer to the newly created
deque. The returned POINTER TO BYTE must be cast to the correct type before it is
used. A deque created with this function must be destroyed with fun_DeleteDeque()
when it is no longer needed.
Inputs
Name IEC 61131 Type Description
elementSize UDINT The size of each element in the deque.
Return Value
IEC 61131 Type Description
POINTER TO BYTE Pointer to the newly created deque. This pointer is null if the deque could
not be created.
Processing
ä Creates a new deque with the specified elementSize and returns a pointer to the newly
created deque.
ä Returns a null pointer if the deque could not be created.
fun_NewTypeDeque (Function)
This function creates a new deque of the type specified and returns a pointer to the newly
created deque. The returned POINTER TO BYTE must be cast to the correct type before it
is used. A deque created with this function must be destroyed with fun_DeleteDeque()
when it is no longer needed.
Inputs
Name IEC 61131 Type Description
dequeType enum_DynamicDequeType The desired type of deque.
Return Value
IEC 61131 Type Description
POINTER TO BYTE Pointer to the newly created deque. This pointer is null if the deque could
not be created.
Processing
ä Creates a new deque of the type specified and returns a pointer to the newly created
deque.
ä Returns a null pointer if the deque could not be created.
fun_DeleteDeque (Function)
This function deletes a deque created with fun_NewDeque() or fun_NewTypeDeque().
After deletion, any pointers to the deleted deque are no longer valid.
Inputs
Name IEC 61131 Type Description
deque I_Deque The deque to delete.
Return Value
IEC 61131 Type Description
BOOL TRUE if deque is successfully deleted. False if an error occurs.
Interfaces
This library provides the following interface.
I_Queue (Interface)
This interface is implemented by any class that provides a queue data type.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Clear (Method)
Deallocates all memory associated with the queue. Call this method only if the queue is
instantiated with limited scope (i.e., if it is instantiated as a local variable of a function or
method).
Return Value
IEC 61131 Type Description
BOOL TRUE if the queue successfully deallocates its internal memory. FALSE
if an error occurs.
EraseFront (Method)
This method deletes the specified number of elements from the front of the queue.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the front of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the queue.
Processing
ä Removes as many as numToErase elements from the front of the queue.
ä If the Size of the queue is less than numToErase, only Size elements are removed
from the queue.
Front (Method)
This method copies the specified number of elements from the front of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the front of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the front of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
PopFront (Method)
This method copies the specified number of elements from the front of the queue to the
provided pointer location and deletes them from the queue.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the front of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the queue.
Zero if the queue was not modified.
Processing
ä Copies as many as numToPop elements from the front of the queue to pt_destination.
ä If the Size of the queue is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the queue.
ä If pt_destination is invalid or the elements cannot be copied, the queue is not modi-
fied and zero is returned.
PushBack (Method)
This method copies elements from the specified pointer location and pushes them onto the
back of the queue.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the queue. Zero if an
error occurred and the queue was not modified.
Processing
ä If the queue is not large enough to contain the new elements, additional memory is
allocated to enlarge the queue.
ä Copies the elements from pt_source and pushes them onto the back of the queue.
ä If pt_source is invalid or numToPush is zero, the queue is not modified and zero is
returned.
Recycle (Method)
This method removes all elements from the queue without modifying the memory allocated
to the queue.
Return Value
IEC 61131 Type Description
BOOL TRUE if the queue successfully removes all elements. FALSE if an error
occurs.
Processing
All elements are removed from the queue.
ä After recycling, the Size of the queue is zero.
ä The MaxSize is unchanged after a call to Recycle().
ä This method neither allocates nor frees any memory.
Classes
class_Deque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque can handle objects of arbitrary size, so long as the number of bytes
required for each element is the same.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
elementSize UDINT The number of bytes required for each element that this
deque can hold. If zero, defaults to one.
numElements UDINT The number of elements to allocate initially. If zero, g_-
p_DefaultQueueSize is used.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_ByteDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type BYTE.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
BackByte (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontByte (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackByte (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontByte (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackByte (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element BYTE The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontByte (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element BYTE The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_DwordDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type DWORD.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
BackDword (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontDword (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackDword (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontDword (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackDword (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element DWORD The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontDword (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element DWORD The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_LwordDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type DWORD.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
BackLword (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontLword (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackLword (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontLword (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackLword (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element LWORD The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontLword (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element LWORD The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_LrealDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type LREAL.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
BackLreal (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontLreal (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackLreal (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontLreal (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackLreal (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element LREAL The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontLreal (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element LREAL The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_PointerDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type POINTER TO ANY.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
BackPointer (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontPointer (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackPointer (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontPointer (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackPointer (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element POINTER TO BYTE The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontPointer (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element POINTER TO BYTE The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_RealDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type REAL.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
BackReal (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontReal (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackReal (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontReal (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackReal (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element REAL The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontReal (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element REAL The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
class_WordDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type WORD.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue
Initialization Inputs
Name IEC 61131 Type Description
numElements UDINT The number of elements to allocate initially. If zero, use
g_p_DefaultQueueSize.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.
Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.
BackWord (Method)
This method provides the element at the back of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.
Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.
Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.
FrontWord (Method)
This method provides the element at the front of the deque without modifying the deque.
Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the front of the deque. If the return
value is false, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.
PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.
Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.
PopBackWord (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PopFrontWord (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.
Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.
PushBackWord (Method)
This method appends a copy of the provided element to the back of the deque.
Inputs
Name IEC 61131 Type Description
element WORD The element to append to the back of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.
Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.
Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.
PushFrontWord (Method)
This method appends a copy of the provided element to the front of the deque.
Inputs
Name IEC 61131 Type Description
element WORD The element to append to the front of the deque.
Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.
Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.
Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.
Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.
Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.
Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.
Resize2 (Method)
This method provides identical functionality to the Resize method but additionally updates
the Size property to reflect the requested newMaxSize.
Processing
ä The deque Size property will be updated to reflect the new maximum size declared by
newMaxSize. Note: This does not initalize the associated memory space. Push
or pop operations should be avoided until the memory space is initialized by the
user.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3505
â R134 firmware
Back_TYPE_
The posted time is the average execution time of 100 calls when the Back_TYPE_() method
copies one element from a deque containing 100 elements.
Clear
The posted time is the average execution time of 100 calls when clearing a deque containing
100 elements.
EraseBack - 1 Element
The posted time is the average execution time of 100 calls when the EraseBack method
removes one element from a deque containing 100 elements.
EraseFront - 1 Element
The posted time is the average execution time of 100 calls when the EraseFront() method
removes one element from a deque containing 100 elements.
Front_TYPE_
The posted time is the average execution time of 100 calls when the Front_TYPE_()
method copies one element from a deque containing 100 elements.
PopBack_TYPE_
The posted time is the average execution time of 100 calls when popping one element from
a deque containing 100 elements.
PopFront_TYPE_
The posted time is the average execution time of 100 calls when popping one element from
a deque containing 100 elements.
PushBack_TYPE_
The posted time is the average execution time of 100 calls when pushing an element onto
a deque without causing a resize.
PushFront_TYPE_
The posted time is the average execution time of 100 calls when pushing an element onto
a deque without causing a resize.
Recycle
The posted time is the average execution time of 100 calls when recycling a deque contain-
ing 100 elements.
Resize - Enlarging
The posted time is the average execution time of 100 calls when resizing a full deque from
32 elements to 64 elements.
Resize - Shrinking
The posted time is the average execution time of 100 calls when resizing a full deque from
64 elements to 32 elements.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3555 SEL-3530 SEL-3505
Back - Byte 1 7 53
Back - Dword 1 5 16
Back - LReal 1 6 17
Back - Lword 1 4 23
Back - Pointer 1 5 26
Back - Real 1 6 28
Back - Word 1 6 19
Back 100 - Byte 1 3 16
Back 100 - Dword 1 3 8
Back 100 - LReal 1 6 10
Back 100 - Lword 1 4 14
Back 100 - Pointer 1 3 13
Back 100 - Real 1 5 14
Back 100 - Word 1 3 9
Clear - Byte 3 24 57
Clear - Dword 2 15 69
Clear - LReal 2 33 55
Clear - Lword 2 15 61
Clear - Pointer 2 16 61
Clear - Real 2 24 60
Clear - Word 2 17 58
EraseBack 1 - Byte 1 2 3
EraseBack 1 - Dword 1 2 3
EraseBack 1 - LReal 1 2 3
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Objective
This example comprises the following steps:
Step 1. Add a series of UINT values to a UINT deque; the first as a single value, and
the second from an array of values.
Step 2. Remove one value from the front.
Sequence of Operations
The operations that make up the solution are outlined here in detail. After each operation,
the expected state of the deque is shown. The notation used in this example assumes the
front of the deque is on the left and the back is on the right.
1. The deque begins empty
F ront [ ] Back
3. An array of values, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], is pushed onto the back of the deque.
4. Five values are popped off of the front of the deque and into an array.
6. An array with four values, [11, 12, 13, 14], are then pushed onto the front.
7. Six values are then popped off the back into an array.
The resulting array that was popped off contains [14, 5, 6, 7, 8, 9].
8. The values 11, 12, and 13 are then obtained by popping the remaining values off
the front of the deque one at a time, leaving it empty again.
F ront [ ] Back
Solution
The implementation of this example is shown in Code Snippet 28.1.
(* Arrays to push*)
Step3ArrayToPush : ARRAY[1..c_NumPushStep3] OF UINT :=
[1,2,3,4,5,6,7,8,9,10];
Step6ArrayToPush : ARRAY[1..c_NumPushStep6] OF UINT := [11,12,13,14];
(* Results *)
Step4ArrayPopped : ARRAY[1..c_NumPopStep4] OF UINT; // Expect :
[0,1,2,3,4]
Step5Popped : UINT; // Expect : 10
Step7ArrayPopped : ARRAY[1..c_NumPopStep7] OF UINT; // Expect :
[14,5,6,7,8,9]
Step8val1, Step8val2, Step8val3 : UINT; // Expect: 11, 12, 13
END_VAR
Objective
This example comprises the following steps:
Step 1. Dynamically generate a deque of type REAL
Step 2. Push values to the front of the deque
Step 3. Erase a group of five values from the back
Step 4. Check size of deque after erasing
Step 5. Store remaining values in an array
Step 6. Resize the deque to hold two values
Step 7. Check size of deque after resizing
Step 8. Store remaining values in an array
Step 9. Wait 10 seconds
Sequence of Operations
The operations that make up the solution are outlined here in detail. After each operation,
the expected state of the deque is shown. The notation used in this example assumes the
front of the deque is on the left and the back is on the right.
1. A new empty deque is generated.
F ront [ ] Back
2. An array of values, [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], is pushed onto the front of the deque.
Solution
The implementation of this example is shown in Code Snippet 28.2.
Quicksort
Introduction
This library implements the Quicksort algorithm for sorting arrays of objects. Due to the
strongly typed nature of IEC 61131, the sorting is provided with multiple functions, one
for each of the following datatypes:
ä USINT
ä SINT
ä UINT
ä INT
ä UDINT
ä DINT
ä ULINT
ä LINT
ä REAL
ä LREAL
This library also allows the sorting of arbitrary objects implementing the I_Comparable
interface. All functions sort in ascending order.
Functions
The following functions are provided by this library.
fun_SortUSINT (Function)
This function takes a pointer to an array of USINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO USINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortSINT (Function)
This function takes a pointer to an array of SINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO SINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortUINT (Function)
This function takes a pointer to an array of UINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO UINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortINT (Function)
This function takes a pointer to an array of INTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO INT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortUDINT (Function)
This function takes a pointer to an array of UDINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO UDINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortDINT (Function)
This function takes a pointer to an array of DINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO DINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortULINT (Function)
This function takes a pointer to an array of ULINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO ULINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortLINT (Function)
This function takes a pointer to an array of LINTs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO LINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortREAL (Function)
This function takes a pointer to an array of REALs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO REAL Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortLREAL (Function)
This function takes a pointer to an array of LREALs and sorts the array in-place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO LREAL Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.
fun_SortI_Comparable (Function)
This function takes a pointer to an array of I_Comparable objects and sorts the array in-
place by value.
Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO I_Comparable Pointer to the array to sort.
arraySize UDINT The number of elements in the array.
Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.
Processing
This function sorts the array in-place using the Quicksort algorithm.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä The function returns false and does not attempt to sort the array if any members of
the array pointed to by arrayPointer are invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, the array is
sorted using an in-place Quicksort algorithm and true is returned.
Interfaces
This library provides the following interfaces.
I_Comparable (Interface)
This interface is implemented by any class needing to be sortable. Any libraries needing
to sort arbitrary objects can create a class that implements this interface.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
CompareTo (Method)
This method compares this object to another object of the same type. If the compare object
is not of the same class, exceptions will occur.
Inputs
Name IEC 61131 Type Description
compare I_Comparable The object to compare.
Return Value
IEC 61131 Type Description
INT Returns a signed integer representing the sorting order. A negative value
means this object goes before the compare object. Zero means this object
is equivalent to the compare object. A positive value means this object
goes after the compare object.
Processing
Compares this object to another object of the same type.
ä Returns a negative value if this object goes before the compare object.
ä Returns zero if this object is equivalent to the compare object.
ä Returns a positive value if this object goes after the compare object.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R134 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
DATATYPE InOrderSort
The average time for completion of the sort method when all data are presorted.
DATATYPE ReverseOrderSort
The average time for completion of the sort method when all data are in reverse order.
DATATYPE RandomOrderSort
The average time for completion of the sort method when data are in random order.
Benchmark Results
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
Code Snippet 29.1 prg_SortInt
PROGRAM prg_SortInt
VAR
intArray : ARRAY [1..5] OF INT;
END_VAR
RecordingTriggers
Introduction
This library provides various function blocks to detect specific conditions in analog and
digital signals to initiate the capture of data in oscillography recording devices, such as
RTAC Recording Groups or SEL-2245 analog input modules.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_DigitalTriggerModes
This enumeration defines the operating mode of the fb_DigitalTrigger function block.
Enumeration Description
LEVEL Level mode
RISING_EDGE Rising-Edge mode
FALLING_EDGE Falling-Edge mode
RISING_FALLING_EDGE Rising/Falling-Edge mode
Function Blocks
fb_HighThreshold (Function Block)
This function block monitors the value of an analog signal and compares it against a prede-
fined threshold value to detect if the signal is above the threshold. This function block has
two operating modes. The operating mode is selected by setting the initialization argument
risingEdgeMode to TRUE or FALSE when the function block is instantiated.
1. Level mode: The output of the function block asserts when the value of the analog
signal first becomes greater than or equal to the threshold value. The output of the
function block remains asserted until the value of the signal becomes less than or
equal to the threshold value minus the hysteresis value.
2. Rising-Edge mode: The output of the function block asserts for one RTAC process-
ing interval when the value of the analog signal first becomes greater than or equal
to the threshold value.
Initialization Inputs
Name IEC 61131 Type Description
risingEdgeMode BOOL Defines the operating mode of the function block.
When TRUE, the function block is in Rising-Edge
mode. When FALSE, the function block is in Level
mode.
Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal REAL Analog signal to observe.
Threshold REAL Minimum value of the analog signal required to assert the
trigger output of the function block.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL High-threshold condition is detected.
Processing
ä Compare InSignal to Threshold.
ä If the function block was initialized in Rising-Edge mode(risingEdgeMode = TRUE):
â If InSignal becomes greater than or equal to Threshold, then assert TriggerOut
for one RTAC processing interval.
ä If the function block was initialized in Level mode risingEdgeMode = FALSE):
â If InSignal becomes greater than or equal to Threshold, then assert TriggerOut.
â If TriggerOut is asserted AND InSignal becomes less than or equal to (Thresh-
old-Hysteresis), then deassert TriggerOut.
Initialization Inputs
Name IEC 61131 Type Description
risingEdgeMode BOOL Defines the operating mode of the function block.
When TRUE, the function block is in Rising-Edge
mode. When FALSE, the function block is in Level
mode.
Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal REAL Analog signal to observe.
Threshold REAL Maximum value of the analog signal required to assert the
trigger output of the function block.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL Low threshold condition is detected.
Processing
ä Compare InSignal to Threshold.
ä If the function block was initialized in Rising-Edge mode(risingEdgeMode = TRUE):
â If InSignal becomes less than or equal to Threshold, then assert TriggerOut for
one RTAC processing interval.
ä If the function block was initialized in Level mode risingEdgeMode = FALSE):
â If InSignal becomes less than or equal to Threshold, then assert TriggerOut.
â If TriggerOut is asserted AND InSignal becomes greater than or equal to (Thresh-
old+Hysteresis), then deassert TriggerOut.
Initialization Inputs
Name IEC 61131 Type Description
risingEdgeMode BOOL Defines the operating mode of the function block.
When TRUE, the function block is in Rising-Edge
mode. When FALSE, the function block is in Level
mode.
Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal REAL Analog signal to observe.
RateOfChange REAL Minimum change of the analog signal over a Sampling-
Period time required to set the trigger output of the
function block.
SamplingPeriod TIME Time period at which the analog signal is sampled to
detect a rate-of-change condition. This input should be
set to a multiple of the RTAC processing scan time on
which this object is instantiated.
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL A rate-of-change condition is detected.
Sample_DN BOOL This output asserts for one RTAC processing cycle when
the analog signal is sampled and the rate-of-change calcu-
lation logic is executed.
Processing
The following logic is performed every SamplingPeriod time interval k):
ä Calculate the analog input change:
Initialization Inputs
Name IEC 61131 Type Description
OpMode enum_DigitalTriggerModes Defines the operating mode of the function block.
Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal BOOL Digital signal to observe.
Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL Trigger condition is detected.
Processing
ä If the function block was initialized in Rising-Edge mode (OpMode = RISING_-
EDGE):
â If InSignal changes from FALSE to TRUE, then assert TriggerOut for one
RTAC processing interval.
ä If the function block was initialized in Falling-Edge mode OpMode = FALLING_-
EDGE):
â If InSignal changes from TRUE to FALSE, then assert TriggerOut for one
RTAC processing interval.
ä If the function block was initialized in Rising-/Falling-Edge mode OpMode = RIS-
ING_FALLING_EDGE):
â If a change of state is detected on InSignal, then assert TriggerOut for one
RTAC processing interval.
ä If the function block was initialized in Level mode (OpMode = LEVEL):
â If InSignal asserts, then TriggerOut is asserted.
â If InSignal deasserts, then TriggerOut is deasserted.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R139-V0 firmware
ä SEL-3530
â R139-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R139-V0 firmware
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fb_HighThreshold 1 1 1
fb_LowThreshold 2 1 1
fb_RateOfChange 2 1 1
fb_DigitalTriggers 1 1 1
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project.
Solution
To assert Output OUT201 when the analog signal is greater than or equal to 75, the user
can create a program as shown in Code Snippet 30.1.
HighTrigger_pulse(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);
Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project, and a global variable named Alarm exists in the project.
Solution
To assert the Alarm variable when the analog signal is greater than or equal to 100, and
deassert the variable when the analog signal drops to 95 or below, the user can create a
program as shown in Code Snippet 30.2.
HighTrigger_level(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);
Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project.
Solution
To assert Output OUT201 when the analog signal is less than or equal to 50, the user can
create a program as shown in Code Snippet 30.3.
LowTrigger_pulse(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);
Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project, and a global variable named Alarm exists in the project.
Solution
To assert the Alarm variable when the analog signal is less than or equal to 25, and deassert
the variable when the analog signal becomes greater than or equal to 28, the user can create
a program as shown in Code Snippet 30.4.
fb_RateOfChange
Objective
A user is using a Modbus client on the RTAC to read a temperature value from the field. The
user wants to assert the RTAC output OUT201 when the rate-of-change of the temperature
exceeds 10℃ per minute.
Assumptions
This example assumes that there is a Modbus client in the RTAC project, and it is configured
to read a temperature, in Celsius, from a measurement device installed on the field. The
name of the Modbus client in the project is myModbus_MODBUS and the temperature of
interest is mapped in the Modbus Holding Register Address 0.
Solution
To assert Output OUT201 when the rate-of-change of the temperature is greater than or
equal to 10℃ per minute, the user can create a program as shown in Code Snippet 30.5:
TemperatureRoC(InSignal := myModbus_MODBUS.HREG_00000.Status.stVal);
//Assert OUT201 if the function block output has triggered:
IF TemperatureRoC.TriggerOut THEN
SystemTags.OUT201.operSet.ctlVal := TRUE;
SystemTags.OUT201.operClear.ctlVal := FALSE;
ELSE
SystemTags.OUT201.operSet.ctlVal := FALSE;
SystemTags.OUT201.operClear.ctlVal := TRUE;
END_IF
fb_DigitalTrigger
Objective
A user is monitoring the status of a circuit breaker using a digital input channel in the
RTAC. The user wants to generate an oscillography event file when the circuit breaker
trips or closes (rising edge and falling edge).
Assumptions
This example assumes the following:
ä The circuit breaker is wired to the Digital Input IN201.
ä The oscillography is generated by using an RTAC recording group. The name of the
recording group in the RTAC project is recGroup.
Solution
To trigger the recording group when a change of state occurs on Input IN201 , the user can
create a program as shown in Code Snippet 30.6.
BreakerStatusChange(InSignal := SystemTags.IN201.stVal);
ReportGenerator
Introduction
The ReportGenerator library is intended for use by extensions that support the extension
text editor object but can be broadly applied as an advanced file writer/manager.
The term report, as used in this document, refers to the contents of a Queue.class_Byt-
eDeque instance at the time of calling the MakeReport() method plus ASCII 16#20(New-
line) characters and report management metadata as deemed necessary by the configured
ReportMethod input.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := myReportGeneratorObject.value;
// As is this
pt_myReportGeneratorObject := ADR(myReportGeneratorObject);
ä All file read operations are done completely into RAM. This means that the reading
of large files that exceed the available RAM will not work as expected.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_ReportMethods
Enumeration Description
SINGLE_REPORT_FILES Each new report is placed in a dedicated file. The
file name contains the user settable fileName input
followed by a timestamp representing the RTAC
system time when the report was triggered.
MULTIPLE_REPORT_FILES New triggered reports are appended to the same
file. When the number of reports added to the file
equals the user-configured MaxReports setting, a
new file is created to contain the new report. File
names contain a timestamp that reflects the RTAC
system time when the oldest report in the file
was triggered. This timestamp has a resolution in
seconds.
enum_FileType
Enumeration Description
TXT File names are given a ".txt" extension.
HTML File names are given a ".html" extension.
CSV File names are given a ".csv" extension.
Classes
This library provides the following classes as extensions of the IEC-61131 function block.
class_ReportGenerator (Class)
This class facilitates the writing and management of user-defined reports within one or
more files.
Outputs
Name IEC 61131 Type Description
Initialized BOOL TRUE if the class instance is initialized and ready to ac-
cept new report requests via the MakeReport() method.
Busy BOOL TRUE if the class instance is performing file manage-
ment or file write activities.
Error BOOL TRUE if an internal processing error has occurred
ErrorMessage STRING(255) A text description of the last error encountered by this
class instance.
Initialize (Method)
Call this method to assign the inputs and in/out variable for this class instance. This method
must be called whenever new project settings are sent to the RTAC or power to the RTAC
is cycled.
Inputs
Name IEC 61131 Type Description
Directory STRING(100) The directory in which to store and manage re-
port files. 100 characters max. / delimits the
folder path. It cannot contain any file path ma-
nipulation variables (\\, /./, /../).
FileName STRING(100) The name of the report, 100 characters max
FileType enum_FileType TXT, HTML, or CSV. Defines the file name ex-
tension. Does not affect formatting of report con-
tent.
ReportMethod enum_ReportMethods Method of report vs file creation.
MaxReports UINT For ReportMethod other than an SINGLE_-
REPORT_FILES MaxReports is the maximum
number of reports that can be contained within a
single file.
LogRuntimeErrors BOOL If TRUE, runtime errors are logged in the RTAC
SOE viewer.
InstanceName STRING(100) Context identification string for use with SOE
logging.
Note: FileName and Directory settings may contain all printable ASCII characters
between 16#20(Space) and 16#7E(tilde) except for ", ’, :, <, %, >, ?, \, and |.
The specified directory should already exist prior to calling Initialize(). If not, the
outputs may reflect an error condition until the first report is created.
Inputs/Outputs
Name IEC 61131 Type Description
Report Queue.class_ByteDeque A class_ByteDeque instance that will contain the full con-
tent of the report. It is the users’ responsibility to populate
the queue prior to calling the MakeReport() method.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if initialization completes without error.
Processing
ä If the Initialized class output is TRUE:
â Returns FALSE.
ä If the Initialized output is FALSE:
â Maps input variables to internal class variables.
â Assigns internal reference to manage the operation of the Report class_ByteD-
eque instance.
â Validates FileType, ReportMethod, and MaxReports inputs against specified
bounds.
â Returns TRUE if inputs are valid.
â Sets Initialized class output to the return value.
MakeReport (Method)
Call this method to generate a new report.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors encountered.
Processing
ä If the Busy output is FALSE:
â The current RTAC system time is saved and may subsequently be appended to
a new file name depending upon the Report Method and state of the active file.
See description of enum_ReportMethods and the processing section of the Run
method for more information.
â Empties the contents of the Report class_ByteDeque instance into a local queue.
ä If the Busy output is TRUE:
â Returns FALSE.
Run (Method)
Call this method every task cycle to allow for the execution of asynchronous file operations.
The term active file is used here to describe a file in the RTAC file system that the next
triggered report is written to.
Processing - General
ä No work is done until the Initialized output is TRUE.
ä If Initialized is TRUE, work is done, regardless of the state of Error.
SELEthernetController
Introduction
The SELEthernetController library provides the ability to stream data through TCP and
UDP ports. It provides client and server functionality for both TCP and UDP connections.
Various methods are used to initiate new read or write operations.
Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.
// This is fine
someVariable := mySocketObject.value;
// As is this
pt_mySocketObject := ADR(mySocketObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_SocketState
Enumeration Description
LISTENING The server socket is ready to receive communication requests.
OPEN The socket is ready to send and receive UDP data.
CONNECTED The socket has an active client server TCP session.
CLOSED The socket will no longer allow communication.
ERROR The socket has encountered an error and needs reconfiguration.
Aliases
This section lists aliases that this library defines.
SESSION_HANDLE
Alias IEC 61131 Type
SESSION_HANDLE POINTER TO BYTE
Functions
This library provides the following functions.
fun_StringToInaddr
Convert basic strings to the INADDR type this library uses. Strings provided to this func-
tion must be in the format xxx.xxx.xxx.xxx, where xxx is a number between 0 and 255.
Inputs
Name IEC 61131 Type Description
ipAddrString STRING(15) The string to convert to an INADDR.
Outputs
Name IEC 61131 Type Description
ipAddr INADDR The converted INADDR.
Return Value
IEC 61131 Type Description
BOOL TRUE if the string could be converted.
Processing
The fun_StringToInaddr() function does the following:
ä Parses the provided string into four bytes.
ä Outputs those bytes ordered in an INADDR.
ä Returns false and outputs an IP address of 0.0.0.0 if the string could not be converted.
fun_InaddrToString
Converts an INADDR to a string in the format xxx.xxx.xxx.xxx, where xxx is a number
between 0 and 255.
Inputs
Name IEC 61131 Type Description
ipAddr INADDR The INADDR to convert to a string.
Return Value
IEC 61131 Type Description
STRING(15) The resulting IP address as a string.
Processing
The fun_InaddrToString() function does the following:
ä Parses the provided INADDR by its four bytes.
ä Returns a string in the format xxx.xxx.xxx.xxx, where xxx is a number between 0 and
255.
Classes
Classes are a particular implementation of a Function Block(FB). They provide methods
and properties, which a normal FB does not provide.
class_UdpSocket (Class)
This class provides a socket for sending and receiving using through use of the UDP pro-
tocol. Once enabled, the class creates, binds, sends, and receives to the configured ports.
Initialization Inputs
Name IEC 61131 Type Description
maxPacketSize DINT The maximum packet size, in bytes, to obtain through
use of this socket. A value of zero or less results in the
class imposing no limit on inbound packet size.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
bootstrap_SetLocalIP (Method)
Perform a one-time setting of the local IP address and port this socket will use.
Inputs
Name IEC 61131 Type Description
localPort UINT The port number through which this socket receives and
sends data through.
localIPAddr INADDR The IP address on the local box this socket uses. Use
0.0.0.0 to allow all local IP addresses.
Return Value
IEC 61131 Type Description
BOOL TRUE if the IP address and port number are set.
Processing
The bootstrap_SetLocalIP() method does the following:
ä Immediately returns FALSE if the port and IP address are already set.
ä Sets the IP address and port on the local machine for use by this socket.
Open (Method)
Configure the class_UdpSocket to allow communication.
Return Value
IEC 61131 Type Description
BOOL TRUE if the port is ready to send data.
Processing
The Open() method does the following:
ä Opens the port for sending and receiving communication.
ä Returns FALSE if the socket was unable to bind.
Close (Method)
Unconfigure the class_UdpSocket to disable communication.
Processing
The Close() method does the following:
ä Discards any unread messages.
ä Makes the socket unable to send or receive data.
ä Forces reopening of the socket before processing additional communication.
SendData (Method)
Send a block of data to the socket.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The data to send.
numBytes DINT The quantity of data in bytes.
destIPAddr INADDR The IP address to which data are sent.
destPort UINT The destination port to which data are sent.
Return Value
IEC 61131 Type Description
DINT The number of bytes sent.
Processing
The SendData() method does the following:
ä Sends data if Open() has been successfully called.
ä Validates access to the pointer provided.
ä Limits numBytes to a positive number.
ä Sends numBytes of data, starting at pt_data, to the socket.
ä Returns the number of bytes successfully sent.
SendQueuedData(Method)
Send a block of data to the socket from the front of a queue.
Inputs
Name IEC 61131 Type Description
destIPAddr INADDR The IP address to which data are sent.
destPort UINT The destination port to which data are sent.
Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The queued data to send.
Return Value
IEC 61131 Type Description
DINT The number of bytes sent.
Processing
The SendQueuedData() method does the following:
ä Sends data if Open() has been successfully called.
ä Sends all data, starting at the front of queue, to the socket.
ä Returns the number of bytes successfully sent.
ä Removes bytes sent from the front of queue.
ReceiveFrom (Method)
Overwrites data with the first packet available to the socket.
Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector The container to which the data are written.
Outputs
Name IEC 61131 Type Description
fromIpAddr INADDR The IP address from which the data came.
fromPort UINT The port from which the data came.
Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.
Processing
The ReceiveFrom() method does the following:
ä Does nothing if the socket is not open or a new packet is not available.
ä Deletes any data found in data.
ä Places the first packet—as many as maxPacketSize bytes—from this socket in data.
ä Returns the number of bytes loaded into data.
ReceiveToQueueFrom (Method)
Overwrites data with the first packet available to the socket.
Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteDeque The container to which the data are written.
Outputs
Name IEC 61131 Type Description
fromIpAddr INADDR The IP address from which the data came.
fromPort UINT The port from which the data came.
Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.
Processing
The ReceiveToQueueFrom() method does the following:
ä Does nothing if the socket is not open or a new packet is not available.
ä Deletes any data found in data.
ä Places the first packet—as many as maxPacketSize bytes—from this socket in data.
ä Returns the number of bytes loaded into data.
class_TcpClient (Class)
This class provides a client socket for the TCP protocol. Once enabled, the class creates,
binds, and sends to the configured port. Because TCP is session-based communication, the
client should close the session upon completion of the communication to conserve server
resources.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
bootstrap_SetLocalIP (Method)
Perform a one-time setting of the local IP address and port this socket will use.
Inputs
Name IEC 61131 Type Description
localPort UINT The port number through which this socket receives and
sends data. If this value is zero then the OS will choose a
random outgoing port.
localIPAddr INADDR The IP address on the local box this socket uses. Use
0.0.0.0 to allow all local IP addresses.
Return Value
IEC 61131 Type Description
BOOL TRUE if the IP address and port number are set.
Processing
The bootstrap_SetLocalIP() method does the following:
ä Immediately returns FALSE if the port and IP address are already set.
ä Sets the IP address and port on the local machine for use by this socket.
SetIP (Method)
Set the IP address and port to be used on the next Open() request.
Inputs
Name IEC 61131 Type Description
destIPAddr INADDR The IP address to which data is sent.
destPort UINT The destination port to which data is sent.
Processing
The SetIP() method does the following:
ä Sets the IP address and port that will become the new destination the next time
Open() is called.
Open (Method)
Configure the class_TcpClient to allow communication.
Return Value
IEC 61131 Type Description
BOOL TRUE if the port is ready to send data.
Processing
The Open() method does the following:
ä Opens the port for sending and receiving communication, if SetIP() has been suc-
cessfully run.
ä Returns FALSE if the socket was unable to connect or another error was encountered.
Close (Method)
Unconfigure the class_TcpClient, to disable communication.
Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.
Processing
The Close() method does the following:
ä Discards any unread data.
ä Allows server to retain session until all data are read, if forceClose is FALSE.
ä Makes the socket unable to send data or receive replies.
ä Forces reopening of the socket before processing additional communication.
SendData (Method)
Send a block of data to the socket.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The data to send.
numBytes DINT The quantity of data in bytes.
Return Value
IEC 61131 Type Description
DINT The number of bytes sent.
Processing
The SendData() method does the following:
ä Does nothing if the socket is not open.
ä Validates access to the pointer provided.
ä Limits numBytes to a positive number.
ä Sends all provided data to the socket.
ä Returns the number of bytes successfully sent.
SendQueuedData (Method)
Send a block of data to the socket from the front of a queue.
Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The data to send.
Return Value
IEC 61131 Type Description
DINT The number of bytes sent.
Processing
The SendQueuedData() method does the following:
ä Does nothing if the socket is not open.
ä Sends all provided data, starting at the front of queue, to the socket.
ä Returns the number of bytes successfully sent.
ä Removes bytes sent from the front of queue.
ReceiveData (Method)
Appends a block of data from the socket to data.
Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.
Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector The container to which the data are written.
Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.
Processing
The ReceiveData() method does the following:
ä Does nothing if the socket is not open.
ä Requests data from the socket until there are either no more or it reaches numBytes,
whichever happens first.
ä Appends all data retrieved to data.
ä Returns the number of bytes appended.
ReceiveToQueue (Method)
Pushes a block of data from the socket to the back of queue.
Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.
Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The container to which the data are written.
Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.
Processing
The ReceiveToQueue() method does the following:
ä Does nothing if the socket is not open.
ä Requests data from the socket until there are either no more or it reaches numBytes,
whichever happens first.
ä Pushes all data retrieved to the back of queue.
ä Returns the number of bytes pushed.
class_TcpServer (Class)
This class provides a listening socket for the TCP protocol. Once enabled the class creates,
binds, and receives on the configured port.
Initialization Inputs
Name IEC 61131 Type Description
maxSessions USINT The maximum number of concurrent sessions to allow on
this socket. This will be forced to at least one.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
bootstrap_SetLocalIP (Method)
Perform a one-time setting of the local IP address and port this socket will use.
Inputs
Name IEC 61131 Type Description
localPort UINT The port number through which this socket receives and
sends data.
localIPAddr INADDR The IP address on the local box this socket uses. Use
0.0.0.0 to allow all local IP addresses.
Return Value
IEC 61131 Type Description
BOOL TRUE if the IP address and port number are set.
Processing
The bootstrap_SetLocalIP() method does the following:
ä Immediately returns FALSE if the port and IP address are already set.
ä Sets the IP address and port on the local machine used by this socket.
Open (Method)
Configure the class_TcpServer to allow for communication.
Return Value
IEC 61131 Type Description
BOOL TRUE if the port is ready to receive connections.
Processing
The Open() method does the following:
ä Configures the server to receive client connections.
ä Returns FALSE if the socket was unable to bind.
Close (Method)
Unconfigure the class_TcpServer to disable communication.
Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.
Processing
The Close() method does the following:
ä Discards any unread data.
ä Closes all open client sessions: gracefully if forceClose is FALSE.
ä Makes the socket unable to send data or receive replies.
ä Forces reconfiguration of the socket before attempting additional communication.
AcceptNextSession (Method)
Accept the next new inbound data session. This does not change the active session.
Return Value
IEC 61131 Type Description
SESSION_HANDLE The descriptor to allow further communication through this session.
Processing
The AcceptNextSession() method does the following:
SetSession (Method)
Select the session from which the class reads data from and replies to based on a previously
received identifier.
Inputs
Name IEC 61131 Type Description
sessionID SESSION_HANDLE The identifier of the desired session as returned by
AcceptNextSession().
Return Value
IEC 61131 Type Description
BOOL TRUE if the session exists.
Processing
The SetSession() method does the following:
ä Selects the read and write session tied to sessionID.
ä Sets DestIPAddr and DestPort to the values for the selected session.
ä Returns false and sets DestIPAddr to 0.0.0.0, DestPort to 0, and SessionState
to closed if sessionID does not represent an active session.
GetSessionInfo (Method)
Get the IP address and port number related to a session handle.
Inputs
Name IEC 61131 Type Description
sessionID SESSION_HANDLE The identifier of a session as returned by
AcceptNextSession().
Outputs
Name IEC 61131 Type Description
sessionIPAddr INADDR The IP address attached to sessionID.
sessionPort UINT The port number attached to sessionID.
Processing
The GetSessionInfo() method does the following:
ä Outputs the IP address and port number tied to sessionID.
ä Sets sessionIPAddr to 0.0.0.0 and sessionPort to 0, if sessionID does not represent
an active session.
CloseSession (Method)
Close the selected session and clear any pending data.
Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.
Processing
The CloseSession() method does the following:
ä Closes the active session.
ä Sets DestIPAddr and DestPort to zero.
ä Discards any unread data.
ä Allows client to retain session until all data are read, if forceClose is FALSE.
ä Decrements NumSessions.
SendData (Method)
Send a block of data to the socket.
Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The data to send.
numBytes DINT The quantity of data in bytes.
Return Value
IEC 61131 Type Description
DINT The number of bytes sent.
Processing
The SendData() method does the following:
ä Does nothing if no valid session has been selected.
ä Validates access to the pointer provided.
ä Limits numBytes to a positive number.
ä Sends all provided data to the socket.
ä Returns the number of bytes successfully sent.
SendQueuedData (Method)
Send a block of data to the socket from the front of a queue.
Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The data to send.
Return Value
IEC 61131 Type Description
DINT The number of bytes sent.
Processing
The SendQueuedData() method does the following:
ä Does nothing if the socket is not open.
ä Sends all provided data, starting at the front of the queue, to the socket.
ä Returns the number of bytes successfully sent.
ä Removes bytes sent from the front of queue.
ReceiveData (Method)
Receive a block of data from the active session.
Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.
Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector The container to which the data are written.
Return Value
IEC 61131 Type Description
DINT The number of bytes loaded into data.
Processing
The ReceiveData() method does the following:
ä Does nothing if no valid session has been selected.
ä Checks for available data in the selected session.
ä Requests data from the socket until there are no more or it reaches numBytes, whichever
happens first.
ä Appends all data retrieved to data.
ä Returns the number of bytes appended.
ReceiveToQueue (Method)
Pushes a block of data from the socket to the back of queue.
Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.
Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The container to which the data are written.
Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.
Processing
The ReceiveToQueue() method does the following:
ä Does nothing if the socket is not open.
ä Requests data from the socket until there are no more or it reaches numBytes, whichever
happens first.
ä Pushes all data retrieved to the back of queue.
ä Returns the number of bytes pushed.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware
ä SEL-3530
â R134-V0 firmware
ä SEL-3505
â R134-V0 firmware
fun_InaddrToString
The posted time is the average execution time of 100 consecutive calls for the IP address
192.168.100.100.
class_UdpSocket.Open
The posted time is the average execution time of 100 successful method calls to open a
socket.
class_UdpSocket.Close
The posted time is the average execution time of 100 successful method calls to close a
socket.
class_UdpSocket.SendData
The posted time is the average execution time of 100 consecutive calls when sending 504
bytes of data, resulting in a 512-byte total packet size.
class_UdpSocket.SendQueuedData
The posted time is the average execution time of 100 consecutive calls when sending 504
bytes of data, resulting in a 512-byte total packet size.
class_UdpSocket.ReceiveFrom
The posted time is the average execution time of 100 consecutive calls when receiving 504
bytes of data, resulting in a 512-byte total packet size.
class_UdpSocket.ReceiveToQueueFrom
The posted time is the average execution time of 100 consecutive calls when receiving 504
bytes of data, resulting in a 512-byte total packet size.
class_TcpClient.SetIP
The posted time is the average execution time of 100 consecutive calls.
class_TcpClient.Open
The posted time is the average execution time of 100 successful method calls to open a
socket.
class_TcpClient.Close
The posted time is the average execution time of 100 successful method calls to close a
socket.
class_TcpClient.SendData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.
class_TcpClient.SendQueuedData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.
class_TcpClient.ReceiveData
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.
class_TcpClient.ReceiveToQueue
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.
class_TcpServer.Open
The posted time is the average execution time of 100 successful method calls to open a
socket.
class_TcpServer.Close
The posted time is the average execution time of 100 successful method calls to close a
socket.
class_TcpServer.AcceptNextSession
The posted time is the average execution time of 100 successful method calls when there
is another session to accept.
class_TcpServer.SetSession
The posted time is the average execution time of 100 consecutive calls.
class_TcpServer.GetSessionInfo
The posted time is the average execution time of 100 consecutive calls.
class_TcpServer.CloseSession
The posted time is the average execution time of 100 successful method calls to close a
session.
class_TcpServer.SendData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.
class_TcpServer.SendQueuedData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.
class_TcpServer.ReceiveData
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.
class_TcpServer.ReceiveToQueue
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3555 SEL-3530 SEL-3505
fun_StringToInaddr 2 12 18
fun_InaddrToString 6 40 63
class_UdpSocket.Open 25 150 330
class_UdpSocket.Close 13 65 117
class_UdpSocket.SendData 26 150 380
class_UdpSocket.SendQueuedData 25 160 380
class_UdpSocket.ReceiveFrom 12 90 200
class_UdpSocket.ReceiveToQueueFrom 12 100 220
class_TcpClient.SetIP 1 1 1
class_TcpClient.Open 67 740 1200
class_TcpClient.Close 41 310 660
class_TcpClient.SendData 1 3 6
class_TcpClient.SendQueuedData 1 3 5
class_TcpClient.ReceiveData 8 80 110
class_TcpClient.ReceiveToQueue 7 80 110
class_TcpServer.Open 36 200 400
class_TcpServer.Close 20 100 140
class_TcpServer.AcceptNextSession 20 97 130
class_TcpServer.SetSession 2 4 6
class_TcpServer.GetSessionInfo 2 5 14
class_TcpServer.CloseSession 33 320 690
class_TcpServer.SendData 1 3 6
class_TcpServer.SendQueuedData 1 3 5
class_TcpServer.ReceiveData 9 80 110
class_TcpServer.ReceiveToQueue 8 75 110
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Solution
The user can create the program shown in Code Snippet 32.1 to send the byte array out
each task cycle.
// Initialization variables.
SocketInitialized : BOOL := FALSE;
LocalIP : SELEthernetController.INADDR;
DestIP : SELEthernetController.INADDR;
END_VAR
Assumptions
This solution assumes that the AcRTAC project containing the provided code includes an
Access Point opening at the desired port and that the inbound packets are not larger than
1024 bytes.
Solution
The user can create the program shown in Code Snippet 32.2 to receive one inbound data
packet each task cycle.
Assumptions
For this use case, we assume that the server doubles any data that are sent to it.
Solution
The user can create the program defined in Code Snippet 32.3 to send packets to the remote
server and receive data in reply.
PROGRAM prg_TcpClient
VAR
// Configuration Information - Uses any available interface.
LocalIPAddress : STRING(15) := '0.0.0.0';
LocalPortNumber : UINT := 2442;
DestinationIPAddress : STRING(15) := '10.10.10.10';
DestinationPortNumber : UINT := 2442;
// IP address variables.
LocalIP : SELEthernetController.INADDR;
DestIP : SELEthernetController.INADDR;
Objective
Parse the data stream of information sent from a TCP server to the TCP client on the RTAC.
Increment a counter every time the characters “SEL” are seen in the stream.
Assumptions
This example assumes that there is a server to connect to and streams data through the
connection once the connection is established. It also assumes that the library Queue has
been inserted in the project.
Solution
The deque is used as storage for information received from a TCP socket. The received data
are then searched for the string ’SEL’ and a counter is incremented every time the string is
found. As it searches for the string, data are discarded from the front of the deque. This
implementation is shown in Code Snippet 32.4
SocketInitialized := TRUE;
ELSE
// Read new data from the socket.
IF 0 <> TcpClient.ReceiveToQueue(10_000, DataIn) THEN
searching := TRUE;
WHILE searching DO
// See if the string 'SEL' appears in the front of the deque.
IF 3 = DataIn.Front(ADR(peek), 3) THEN
IF peek = TargetString THEN
(* The string 'SEL' was found, increment the counter
and erase the string from the deque. *)
Counter := Counter + 1;
DataIn.EraseFront(3);
ELSE
(* The string wasn't found, erase the first character
and continue looking. *)
DataIn.EraseFront(1);
END_IF
ELSE
Searching := FALSE;
END_IF
END_WHILE
END_IF
END_IF
Assumptions
This example assumes that Port 10024 is open through use of an Access Point configured
as Ethernet Incoming and set to receive Raw TCP. It also assumes that the client can access
that port through any intermediary firewalls. It also assumes that the library Queue has
been inserted in the project.
All error checking has been omitted to facilitate the brevity of this implementation.
There must be a structure defined to hold session related data. Code Snippet 32.5 shows an
example for this implementation.
Solution
Instantiate a class_TcpServer and associated data control objects as seen in Code Snip-
pet 32.6. Allow this program to run every task scan.
Verification
To verify that this solution is functional, start running the server on the RTAC and then
attach with a raw TCP connection on port 10024. Any instance of the word “Hello” should
be followed immediately by the echo “World.”
Characters other than new-lines should eventually echo “Usage : Hello.”
The code as written should accept as many as five concurrent sessions with more allowed
after a given session disconnects.
Peek : STRING(5);
Reply : STRING(7) := 'World$R$N';
Reply2 : STRING(15) := 'Usage : Hello$R$N';
tempSession : SESSION_HANDLE;
sendByteCount : DINT;
numSend : DINT;
i : UDINT;
END_VAR
END_IF
END_IF
END_FOR
TcpServer.SendQueuedData(Sessions[i].SendDeque);
SELRand
Introduction
The SELRand library contains a set of functions that return pseudo-random numbers for
testing and other non-cryptographic purposes. A pseudo-random number generator is a
math function that takes advantage of its previous result and large number manipulations to
perform operations that are not immediately predictable. The beginning value for each use
of the sequence is called the seed. Generally, the seed is created from some measurement
expected to have a wide range of variance. Commonly, this can be noise on a wire, small
units of time, quantity and value of user input, or some other equally unpredictable quantity.
Pseudo-random number generators do tend to be cyclic in nature, but they can have very
large cycle times and excellent distribution.
These functions are not intended to be used for implementing any security feature.
Functions
fun_Rand (Function)
This function randomly seeds itself and returns a pseudo-random number in the range of 0
inclusive to 232 exclusive.
Return Value
IEC 61131 Type Description
UDINT A random number between 0 inclusive to 232 exclusive.
Processing
At the first call of this function it randomly seeds itself. It will continually return pseudo-
random values with each use.
fun_RandRepeatable (Function)
This function always seeds itself with the same value and returns a pseudo-random number
in the range of 0 inclusive to 232 exclusive.
Return Value
IEC 61131 Type Description
UDINT A random number between 0 inclusive to 232 exclusive.
Processing
At the first call of this function it seeds itself, always with the same value. It then returns
the same sequence of pseudo-random values with each use.
fun_RandRanged (Function)
This function randomly seeds itself and returns a pseudo-random number between mini-
mum to maximum, inclusive.
Inputs
Name IEC 61131 Type Description
minimum UDINT The lower limit of the return value.
maximum UDINT The upper limit of the return value.
Return Value
IEC 61131 Type Description
UDINT A random number between minimum and maximum, inclusive.
Processing
At the first call of this function, randomly seeds itself. It then continually returns pseudo-
random values within the requested range.
fun_RandRangedRepeatable (Function)
This function always seeds itself with the same value and subsequently returns a pseudo-
random number between minimum to maximum, inclusive.
Inputs
Name IEC 61131 Type Description
minimum UDINT The lower limit of the return value.
maximum UDINT The upper limit of the return value.
Return Value
IEC 61131 Type Description
UDINT A random number between minimum and maximum, inclusive.
Processing
At the first call of function it seeds itself, always with the same value. It then continually
returns the same sequence of pseudo-random values within the requested range.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R134-V0 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 1 GB DDR ECC SDRAM
â SEL-3532 RTAC Conversion Kit
â R132-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware
fun_Rand()
The posted time is the average execution time of 100 consecutive calls.
fun_RandRanged()
The posted time is the average execution time of 100 consecutive calls with a range of 1 to
100.
fun_RandRepeatable()
The posted time is the average execution time of 100 consecutive calls.
fun_RandRangedRepeatable()
The posted time is the average execution time of 100 consecutive calls with a range of 1 to
100.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3530 SEL-3354 SEL-3555
fun_Rand() 1 1 1
fun_RandRanged() 2 1 1
fun_RandRepeatable() 1 1 1
fun_RandRangedRepeatable() 1 1 1
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that there is a user specified IEC 61131 function that is defined as
shown in Code Snippet 33.1.
END_VAR
Solution
The user can create the program in Code Snippet 33.2 to run the function 1000 times with
assorted input.
FOR i := 1 to 1000 DO
//This gives a random number from 10 to 50;
randomNum := fun_RandRanged(10, 51);
//Call the function with the random number
results[i] := fun_SomeFunction(randomNum);
END_FOR
Assumptions
This example assumes that there is a user-specified IEC 61131 function that is defined as
shown in Code Snippet 33.3
Solution
The user can create the program in Code Snippet 33.4 to run the function 1000 times with
assorted input but a set order.
FOR i := 1 TO 1000 DO
//This gives a random number;
randomNum := fun_RandRepeatable();
//Call the function with the random number
results[i] := fun_TestFunction(randomNum);
END_FOR
SELServerSimulators
Introduction
This library provides simulators for various SEL devices using the SEL Fast Meter protocol.
Since this library is primarily a testing and debugging tool, not all commands may be
supported for a particular device. There may also be variances in the responses generated
when compared to the real device.
Special Considerations
Classes in this library have memory allocated inside them. As such, they should only be
created in environments of permanent scope (e.g., Programs, Global Variable Lists, or
VAR_STAT sections).
Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.
// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_Object"
myObject := otherObject;
// This is fine
someVariable := myObject.value;
// As is this
pt_myObject := ADR(myObject);
Supported Devices
This library contains simulators for the following devices:
ä SEL-351
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_PointType
This enumeration defines all possible point types for a relay.
Enumeration Description
DIGITAL A digital (Boolean) point.
INT16 An analog point stored as a 16-bit integer value.
FLOAT32 An analog point stored as a 32-bit floating-point value.
FLOAT64 An analog point stored as a 64-bit floating-point value.
STRING80 A point stored as a string of as many as 80 characters.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Because of the significant number of values in these structures, this document does not
provide a complete list of the values.
struct_SEL351_Analog
This structure defines the analog points available on an SEL-351. For example, this struc-
ture might contain the following:
struct_SEL351_Binary
This structure defines the digital points available on an SEL-351.
struct_SEL351_Strings
This structure defines the string points available on an SEL-351.
Interfaces
I_Session
This interface defines a set of methods for interacting with a client session. A session is a
generic object that allows for reading and writing of bytes.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Close (Method)
Closes the session to the client.
Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.
ReadData (Method)
Read data from the client.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE Pointer to where the incoming data are written.
numBytes UDINT The maximum number of bytes to read.
Return Value
IEC 61131 Type Description
UDINT The number of bytes read from the session.
WriteData (Method)
Write data to the client.
Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE Pointer from where the outgoing data are read.
numBytes UDINT The number of bytes to read from pt_source and write to
the session.
Return Value
IEC 61131 Type Description
UDINT The number of bytes written to the session.
I_SessionManager
This interface defines a set of methods for an object that is able to manage multiple I_-
SessionProvider objects and their sessions.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
AddSessionProvider (Method)
Adds an I_SessionProvider to this session manager.
Inputs
Name IEC 61131 Type Description
sessionProvider I_SessionProvider The object that is providing sessions to be managed.
Return Value
IEC 61131 Type Description
BOOL TRUE if the session provider was successfully added to the session man-
ager. FALSE if an error occurred.
NextSession (Method)
Iterates over all I_Session objects referenced within the session manager and returns the
next session.
Return Value
IEC 61131 Type Description
I_Session Reference to the next session object.
Run (Method)
This method processes all session activity and must be called once per scan.
I_SessionProvider
This interface defines a set of methods for an object that can provide I_Session objects to
an I_SessionManager object.
GetSessions (Method)
Provides pointers to all I_Session objects available from this provider.
Inputs/Outputs
Name IEC 61131 Type Description
sessionVector class_PointerVector All I_Session references in the session provider are writ-
ten to this vector.
Run (Method)
This method processes all session activity and must be called once per scan.
I_SELServerPoint
This interface defines common methods for all analog and digital points.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
I_SELServerAnalogPoint
This interface defines common methods unique to analog points. This interface extends
I_SELServerPoint.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Classes
class_TelnetServer
This object implements a Telnet server. This server will create and manage an internal
object for each Telnet session. These internal objects implement I_Session and can be
accessed via the I_SessionProvider interface. This server is not intended to be used as a
generic Telnet server and should only be used within the context of this library.
This Telnet server automatically attempts to negotiate the following Telnet features:
ä Binary Transmission
ä Suppress Go Ahead
ä Echo
No other Telnet features are supported.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SessionProvider
Initialization Inputs
Name IEC 61131 Type Description
listenIP STRING(15) The local IP address for the server to listen on. Set to
0.0.0.0 to listen on all available interfaces.
listenPort UINT The local port number on which the server listens.
numSessions USINT The maximum number of Telnet sessions to support.
Destroy (Method)
This method deallocates all memory allocated by this object. This method must be called
before the object goes out of scope, otherwise a memory leak will result.
Return Value
IEC 61131 Type Description
BOOL TRUE if all memory was successfully deallocated.
class_SELServerInt16
This class defines an analog point represented as a 16-bit integer value.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerAnalogPoint
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Initialize (Method)
This method initializes the point.
Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal INT The initial stVal of the point.
scaleFactorType BYTE The scale factor type for the point.
scaleFactorOffset WORD The scale factor offset for the point.
class_SELServerFloat32
This class defines an analog point represented as a 32-bit floating point value.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerAnalogPoint
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Initialize (Method)
This method initializes the point.
Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal REAL The initial stVal of the point.
scaleFactorType BYTE The scale factor type for the point.
scaleFactorOffset WORD The scale factor offset for the point.
class_SELServerFloat64
This class defines an analog point represented as a 64-bit floating point value.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerAnalogPoint
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Initialize (Method)
This method initializes the point.
Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal LREAL The initial stVal of the point.
scaleFactorType BYTE The scale factor type for the point.
scaleFactorOffset WORD The scale factor offset for the point.
class_SELServerDigital
This class defines a digital point.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerPoint
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Initialize (Method)
This method initializes the point.
Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal INT The initial stVal of the point.
index UINT The index value for the digital point. This is used for deter-
mining the order of the Relay Word bits. The index is zero
for the MSB in Row 0, 8 for the MSB in Row 1, etc.
class_SELServerString
This class defines a point represented as a string.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerPoint
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Initialize (Method)
This method initializes the point.
Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal STRING The initial stVal of the point.
class_SEL351ServerSimulator
This class implements a server simulating an SEL-351 relay with firmware version R515.
The following ASCII commands are supported:
Some commands have optional parameters that may not be supported by the simulator.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Input
Inputs
Name IEC 61131 Type Description
Analog struct_SEL351_Analog Analog points for an SEL-351.
Binary struct_SEL351_Binary Relay Word bits for an SEL-351.
Strings struct_SEL351_String Strings for an SEL-351.
Outputs
Name IEC 61131 Type Description
ENO BOOL TRUE if the simulator is initialized and enabled. FALSE if ini-
tialization failed or an error occurred during runtime.
bootstrap_AddSessionManager
This method assigns the session manager that will manage all I_Session objects for this
simulator. This method assumes that the session manager already contains all desired ses-
sions. Once a session manager is added here, more session providers should not be added
to the session manager.
Inputs
Name IEC 61131 Type Description
sessionManager I_SessionManager The session manager containing I_Session objects for
the simulator.
CreateEvent (Method)
This method creates a new event within the simulator. When the event is created, it will be
automatically assigned the next available record number. The event created by this method
will contain four samples per cycle. The analog values, Relay Word bit values, and relay
settings will consist of internal hard-coded values and will not match the values already set
in the simulator.
Inputs
Name IEC 61131 Type Description
refNum UINT Reference number of the event
event STRING(8) Type of event
location REAL Location of the fault
current UINT Peak current detected during the fault
group USINT Group number
shot UINT Number of reclose events
targets STRING Target elements for the event
Return Value
IEC 61131 Type Description
BOOL TRUE if the event was successfully created.
DeleteEvent (Method)
This method deletes an event from the simulator that was created with CreateEvent().
Inputs
Name IEC 61131 Type Description
recNum UINT The record number for the event as provided by the CHI com-
mand.
Return Value
IEC 61131 Type Description
BOOL TRUE if the event was successfully deleted. FALSE if the event did not
exist or an error occurred.
Destroy (Method)
This method deallocates all memory allocated by this object. This method must be called
before the object goes out of scope; otherwise, a memory leak will result.
Return Value
IEC 61131 Type Description
BOOL TRUE if all memory was successfully deallocated.
Run (Method)
This method handles processing communication between the server and all connected
clients. This method must be called once per scan.
Processing
The Run() method does the following:
ä Reads any pending requests from clients.
ä If a valid command is received, the applicable response is generated and sent to the
client.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Simulating an SEL-351
Objective
This example creates a simulator for an SEL-351 Relay on an RTAC. Changing analog and
digital values is also demonstrated.
Assumptions
This example assumes that an Access Point has been defined for TCP Port 23 on the RTAC.
This is necessary for the simulator to communicate via Telnet to other RTACs or to a user’s
interactive Telnet session.
Solution
The program shown in Code Snippet 34.1 shows a minimal example of running a simulator
of the SEL-351. This example instantiates a Telnet server that can handle as many as ten
simultaneous connections. On the first scan, the system frequency of the simulator is set
to 60 Hz and the daylight-saving time Relay Word bit is set to TRUE.
IF FirstScan then
// Add the Telnet server as a session provider to the session manager.
SessionManager.AddSessionProvider(TelnetServer);
// Add the session manager to the SEL-351 simulator.
Sel351.bootstrap_AddSessionManager(SessionManager);
// Set the simulator frequency to 60 Hz.
Sel351.Analog._FREQ.stVal := 60;
// Set the daylight saving time Relay Word bit to true.
Sel351.Binary._DST.stVal := TRUE;
FirstScan := FALSE;
END_IF
Assumptions
This example assumes that an Access Point has been defined for TCP Port 23 on the RTAC.
This is necessary for the simulators to communicate via Telnet to other RTACs or to a user’s
interactive Telnet session. For this example, it is necessary to use two network interfaces
on the RTAC, one with the IP address 192.168.0.100 and the other with 192.168.1.100.
Solution
The program shown in Code Snippet 34.2 shows an example of running two distinct SEL-
351 simulators on the same RTAC. One simulator listens on the network interface with
the IP address 192.168.0.100 and the other listens on the second interface with address
192.168.1.100.
IF FirstScan then
// Add a Telnet server as a session provider to the respective session
manager.
SessionManager1.AddSessionProvider(TelnetServer1);
SessionManager2.AddSessionProvider(TelnetServer2);
// Add the respective session manager to the SEL-351 simulator.
Sel351_1.bootstrap_AddSessionManager(SessionManager1);
Sel351_2.bootstrap_AddSessionManager(SessionManager2);
// Set the first simulator frequency to 60 Hz.
Sel351_1.Analog._FREQ.stVal := 60;
// Set the second simulator frequency to 50 Hz.
Sel351_2.Analog._FREQ.stVal := 50;
FirstScan := FALSE;
END_IF
Assumptions
This example assumes that an Access Point has been defined for TCP Ports 23 and 8023 on
the RTAC. This is necessary for the simulator to communicate via Telnet to other RTACs
or to a user’s interactive Telnet session.
Solution
The program shown in Code Snippet 34.3 shows an example of running a simulator of the
SEL-351 that listens on Ports 23 and 8023. This example instantiates two Telnet servers,
one on each port, that can handle as many as ten simultaneous connections each. Connec-
tions to these simulators will be allowed on all network interfaces.
IF FirstScan then
// Add both Telnet servers as session providers to the session manager.
SessionManager.AddSessionProvider(TelnetServer1);
SessionManager.AddSessionProvider(TelnetServer2);
// Add the session manager to the SEL-351 simulator.
Sel351.bootstrap_AddSessionManager(sessionManager);
FirstScan := FALSE;
END_IF
Assumptions
This example assumes that an Access Point has been defined for TCP Port 23 on the RTAC.
This is necessary for the simulator to communicate via Telnet to other RTACs or to a user’s
interactive Telnet session.
Solution
The program shown in Code Snippet 34.4 shows a minimal example of running a simulator
of the SEL-351 and adding an event. This example instantiates a Telnet server that can
handle as many as ten simultaneous connections. On the first scan, an event is created.
The event date and time will be set to the present date and time of the RTAC system.
IF FirstScan then
// Add the Telnet server as a session provider to the session manager.
SessionManager.AddSessionProvider(TelnetServer);
// Add the session manager to the SEL-351 simulator.
Sel351.bootstrap_AddSessionManager(SessionManager);
// Add an event to the simulator. The reference number is 1, type is
TRIG,
// location of zero, maximum current of zero, group 1, shot 1, and no
// targets. Other event values are set automatically.
Sel351.CreateEvent(1, 'TRIG', 0, 0, 1, 1, '');
FirstScan := FALSE;
END_IF
SELString
Introduction
The purpose of this library is to provide a single object for performing string manipulations.
It is intended to allow for a variety of string manipulations without requiring lengths to be
predefined.
References to ASCII characters within this document are given in base-10. Whitespace for
the scope of this document includes the following: spaces (32), tabs (9), newlines (10), and
carriage returns (13). Invalid Characters are any characters that fall in the ASCII range
0–8, 11, 12, 14–27, or ≥127.
This document refers to iterator methods in a state called locked out. This refers to the state
of the object being such that the user cannot retrieve non-NULL(0) values from Next() or
Previous() without a new call to Begin(), End(), or Position().
Special Considerations
Classes in this library have memory allocated inside them. As such, they should only be
created in environments of permanent scope (e.g., Programs, Global Variable Lists, or
VAR_STAT sections).
Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.
// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_SELStringObject"
mySELStringObject := otherSELStringObject;
// This is fine
someVariable := mySELStringObject.value;
// As is this
pt_mySELStringObject := ADR(mySELStringObject);
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Functions
fun_SELString_IsValidChar (Function)
This function takes a character in the form of a BYTE and returns TRUE if it is a valid
printable character; otherwise, this function returns FALSE.
Inputs
Name IEC 61131 Type Description
character BYTE Byte to be evaluated as a printable character.
Return Value
IEC 61131 Type Description
BOOL TRUE if character is a valid printable character.
Processing
If character is an invalid character, this function returns FALSE; otherwise, this function
returns TRUE.
fun_SELString_IsWhitespace (Function)
This function takes a character in the form of a BYTE and returns TRUE if it is a whitespace
character; otherwise, this function returns FALSE.
Inputs
Name IEC 61131 Type Description
character BYTE Character to be evaluated for being whitespace.
Return Value
IEC 61131 Type Description
BOOL TRUE if character is a whitespace character.
Processing
ä If character is a whitespace character, this function returns TRUE; otherwise, this
function returns FALSE.
fun_ByteIsAlpha (Function)
This function determines whether an input byte is an alphabetic character (i.e., A-Z or a-z).
Inputs
Name IEC 61131 Type Description
Input BYTE Byte to be tested as an alphabetic character.
Return Value
IEC 61131 Type Description
BOOL TRUE if Input is an alphabetic character.
Processing
The fun_ByteIsAlpha function performs the following action:
ä If the decimal representation of Input is within the ASCII ranges ([65-90] and [97-
122]) for alphabetic characters, the function returns TRUE. Anything outside that
range, returns FALSE.
fun_ByteIsNumeric (Function)
This function determines whether an input byte is a numeric character (i.e., 0-9).
Inputs
Name IEC 61131 Type Description
Input BYTE Byte to be tested as a numeric character.
Return Value
IEC 61131 Type Description
BOOL TRUE if Input is a numeric character.
Processing
The fun_ByteIsNumeric function performs the following action:
ä If the decimal representation of Input is within the ASCII ranges for numeric charac-
ters [48-57], function returns TRUE. If the decimal representation is anything outside
that range, returns FALSE.
fun_ByteIsAlphaNumeric (Function)
This function determines whether an input byte is an alphanumeric character (i.e., A-Z,
a-z, or 0-9).
Inputs
Name IEC 61131 Type Description
Input BYTE Byte to be tested as an alphanumeric character.
Return Value
IEC 61131 Type Description
BOOL TRUE if Input is an alphabetic or numeric character.
Processing
The fun_ByteIsAlphaNumeric function performs the following action:
ä If the decimal representation of Input is within the ASCII ranges for alphabetic and
numeric characters ([48-90], [65-90], and [97-122]), returns TRUE. If the decimal
representation is anything outside that range, returns FALSE.
fun_LowercaseByte (Function)
This function returns the input byte as its lowercase equivalent if the input is an alphabetic
character (i.e., A-Z).
Inputs
Name IEC 61131 Type Description
Input BYTE The byte to be cast to lowercase if applicable.
Return Value
IEC 61131 Type Description
BYTE The byte in lowercase if applicable.
Processing
The fun_LowercaseByte function performs the following action:
ä If Input is a valid uppercase character, it is cast to lowercase.
ä Lowercase or numeric characters remain unchanged.
ä Non-printable characters and non-alphanumeric characters remain unchanged.
fun_UppercaseByte (Function)
This function returns the input byte as its uppercase equivalent if the input is an alphabetic
character (i.e., a-z).
Inputs
Name IEC 61131 Type Description
Input BYTE The byte to be cast to uppercase if applicable.
Return Value
IEC 61131 Type Description
BYTE The byte in uppercase if applicable.
Processing
The fun_UppercaseByte function performs the following action:
ä If Input is a valid lowercase character, it is cast to uppercase.
ä Uppercase or numeric characters remain unchanged.
ä Non-printable characters and non-alphanumeric characters remain unchanged.
Classes
class_SELString (Class)
class_SELString exists as the single class required to perform string manipulations. This
class maintains a sequence of characters and is initialized to an empty set of characters.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
FromString (Method)
This method takes an IEC 61131 string, str, as an input to be stored within the class_-
SELString.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string to be stored and ma-
nipulated within the SELString.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The FromString method performs the following actions:
ä Accepts any valid IEC 61131 string up to g_p_MaxIec61131StringSize characters
in size.
ä Accepts all characters from the beginning of str until an invalid character, an end-
of-string character, or g_p_MaxIec61131StringSize characters are reached; and no
following characters.
ä Replaces all current characters within class_SELString with characters from str.
ä Populates all available characters with the leading characters in str if the library runs
out of memory. In this case, this method returns a pointer to an error string.
ä Returns 0 on success.
FromByteArray (Method)
This method takes a pointer to the beginning of a byte array and the number of bytes to be
copied. It then stores the byte array within the class_SELString object. This method stores
any values represented in the byte array—it does not check for valid characters.
Inputs
Name IEC 61131 Type Description
pt_byteArray POINTER TO BYTE The address returned by calling ADR() on the byte array
to copy data from.
numBytes UDINT The number of bytes to be copied from the byte array.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The FromByteArray method performs the following actions:
ä Accepts all characters from the beginning of pt_byteArray until numBytes bytes.
ä Replaces all current characters within this class_SELString with bytes from pt_-
byteArray.
ä Populates all available characters with the leading bytes in pt_byteArray if the library
runs out of memory and returns a pointer to an applicable error string.
ä Returns 0 on success.
CopyTo (Method)
This method copies the contents of this object into the class_SELString provided by the
user. Both the input and this class_SELString will contain duplicate contents following
this method call.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString to which this object’s contents will be
copied.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The CopyTo method performs the following actions:
ä Replaces all current characters within the class_SELString specified str with the
contents of this class_SELString.
ä Populates as many characters as possible in str with the content of this class_SEL-
String if the library runs out of memory and returns a pointer to an applicable error
string.
ä Returns 0 on success.
ToString (Method)
This method outputs an IEC 61131 string representation of the data being stored within the
SELString.
Return Value
IEC 61131 Type Description
STRING(g_p_MaxIec61131StringSize) An IEC 61131 string equivalent of the data stored
within the SELString.
Processing
The ToString method performs the following actions:
ä Returns an IEC 61131 string, up to g_p_MaxIec61131StringSize characters in size,
that represents the first g_p_MaxIec61131StringSize characters of this class_SEL-
String.
ä If nothing has been assigned to this class_SELString, then the return value is an
empty IEC 61131 string.
ä The character immediately following the last character inserted into the IEC 61131
string is a string terminator character.
ToByteArray (Method)
This method copies the contents of the class_SELString to the address provided. It stops
copying once maxBytes is reached or the class_SELString is completely copied.
Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE The destination to which the content is copied.
maxBytes UDINT The maximum number of bytes to copy.
Return Value
IEC 61131 Type Description
UDINT The number of bytes successfully copied to the destination.
Processing
The ToByteArray method performs the following actions:
ä Writes the contents of the class_SELString to the address provided.
ä Copying stops when one of the following occurs:
1. The number of bytes copied is equal to maxBytes.
2. All bytes in the class_SELString have been copied.
ä The number of bytes copied before encountering one of the above criteria is returned
as an integer. This will be 0 if class_SELString is empty or maxBytes is 0.
ä No termination byte is appended.
Replace (Method)
This method replaces every occurrence of the string before with the string after.
Inputs/Outputs
Name IEC 61131 Type Description
before class_SELString The class_SELString containing the combination of characters
to be replaced.
after class_SELString The class_SELString containing the combination of characters
that will replace all characters of before.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Replace method performs the following actions:
ä Does not modify before or after.
ä Is case sensitive.
ä Replaces all occurrences of before with after in a single pass. This prevents an in-
finite loop in cases like before=“abc” and after=“abcabc” and produces a reliable
output in cases like before=“abcbcbef” and after=“bcb”.
ä If before or after is this object, then this method leaves all objects unchanged. It then
returns a pointer to an applicable IEC 61131 error string.
ä If the library runs out of memory, this method exits immediately in an undefined
state. It returns a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.
Split (Method)
This method splits the class_SELString into multiple class_SELStrings wherever sep oc-
curs and places the result in a class_SELStringList.
Inputs/Outputs
Name IEC 61131 Type Description
sep class_SELString The combination of characters defining where the string will
split.
stringlist class_SELStringList The string list to be populated.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Split method performs the following actions:
ä Creates divisions at every occurrence of sep. For example:
â In “tgeadadagt”, using a sep of “ada” results in “tge”, “dagt”.
â In “tgeadadagt”, using a sep of “ad” results in “tge”, “”, “agt”.
â In “decide”, using a sep of “de” results in “”, “ci”, “”.
ä Is case sensitive.
ä If the class_SELString was never assigned a string or contains an empty string, it
fills stringlist with only an empty string in the first position.
ä Erases any prior contents of stringlist.
ä If sep does not exist in this class_SELString, it places the full class_SELString into
the first position.
ä If sep is empty, it places each character of this class_SELString into its own string.
Example: “Hello” becomes: “H”, “e”, “l”, “l”, “o”.
ä Adds substrings to stringlist in order from left to right.
ä Empties this class_SELString object.
ä If sep is this object, leaves all objects unchanged. It then returns a pointer to an
applicable IEC 61131 error string.
ä Returns a pointer to an applicable IEC 61131 error string if the class_SELStringList
specified for stringlist contains the class_SELString to be split, or the class_SEL-
String specified for sep.
Trim (Method)
This method removes excess whitespace from this class_SELString. In this method, whites-
pace includes any character that results in TRUE being returned from fun_SELString_-
IsWhitespace.
Processing
The Trim method performs the following actions:
ä Removes all whitespace from the beginning of the string to the first non-whitespace
character.
ä Removes all whitespace from the last non-whitespace character to the end of the
string.
ä Replaces any number of consecutive whitespace characters with a single space char-
acter.
ä Leaves a class_SELStrings containing no whitespace and empty strings unchanged.
ä Replaces strings containing only whitespace with an empty string.
Append (Method)
This method appends the input, str, onto the end of this class_SELString. The input, str, is
empty upon completion of this method.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that will be ap-
pended to this class_SELString.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Append method performs the following actions:
ä Adds all characters from str after the last character of this class_SELString.
ä Removes all characters from str.
ä If this class_SELString is empty, moves the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in either class_SELString.
ä Changes nothing if str is this object. It then returns a pointer to an applicable
IEC 61131 error string.
ä Always appends as many characters as possible. If the library runs out of memory,
str is empty upon completion and it returns a pointer to an applicable IEC 61131
error string.
ä Returns 0 on success.
AppendByteArray (Method)
This method takes a pointer to the beginning of a byte array and the number of bytes to be
copied. It then stores the byte array onto the end of this class_SELString.
Inputs
Name IEC 61131 Type Description
pt_byteArray POINTER TO BYTE The address returned by calling ADR() on the byte ar-
ray to copy data from.
numBytes UDINT The number of bytes to copy from the byte array.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The AppendByteArray method performs the following actions:
ä Adds numBytes characters from pt_byteArray after the last character of this class_-
SELString.
ä If this class_SELString is empty, adds numBytes characters from pt_byteArray to
this class_SELString.
ä If numBytes is 0, changes nothing in this class_SELString.
ä Always appends as many characters as possible. If the library runs out of memory,
it returns a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.
AppendString (Method)
This method appends the characters of the input, str, onto the end of this class_SELString.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters that will be appended to this class_-
SELString.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The AppendString method performs the following actions:
ä Adds all characters from str after the last character of this class_SELString.
ä If this class_SELString is empty, adds the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in this class_SELString.
ä Always appends as many characters as possible. If the library runs out of memory,
it returns a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.
Prepend (Method)
This method prepends the input, str, onto the beginning of this class_SELString. The input,
str, is empty upon completion of this method.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters to be prepended
to this class_SELString.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Prepend method performs the following actions:
ä Adds all characters from str before the first character of this class_SELString.
PrependString (Method)
This method prepends the characters of the input, str, to the beginning of this class_SEL-
String.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters to be prepended to this class_SEL-
String.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The PrependString method performs the following actions:
ä Adds all characters from str before the first character of this class_SELString.
ä If this class_SELString is empty, adds the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in this class_SELString.
ä If the library runs out of memory, leaves all objects unchanged and returns a pointer
to an applicable IEC 61131 error string.
ä Returns 0 on success.
Insert (Method)
This method inserts the input class_SELString, str, into this class_SELString at the index
specified by the user. The input str is empty upon completion of this method.
Inputs
Name IEC 61131 Type Description
index UDINT The index where str will be inserted.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that will be in-
serted to this class_SELString.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Insert method performs the following actions:
ä Inserts at index, where an index of zero corresponds to immediately before the first
character and is incremented by one for each character thereafter.
ä Removes all characters from str.
ä Inserts all characters from str into this class_SELString at position index.
ä If index is larger than the size of this class_SELString, appends str at the end of this
class_SELString.
ä If this class_SELString is empty, moves the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in either class_SELString.
ä Changes nothing if str is this object. It then returns a pointer to an applicable
IEC 61131 error string.
ä If the library runs out of memory, places all characters of str into this class_SEL-
String, truncates the result, and returns a pointer to an applicable IEC 61131 error
string.
ä Returns 0 on success.
Find (Method)
This method returns the first position after the provided index where the character combi-
nation provided in str exists. If the character combination does not exist after the provided
index, a –1 is returned.
Inputs
Name IEC 61131 Type Description
index UDINT The index where this class_SELString will begin to search.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that are being
searched for within this class_SELString.
Return Value
IEC 61131 Type Description
DINT The index of the first match of str within this object. If str cannot be found,
this method will return ‘–1’. (This value is always ≥ ‘–1’)
Processing
The Find method performs the following actions:
ä Begins its search at index, where an index of zero corresponds to immediately before
the first character and is incremented by one for each character thereafter. The same
is true of the return value.
ä Is case sensitive.
ä Returns the index of the first occurrence of str appearing after the given index.
ä If index is larger than the size of this class_SELString, returns –1.
ä If str cannot be found, returns –1.
ä If str is empty, returns –1.
ä If str is this object, then –1 is returned.
FindString (Method)
This method returns the first position after the provided index where the character combi-
nation provided in str exists. If the character combination does not exist after the provided
index, a –1 is returned.
Inputs
Name IEC 61131 Type Description
index UDINT The index where this class_SELString will begin to search.
Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters that are being searched for within
this class_SELString.
Return Value
IEC 61131 Type Description
DINT The index of the first match of str within this object. If str cannot be found,
this method will return –1. (This value is always ≥ –1)
Processing
The FindString method performs the following actions:
ä Begins its search at index, where an index of zero corresponds to immediately before
the first character and is incremented by one for each character thereafter. The same
is true of the return value.
ä Is case sensitive.
ä Returns the index of the first occurrence of str appearing after the given index.
ä If index is larger than the size of this class_SELString, returns –1.
ä If str cannot be found, returns –1.
ä If str is empty, returns –1.
ä If str system state prevents the search, then –1 is returned.
Clear (Method)
This method removes all character data from the class_SELString.
Return Value
IEC 61131 Type Description
BOOL Success indicator of clear operation; TRUE if memory is cleared without
errors.
Processing
The Clear method performs the following actions:
ä Removes all character data within the class_SELString.
ä Resets the size of the class_SELString to zero.
ä Resets the return value of ToString to an empty string.
ä Any used memory is returned to the library.
Item (Method)
This method returns the character at the requested index.
Inputs
Name IEC 61131 Type Description
index UDINT The index of the character being requested.
Return Value
IEC 61131 Type Description
BYTE The ASCII value of the character at the requested index. If index is out of
range, returns NULL(0).
Processing
The Item method performs the following actions:
ä Treats the first character as index zero with each additional character being an addi-
tion of one.
ä Returns the character positioned at the user requested index.
ä If index is greater than or equal to the number of characters in this class_SELString,
returns NULL.
ä Returns NULL on an empty string.
Begin (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the first character of this class_SELString object.
Processing
The Begin method places the iterator such that:
ä The iterator is not locked out.
ä A subsequent Next() returns the first character.
ä A subsequent Previous() returns NULL and leaves the iterator locked out.
ä For an empty string, Next() and Previous() return NULL and leave the iterator
locked out.
End (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator immediately after the last character of this class_SELString object.
Processing
The End method places the iterator such that:
ä The iterator is not locked out.
ä A subsequent Previous() returns the last character.
ä A subsequent Next() returns NULL and leaves the iterator locked out.
ä For an empty string Next() and Previous() return NULL and leave the iterator
locked out.
Position (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the character at index.
Inputs
Name IEC 61131 Type Description
index UDINT The location where the character iterator will be assigned.
Processing
The Position method places the iterator such that:
ä The first character in the class_SELString is index zero with each additional character
being an addition of one.
ä An index greater than or equal to the number of characters in this class_SELString
leaves the iterator locked out.
ä Otherwise the iterator is not locked out.
ä A subsequent Next() returns the character at the provided index.
ä A subsequent Previous() returns the character immediately before the provided
index.
ä For an empty string Next() and Previous() return NULL and leave the iterator
locked out.
Next (Method)
This method is used in conjunction with Begin(), Position(), End(), and Previous().
This method returns the character at the current internal iterator position then increments
the iterator.
Return Value
IEC 61131 Type Description
BYTE The ASCII value of the character at the current iterator position. If no
character exists, returns NULL(0).
Processing
The Next method performs the following actions:
ä Returns the character at the current internal iterator position and then increments the
iterator.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iterator
increments to a position greater than the number of characters in this class_SEL-
String.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().
Previous (Method)
This method is used in conjunction with Begin(), Position(), End(), and Next(). This
method decrements the current internal iterator position and then returns the character at
the new position.
Return Value
IEC 61131 Type Description
BYTE The ASCII value of the character at the decremented iterator position. If
no character exists, returns NULL(0).
Processing
The Previous method performs the following actions:
ä Decrements the internal iterator position then returns the character new position.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iterator
decrements to a position less than index 0.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().
ToAsciiHex (Method)
This method copies an ASCII-encoded hexadecimal representation of the contents of this
object into the class_SELString provided by the user. For example, a character of ‘A’ (raw
byte content of 65, hex 0x41) is converted to a ‘4’ and a ‘1’ (raw byte content of 52 and
49) when appended to str.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString to which the ASCII-encoded hexadecimal
representation of this object’s contents will be copied.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The ToAsciiHex method performs the following actions:
ä Empties the class_SELString specified by str as per Clear().
ä Iterates through this class_SELString one character at a time and appends two char-
acters to the class_SELString specified by str, representing an ASCII-encoded hex-
adecimal copy of the raw byte content from this class_SELString.
ä If the library encounters an error, a pointer to a string describing that error is returned.
ä Returns 0 on success.
FromAsciiHex (Method)
This method takes an ASCII-encoded hexadecimal class_SELString, str, as an input to
be interpretted as raw hexadecimal data and stores the converted data within this class_-
SELString object. For example, two sequential characters of ‘4’ and ‘1’ (raw data of 52
and 49) are interpretted as hexadecimal 0x41 and stored in this class_SELString as raw
byte content of 65 (the character ‘A’).
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString whose ASCII-encoded hexadecimal data
will be used to fill this object. Must be of an even length and
only contain characters that are considered to be ASCII repre-
sentations of valid hex digits (0-9, A-F, a-f).
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The FromAsciiHex method performs the following actions:
ä Empties this class_SELString as per Clear().
ä Validates that the class_SELString specified as str contains an even number of char-
acters; returns an error string and does no work if the string is of an odd length of
characters.
ä Iterates through the class_SELString specified as str two characters at a time and
uses fun_IsValidHexChar to validate that each character can be interpreted as a valid
hex digit. Returns an error string if any unexpected characters are encountered.
ä Converts each pair of characters into a single byte and appends those raw data onto
this class_SELString.
ä Returns 0 on success.
StartsWith (Method)
This method searches for an exact match passed as an IEC 61131 string at the beginning
of the class_SELString. It returns TRUE if an exact match was found and false if no match
was found. This method is case-sensitive.
Inputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters that are being searched for at the be-
ginning of the class_SELString.
Return Value
IEC 61131 Type Description
BOOL TRUE if str is located at the beginning of the class_SELString.
Processing
The StartsWith method performs the following actions:
ä Calls the method FindString starting at index zero.
ä If the method FindString finds a match at index zero, returns TRUE.
ä If the method FindString does not find a match at index zero, returns FALSE.
ä Returns FALSE on an empty IEC 61131 string.
EndsWith (Method)
This method searches for an exact match to the passed in IEC 61131 string at the end of
the class_SELString. It returns TRUE if the exact match was found and returns false if no
match was found. This method is case-sensitive.
Inputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters that are being searched for at the end
of the class_SELString.
Return Value
IEC 61131 Type Description
BOOL TRUE if str is located at the end of the class_SELString.
Processing
The EndsWith method performs the following actions:
ä Calculates the index to start looking for an exact match.
ä Calls the method FindString at that index.
ä If the method FindString finds a match at the calculated index, returns TRUE.
ä If the method FindString does not find a match, returns FALSE.
ä Returns FALSE on an empty IEC 61131 string.
Strip (Method)
This method removes excess whitespace characters from the beginning and end of the
class_SELString. In this method, whitespace includes any character that results in TRUE
being returned from fun_SELString_IsWhitespace.
Processing
The Strip method performs the following actions:
ä Removes all whitespace from the beginning of the string to the first non-whitespace
character.
ä Removes all whitespace from the last non-whitespace character to the end of the
string.
ä Leaves a class_SELString containing no whitespace and empty strings unchanged.
ä Replaces strings containing only whitespace with an empty string.
LeftStrip (Method)
This method removes all whitespace from the beginning of this class_SELString to the first
non-whitespace character. In this method, whitespace includes any character that results
in TRUE being returned from fun_SELString_IsWhitespace.
Processing
The LeftStrip method performs the following actions:
ä Removes all whitespace from the beginning of the string to the first non-whitespace
character.
ä Leaves a class_SELString containing no whitespace and empty strings unchanged.
ä Replaces strings containing only whitespace with an empty string.
RightStrip (Method)
This method removes all whitespace from the last non-whitespace character to the end
of the class_SELString. In this method, whitespace includes any character that results in
TRUE being returned from fun_SELString_IsWhitespace.
Processing
The RightStrip method performs the following actions:
ä Removes all whitespace from the last non-whitespace character to the end of the
string.
ä Leaves a class_SELString containing no whitespace and empty strings unchanged.
ä Replaces strings containing only whitespace with an empty string.
LeftJustify (Method)
This method justifies the class_SELString to the left. The method takes two inputs: the
size that the class_SELString shall be extended to, and the character to append to the end
of the class_SELString to achieve the specified length.
Inputs
Name IEC 61131 Type Description
newSize UDINT The size that the class_SELString shall have after ap-
pending the paddingCharacter.
paddingCharacter STRING(1) The ASCII representation of the character that is be-
ing used to justify the class_SELString to the left.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The LeftJustify method performs the following actions:
ä Appends the paddingCharacter as many times as needed to reach the newSize.
ä Validates that paddingCharacters are those outlined in fun_SELString_IsValidChar.
RightJustify (Method)
This method justifies the class_SELString to the right. It takes two inputs: the size that the
class_SELString shall be extended to, and the character to prepend to the beginning of the
class_SELString to achieve the specified length.
Inputs
Name IEC 61131 Type Description
newSize UDINT The size that the class_SELString shall have after
prepending the paddingCharacter.
paddingCharacter STRING(1) The ASCII representation of the character that is be-
ing used to justify the class_SELString to the right.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The RightJustify method performs the following actions:
ä Prepends the paddingCharacter as many times needed to reach the newSize.
ä Validates that paddingCharacters are those outlined in fun_SELString_IsValidChar.
ä If paddingCharacter is invalid, leaves all objects unchanged and returns a pointer to
an applicable invalid character error string.
ä Leaves a class_SELStrings of size g_p_SELStringInitialSize unchanged.
ä If the library runs out of memory, leaves all objects unchanged and returns a pointer
to an applicable IEC 61131 error string.
ä Returns 0 on success.
Count (Method)
This method counts the number of occurrences of a given class_SELString. It returns a
DINT representing the total number of appearances.
Inputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that are being
counted within the class_SELString object.
Return Value
IEC 61131 Type Description
DINT Numeric value representing the number of occurrences of a class_SEL-
String in a given class_SELString.
Processing
The Count method performs the following actions:
ä Counts the number of times that the Find method returns a positive value.
ä If str is not found, returns 0.
ä If str is this object, returns -1.
ä An empty str returns -2.
class_SELStringList (Class)
class_SELStringList exists to store and perform operations on a list of strings using 0-based
indexing.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Append (Method)
This method adds the requested string to the end of the list.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The string to be added to the end of the class_SELStringList.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Append method performs the following actions:
ä Places str at the end of the current list (position zero for an empty list) and increments
the size of the list.
ä Empties the contents of str.
ä Allows empty strings to be added to the list.
ä If the object str is already a member of the list, empties the contents of str and places
the contents of str at the end of the list.
For example: If this list is [“dog”,“cat”,“bird”] and Item 1 (“cat”) is appended, the
new list is: [“dog”,“”,“bird”,“cat”].
ä If the library runs out of memory, it leaves this object and str unchanged and returns
a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.
Insert (Method)
This method inserts the requested string into the list at the position specified.
Inputs
Name IEC 61131 Type Description
index UDINT The location where str will be inserted.
Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString to be inserted into the class_SEL-
StringList.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Insert method performs the following actions:
ä Places the index zero immediately before the first class_SELString and increments
by one for each string thereafter.
ä Empties the contents of str.
ä Allows empty strings to be added to the list.
ä When index is equal to the length of list or more, behaves the same as Append().
ä If the object str is already a member of the list, empties the contents of str and places
the contents of str at the requested location.
For example: If this list is [“dog”,“cat”,“bird”] and Item 0 (“dog”) is inserted at
Position 2, the new list is: [“”,“cat”,“dog”,“bird”].
ä Increases the size of the list by one.
ä If the library runs out of memory, removes the final class_SELString from this object
and inserts str at the desired index except in the case where str would be appended,
in which case the Insert method behaves the same as Append(). It then returns a
pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.
RemoveLast (Method)
This method removes the last string in the list.
Processing
The RemoveLast method performs the following actions:
ä Removes the last class_SELString from the class_SELStringList.
ä Decrements the size of the class_SELStringList.
ä Does nothing if the class_SELStringList is empty.
ä Returns the freed memory.
Clear (Method)
This method removes all class_SELString objects from the list.
Return Value
IEC 61131 Type Description
BOOL Success indicator of clear operation; TRUE if memory is cleared without
errors.
Processing
The Clear method performs the following actions:
ä Removes all class_SELStrings in the class_SELStringList.
ä Sets the size of the class_SELStringList to zero.
ä Causes all other methods to respond that there are no objects in the list.
ä Returns the freed memory.
Item (Method)
This method returns a pointer to the class_SELString at the requested index.
Inputs
Name IEC 61131 Type Description
index UDINT The location of the desired string in the list.
Return Value
IEC 61131 Type Description
POINTER TO class_SELString A pointer to the class_SELString located at index. If index
does not exist, returns NULL(0).
Processing
The Item method performs the following actions:
ä Returns a pointer to the class_SELString that exists at index.
ä Returns NULL if index is outside the bounds of the list.
Begin (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the first string in the list.
Processing
The Begin method places the iterator in a location to comply with the following items:
ä The iterator is not locked out.
End (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator immediately after the last string in the list.
Processing
The End method places the iterator in a location to comply with the following items:
ä The iterator is not locked out.
ä A subsequent Next() returns NULL and leaves the iterator locked out.
ä A subsequent Previous() returns the first string in the list.
ä For an empty list Next() and Previous() return NULL and leave the iterator
locked out.
Position (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the string at index.
Inputs
Name IEC 61131 Type Description
index UDINT List location of the desired string.
Processing
The Position method places the iterator in a location to comply with the following items:
ä The first string in the class_SELStringList is index zero with each additional string
being an addition of one.
ä An index greater than or equal to the number of strings in this class_SELStringList
leaves the iterator locked out.
ä Otherwise the iterator is not locked out.
ä A subsequent Next() returns the string at the provided index.
ä A subsequent Previous() returns the string immediately before the provided index.
ä For an empty string list, Next() and Previous() return NULL and leave the iterator
locked out.
Next (Method)
This method is used in conjunction with Begin(), Position(), End(), and Previous().
This method returns the string at the current internal iterator position then increments the
iterator.
Return Value
IEC 61131 Type Description
POINTER TO class_SELString A pointer to the string at the current iterator position. If no
string exists, returns NULL(0).
Processing
The Next method performs the following actions:
ä Returns the string at the current internal iterator position and then increments the
iterator.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iter-
ator increments to a position greater than the number of strings in this class_SEL-
StringList.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().
Previous (Method)
This method is used in conjunction with Begin(), Position(), End(), and Next(). This
method decrements the internal iterator position and returns a pointer to the string at the
new position.
Return Value
IEC 61131 Type Description
POINTER TO class_SELString A pointer to the string at the decremented iterator position. If
no string exists, returns NULL(0).
Processing
The Previous method performs the following actions:
ä Decrements the internal iterator position and returns a pointer to the string at the new
position.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iterator
decrements below position 0.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().
Join (Method)
This method creates a single class_SELString containing the full list of class_SELStrings,
each separated from the other by the provided str. This object is empty upon successful
completion.
Inputs/Outputs
Name IEC 61131 Type Description
outStr class_SELString The user provided class_SELString in which this method will
join all class_SELStrings within the stringlist separated by str.
Any existing content of this string will be overwritten.
str class_SELString The class_SELString to be inserted between each entry in the
class_SELStringList.
Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.
Processing
The Join method performs the following actions:
ä Loads the outStr class_SELString with the full list of class_SELStrings separated by
str.
Example: If the class_SELStringList contains: [“b”,“n”,“n”,“s”] and str is “a” then
the return value is “bananas”.
ä Loads the outStr class_SELString with an empty string, if empty.
ä Loads the outStr class_SELString containing the full list of strings if str is an empty
string. For example: If the stringlist contains [“H”,“e”,“l”,“l”,“o”] and str is empty,
the return value is “Hello”.
ä Empties this class_SELStringList as per Clear().
ä If str is a member of this list, loads the outStr class_SELString with undefined values.
ä If the library runs out of memory, the output class_SELString will contain all class_-
SELStrings in the list that were loaded prior to the error. This class_SELStringList
object will be cleared.
ä Returns 0 on success.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530-4
â R132 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 1 GB DDR ECC SDRAM
â SEL-3532 RTAC Conversion Kit
â R132 firmware
FromString Replace
This test calls FromString() and replaces g_p_StringSize characters with g_p_StringSize
different characters.
FromString Populate
This test calls FromString() on an empty class_SELString and populates it with g_p_-
StringSize characters.
FromString Depopulate
This test calls FromString() on a class_SELString with g_p_StringSize characters and
populates it with zero characters.
ToString
This test calls ToString() on a class_SELString with g_p_StringSize characters.
FromByteArray Replace
This test calls FromString() and replaces g_p_StringSize characters with g_p_StringSize
different characters.
FromByteArray Populate
This test calls FromString() on an empty class_SELString and populates it with g_p_-
StringSize characters.
FromByteArray Depopulate
This test calls FromString() on a class_SELString with g_p_StringSize characters and
populates it with zero characters.
ToByteArray
This test calls ToString() on a class_SELString with g_p_StringSize characters.
Split 0 Char
This test calls Split() with an empty separator in a class_SELString of length g_p_-
StringSize. It is designed to show the cost of splitting a string into its constituent characters.
Trim No Whitespace
This test calls Trim() on a length g_p_StringSize class_SELString containing no whites-
pace. It is designed to show the cost of searching for whitespace.
Size
This test calls Size() on a length g_p_StringSize class_SELString.
Append
This test calls Append() with varying length class_SELString.
AppendString
This test calls AppendString() with a g_p_MaxIec61131StringSize length string.
Prepend
This test calls Prepend() with varying length class_SELString.
PrependString
This test calls PrependString() with a g_p_MaxIec61131StringSize length string.
Insert Middle
This test calls Insert() to place one character in the middle of a class_SELString.
Find 1 Char
This test calls Find() for a single character not found in a length g_p_StringSize class_-
SELString.
Find Max/2
This test calls Find() searching for “aaaaaaab” while having a current of “aaaaaaaaaaaaab”
but with sizes of g_p_StringSize/2 and g_p_StringSize respectively. It is designed to show
the cost of heavy recursive searching using Find().
Find Max
This test calls Find() searching for a length g_p_StringSize string inside a length g_p_-
StringSize class_SELString.
FindString 1 Char
This test calls FindString() for a single character not found in a length g_p_StringSize
class_SELString.
FindString Max/2
This test calls FindString() searching for “aaaaaaab” of size g_p_StringSize/2 while
having a current of “aaaaaaaaaaaaab” or size of g_p_StringSize. It is designed to show the
cost of heavy recursive searching using FindIecString().
FindString Max
This test calls FindString() searching for a length g_p_StringSize string inside a length
g_p_StringSize class_SELString.
Clear
This test calls Clear() on a class_SELString of length g_p_StringSize.
Item Middle
This test calls Item() requesting the middle of a length g_p_StringSize class_SELString.
Begin
This test calls Begin().
End
This test calls End() on a length g_p_StringSize class_SELString.
Position Middle
This test calls Position() requesting the middle of a length g_p_StringSize class_SEL-
String.
Next
This test calls Next() while both locked out and responsive.
Previous
This test calls Previous() while both locked out and responsive.
Append
This test calls Append() on a class_SELStringList of g_p_StringSize class_SELStrings.
Insert Middle
This test calls Insert() requesting the middle of a class_SELStringList of length g_p_-
StringSize.
RemoveLast
This test calls RemoveLast() on a class_SELStringList of g_p_StringSize class_SEL-
Strings.
Size
This test calls Size() on a class_SELStringList of g_p_StringSize class_SELStrings.
Item Middle
This test calls Item() requesting the middle of a class_SELStringList containing g_p_-
StringSize number of one character class_SELStrings.
Begin
This test calls Begin().
End
This test calls End() on a class_SELStringList of g_p_StringSize class_SELStrings.
Position Middle
This test calls Position() requesting the middle class_SELString of a class_SELStringList
containing g_p_StringSize class_SELStrings.
Next
This test calls Next() while both locked out and responsive.
Previous
This test calls Previous() while both locked out and responsive.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
class_SELString Examples
The following examples demonstrate simple uses of class_SELString.
FromString
ToString
FromByteArray ToByteArray
If data is being read-in from, or out to a communication buffer, it is likely to contain non-
printable characters that are deliberately ignored by the FromString and ToString methods.
This example shows how to accomplish the same thing, using the FromByteArray and
ToByteArray methods, which are able to accept all byte values.
Replace
Split
firstString : STRING;
secondString : STRING;
END_VAR
Trim
Code Snippet 35.6 SELString Trim Example
PROGRAM prg_TrimExample
VAR
selString : class_SELString;
END_VAR
Size
Code Snippet 35.7 SELString Size Example
PROGRAM prg_SizeExample
VAR
selString : class_SELString;
size : UDINT;
END_VAR
Append
Prepend
Insert
Code Snippet 35.10 SELString Insert Example
PROGRAM prg_InsertExample
VAR
firstString : class_SELString;
secondString : class_SELString;
END_VAR
Find
Code Snippet 35.11 SELString Find Example
PROGRAM prg_FindExample
VAR
firstString : class_SELString;
secondString : class_SELString;
index : DINT;
END_VAR
Clear
Code Snippet 35.12 SELString Clear Example
PROGRAM prg_ClearExample
VAR
selString : class_SELString;
END_VAR
Item
Code Snippet 35.13 SELString Item Example
PROGRAM prg_ItemExample
VAR
selString : class_SELString;
character : BYTE;
END_VAR
CopyTo
AppendByteArray
IF RUNONCE THEN
// Populate SELString
selString.FromString('This is a string ');
// AppendByteArray resulting in:
// 'This is a string with appended content.'
selString.AppendByteArray(ADR(stringToAppend), lenStringToAppend);
END_IF
RUNONCE := FALSE;
ToAsciiHex
Code Snippet 35.17 SELString ToAsciiHex Example
PROGRAM prg_ToAsciiHex
VAR
stringInAscii : STRING := 'A';
asciiSELString1 : class_SELString;
hexSELString1 : class_SELString;
asciiSELString2 : class_SELString;
hexSELString2 : class_SELString;
stringInHEX1 : STRING;
stringInHEX2 : STRING;
END_VAR
FromAsciiHex
Code Snippet 35.18 SELString FromAsciiHex Example
PROGRAM prg_FromAsciiHex
VAR
stringInHEX : STRING := '41';
hexSELString1 : class_SELString;
asciiSELString1 : class_SELString;
hexSELString2 : class_SELString;
asciiSELString2 : class_SELString;
stringInAscci1 : STRING;
stringInAscci2 : STRING;
END_VAR
Strip
LeftStrip
RightStrip
class_SELStringList Examples
The following examples demonstrate simple uses of class_SELStringList.
Size
Code Snippet 35.24 SELStringList Size Example
PROGRAM prg_SizeExample
VAR
selString : class_SELString;
selStringList : class_SELStringList;
listSize : UDINT;
END_VAR
Append
Insert
Code Snippet 35.26 SELStringList Insert Example
PROGRAM prg_InsertExample
VAR
selString1 : class_SELString;
selString2 : class_SELString;
selString3 : class_SELString;
selStringList : class_SELStringList;
END_VAR
RemoveLast
Code Snippet 35.27 SELStringList RemoveLast Example
PROGRAM prg_RemoveLastExample
VAR
selString1 : class_SELString;
selString2 : class_SELString;
selStringList : class_SELStringList;
END_VAR
Clear
Code Snippet 35.28 SELStringList Clear Example
PROGRAM prg_ClearExample
VAR
selString1 : class_SELString;
selString2 : class_SELString;
selStringList : class_SELStringList;
END_VAR
Item
Code Snippet 35.29 SELStringList Item Example
PROGRAM prg_ItemExample
VAR
selStringList : class_SELStringList;
firstString : class_SELString;
middleString : class_SELString;
lastString : class_SELString;
Join
Code Snippet 35.31 SELStringList Join Example
PROGRAM prg_JoinExample
VAR
selStringList : class_SELStringList;
firstString : class_SELString;
middleString : class_SELString;
lastString : class_SELString;
delimiter : class_SELString;
joinedString : class_SELString;
END_VAR
SELUtils
Introduction
The SELUtils library is a collection of utility functions and function blocks provided to
meet common RTAC user workflows.
The SELUtils library is included in RTAC projects by default, granting access to the com-
mon functions without the need for users to first add the library to a project. The SELUtils
library does not automatically resolve to the latest version following a project upgrade;
instead, the library will remain at its previous fixed version in the project to ensure that
no functional changes are made when going online with an RTAC. To force the SELUtils
library to resolve to the latest version, use of the Clean Project function in ACSELERATOR
RTAC.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
Enumerations defined in this, the SELUtils library, are positioned to be accessed by various
external libraries in order to reduce redundant enumeration descriptions.
enum_FilenameScheme
Enumeration Description
SEL_FILEIO_LOCAL SEL IEC 61131-3 FileIO Library File Naming Scheme Require-
ments for Local RTAC File System.
INVALID CHARACTERS: ", ', :, <, %, >, ?, \, |, //, /./, /../
SEL_FILEIO_REMOTE SEL IEC 61131-3 FileIO Library File Naming Scheme Require-
ments for Remote Server File Systems.
INVALID CHARACTERS: ", '
enum_RegExOutputTypes
Enumeration Description
JSON_OUTPUT RegEx output file should be generated according to JSON format.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Structures defined in this, the SELUtils library, are positioned to be accessed by various
external libraries in order to reduce redundant structure descriptions.
struct_RegExRule
Name IEC 61131 Type Description
Label STRING(255) Label to be associated with the particular rule speci-
fied; will be used to identify respondent data in resul-
tant RegEx file.
pt_RegEx POINTER TO BYTE Pointer to the first byte of a Regular Expression char-
acterization string; must meet the Perl5 RegEx syntax
requirements; characters that should be escaped (not
treated as control characters) should be preceded by a
double-backslash (e.g., \\)
RegExLength UDINT Number of characters that are contained in the string of
Regular Expression characters referenced by the pt_-
RegEx pointer.
Instances UINT Number of instances that the Regular Expression
should be applied to find sequential results.
Global Constants
This section lists values of math and global constants provided for facilitating work.
Functions
This library provides various utility functions, subroutines that can be utilized by the user.
fun_IsValidReal (Function)
This function accepts a value of type REAL and returns TRUE if it is a valid number.
The function outputs a STRING representation of the value. If the number is valid, the
STRING representation will be the result of calling REAL_TO_STRING on the input. Oth-
erwise, the function will return FALSE and the STRING representation will be 'Infinity',
'-Infinity', or 'NaN' ("Not a Number"), as the value dictates.
Inputs
Name IEC 61131 Type Description
inReal REAL The value to validate.
Outputs
Name IEC 61131 Type Description
stringRepresentation STRING STRING representation of inReal.
Return Value
IEC 61131 Type Description
BOOL TRUE if the value inReal is a valid number.
Processing
ä The function converts inReal to a STRING and assigns the result to output stringRep-
resentation. If inReal is not a valid number, the STRING representation will be
'Infinity', '-Infinity', or 'NaN' ("Not a Number"), as the value dictates.
ä If inReal is a valid number, the function returns TRUE. Otherwise the function re-
turns FALSE.
fun_IsValidLreal (Function)
This function accepts a value of type LREAL and returns TRUE if it is a valid number. The
function outputs a STRING representation of the value. If the number is valid, the STRING
representation will be the result of calling LREAL_TO_STRING on the input. Other-
wise, the function will return FALSE and the STRING representation will be 'Infinity',
'-Infinity', or 'NaN' ("Not a Number"), as the value dictates.
Inputs
Name IEC 61131 Type Description
inLreal LREAL The value to validate.
Outputs
Name IEC 61131 Type Description
stringRepresentation STRING STRING representation of inLreal.
Return Value
IEC 61131 Type Description
BOOL TRUE if the value inLreal is a valid number.
Processing
ä The function converts inLreal to a STRING and assigns the result to output stringRep-
resentation. If inLreal is not a valid number, the STRING representation will be
'Infinity', '-Infinity', or 'NaN' ("Not a Number"), as the value dictates.
ä If inLreal is a valid number, the function returns TRUE. Otherwise the function
returns FALSE.
fun_IsValidFilename (Function)
Function to validate a STRING(255) input representing a filename, returns TRUE if valid
filename without any invalid characters, FALSE otherwise. Invalid character set is desig-
nated by the enum_FilenameScheme input.
Inputs
Name IEC 61131 Type Description
Filename STRING(255) Filename which should be validated.
NameScheme enum_FilenameScheme Filename validation scheme which name should be
validated against.
Return Value
IEC 61131 Type Description
BOOL Indicator of valid filename, TRUE when input does not contain any illegal
characters, FALSE otherwise.
Processing
ä The function validates that each character in the input string is a valid, printable
ASCII character.
ä The function validates that none of the invalid characters described by the NameScheme
input are contained within the input string.
fun_IsValidHexChar (Function)
This function takes a BYTE and determines if it is a valid representation of a hexadecimal
digit in ASCII range 48-57 (0-9), 65-70 (A-F), or 97-102 (a-f).
Inputs
Name IEC 61131 Type Description
character BYTE Byte to be evaluated as a hexadecimal digit.
Return Value
IEC 61131 Type Description
BOOL TRUE if character is a valid hexadecimal notation digit.
Processing
If character is within the ASCII range for hexadecimal digits ( 48-57 (0-9), 65-70 (A-F),
or 97-102 (a-f)), this function returns TRUE. Otherwise, it retuns FALSE.
fun_IsValidHexString (Function)
This function takes a STRING(255) and returns TRUE if all characters are valid hexadec-
imal digits (0-9), (A-F), or (a-f). Otherwise, it returns FALSE.
Inputs
Name IEC 61131 Type Description
Input STRING String to be evaluated as hexadecimal digits.
Return Value
IEC 61131 Type Description
BOOL TRUE if Input contains only valid hexadecimal digits.
Processing
ä Compares each element of the string using fun_IsValidHexChar.
ä Returns TRUE if all characters in STRING are valid hexadecimal digits; otherwise,
returns FALSE.
REAL_TO_FORMATTED_STRING (Function)
This function takes a REAL variable, a BOOLEAN specifying either standard or scientific
notation, and the desired number of decimals to display. It returns a formatted STRING
representing the value of the floating-point number provided.
Inputs
Name IEC 61131 Type Description
inReal REAL The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..5) The number of decimal places to include in the
range [0..5].
Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.
Processing
ä The number inReal is converted to a STRING in either standard or scientific notation,
specified by the useScientificNotation parameter, and with the number of decimal
places specified in the decimals parameter.
ä If the number of decimal places specified is outside of the range [0..5], it defaults to
3.
LREAL_TO_FORMATTED_STRING (Function)
This function takes an LREAL variable, a BOOLEAN specifying either standard or scien-
tific notation, and the desired number of decimals to display. It returns a formatted STRING
representing the value of the floating-point number provided.
Inputs
Name IEC 61131 Type Description
inLreal LREAL The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..13) The number of decimal places to include in the
range [0..13].
Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.
Processing
ä The number inLreal is converted to a STRING in either standard or scientific nota-
tion, specified by the useScientificNotation parameter, and with the number of deci-
mal places specified in the decimals parameter.
ä If the number of decimal places specified is outside of the range [0..13], it defaults
to 3.
ä The formatted STRING is returned.
MV_TO_FORMATTED_STRING (Function)
This function takes an MV variable, a BOOLEAN specifying either standard or scientific
notation, the desired number of decimals to display, and a STRING as a delimiter. It returns
a formatted STRING representing the .instMag component of the MV provided, its time
stamp, and its quality.
Inputs
Name IEC 61131 Type Description
inMV MV The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..5) The number of decimal places to include in the
range [0..5].
delimiterString STRING The character used to separate the contents of
the resultant string. If the character is an empty
string, the output will be in the form: magnitude
[YYYY-MM-DD-hh:mm:ss.000000 / quality].
Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.
Processing
ä The .instMag attribute taken from measured value inMV is converted to a STRING
in either standard or scientific notation, specified by the useScientificNotation pa-
rameter, and with the number of decimal places specified in the decimals parameter
using the REAL_TO_FORMATTED_STRING function.
ä The time when the value was measured is taken using the function TIMESTAMP_-
TO_STRING and added to the formatted string.
ä The quality when the value was measured is taken using the function VALIDITY_-
TO_STRING and added to the formatted string.
ä If an empty string is used as the delimiter, the formatted STRING is returned in the
format: Numeric value [YYYY-MM-DD-hh:mm:ss.000000 / quality]
ä If a comma is used as a delimiter, the formatted STRING is returned in the format:
Numeric value,YYYY-MM-DD-hh:mm:ss.000000,quality
CMV_TO_FORMATTED_STRING (Function)
This function takes a CMV variable, a BOOLEAN specifying either standard or scientific
notation, the desired number of decimals to display, a BOOLEAN specifying either polar
or rectangular coordinates, and a STRING as a delimiter. It returns a formatted STRING
representing the values of the instCVal.mag and instCVal.ang components of the CMV
provided in polar or rectangular coordinates, its timestamp and its quality.
Inputs
Name IEC 61131 Type Description
inCMV CMV The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and
TRUE for scientific notation.
decimals UINT(0..5) The number of decimal places to include in
the range [0..5].
useRectangularCoordinates BOOL Set to FALSE for polar coordinates and
TRUE for rectangular coordinates.
delimiterString STRING The character used to separate the contents
of the resultant string. If the character is
an empty string, the output will be in the
form: (magnitude, angle◦ ) [YYYY-MM-
DD-hh:mm:ss.000000 / quality]
Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.
Processing
ä The .instCVal.mag attribute taken from complex measured value inCMV is converted
to a STRING in either standard or scientific notation, specified by the useScientific-
Notation parameter, and with the number of decimal places specified in the decimals
parameter using the REAL_TO_FORMATTED_STRING function.
ä The .instCVal.ang attribute taken from complex measured value inCMV is converted
to a STRING using two decimal places.
ä If useRectangularCoordinates is set to TRUE, the rectangular coordinates are ob-
tained using the function vector_t_TO_struct_ComplexRect.
ä The time when the value was measured is taken using the function TIMESTAMP_-
TO_STRING and added to the formatted string.
ä The quality when the value was measured is taken using the function VALIDITY_-
TO_STRING and added to the formatted string.
ä If useRectangularCoordinates is set to TRUE, and a comma is used as the delimiter,
the formatted STRING is returned in the format: real ±imaginary,YYYY-MM-DD-
hh:mm:ss.000000,quality
ä If useRectangularCoordinates is set to FALSE, and an empty string is used as the
delimiter, the formatted STRING is returned in the format: (magnitude, angle◦ )
[YYYY-MM-DD-hh:mm:ss.000000 / quality]
ä If useRectangularCoordinates is set to FALSE, and a comma is used as a delimiter,
the formatted STRING is returned in the format: magnitude,angle◦ ,YYYY-MM-
DD-hh:mm:ss.000000,quality
INS_TO_FORMATTED_STRING (Function)
This function takes an INS variable, a BOOLEAN specifying either standard or scientific
notation, the desired number of decimals to display, and a STRING as a delimiter. It returns
a formatted STRING representing the value of the .stVal component of the INS provided,
its time stamp, and its quality.
Inputs
Name IEC 61131 Type Description
inINS INS The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..5) The number of decimal places to include in the
range [0..5].
delimiterString STRING The character used to separate the contents
of the resultant string. If the character
is an empty string, the output will be in
the form: Numeric Value [YYYY-MM-DD-
hh:mm:ss.000000 / quality]
Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.
Processing
ä The .stVal attribute taken from the value inINS is converted to a STRING in ei-
ther standard or scientific notation, specified by the useScientificNotation parameter,
and with the number of decimal places specified in the decimals parameter using
the REAL_TO_FORMATTED_STRING function and DINT_TO_REAL conver-
sion operator. Note that the number of decimals is only considered if useScientific-
Notation is TRUE.
ä The time when the value was measured is taken using the function TIMESTAMP_-
TO_STRING and added to the formatted string.
ä The quality when the value was measured is taken using the function VALIDITY_-
TO_STRING and added to the formatted string.
ä If an empty string is used as the delimiter, the formatted STRING is returned in the
format: Numeric value [YYYY-MM-DD-hh:mm:ss.000000 / quality]
ä If a comma is used as a delimiter, the formatted STRING is returned in the format:
Numeric value,YYYY-MM-DD-hh:mm:ss.000000,quality
SPS_TO_FORMATTED_STRING (Function)
This function takes an SPS variable, a BOOLEAN specifying either boolean (TRUE/-
FALSE) or numeric notation (1/0), and a STRING as a delimiter. It returns a formatted
STRING representing the .stVal component of the SPS provided, its time stamp, and its
quality.
Inputs
Name IEC 61131 Type Description
inSPS SPS The value to format as a STRING.
useNumericNotation BOOL Set to FALSE for boolean notation (TRUE/-
FALSE) for numeric notation (1/0).
delimiterString STRING The character used to separate the contents of the
resultant string. If the character is an empty string,
the output will be in the form: Boolean State
[YYYY-MM-DD-hh:mm:ss.000000 / quality]
Return Value
IEC 61131 Type Description
STRING(255) The formatted boolean represented as a STRING.
Processing
ä The .stVal attribute taken from the status inSPS is converted to a STRING in either
boolean or numeric notation, specified by the useNumericNotation parameter.
ä If the numeric notation is set to TRUE, the formatted STRING is returned with a 1
or a 0 for the status of the BOOLEAN attribute.
ä The time when the value was measured is taken using the function TIMESTAMP_-
TO_STRING and added to the formatted string.
ä The quality when the value was measured is taken using the function VALIDITY_-
TO_STRING and added to the formatted string.
ä If an empty string is used as the delimiter, the formatted STRING is returned in the
format: Boolean Status [YYYY-MM-DD-hh:mm:ss.000000 / quality]
ä If a comma is used as a delimiter, the formatted STRING is returned in the format:
Boolean Status,YYYY-MM-DD-hh:mm:ss.000000,quality
BCR_TO_FORMATTED_STRING (Function)
This function takes a BCR variable, a BOOLEAN specifying either standard or scientific
notation, the desired number of decimals to display, and a STRING as a delimiter. It returns
a formatted STRING representing the value of the .actVal and the .frVal components of the
BCR provided, its time stamp, and its quality.
Inputs
Name IEC 61131 Type Description
inBCR BCR The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..5) The number of decimal places to include in the
range [0..5].
delimiterString STRING The character used to separate the contents of
the resultant string. If the character is an empty
string, the output will be in the form: Nu-
meric Value / Numeric Value [YYYY-MM-DD-
hh:mm:ss.000000 / quality]
Return Value
IEC 61131 Type Description
STRING(255) The formatted values represented as a STRING.
Processing
ä The .actVal and .frVal components taken from the value inBNC are converted to a
STRING in either standard or scientific notation, specified by the useScientificNo-
tation parameter, and with the number of decimal places specified in the decimals
parameter using the REAL_TO_FORMATTED_STRING function and UDINT_-
TO_REAL conversion operator. Note that the number of decimals is only considered
if useScientificNotation is TRUE.
ä The time when the value was measured is taken using the function TIMESTAMP_-
TO_STRING and added to the formatted string.
ä The quality when the value was measured is taken using the function VALIDITY_-
TO_STRING and added to the formatted string.
ä If an empty string is used as the delimiter, the formatted STRING is returned in
the format: Numeric value / Numeric value [YYYY-MM-DD-hh:mm:ss.000000 /
quality]
ä If a comma is used as a delimiter, the formatted STRING is returned in the format:
Numeric value,Numeric value,YYYY-MM-DD-hh:mm:ss.000000,quality
TIMESTAMP_TO_STRING (Function)
This function takes a timestamp_t structure and returns it as a STRING in the form YYYY-
MM-DD-hh:mm:ss.000000. For example, 2018-08-02-23:43:07.364814 represents the Au-
gust 2nd, 2018, at 43 minutes, 7 seconds, and 364814 microseconds into the 23rd hour.
Inputs
Name IEC 61131 Type Description
inTimestamp timestamp_t The time stamp to convert to a STRING.
Return Value
IEC 61131 Type Description
STRING(80) The timestamp_t structure represented as a STRING.
Processing
ä The timestamp_t structure is returned as a STRING in the form YYYY-MM-DD-
hh:mm:ss.000000.
TIMESTAMP_TO_UTC (Function)
This function takes a timestamp_t structure and returns a timeStamp_t adjusted to UTC
time, based on the offsets in the timeStamp_t that is passed in.
The resulting timeStamp_t structure will be identical to the structure passed in, except that
the DST and UTC offsets will be set to zero, and the time will be adjusted to UTC.
Inputs
Name IEC 61131 Type Description
timeStampIn timeStamp_t The time stamp to convert to a UTC.
Return Value
IEC 61131 Type Description
timeStamp_t The timestamp_t structure adjusted to UTC.
Processing
ä The returned timestamp_t structure contains a time stamp in UTC that is derived
from the time stamp, DST offset (taking into account the DST enabled and active
statuses), and UTC offset of the timestamp_t structure that is passed in. The DST
and UTC offset for the returned timestamp_t structure are set to zero.
fun_WrapTo360 (Function)
This function takes a REAL representing an angle in degrees and returns a REAL wrapped
between 0 and 360 degrees. This function will apply formatting to ensure that angles con-
form with the limits of 0 and 360 (inclusive of zero). Inputs with angles which do not
conform will be adjusted accordingly. Such examples of these angles are:
ä Negative angles (i.e., −45◦ )
ä Angles whose absolute value is greater than 360 (i.e., ±520◦ )
Inputs
Name IEC 61131 Type Description
Input REAL The REAL representing an angle to be wrapped.
Return Value
IEC 61131 Type Description
REAL The REAL variable whose angle has been wrapped between 0 and 360
degrees.
Processing
ä The magnitude, time, and quality attributes are directly mapped from input to output,
and the angle will be wrapped to fit within the boundaries of 0 and 360 degrees.
fun_WrapTo180 (Function)
This function takes a REAL representing an angle in degrees and returns a REAL wrapped
between -180 and 180 degrees. This function will apply formatting to ensure that angles
conform with the limits of -180 and 180 (inclusive of 180). Inputs with angles which do
not conform will be adjusted accordingly. Such examples of these angles are:
ä Angles evaluated between 180 and 360 degrees (i.e., −270◦ )
ä Angles whose absolute value is greater than 360 (i.e., ±520◦ )
Inputs
Name IEC 61131 Type Description
Input REAL The REAL representing an angle to be wrapped.
Return Value
IEC 61131 Type Description
REAL The REAL variable whose angle has been wrapped between -180 and 180
degrees.
Processing
ä The magnitude, time, and quality attributes are directly mapped from input to output,
and the angle will be wrapped to fit within the boundaries of -180 and 180 degrees.
fun_dateTime_t_TO_ULINT (Function)
This function takes a dateTime_t structure and returns a ULINT representing the time since
epoch (1970-01-01:00:00:00.000000) in units of microseconds.
Inputs
Name IEC 61131 Type Description
Input dateTime_t The date time to convert to a ULINT.
Return Value
IEC 61131 Type Description
ULINT Representation of Input in units of microseconds since epoch (1970-01-
01:00:00:00.000000).
Processing
ä Both dateTime and uSec structure components are converted to ULINT representa-
tions and scaled such that they represent microseconds before being added together
and returned.
fun_ULINT_TO_dateTime_t (Function)
This function takes a ULINT representing microseconds since epoch (1970-01-01:00:00:00.000000)
and returns a dateTime_t structure evaluation of the ULINT.
Inputs
Name IEC 61131 Type Description
Input ULINT The ULINT storing time in units of microseconds since epoch
(1970-01-01:00:00:00.000000) to be converted.
Return Value
IEC 61131 Type Description
dateTime_t Representation of Input ULINT in microseconds.
Processing
ä Both dateTime and uSec structure components are constructed using a decomposi-
tion of the ULINT.
fun_AddTIME (Function)
This function adds an input TIME quantity to an input dateTime_t quantity and returns an
adjusted dateTime_t quantity.
Inputs
Name IEC 61131 Type Description
TimeToAdd TIME Amount of time to add to the reference input.
DateTimeIn dateTime_t Reference input time stamp to be adjusted by TimeToAdd.
Return Value
IEC 61131 Type Description
dateTime_t The effective addition of TimeToAdd and DateTimeIn.
Processing
ä Both the dateTime_t value and the TIME are converted to their ULINT representa-
tions before the TIME value is added to the dateTime_t value.
ä If the resultant ULINT experiences a rollover in the positive direction (effectively
passes zero and becomes a very small number) the ULINT will be forced to
264 − 1
, thus preparing the returned dateTime_t to represent the maximum supported time
for the dateTime_t structure.
ä The resultant ULINT is converted back to a dateTime_t structure.
fun_AddLTIME (Function)
This function adds an input LTIME quantity to an input dateTime_t quantity and returns
an adjusted dateTime_t quantity.
Inputs
Name IEC 61131 Type Description
TimeToAdd LTIME Amount of time to add to the reference input.
DateTimeIn dateTime_t Reference input time stamp to be adjusted by TimeToAdd.
Return Value
IEC 61131 Type Description
dateTime_t The effective addition of TimeToAdd and DateTimeIn.
Processing
ä Both the dateTime_t value and the LTIME are converted to their ULINT represen-
tations before the LTIME value is added to the dateTime_t value.
ä If the resultant ULINT experiences a rollover in the positive direction (effectively
passes zero and becomes a very small number) the ULINT will be forced to
264 − 1
, thus preparing the returned dateTime_t to represent the maximum supported time
for the dateTime_t structure.
ä The resultant ULINT is converted back to a dateTime_t structure.
fun_SubtractTIME (Function)
This function subtracts an input TIME quantity from an input dateTime_t quantity and
returns an adjusted dateTime_t quantity.
Inputs
Name IEC 61131 Type Description
TimeToSubtract TIME Amount of time to subtract from the reference input.
DateTimeIn dateTime_t Reference input time stamp to be adjusted by TimeTo-
Subtract.
Return Value
IEC 61131 Type Description
dateTime_t The effective subtraction of TimeToSubtract from DateTimeIn.
Processing
ä Both the dateTime_t value and the TIME are converted to their ULINT representa-
tions before the TIME value is subtracted from the dateTime_t value.
ä If the resultant ULINT experiences a rollover in the negative direction (effectively
passes zero and becomes a very large number) the ULINT will be forced to zero,
thus preparing the returned dateTime_t to represent the epoch.
ä The resultant ULINT is converted back to a dateTime_t structure.
fun_SubtractLTIME (Function)
This function subtracts an input LTIME quantity from an input dateTime_t quantity and
returns an adjusted dateTime_t quantity.
Inputs
Name IEC 61131 Type Description
TimeToSubtract LTIME Amount of time to subtract from the reference input.
DateTimeIn dateTime_t Reference input time stamp to be adjusted by TimeTo-
Subtract.
Return Value
IEC 61131 Type Description
dateTime_t The effective subtraction of TimeToSubtract from DateTimeIn.
Processing
ä Both the dateTime_t value and the LTIME are converted to their ULINT represen-
tations before the LTIME value is subtracted from the dateTime_t value.
ä If the resultant ULINT experiences a rollover in the negative direction (effectively
passes zero and becomes a very large number) the ULINT will be forced to zero,
thus preparing the returned dateTime_t to represent the epoch.
ä The resultant ULINT is converted back to a dateTime_t structure.
fun_Checksum (Function)
This function accepts a pointer to BYTE and array length input and evaluates the sum of
ASCII encoded values, returning a string representing the summation as a hex string. The
resulting string will be clamped to the range of a WORD variable (0 to 65535), and thus
will always be 4 ASCII characters in length.
Inputs
Name IEC 61131 Type Description
pt_Byte POINTER TO BYTE Pointer to the first character in a string or array of bytes whose
values should be evaluated using a checksum.
Length UDINT Number of bytes in array which should be evaluated in the
checksum.
Return Value
IEC 61131 Type Description
STRING(4) The hex string representing the output sum of all input bytes.
Processing
ä The ASCII values of each character in the input string are summed.
ä The summation result is converted to a string representing the number in hex.
fun_GetBit (Function)
This function allows a bit-level read operation from a bit pattern stored in a BYTE, WORD,
DWORD, or LWORD data type. Returns FALSE and does no work if the BitIndex input is
out of bounds for the given datatype.
Inputs
Name IEC 61131 Type Description
InPattern ANY_BIT Input bit pattern to be analyzed. Accepts BYTE, WORD,
DWORD, and LWORD data types.
BitIndex UINT Zero-based index of bit status to retrieve from InPattern.
Outputs
Name IEC 61131 Type Description
BitStatus BOOL Boolean status of the bit at BitIndex.
Return Value
IEC 61131 Type Description
BOOL TRUE if bit status was successfully retrieved.
Processing
ä Loads BitStatus with the status of the InPattern bit at BitIndex if the following are
true:
â The data type of the variable passed into InPattern is included in the specified
list.
â The BitIndex is within the range of allowed bit indexes for that data type.
(BYTE : 0-7, WORD : 0-15, DWORD : 0-31, LWORD : 0-63)
fun_SetBit (Function)
This function allows a bit-level write operation to a bit pattern stored in a BYTE, WORD,
DWORD, or LWORD data type. Returns FALSE and does no work if the BitIndex input is
out of bounds for the given datatype.
Inputs
Name IEC 61131 Type Description
InPattern ANY_BIT Input bit pattern to be written to. Accepts BYTE, WORD,
DWORD, and LWORD data types.
BitIndex UINT Zero-based index of bit to overwrite within InPattern.
SetVal BOOL The value with which to overwrite the InPattern bit at BitIn-
dex.
Return Value
IEC 61131 Type Description
BOOL TRUE if bit was successfully overwritten.
Processing
ä Overwrites the InPattern bit at BitIndex with SetVal if the following are true:
â The data type of the variable passed into InPattern is included in the specified
list.
â The BitIndex is within the range of allowed bit indexes for that data type.
(BYTE : 0-7, WORD : 0-15, DWORD : 0-31, LWORD : 0-63)
VALIDITY_TO_STRING (Function)
This function takes a validity_t enumeration and returns the validity as a STRING (good,
invalid, reserved, questionable, or undefined).
Inputs
Name IEC 61131 Type Description
inValidity validity_t The validity_t enumeration to convert to a STRING.
Return Value
IEC 61131 Type Description
STRING(80) The validity represented as a STRING.
Processing
ä The validity_t enumeration is returned as a STRING (good, invalid, reserved,
or questionable).
ä undefined will be returned for a malformed validity_t.
BYTE_TO_ASCII (Function)
This function takes a BYTE and returns the STRING character representation of the ASCII
character code of the BYTE.
Inputs
Name IEC 61131 Type Description
character BYTE The BYTE for which the ASCII representation should be eval-
uated.
Return Value
IEC 61131 Type Description
STRING(1) The ASCII representation of the input BYTE.
Processing
ä The ASCII character code representation of the input BYTE is evaluated as a STRING(1).
BYTE_TO_HEX_STRING (Function)
This function takes a BYTE and returns the STRING of the byte’s numeric representation
encoded in hex.
Inputs
Name IEC 61131 Type Description
Input BYTE The BYTE for which the hex representation should be evaluated.
Return Value
IEC 61131 Type Description
STRING(2) The hex representation of the numeric value of the input BYTE.
Processing
ä The hex-encoded numeric representation of the input BYTE is evaluated as a STRING.
HEX_STRING_TO_BYTE (Function)
This function takes a STRING(2) representing the two-character ASCII representation of
a single byte and returns the BYTE equivalent.
Inputs
Name IEC 61131 Type Description
Input STRING(2) The hexadecimal STRING whose value should be converted to
a plain byte.
Return Value
IEC 61131 Type Description
BYTE The byte representation of the HEX input.
Processing
ä The string representing the HEX ASCII characters is converted to a BYTE.
ä Single-character strings are considered as two-character strings by appending a lead-
ing zero.
ä If an invalid character is found in the string, the function returns zero.
WORD_TO_HEX_STRING (Function)
This function takes a WORD and returns the STRING of the word’s numeric representation
encoded in hex.
Inputs
Name IEC 61131 Type Description
Input WORD The WORD for which the hex representation should be evalu-
ated.
Return Value
IEC 61131 Type Description
STRING(4) The hex representation of the numeric value of the input WORD.
Processing
ä The hex-encoded numeric representation of the input WORD is evaluated as a STRING.
HEX_STRING_TO_WORD (Function)
This function takes a STRING(4) representing the four-character evaluation of a single
word and returns the word equivalent.
Inputs
Name IEC 61131 Type Description
Input STRING(4) The HEX STRING for which the word representation should be
evaluated.
Return Value
IEC 61131 Type Description
WORD The WORD representation of the HEX input.
Processing
ä The string representing the HEX ASCII characters is converted to a WORD.
ä Strings whose length is less than four are considered as a four-character string by
appending the required leading zeros.
ä If an invalid character is found in the string, the function returns zero.
DWORD_TO_HEX_STRING (Function)
This function takes a DWORD and returns the STRING of the double-word’s numeric
representation encoded in hex.
Inputs
Name IEC 61131 Type Description
Input DWORD The DWORD for which the hex representation should be evalu-
ated.
Return Value
IEC 61131 Type Description
STRING(8) The hex representation of the numeric value of the input DWORD.
Processing
ä The hex-encoded numeric representation of the input DWORD is evaluated as a
STRING.
HEX_STRING_TO_DWORD (Function)
This function takes a STRING(8) representing the eight-character evaluation of a double-
word in hex notation and returns the DWORD equivalent.
Inputs
Name IEC 61131 Type Description
Input STRING(8) The HEX STRING for which the DWORD representation
should be evaluated.
Return Value
IEC 61131 Type Description
DWORD The DWORD representation of the HEX input.
Processing
ä The string representing the HEX ASCII characters is converted to a DWORD.
ä Strings whose length is less than eight are considered as an eight-character string by
appending the required leading zeros.
ä If an invalid character is found in the string, the function returns zero.
fun_PadString (Function)
Function to pad a string with a character (either appending or prepending) the string with
the character repeatedly until the length of the concatenated string is equal to the desired
total length.
Inputs
Name IEC 61131 Type Description
InString STRING(255) The input string which should be appended or optionally
prepended with padding characters.
Character STRING(1) Single character which should be appended (or optionally
prepended) to the input string iteratively to create a string
of length TotalLength.
TotalLength INT Control to specify the total number of characters that the
output should be; if the input length is of greater value the
input string will be returned. A negative TotalLength value
will force the function to prepend padding characters rather
than appending them.
Return Value
IEC 61131 Type Description
STRING(255) Padded string which will be appended (or prepended) with repeated in-
put ‘Character‘ until the string’s length is equal to the TotalLength input
(unless the input string is of greater length than TotalLength).
Processing
ä Determination is made whether operation appends, or prepends.
ä If the TotalLength input is greater than the initial length of the InString, the Character
input will be concatenated with the InString until the length of the joined string is
equal to TotalLength.
ComposeApparentPower (Function)
This function takes two REAL inputs representing the voltage and current magnitudes with
a third REAL input representing a scale factor (multiplier), and returns the evaluated mag-
nitude of apparent (the combination of real and reactive power components) power. The
formula for this calculation is evaluated as follows where S is the apparent power value.
Inputs
Name IEC 61131 Type Description
Voltage REAL The REAL representing the voltage magnitude.
Current REAL The REAL representing the current magnitude.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
REAL The apparent power calculated from input current and voltage.
Processing
ä The apparent power is calculated as the product of the current and voltage.
MVComposeApparentPower (Function)
This function takes two MV inputs representing the voltage and current magnitudes with a
third REAL input representing a scale factor (multiplier), and returns the evaluated mag-
nitude of apparent (the combination of real and reactive power components) power. The
formula for this calculation is evaluated as follows where S is the apparent power value.
Inputs
Name IEC 61131 Type Description
Voltage MV The MV representing the voltage magnitude.
Current MV The MV representing the current magnitude.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
MV The apparent power calculated from input current and voltage.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The apparent power is calculated as the product of the current and voltage.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
CMVComposeApparentPower (Function)
This function takes two CMV inputs providing complex (magnitude/angle) representations
of the voltage and current with a third REAL input representing a scale factor (multiplier)
for the calculation, and returns the evaluated apparent (the combination of real and reactive
power components) power. The formula for this calculation is evaluated as follows, where
S is the apparent power value.
|S| = |V | · |I|
S= V − I
Inputs
Name IEC 61131 Type Description
Voltage CMV The CMV representing the voltage magnitude and angle.
Current CMV The CMV representing the current magnitude and angle.
Scale REAL The REAL representing the scale factor (a multiplier) for the
magnitude.
Return Value
IEC 61131 Type Description
CMV The apparent power magnitude and angle calculated from input current
and voltage.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The apparent power magnitude is calculated as the product of the current and voltage
magnitudes.
ä The apparent power angle is calculated as the difference between the voltage and
current angles.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
ComposePF (Function)
This function takes two REAL inputs representing the voltage and current angles measured
in degrees and a scale factor (multiplier) and returns the evaluated magnitude of power
factor. The formula for this calculation is evaluated as follows, where PF is the power
factor value.
The formula will evaluate the sign (indicating direction of power flow) according to the
angle difference between the values. Should the absolute value of the angle difference be
between 0 and 90 degrees, the sign will be positive. All other values will result in a negative
quantity.
Inputs
Name IEC 61131 Type Description
VoltageAngle REAL The REAL representing the voltage angle in degrees.
CurrentAngle REAL The REAL representing the current angle in degrees.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
REAL The power factor calculated from input voltage and current angles.
Processing
ä The power factor is calculated using the formula shown above.
CMVComposePF (Function)
This function takes two CMV inputs representing the voltage and current angles measured in
degrees and a scale factor (multiplier) and returns the evaluated magnitude of power factor.
The formula for this calculation is evaluated as follows, where PF is the power factor value.
The formula will evaluate the sign (indicating direction of power flow) according to the
angle difference between the values. Should the absolute value of the angle difference be
between 0 and 90 degrees, the sign will be positive. All other values will result in a negative
quantity.
Inputs
Name IEC 61131 Type Description
Voltage CMV The CMV representing the voltage magnitude and angle.
Current CMV The CMV representing the current magnitude and angle.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
MV The power factor calculated from input voltage and current angles.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The power factor is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
ComposeVAR (Function)
This function takes four REAL inputs representing the voltage magnitude, current magni-
tude, voltage angle, and current angle with a fifth input representing a scale factor multiplier
and returns the evaluated magnitude of reactive power. The formula for this calculation is
evaluated as follows, where Q is the reactive power value.
Inputs
Name IEC 61131 Type Description
VoltageMagnitude REAL The REAL representing the voltage magnitude.
CurrentMagnitude REAL The REAL representing the current magnitude.
VoltageAngle REAL The REAL representing the voltage angle.
CurrentAngle REAL The REAL representing the current angle.
Scale REAL The REAL representing the scale factor (a multi-
plier).
Return Value
IEC 61131 Type Description
REAL The reactive power calculated from input voltage and current.
Processing
ä The reactive power is calculated using the formula shown above.
MVComposeVAR (Function)
This function takes four MV inputs representing the voltage magnitude, current magnitude,
voltage angle, and current angle with a fifth input representing a scale factor multiplier
and returns the evaluated magnitude of reactive power. The formula for this calculation is
evaluated as follows, where Q is the reactive power value.
Inputs
Name IEC 61131 Type Description
VoltageMagnitude MV The MV representing the voltage magnitude.
CurrentMagnitude MV The MV representing the current magnitude.
VoltageAngle MV The MV representing the voltage angle.
CurrentAngle MV The MV representing the current angle.
Scale REAL The REAL representing the scale factor (a multi-
plier).
Return Value
IEC 61131 Type Description
MV The reactive power calculated from input voltage and current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The reactive power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output time stamp.
CMVComposeVAR (Function)
This function takes two CMV inputs representing the voltage and current magnitudes and
angles with a third input representing a scale factor multiplier and returns the evaluated
magnitude of reactive power as an MV. The formula for this calculation is evaluated as
follows, where Q is the reactive power value.
Inputs
Name IEC 61131 Type Description
Voltage CMV The CMV representing the voltage magnitude and angle.
Current CMV The CMV representing the current magnitude and angle.
Scale REAL The REAL representing the scale factor (a multiplier) for the
magnitude.
Return Value
IEC 61131 Type Description
MV The reactive power calculated from input voltage and current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The reactive power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
ComposeWatts (Function)
This function takes three REAL inputs representing the voltage, current, and power factor
magnitudes with a fourth input representing a scale factor magnitude, and returns the eval-
uated magnitude of real power. The formula for this calculation is evaluated as follows,
where P is the reactive power value.
|P | = |V | · |I| · PF · SCALE
Inputs
Name IEC 61131 Type Description
Voltage REAL The REAL representing the voltage magnitude.
Current REAL The REAL representing the current magnitude.
PF REAL The REAL representing the power factor.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
REAL The real power calculated from input voltage, current, and power factor.
Processing
ä The real power is calculated using the formula shown above.
MVComposeWatts (Function)
This function takes three MV inputs representing the voltage, current, and power factor mag-
nitudes with a fourth input representing a scale factor magnitude, and returns the evaluated
magnitude of real power. The formula for this calculation is evaluated as follows, where P
is the reactive power value.
|P | = |V | · |I| · PF · SCALE
Inputs
Name IEC 61131 Type Description
Voltage MV The MV representing the voltage magnitude.
Current MV The MV representing the current magnitude.
PF MV The MV representing the power factor.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
MV The real power calculated from input voltage, current, and power factor.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The real power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
CMVComposeWatts (Function)
This function takes two CMV inputs representing the voltage and current magnitudes and
angles and a third input representing a scale factor magnitude and returns the evaluated
magnitude of real power as an MV. The formula for this calculation is evaluated as follows,
where P is the reactive power value.
Inputs
Name IEC 61131 Type Description
Voltage CMV The CMV representing the voltage magnitude.
Current CMV The CMV representing the current magnitude.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
MV The real power calculated from input voltage and current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The real power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
WATT_VAR_TO_VA (Function)
This function takes two REAL inputs representing the real and reactive power magnitudes
and returns the evaluated magnitude of apparent (combined real and reactive) power. The
formula for this calculation is evaluated as follows, where S is the apparent power value.
p
|S| = |PMAG |2 + |QMAG |2
Inputs
Name IEC 61131 Type Description
Watts REAL The REAL representing the real power magnitude.
VARs REAL The REAL representing the reactive power magnitude.
Return Value
IEC 61131 Type Description
REAL The apparent power calculated from input real and reactive power magni-
tudes.
Processing
ä The apparent power magnitude is calculated using the formula shown above.
MV_WATT_VAR_TO_VA (Function)
This function takes two MV inputs representing the real and reactive power magnitudes
and returns the evaluated magnitude of apparent (combined real and reactive) power. The
formula for this calculation is evaluated as follows, where S is the apparent power value.
p
|S| = |PMAG |2 + |QMAG |2
Inputs
Name IEC 61131 Type Description
Watts MV The MV representing the real power magnitude.
VARs MV The MV representing the reactive power magnitude.
Return Value
IEC 61131 Type Description
MV The apparent power magnitude calculated from input real and reactive
power magnitudes.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The apparent power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
VA_WATT_TO_VAR (Function)
This function takes two REAL inputs representing the apparent and real power magnitudes
and returns the evaluated magnitude of reactive (imaginary) power. The formula for this
calculation is evaluated as follows, where Q is the reactive power value.
p
|Q| = |SMAG |2 − |PMAG |2
Inputs
Name IEC 61131 Type Description
VAs REAL The REAL representing the apparent power magnitude.
Watts REAL The REAL representing the real power magnitude.
Return Value
IEC 61131 Type Description
REAL The reactive (imaginary) power magnitude calculated from input real and
apparent power magnitudes.
Processing
ä The reactive power is calculated using the formula shown above.
MV_VA_WATT_TO_VAR (Function)
This function takes two MV inputs representing the apparent and real power magnitudes
and returns the evaluated magnitude of reactive (imaginary) power. The formula for this
calculation is evaluated as follows, where Q is the reactive power value.
p
|Q| = |SMAG |2 − |PMAG |2
Inputs
Name IEC 61131 Type Description
VAs MV The MV representing the apparent power magnitude.
Watts MV The MV representing the real power magnitude.
Return Value
IEC 61131 Type Description
MV The reactive (imaginary) power magnitude calculated from input real and
apparent power magnitudes.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The reactive power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
VA_VAR_TO_WATT (Function)
This function takes two REAL inputs representing the apparent and reactive power mag-
nitudes and returns the evaluated magnitude of real (active) power. The formula for this
calculation is evaluated as follows, where P is the reactive power value.
p
|P | = |SMAG |2 − |QMAG |2
Inputs
Name IEC 61131 Type Description
VAs REAL The REAL representing the apparent power magnitude.
VARs REAL The REAL representing the reactive power magnitude.
Return Value
IEC 61131 Type Description
REAL The real (active) power magnitude calculated from input real and apparent
power magnitudes.
Processing
ä The real power is calculated using the formula shown above.
MV_VA_VAR_TO_WATT (Function)
This function takes two MV inputs representing the apparent and reactive power magnitudes
and returns the evaluated magnitude of real (active) power. The formula for this calculation
is evaluated as follows, where P is the real power value.
p
|P | = |SMAG |2 − |QMAG |2
Inputs
Name IEC 61131 Type Description
VAs MV The MV representing the apparent power magnitude.
VARs MV The MV representing the reactive power magnitude.
Return Value
IEC 61131 Type Description
MV The real (active) power magnitude calculated from input real and apparent
power magnitudes.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The real power is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
MV_VA_W_VAR_TO_PF (Function)
This function takes three MV inputs representing the apparent power, real power, and reactive
power measured in VA, W, and VAR and a scale factor (multiplier). It returns the evaluated
magnitude of the power factor. The formula for this calculation is evaluated as follows,
where PF is the power factor value.
PF = (P/S) ∗ scale
Worth noting is the fact that this function follows the convention where a “lagging” power
factor is the result of a measured positive real power and a positive reactive power, or a
negative real power and a negative reactive power.
Conversely, a “leading” power factor is found when the measured real power is positive
and the reactive power is negative, or when the measured real power is negative and the
reactive power is positive.
According to this convention, lagging values are represented as positive numbers while
leading values are represented as negative.
Inputs
Name IEC 61131 Type Description
ApparentPower MV The MV representing the apparent power in VA.
RealPower MV The MV representing the real power in W.
ReactivePower MV The MV representing the reactive power in VAR.
Scale REAL The REAL representing the scale factor (a multiplier).
Return Value
IEC 61131 Type Description
MV The power factor calculated from the relation between real power and ap-
parent power.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The .instMag attributes of the MV input values are verified to be valid REALs with
the function fun_IsValidReal.
ä The power factor is calculated using the formula shown above.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output time stamp.
VLL_TO_VLN (Function)
This function takes a single REAL input representing the line-to-line voltage magnitude
and returns the evaluated magnitude of the line-to-neutral voltage. The formula for this
calculation is evaluated as follows.
|Vline-to-line |
|Vline-to-neutral | = √
3
Inputs
Name IEC 61131 Type Description
VLL REAL The REAL representing the line-to-line voltage magnitude.
Return Value
IEC 61131 Type Description
REAL The line-to-neutral voltage calculated from input line-to-line voltage.
Processing
ä The line-to-neutral voltage magnitude is calculated using the formula shown above.
MV_VLL_TO_VLN (Function)
This function takes a single MV input representing the line-to-line voltage magnitude and
returns the evaluated magnitude of the line-to-neutral voltage. The formula for this calcula-
tion is evaluated as follows. This formula is only valid under balanced, three-phase system
conditions.
|Vline-to-line |
|Vline-to-neutral | = √
3
Inputs
Name IEC 61131 Type Description
VLL MV The MV representing the line-to-line voltage magnitude.
Return Value
IEC 61131 Type Description
MV The line-to-neutral voltage calculated from input line-to-line voltage.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The line-to-neutral voltage magnitude is calculated using the formula shown above.
CMV_VLL_TO_VLN (Function)
This function takes a single CMV input representing the line-to-line voltage magnitude and
angle and returns the evaluated magnitude and angle of the line-to-neutral voltage. The for-
mula for this calculation is evaluated as follows. This formula is only valid under balanced,
three-phase system conditions.
Vline-to-line
Vline-to-neutral = √
3 30
Inputs
Name IEC 61131 Type Description
VLL CMV The CMV representing the line-to-line voltage magnitude.
Return Value
IEC 61131 Type Description
CMV The line-to-neutral voltage calculated from input line-to-line voltage.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The line-to-neutral voltage magnitude is calculated using the formula shown above.
VLN_TO_VLL (Function)
This function takes a single REAL input representing the line-to-neutral voltage magnitude
and returns the evaluated magnitude of the line-to-line voltage. The formula for this cal-
culation is evaluated as follows. This formula is only valid under balanced, three-phase
system conditions.
√
|Vline-to-line | = |Vline-to-neutral | · 3
Inputs
Name IEC 61131 Type Description
VLN REAL The REAL representing the line-to-neutral voltage magnitude.
Return Value
IEC 61131 Type Description
REAL The line-to-line voltage calculated from input line-to-neutral voltage.
Processing
ä The line-to-line voltage magnitude is calculated using the formula shown above.
MV_VLN_TO_VLL (Function)
This function takes a single MV input representing the line-to-neutral voltage magnitude and
returns the evaluated magnitude of the line-to-line voltage. The formula for this calculation
is evaluated as follows. This formula is only valid under balanced, three-phase system
conditions.
√
|Vline-to-line | = |Vline-to-neutral | · 3
Inputs
Name IEC 61131 Type Description
VLN MV The MV representing the line-to-neutral voltage magnitude.
Return Value
IEC 61131 Type Description
MV The line-to-line voltage calculated from input line-to-neutral voltage.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The line-to-line voltage magnitude is calculated using the formula shown above.
CMV_VLN_TO_VLL (Function)
This function takes a single CMV input representing the line-to-neutral voltage magnitude
and angle and returns the evaluated magnitude and angle of the line-to-line voltage. The
formula for this calculation is evaluated as follows. This formula is only valid under bal-
anced, three-phase system conditions.
√
Vline-to-line = Vline-to-neutral · 3 30
Inputs
Name IEC 61131 Type Description
VLN CMV The CMV representing the line-to-neutral voltage magnitude.
Return Value
IEC 61131 Type Description
CMV The line-to-line voltage calculated from input line-to-neutral voltage.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The line-to-line voltage magnitude is calculated using the formula shown above.
ä The line-to-line voltage angle is calculated by adding an additional thirty degrees.
IP_TO_IL (Function)
This function takes a single REAL input representing the phase-current magnitude and re-
turns the evaluated magnitude of the line-current. The formula for this calculation is evalu-
ated as follows. This formula is only valid under balanced, three-phase system conditions.
√
|Iline | = |Iphase | · 3
Inputs
Name IEC 61131 Type Description
IP REAL The REAL representing the phase-current magnitude.
Return Value
IEC 61131 Type Description
REAL The line-current calculated from input phase-current.
Processing
ä The line-current magnitude is calculated using the formula shown above.
MV_IP_TO_IL (Function)
This function takes a single MV input representing the phase-current magnitude and returns
the evaluated magnitude of the line-current. The formula for this calculation is evaluated
as follows. This formula is only valid under balanced, three-phase system conditions.
√
|Iline | = |Iphase | · 3
Inputs
Name IEC 61131 Type Description
IP MV The MV representing the phase-current magnitude.
Return Value
IEC 61131 Type Description
MV The line-current calculated from input phase-current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The line-current magnitude is calculated using the formula shown above.
CMV_IP_TO_IL (Function)
This function takes a single CMV input representing the phase-current magnitude and angle
(in degrees) and returns the evaluated magnitude and angle (in degrees) of the line-current.
The formula for this calculation is evaluated as follows. This formula is only valid under
balanced, three-phase system conditions.
√
Iline = Iphase · 3 30◦
Inputs
Name IEC 61131 Type Description
IP CMV The CMV representing the phase-current magnitude.
Return Value
IEC 61131 Type Description
CMV The line-current calculated from input phase-current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The line-current magnitude is calculated using the formula shown above.
ä The line-current angle is calculated using the formula shown above.
IL_TO_IP (Function)
This function takes a single REAL input representing the line-current magnitude and returns
the evaluated magnitude of the phase-current. The formula for this calculation is evaluated
as follows. This formula is only valid under balanced, three-phase system conditions.
|Iline |
|Iphase | = √
3
Inputs
Name IEC 61131 Type Description
IP REAL The REAL representing the line-current magnitude.
Return Value
IEC 61131 Type Description
REAL The phase-current calculated from input line-current.
Processing
ä The phase-current magnitude is calculated using the formula shown above.
MV_IL_TO_IP (Function)
This function takes a single MV input representing the line-current magnitude and returns
the evaluated magnitude of the phase-current. The formula for this calculation is evaluated
as follows. This formula is only valid under balanced, three-phase system conditions.
|Iline |
|Iphase | = √
3
Inputs
Name IEC 61131 Type Description
IL MV The MV representing the line-current magnitude.
Return Value
IEC 61131 Type Description
MV The phase-current calculated from input line-current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The phase-current magnitude is calculated using the formula shown above.
CMV_IL_TO_IP (Function)
This function takes a single CMV input representing the line-current magnitude and angle (in
degrees) and returns the evaluated magnitude and angle (in degrees) of the phase-current.
The formula for this calculation is evaluated as follows. This formula is only valid under
balanced, three-phase system conditions.
Iline
Iphase = √
3 30◦
Inputs
Name IEC 61131 Type Description
IP CMV The CMV representing the line-current magnitude.
Return Value
IEC 61131 Type Description
CMV The phase-current calculated from input line-current.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality value from the input is loaded into the output.
ä The time stamp value of the input is loaded into the output.
ä The phase-current magnitude is calculated using the formula shown above.
HP_TO_WATTS (Function)
This function takes a single REAL input representing power measured in units of horse-
power and returns the same quantity, measured in Watts. The formula for this calculation
is evaluated as follows.
Inputs
Name IEC 61131 Type Description
Horsepower REAL The REAL representing a power value measured in units
of horsepower.
Return Value
IEC 61131 Type Description
REAL The power quantity represented in Watts.
Processing
ä The power (in units of horsepower) is multiplied by the conversion factor to evaluate
the power in Watts.
WATTS_TO_HP (Function)
This function takes a single REAL input representing power measured in Watts and returns
the same quantity, measured in units of horsepower. The formula for this calculation is
evaluated as follows.
Pwatts
Phorsepower =
745.699872
Inputs
Name IEC 61131 Type Description
Watts REAL The REAL representing a power value measured in Watts.
Return Value
IEC 61131 Type Description
REAL The power quantity represented in units of horsepower.
Processing
ä The power (in Watts) is divided by the conversion factor to evaluate the power mea-
sured in units of horsepower.
PEAK_TO_RMS (Function)
This function takes a single REAL input representing the peak magnitude of a phasor (com-
plex, sinusoidally oscillating) quantity and applies the appropriate calculation to represent
the quantity as a root-mean-square (rms) value. The formula for this calculation is evalu-
ated as follows, where RMS represents the root-mean-square evaluated output.
PEAK
RMS = √
2
Inputs
Name IEC 61131 Type Description
PEAK REAL The REAL representing the peak magnitude of the input for
which the root-mean-square (rms) should be evaluated.
Return Value
IEC 61131 Type Description
REAL The root-mean-square (rms) evaluation of the input PEAK.
Processing
ä The input (PEAK) is divided by the square root of two.
RMS_TO_PEAK (Function)
This function takes a single REAL input representing the root-mean-square (rms) magni-
tude of a phasor (complex, sinusoidally oscillating) quantity and applies the appropriate
calculation to represent the quantity as a peak value. The formula for this calculation is
evaluated as follows, where PEAK represents the evaluated peak output magnitude.
√
PEAK = RMS · 2
Inputs
Name IEC 61131 Type Description
RMS REAL The REAL representing the root-mean-square (rms) magnitude
of the input for which the peak magnitude should be evaluated.
Return Value
IEC 61131 Type Description
REAL The evaluated peak magnitude corresponding to the input RMS.
Processing
ä The input (RMS) is multiplied by the square root of two.
ZeroSequence (Function)
This function takes three CMV inputs representing the three phases of an electrical system
and applies the appropriate calculation to evaluate the zero-sequence component equivalent
of these inputs. The formula for this calculation is evaluated as shown below where Px
represents the phase inputs, x is the phase index, N0 is the zero-sequence output, and a is
the symmetrical components operator (sometimes denoted as α), equivalent to: 1 120◦ .
1
N0 = · (P1 + P2 + P3 )
3
Inputs
Name IEC 61131 Type Description
PHASE1 CMV The CMV representing the first phase element (typically de-
noted as Phase A).
PHASE2 CMV The CMV representing the second phase element (typically
denoted as Phase B).
PHASE3 CMV The CMV representing the third phase element (typically de-
noted as Phase C).
Return Value
IEC 61131 Type Description
CMV The CMV representing the zero-sequence symmetrical component.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
ä The magnitudes of the three input phase values are added together to find 3 ∗ N0 .
ä The evaluated magnitude representing 3 ∗ N0 is divided by three to find N0 .
PositiveSequence (Function)
This function takes three CMV inputs representing the three phases of an electrical system
and applies the appropriate calculation to evaluate the positive-sequence component equiv-
alent of these inputs. The formula for this calculation is evaluated as shown below where
Px represents the phase inputs, x is the phase index, N1 is the positive-sequence output,
and a is the symmetrical components operator (sometimes denoted as α), equivalent to:
1 120◦ .
1
· P1 + a · P2 + a2 · P3
N1 =
3
Inputs
Name IEC 61131 Type Description
PHASE1 CMV The CMV representing the first phase element (typically de-
noted as Phase A).
PHASE2 CMV The CMV representing the second phase element (typically
denoted as Phase B).
PHASE3 CMV The CMV representing the third phase element (typically de-
noted as Phase C).
Return Value
IEC 61131 Type Description
CMV The CMV representing the positive-sequence symmetrical component.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
ä The magnitudes of the three input phase values are added together with the appro-
priate symmetrical component operator to find 3 ∗ N1 .
ä The evaluated magnitude representing 3 ∗ N1 is divided by three to find N1 .
NegativeSequence (Function)
This function takes three CMV inputs representing the three phases of an electrical system
and applies the appropriate calculation to evaluate the negative-sequence component equiv-
alent of these inputs. The formula for this calculation is evaluated as shown below where
Px represents the phase inputs, x is the phase index, N2 is the negative-sequence output,
and a is the symmetrical components operator (sometimes denoted as α), equivalent to:
1 120◦ .
1
· P1 + a2 · P2 + a · P3
N2 =
3
Inputs
Name IEC 61131 Type Description
PHASE1 CMV The CMV representing the first phase element (typically de-
noted as Phase A).
PHASE2 CMV The CMV representing the second phase element (typically
denoted as Phase B).
PHASE3 CMV The CMV representing the third phase element (typically de-
noted as Phase C).
Return Value
IEC 61131 Type Description
CMV The CMV representing the negative-sequence symmetrical component.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The quality values from all inputs are merged using the MERGE_q function.
ä The newest time stamp of the inputs is used to evaluate the output timestamp.
ä The magnitudes of the three input phase values are added together with the appro-
priate symmetrical component operator to find 3 ∗ N2 .
ä The evaluated magnitude representing 3 ∗ N2 is divided by three to find N2 .
PHASES_TO_SEQUENCES (Function)
This function takes three CMV inputs representing the three phases of an electrical system
and applies the appropriate calculation to evaluate the sequence component equivalents
of these inputs. The formula for this calculation is evaluated as shown below where Px
represents the phase inputs, x is the phase index, Ny is the sequence outputs, y is the
sequence index, and a is the symmetrical components operator (sometimes denoted as α),
equivalent to: 1 120◦ .
1
N0 = · (P1 + P2 + P3 )
3
1
N1 = · P1 + a · P2 + a2 · P3
3
1
N2 = · P1 + a2 · P2 + a · P3
3
Inputs
Name IEC 61131 Type Description
PHASE1 CMV The CMV representing the first phase element (typically de-
noted as Phase A).
PHASE2 CMV The CMV representing the second phase element (typically
denoted as Phase B).
PHASE3 CMV The CMV representing the third phase element (typically de-
noted as Phase C).
Outputs
Name IEC 61131 Type Description
SEQUENCE0 CMV The CMV representing the zero-sequence symmetrical
component.
SEQUENCE1 CMV The CMV representing the positive-sequence symmetri-
cal component.
SEQUENCE2 CMV The CMV representing the negative-sequence symmet-
rical component.
Return Value
IEC 61131 Type Description
BOOL Status indicator of the calculation, returns TRUE if quality OperatorBlocked
attribute is FALSE.
Example in Structured Text: (* The variables P1, P2, and P3 are all of type CMV, and
represent the three phase inputs; the variables ZSeq, PSeq, and NSeq are also of type CMV,
and represent the calculated sequence components. *)
PHASES_TO_SEQUENCES(P1, P2, P3, SEQUENCE0=>ZSeq, SEQUENCE1=>PSeq,
SEQUENCE2=>NSeq);
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä Zero-sequence value is calculated by use of the ZeroSequence function.
ä Positive-sequence value is calculated by use of the PositiveSequence function.
ä Negative-sequence value is calculated by use of the NegativeSequence function.
ä The return value is set TRUE to indicate successful calculation.
SEQUENCES_TO_PHASES (Function)
This function takes three CMV inputs representing the three symmetrical component values
and applies the appropriate calculation to find the electrical system phase equivalents of
these inputs. The formula for this calculation is evaluated as shown below where Px repre-
sents the phase outputs, x is the phase index, Ny is the sequence inputs, y is the sequence
index, and a is the symmetrical components operator (sometimes denoted as α), equivalent
to: 1 120◦ .
P1 = (N0 + N1 + N2 )
P2 = N0 + a2 · N1 + a · N2
P3 = N0 + a · N1 + a2 · N2
Inputs
Name IEC 61131 Type Description
SEQUENCE0 CMV The CMV representing the zero-sequence symmetrical
component.
SEQUENCE1 CMV The CMV representing the positive-sequence symmetri-
cal component.
SEQUENCE2 CMV The CMV representing the negative-sequence symmet-
rical component.
Outputs
Name IEC 61131 Type Description
PHASE1 CMV The CMV representing the first phase element (typically de-
noted as Phase A).
PHASE2 CMV The CMV representing the second phase element (typically
denoted as Phase B).
PHASE3 CMV The CMV representing the third phase element (typically de-
noted as Phase C).
Return Value
IEC 61131 Type Description
BOOL Status indicator of the calculation, returns TRUE if quality OperatorBlocked
attribute is FALSE.
Example in Structured Text: (* The variables ZSeq, PSeq, and NSeq are each of type CMV,
and represent the calculated sequence components; the variables P1, P2, and P3 are also
of type CMV, and represent the three phase outputs. *)
SEQUENCES_TO_PHASES(ZSeq, PSeq, NSeq, PHASE1=>P1, PHASE2=>P2, PHASE3=>P3);
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä Phase index 1 value is calculated by summing sequence inputs.
ä Phase index 2 value is calculated by summing sequence inputs with appropriate mul-
tipliers.
ä Phase index 3 value is calculated by summing sequence inputs with appropriate mul-
tipliers.
ä The return value is set TRUE to indicate successful calculation.
DecodeEventType (Function)
This function takes a INS and returns a STR describing event type in a standardized en-
coding suitable for SCADA communications using DNP3 registers. A list of the possible
interpretations is shown in Table 36 below. This list covers a broad range of event types
reported by several SEL relays.
Table 36.2 Relationship Between DNP3 Register Encoding and Event Descriptions
Inputs
Name IEC 61131 Type Description
EventType INS The INS for which the event type representation should be
evaluated.
Return Value
IEC 61131 Type Description
STR The STR event type representation of the input INS.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The INT input is evaluated against the options listed in Table 36 and the appropriate
string value is returned.
ä If the INT is not found to be one of the possible options listed in Table 36, the string
'Indeterminate' is returned.
EncodeEventType (Function)
This function takes a STR and returns an INS encoding for the event type description in a
standardized format, suitable for SCADA communications using DNP3 registers. A list of
the possible interpretations is shown in Table 36. This list covers a broad range of event
types reported by several SEL relays.
Inputs
Name IEC 61131 Type Description
EventString STR The STR for which the event type representation should be
evaluated.
Return Value
IEC 61131 Type Description
INS The INS event type representation of the input string value.
Processing
ä Input quality OperatorBlocked attribute is tested; if TRUE, function returns without
execution.
ä The string input is evaluated against the options listed in Table 36 and the appropriate
INS value is returned.
ä If the string value is not found to be one of the possible options listed in Table 36,
the integer value 9999 is returned in the INS data structure.
Function Blocks
This library provides the PID function block and the related CascadeControl function block.
Terminology
The following table describes the terminology used in this PID function block section.
Term Description
Process Variable (PV) The actual value of the variable to be controlled. This value is
detected by a sensor and used as the feedback signal as the PID
control is taking place.
Set Point (SP) The target value such as a specific temperature or fluid level that
the PID control system is supposed to reach.
Error The difference between SP and PV.
Term Description
Manipulated Variable (MV) The input of the process (i.e., the physical variable that the con-
troller output is adjusting).
Controller Output (CO) The output of the PID controller, which is equal to the sum of the
proportional, integral, and derivative control actions.
Figure 36.1 shows a PID control system block diagram that includes the terminology shown
in the previous table.
PID Algorithm
The PID function block in the RTAC implements the ideal (ISA) form of the PID positional
algorithm with dependent gains. In this PID equation form, the controller gain Kc equally
affects all three control actions. The standard time-domain PID equation with dependent
gains is shown in Equation 36.1 .
Z
1 d (E)
CO = Kc E + E · dt + Td (Equation 36.1)
Ti dt
where:
E is the error
Kc is the controller gain
Ti is the integral time
Td is the derivative time
The PID algorithm on the RTAC implements different variations of this equation depending
on two input parameters: Source of derivative Source of Derivative on page 36.67) and
control action (Direct/Reverse Control Action on page 36.67). The user selects between
direct and reverse control action and selects the signal input for the derivative term (error
or PV). These two settings affect the terms of the equation, specifically the derivative term.
Table 36.3 contains the time-domain PID equations used by the PID function block.
E · dt + Td d(E)
1
R
Error Direct/Reverse CO = Kc E + Ti dt
+ OutputBias
Reverse
E · dt − Td d(PdtV ) + OutputBias
1
R
(E = SP − P V ) CO = Kc E + Ti
Direct
E · dt + Td d(PdtV ) + OutputBias
1
R
PV (E = P V − SP ) CO = Kc E + Ti
Inputs
Name IEC 61131 Type Description
PV REAL Range: (3.4E+38) to (+3.4E+38), default: 0.
Analog signal from the output of a process.
SP REAL Range: (3.4E+38) to (+3.4E+38), default: 0.
Desired value of the PV.
Kc REAL Range: (3.4E+38) to (+3.4E+38), default: 0.
Controller gain.
Ti REAL Range: (3.4E+38) to (+3.4E+38), default: 0.
Integral time in seconds. Set to 0 to disable integral ac-
tion.
Td REAL Range: (3.4E+38) to (+3.4E+38), default: 0.
Derivative time in seconds.
DoPV BOOL Default = TRUE.
TRUE: Derivative on PV.
FALSE: Derivative on error.
Auto BOOL Default = TRUE.
TRUE: Automatic mode.
FALSE: Manual mode.
ManualOut REAL Range: 0 to 100, default: 0.
PID function block output in manual mode.
OutBias REAL Range: –100 to 100, default: 0.
Value, in percentage (%), manually added to the output
after the PID calculation.
Outputs
Name IEC 61131 Type Description
PIDout REAL PID Output. Result of the PID equation (0% to 100%).
Error_p REAL Error value as a percentage or EU range.
SPramp BOOL SP Ramping. TRUE if the function block is ramping to SP.
Pterm REAL Proportional Term. Kc • Error
Kc
P
Iterm REAL Integral Term. Ti
· Error · ∆T
Processing
Manual/Automatic Modes and Bumpless Transfer
The PID function block has two operation modes, automatic and manual. In automatic
mode, the result of the PID equation determines the controller output value. In manual
mode, the operator sets the controller output value directly by setting the ManualOut input
(0–100 percent).
The PID function block provides bumpless transfer to avoid an abrupt change on the out-
put when switching from manual to automatic. It achieves bumpless transfer by enabling
set-point tracking and output tracking when the controller is in manual mode. Set-point
tracking overwrites the set point with the current PV. Consequently, when the controller
switches to automatic mode, it will begin control with zero error. Output tracking preloads
the integral term with the output value set by the operator. As a result, when the controller
switches to automatic mode, it will begin control from the last output value entered by the
operator.
The PID function block supports ramping to set point. Upon switching to automatic mode,
the function block ramps the set point of the controller at a specified rate (SPrate input) until
reaching the desired SP entered by the user. The SPrate input has to be set in engineering
units per PID execution time.
PV and SP During Manual Mode, Automatic Mode, and Ramp-to-Set Point Fig-
ure 36.2 illustrates the manual/automatic operation and ramp-to-set point.
0 1 2 k k+1k+2k+3k+4k+5k+6
Ramp-to-set point
As illustrated in Figure 36.2, the PID control starts in Manual mode at t = 0 and remains
operating in Manual mode until it is switched to automatic mode at t = k. In Manual
mode (t < k), the PID equation calculates a new value continuously, but this value does not
affect the PID output. Rather, the operator controls the output and directly adjusts its value,
which in turn adjusts the process variable. In Manual mode, the PID equation continuously
calculates the output value needed to smoothly start automatic control upon switching to
Automatic mode. The PID logic ignores the current value on the SP input (blue line) and
overwrites the set point with the current PV value (green line). Consequently, in Manual
mode, the PID equation uses a SP value equal to PV. This is set-point tracking, which allows
bumpless transfer to Automatic mode.
When the PID controller switches to Automatic mode (t = k), it stops set-point tracking
and ramp-to-set point starts (SPramp output goes to TRUE). Immediately after switching
to Automatic mode, the controller gradually increases the set-point value. This starts from
the last value read while in Manual mode (Point A in Figure 36.2) and increases to the
SP value configured by the user (Point B in Figure 36.2). PV follows SP according to the
PID tuning settings and the dynamics of the process. The controller ramps the set point
by an amount equal to SPrate (engineering units) every PID execution cycle. When SP
reaches the value configured by the user (Point B), ramp-to-set point ends (SPramp output
goes to FALSE). After ramp-to-set point ends, if the user makes a set-point change, the PID
equation will immediately use this new SP value to calculate the output value. Ramp-to-set
point will not start again until the next manual-to-automatic transition.
Output Bias
Output bias is an input parameter that you enter. The controller adds this value to the result
of the PID equation, as shown in Table 36.3.
You may use output bias to reset error offset when no integral action is used (P-only con-
trol). You may also use the output bias input for combining the PID controller with feed-
forward control to improve the response to disturbances. The PID controller accepts an
output bias value scaled from –100 to +100 percent. If the output bias is more than 100
percent or less than –100 percent, the controller will clamp it to 100 or –100 percent, re-
spectively.
Source of Derivative
Using the derivative of the error may cause large transients in the controller output because
of set-point changes. In practice, it is better to use the derivative of PV instead of using the
derivative of the error. The derivative of the error works well when SP does not change or
when it changes smoothly.
The DoPV input allows you to select between derivative of PV (DoPV = TRUE) or deriva-
tive of error (DoPV = FALSE).
Reverse control action will be used for controlling direct-acting processes, whereas direct
control action will be used for controlling inverse-acting process. Direct- and Reverse-
Acting Processes describes how to determine whether your process is direct-acting or
reverse-acting.
In both cases, we are controlling the level of the liquid in the tank by manipulating the
opening of the valve. Therefore, the manipulated variable is the opening of the valve and
the process variable is the liquid level. In the process shown on the left side of Figure 36.3,
an increase in the valve opening results in a decrease of the liquid level. Consequently, it
is a reverse-acting process and the PID controller must be configured for direct action. In
the process shown on the right side of Figure 36.3, an increase in the valve opening results
in an increase of the liquid level. Consequently, it is a direct-acting process and the PID
controller must be configured for reverse action. In summary:
ä If the increase of the manipulated variable results in an increase of the process vari-
able, then the process is direct-acting and the PID control shall be configured for
reverse action.
ä If the increase of the manipulated variable results in a decrease of the process vari-
able, then the process is reverse-acting and the PID control shall be configured for
direct action.
Derivative Filter
When derivative action is used, even small amounts of noise in PV may cause large unnec-
essary PID output movements. The PID function block implements a first-order filter to
reduce the noise reading and smooth the signal feeding the derivative term (PV or error).
The frequency-domain transfer function of the derivative filter is shown as follows:
1
H(s) =
1 + F ilterT ime · s
1
fc =
2π · F ilterT ime
where FilterTime is a PID input parameter.
Setting FilterTime to 0 disables the derivative filter.
Output Limiting
The PID function block allows you to set maximum (OutMAX) and minimum (OutMIN)
limits for the output (0–100 percent). The PID function block clamps the output at these
limits, preventing it from exceeding the maximum or minimum limits. An alarm bit is also
set if the calculated output is beyond these limits.
Anti-Integral Windup
Integral windup occurs when the actuator is at its maximum or minimum limit but the
set point has not been reached. The integral term gradually increases, increasing the out-
put more than 100 percent (or less than 0 percent), which is physically impossible for the
actuator.
The problem with integral windup is that it may take a relatively long time to correct,
because the integral term needs to unwind. The top graph in Figure 36.4 illustrates integral
windup. The red line represents the output value that the PID equation is instructing to send.
The blue line represents the output value that is actually sent. A PID control with no integral
antiwindup implementation is not aware of the PID output limits. Consequently, if the error
persists long enough, the integral term may grow indefinitely, beyond the output limit,
driving the actuator to the maximum limit. At this point, the PID equation no longer has
an impact on the controller output or the actuator. When the error changes to the opposite
sign, the output may take a long time to wind down before getting to the operational range.
The bottom graph in Figure 36.4 illustrates a PID output with antiwindup implementation.
When the output reaches the limit, the integral calculation is suppressed and consequently
the output will not accumulate beyond this point. When the error changes to the opposite
sign, the output drops immediately to the operational range.
The PID function block prevents integral windup by switching off integration and keeping
the accumulated integral term constant in either of the following situations:
ä PID output is greater than or equal to the maximum output limit (MaxOUT) and the
error is positive.
ä PID output is less than or equal to the minimum output limit (MinOUT) and the error
is negative.
When the PID output returns to a value in the range between OutMIN and OutMAX, the
integral calculation resumes.
Alarms
The PID function block has an alarm output to alert you of an abnormal condition. The
alarm output is a tag structure of Boolean variables; each Boolean variable within the
structure represents a different alarm. The alarms that are implemented are shown in the
following table.
Alarm Description
Output_High_Limit PID output has reached the maximum limit.
Output_Low_Limit PID output has reached the minimum limit.
SP_Out_of_Range Set-point value is out of the engineering units range MinEU, MaxEU).
PV_Out_of_Range Process variable value is out of the engineering units range MinEU,
MaxEU).
PID Timing
The PID function block uses the Task Cycle Time as its time base, and is executed at a rate
equal to a multiple of this time base. The TimeBase input parameter defines the multiplier
value for the PID execution rate.
For example, if you configure the RTAC to run every 50 milliseconds (Task Cycle Time =
50) and the instance of the PID function block is configured with TimeBase = 10, the PID
code is executed every 500 milliseconds. This allows you to have in your logic multiple
instances of the PID function block running at different rates.
In order to use this function block, set up a cascade control system using the CascadeControl
function block as follows:
1. Incorporate two PID function blocks (primary and secondary) and a CascadeCon-
trol function block in your ACSELERATOR RTAC project.
2. Connect the CascadeControl function block inputs and outputs to the corresponding
inputs and outputs of the primary and secondary PID blocks (refer to the Cascade-
Control Input Table).
3. Configure the individual PID settings (tuning constants, direct/reverse action, deriva-
tive filter, etc.) for the primary and secondary controller.
Inputs
Name IEC 61131 Type Description
Mode CascadeModes The mode input determines the operating mode of the
cascade system. The possible values for this input are
ManualMode, AutoMode, and CascadeMode. When this
input is ManualMode, both primary and secondary con-
trollers are placed in Manual mode. In Manual mode, you
directly determine the output of the secondary controller
by writing to the ManValue input (0–100 percent). When
this output is AutoMode, the primary controller is placed
in Manual mode and the secondary controller is placed
in Automatic mode. You can directly manipulate the set
point of the secondary controller by writing to the Au-
toValue input (0–100 percent). Finally, when this output
is CascadeMode, both primary and secondary controllers
are placed in Automatic mode for full cascade operation.
PVsec REAL Connect the PVsec input to the process variable (PV) sig-
nal of the secondary controller.
Note: The PV signal of the secondary controller must be
in percentage units (0–100 percent).
ManValue REAL The ManValue input determines the output of the sec-
ondary controller when the system is in Manual mode.
When the Mode input is ManualMode, the current value
of this ManValue input is sent to the output of the sec-
ondary controller. When the Mode input is AutoMode
or CascadeMode, the value of this ManValue input is ig-
nored.
AutoValue REAL The AutoValue input determines the set point of the sec-
ondary controller when the system is in Automatic mode.
When the Mode input is AutoMode, the current value of
this AutoValue input is sent to the set point (SP) input of
the secondary controller. When the Mode input is Man-
ualMode or CascadeMode, the value of this AutoValue
input is ignored.
ALARMSsec PID_Alarms Connect the ALARMSsec input to the Alarms output of
the secondary controller.
Outputs
Name IEC 61131 Type Description
AUTOpri BOOL Connect the AUTOpri output to the Auto input of the pri-
mary PID controller.
AUTOsec BOOL Connect the AUTOsec output to the Auto input of the
secondary PID controller.
MANOUTpri REAL Connect the MANOUTpri output to the ManualOut input
of the primary PID controller.
MANOUTsec REAL Connect the MANOUTsec output to the ManualOut in-
put of the secondary PID controller.
FIpri BOOL Connect the FIpri output to the Freeze_I input of the pri-
mary controller.
Outputs
Name IEC 61131 Type Description
Enabled BOOL Indicator that function block is active and calculated values
are valid.
AngleDiff MV Angle difference in degrees bounded between -180 and 180
(inclusive of 180) as a MV.
Alarm1 BOOL Alarm point which will assert if AngleDiff surpasses Thresh-
old1 for a time greater than that specified by PT1.
Alarm2 BOOL Alarm point which will assert if AngleDiff surpasses Thresh-
old2 for a time greater than that specified by PT2.
Processing
ä If not enabled, outputs are all set as defaults such that AngleDiff.instMag equals zero,
AngleDiff.t.value is equal to system start time, Enabled is FALSE, and both alarms
are FALSE.
ä If enabled, the output AngleDiff is loaded with updated attributes from the input
CMVs including the latest time, and the worst-case quality from both input tags.
ä The angle difference is calculated as Phasor1.instCVal.ang − Phasor2.instCVal.ang
where the resulting angle difference is wrapped such that it is bounded by -180 and
180 (inclusive of 180).
ä The absolute value of the evalulated angle difference is used to compare against the
two input thresholds, and this comparison is used to enable the pickup timers for
each respective alarm with time values specified by PT1 and PT2, respectively.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R143-V0 firmware
ä SEL-3530
â R143-V0 firmware
ä SEL-3555
â R143-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R143 firmware
Benchmark Results
Platform (time in ns)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
REAL_TO_FORMATTED_STRING
Average 2540.4 1374.7 54.2
Maximum 10977.8 5904.3 321.1
Minimum 380.3 251.7 8.1
Std Deviation 2722.5 1366.7 55.9
LREAL_TO_FORMATTED_STRING
Average 314.6 204.9 16.7
Maximum 4636.9 1909.5 297.4
Minimum 102.1 76.5 3.8
Std Deviation 548.5 272.1 19.6
TIMESTAMP_TO_STRING
Average 1057.1 631.8 29.2
Maximum 6555.3 3841.6 399.1
Minimum 245.9 275.3 4.1
Std Deviation 749.7 376.6 36.6
VALIDITY_TO_STRING
Average 1057.1 631.8 29.2
Maximum 6555.3 3841.6 399.1
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
// PID ALARMS
IF TemperatureOven . Alarms . Output_High_Limit
OR TemperatureOven . Alarms . Output_Low_Limit
THEN // 10
SEL_16DO_1_ECAT . OUTPUT_001 . operSet . ctlVal := TRUE ;
SEL_16DO_1_ECAT . OUTPUT_001 . operClear . ctlVal := FALSE ;
ELSE
SEL_16DO_1_ECAT . OUTPUT_001 . operSet . ctlVal := FALSE ;
SEL_16DO_1_ECAT . OUTPUT_001 . operClear . ctlVal := TRUE ;
END_IF
The input values that are not configured in the logic retain their default values.
Cascade Control
In some applications, two PID controllers are nested together and used in combination to
improve the control performance over the single-loop system. This is called cascade control
and is used to improve the response of the system to disturbances.
Figure 36.9 shows a typical example of cascade control. The variable to be controlled
(primary variable) is the water temperature leaving the heat exchanger. The operator sets
the desired temperature (set point) on the primary controller, which determines the desired
amount of steam flow to control the temperature. The output of the primary controller
manipulates the set point of the secondary controller, which maintains the steam flow at the
desired level, correcting any steam flow disruption before the primary variable is impacted.
A single PID controller could control the temperature of the water by reading its temper-
ature (PV) and setting the position of the valve without going through a secondary PID
controller. However, if any disturbance occurs on the steam flow, the effect of the distur-
bance has to flow through the water temperature process and move the temperature away
from the set point before it can be corrected by the single PID controller. Introducing a
secondary PID controller to control the steam flow makes the loop control more stable and
faster responding because a flow control loop reacts much faster than a temperature control
loop. Any disturbance that affects the secondary variable is detected and compensated by
the secondary controller before it affects the primary variable.
Cascade control may be implemented on the RTAC by adding two PID function block
instances into the project (primary and secondary controllers) and implementing additional
logic to prevent integral windup and to switch between the different cascade modes. The
way to implement this additional logic is described in Anti-Windup Logic and Cascade
Control Logic Using CascadeControl Function Block following.
Anti-Windup Logic
In a single-loop controller, when the output of the PID function block reaches the limit and
the error contributes to increase the output beyond this point, the integral accumulation is
suspended. When the output returns to the operational range, the integral accumulation
resumes. This is called anti-windup and is described in detail in Anti-Integral Windup on
page 36.69.
In cascade control, integral windup may occur in the primary controller because of the
interaction between the two controllers, and a different anti-windup technique is necessary
to prevent this problem from happening. Integrator windup will occur if the output of
the secondary controller hits the limit and the primary controller continues to integrate
the error. To prevent this, it is necessary to implement an external anti-windup logic to
automatically freeze the integral term of the primary controller when the output of the
secondary controller reaches the limit. The PID function block provides alarm output bits
to indicate that the output is saturated, and also provides a Boolean input to freeze the
integral term. Implementing the external anti-windup logic is straightforward if you use
these alarm output bits and Freeze_I input.
The Structured Text code in Code Snippet 36.6 shows a configuration example of a primary
PID controller. The highlighted line shows how to configure the Freeze_I input to suspend
the integral calculation when the output of the secondary PID controller hits the higher or
lower limit.
Cascade Mode
ä The operator manipulates the set point of
the primary controller.
ä Both primary and secondary controllers are
in automatic mode.
Automatic Mode
ä The operator manipulates the set point of
the secondary controller.
ä Primary controller is in manual mode and
secondary controller is in automatic mode.
Manual Mode
ä The operator directly manipulates the final
control element (valve).
ä Both primary and secondary controllers are
in manual mode.
When implementing the operating modes, take the following considerations into account
to ensure there is no sudden change in the output to the final actuator.
ä Cascade Mode
â Both controllers (primary and secondary) must be placed in Automatic mode.
ä Automatic Mode
â The primary controller should be placed in Manual mode.
â The secondary controller should be placed in Automatic mode.
â The operator directly controls the set point of the secondary controller by set-
ting a value to the ManualOut input of the primary controller.
ä Manual Mode
â Both controllers (primary and secondary) must be placed in Manual mode.
â The operator directly controls the final actuator by setting a value to the Man-
ualOut input of the secondary controller.
â The output of the primary controller must track the process variable (PV) of
the secondary controller. This will allow a bumpless transfer to Automatic or
Cascade mode.
//Static inputs
Warning_Threshold : REAL := 10;
Warning_Pickup_Time : TIME := T#5S;
Alarm_Threshold : REAL := 15;
Alarm_Pickup_Time : TIME := T#10S;
//Outputs
PADM1_OK : BOOL;
PADM1_Angle_Difference : MV;
PADM1_Warning : BOOL;
PADM1_Alarm : BOOL;
END_VAR
// Load outputs
PADM1_OK := PADM1 . Enabled ;
P AD M1 _A ng le_ Di ff er enc e := PADM1 . AngleDiff ;
PADM1_Warning := PADM1 . Alarm1 ;
PADM1_Alarm := PADM1 . Alarm2 ;
SVPplus
Introduction
The SVPplus (Synchrophasor Vector Processor Plus) library provides Prony Analysis of
signals, referred to here as modal analysis. The overall goal of this library is to encapsulate
algorithms that describe the dynamics of a substation or electrical grid.
Sample Timing
The timing requirements of the modal analysis input signal are the responsibility of the
user of the library. The library does not check the times of the samples given. The interval
between each sample must be within acceptable error of the sample rate given in hertz.
For example, if 20 Hz is given, the period between samples should be 0.05 seconds. The
recommended error threshold is 5 percent.
Use Cases
Modal Analysis has been proven significantly useful in several areas of power system anal-
ysis.
Sometimes power system equipment or their controllers can be configured in such a way
that they unintentionally incite growing oscillations. Rapid detection of these forced oscil-
lations is important to guard against excessive mechanical fatigue and system instability.
Modal analysis can detect these events by noting the maximum modal amplitudes of a sys-
tem and triggering an alarm or control action based on larger than normal and/or increasing
magnitude of oscillatory modal amplitude.
Disturbances in the power system are often identifiable from the decaying oscillations vis-
ible from streaming synchrophasor measurements. These events provide an opportunity
to determine the natural system dynamic modes. The dynamic modes inform planners of
the inherent stability, or lack thereof, of the power system and help identify areas where
additional stabilizing devices could be installed.
Modal analysis performed on ambient data can identify the frequency of the natural dy-
namic modes. A change in the frequency component of these modes can indicate a system
change that may require further investigation.
Operation
The modal analysis function block in this library is responsible for two primary tasks. The
first task is to collect and store samples given to it. The second task is to analyze these stored
values once enough new samples are given and return the modes of the stored signal.
The samples are stored in a ring buffer. Once a certain percentage of new samples are
given, modal analysis is conducted on the stored array of samples. Figure 37.1 shows this
visually, where blue indicates old samples and red new samples. If the object has just been
initialized and there are no stored samples, modal analysis is not complete until the entire
buffer has been filled. After the initial filling of the buffer, modal analysis is done once the
percentage of new samples has been reached. For example, if the total number of samples
specified as the initialization variable numSamples is set to 100, and percentUpdate is set
to 10 percent, then the tenth call to GiveSample() will trigger another calculation. This
new modal calculation is performed on the most recent 90 old samples and the 10 new
samples, with the oldest 10 samples having been overwritten in the ring buffer.
Figure 37.1 Ring Buffer Used To Store Samples In Modal Analysis Object
Because modal analysis is very computationally expensive, the analysis is done over many
task cycles. The Run() method of each modal object does part of the analysis each cy-
cle until it is complete. If a new analysis has been triggered and the previous is not yet
complete, it is ignored until the previous analysis is finished. Once the current analysis
is complete, the ignored trigger causes a new analysis to begin immediately. The ignored
trigger is not a queue, but rather is a single request to restart once the previous analysis
completes.
Modes
Modes are returned from modal analysis, which is the decomposition of the input signal into
a series of modes. These modes consist of sinusoidal decaying signals that closely match
the original signal when summed together. The equation used to construct each mode from
their values is given in Equation 37.1 , where A is the amplitude, α is the decay, f is the
frequency, and θ is the angle phase.
The quality of the signal is determined by the signal-to-noise ratio (SNR) returned with
a call to GetModes(). Equation 37.2 shows how the SNR is calculated, where S is the
original signal and N is a signal reconstructed from the modes returned.
p !
S12 + S22 + ... + Sn2
SN R = 20 log10 p
(S1 − N1 )2 + (S2 − N2 )2 + ... + (Sn − Nn )2
(Equation 37.2)
The SNR is calculated by using the decibel logarithmic unit on the ratio of the root-mean-
square of the original signal over the root-mean-square of the difference between the origi-
nal signal and reconstructed signal. If the value is 20, then the amplitude of the signal is 10
times greater than the error; when the value is 40, the amplitude of the signal is 100 times
greater than the error, and so on.
Damping Ratio
The damping ratio ς is determined from the decay α and the frequency f (as seen in “Mod-
ern Solutions for Protection, Control, and Monitoring of Electric Power Systems” ISBN
978-0-9725026-3-4). Equation 37.3 is used to compute the damping ratio. A negative
damping ratio illustrates an increasing oscillation that can lead to power system instability.
α
ς = −p (Equation 37.3)
α2 + (2πf )2
Modal Analysis
Because of the computationally intensive nature of this algorithm, it is very important to
consider benchmarks while using this object. See Benchmarks on page 37.7 for benchmark
information.
Global Constants
This section lists values of global constants provided for facilitating work with the library.
Structure Definitions
This section enumerates structures needed for the user to communicate with this library.
struct_Mode
This object contains the information for one sinusoidal mode returned from class_Modal-
Analysis.
Classes
This section enumerates the classes used to access the functionality of this library.
class_ModalAnalysis (Class)
This class conducts modal analysis on an input signal.
Initialization Inputs
Name IEC 61131 Type Description
numSamples UDINT Total number of samples this modal analysis object uses.
sampleRate UINT Rate at which samples are taken in hertz.
percentUpdate UDINT(10..100) Percentage of new samples this modal analysis collects
before performing analysis.
stepTime ULINT The amount of time in microseconds the Run() method
will run each time it is called.
numModes UDINT(1..16) Number of modes that are returned from analysis.
For any meaningful analysis of a digital input signal, a minimum number of sample history
must be stored in a buffer. numSamples is the size of this buffer for modal analysis.
Outputs
Name IEC 61131 Type Description
IsEnabled BOOL Flag that states if this class instance is active.
Error POINTER TO STRING(80) If class instance failed initialization, this points to a
string describing what failed.
These outputs give the status of the modal analysis object as a whole. If the initialization of
the class instance was successful, it is flagged and enabled and ready to take new samples
to analyze. If initialization failed, it is flagged as not enabled and the error string pointer
returns a pointer to a string which described what failed in initialization.
bootstrap_SetFilter (Method)
This initialization routine sets the filter that is used on the raw input provided by GiveSample().
This routine is optional to call, and if it is not called no filter is used and the raw samples
are fed directly into modal analysis.
Inputs
Name IEC 61131 Type Description
filter I_Filter Interface pointer to filter that will be used on raw input.
Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the filter was successfully added to the object.
Processing
This routine takes the interface to the filter and confirms the pointer to it is real. If the
pointer to the filter is zero or the modal analysis object has already been initialized, it will
return FALSE as a failure.
GiveSample (Method)
This method gives a new sample as input to the modal analysis block. The sample rate
integrity of the signal must be verified by the user, as discussed in Sample Timing on
page 37.1.
Inputs
Name IEC 61131 Type Description
sample REAL New sample.
Processing
This method takes the input sample and stores it within its internal buffer of samples. If
enough new samples have been given or the entire buffer of samples has been populated
for the first time, the method will trigger the calculation of new modes. This calculation is
done over many cycles in the run method.
Reset (Method)
Modal analysis is only effective on a continuous stream of evenly spaced samples. When a
gap in the stream has been detected, modal analysis must be reset. This causes it to discard
all previous samples. Additionally, a sample with unacceptably low quality is considered
a gap in the stream, and therefore, modal analysis must be reset.
Resetting modal analysis delays the next analysis as additional samples will need to be
gathered. A sample is considered bad if it does not meet the timing requirements defined
in Sample Timing on page 37.1 or if the quality of the sample is unacceptable.
Processing
This method will discard all saved samples and start with an empty buffer that needs to be
refilled for modal analysis to happen.
Run (Method)
This method must run once per cycle for each modal analysis object that exists. It is re-
sponsible for processing modal analysis of the samples. It performs a part of an analysis,
if one is pending, each time it is called.
Return Value
IEC 61131 Type Description
UDINT Percentage of completion for modal analysis task from 0 to 100.
Processing
Once the output complete has reached 100, the analysis is complete and GetModes can be
called.
GetModes (Method)
Call this method to get the most recent modal analysis results. If no analysis has yet been
done, this method will return an array of structures whose values are all set to zero.
The range of the signal-to-noise ratio can be anywhere from 0 to the maximum number of
UINT. Increasing the number of modes returned will improve this signal-to-noise ratio.
Inputs
Name IEC 61131 Type Description
pt_modes POINTER TO struct_Mode Address of array to copy modes to as returned by the
ADR() function. This array must contain numModes
structures as specified in the Initialization Inputs of
the class.
Return Value
IEC 61131 Type Description
REAL Signal-to-noise ratio that determines quality of modes returned.
Processing
If no analysis has yet been done, this method will set all structures to zero. If the number
of modes for this object has been initialized with a number n that is less than the global
value g_p_numModes, then all structures past n will be set to zero.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
4 Modes 500 Samples 27 16 2
8 Modes 500 Samples 114 64 6
16 Modes 500 Samples 462 253 21
4 Modes 600 Samples 34 17 3
4 Modes 5k Samples 155 93 2
8 Modes 5k Samples 460 276 23
16 Modes 5k Samples 1586 952 80
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Calculating Modes
Objective
The objective of this example is to calculate the modal frequencies and damping coefficients
of a synchrophasor frequency measurement for oscillation stability analysis at an update
rate of once per second. This example will cover the preconditioning of incoming time
stamps and how to call the ModalAnalysis methods in the appropriate sequence.
Assumptions
This example assumes the following are true:
ä The RTAC project incorporates both the SVPplus and Analog Conditioning libraries.
ä The RTAC is collecting synchrophasor measurements from one synchrophasor mea-
surement device, referenced here as a C37_118 RTAC client called PMU1.
ä The RTAC is performing no tasks other than those referred to in this example.
ä The nominal frequency of the power system is 60 Hz.
ä The synchrophasor message rate is 60 samples per second.
ä The RTAC Main Task cycle time, under which all programs are being run, is set to
8 ms.
ä The Deadband and Zero Deadband settings for the PMU1.FREQ tag are set to 0.
ä There are only four modes of interest in the system. Each is between 0.3 Hz and
10 Hz.
ä Data samples are filtered with a 10 Hz cutoff low-pass filter before being processed
with MA. The ArmaFilter class from the Analog Conditioning library is used to
implement this filter. This is also demonstrated in the example.
ä The global variable list and sample flagging programs shown in Code Snippet 37.1
and Code Snippet 37.2, respectively, are included in the project.
VAR_GLOBAL
g_SampleQuality, g_SampleUpdated, g_SampleTimeValid, g_SampleValid :
BOOL;
g_SNR : REAL;
g_ModeResults : ARRAY [1..g_c_NumModes] OF struct_Mode;
g_DampingAlarm : ARRAY [1 .. g_c_NumModes] OF BOOL;
END_VAR
Solution
Having flagged the incoming samples for quality and continuity, the samples can be filtered
and processed with MA as shown in Code Snippet 37.3.
Analyzing Modes
Objective
The objective of this example is to demonstrate how the output of the ModalAnalysis class
can be processed to flag a necessary control action.
Assumptions
This example extends the previous example. Thus, it is assumed that the getModes()
method has been called successfully. It is further assumed that the program in this example
will accesses the global variable list defined in the previous example.
Solution
The code below shows a simple example which asserts a per-mode alarm bit if the given
mode meets the user-specified criteria. The signal-to-noise ratio output of the getModes()
method is used to validate the accuracy of the modal estimation.
SnmpLite
Introduction
This library encapsulates common communications management responsibilities that in-
dustrial control and monitoring equipment are expected to perform on the communications
fabric of a control system using Simplified Network Management Protocol (SNMP).
The common use for these devices is to annunciate failures within the system. Therefore,
this library only provides basic network interface descriptions and port states to allow detec-
tion and annunciation of device failures. More advanced diagnostic and system description
tools that fully use SNMP are outside the scope of this library, and are not considered to
be common requirements of an automation controller.
Glossary
Abstract Syntax Notation One (ASN.1) A standard that provides rules and a notation
for representing, encoding, transmitting, and decoding data in telecommunications. SNMP
uses this standard to represent the data within a UDP packet.
Management Information Base (MIB) A hierarchical description of the structure and
data available in a device that supports SNMP.
Object Identifier (OID) A unique identifier for an object or leaf in a hierarchically de-
fined namespace, where a “.” specifies the next object as the child of the previous. For
example, the OID 1.3.6.1.2.1.2.2.1 identifies the entries in a table of interfaces. In the con-
text of this library, OIDs uniquely identify information found in communication with the
network devices.
SNMP Trap Unsolicited information SNMP agents send to SNMP managers. Events that
trigger SNMP Traps and the Trap content are configured on the SNMP agent device and
utilize Port 162.
Simplified Network Management Protocol (SNMP) An Internet standard protocol
for managing devices on IP networks. This protocol is generally supported by network-
fabric devices such as Ethernet switches and routers, and it is often used by other network-
centric devices. There are many versions of SNMP. All SNMP traffic, except SNMP traps,
is sent and received on Port 161.
Simple Network Management Protocol Version 2, Community-Based SNMPv2c)
This version of the protocol transmits all data, including the community strings used to
group SNMP agents and managers, in raw form with no encryption.
User Datagram Protocol (UDP) A connectionless, packet-based protocol used to stream
data between two devices without requiring responses. UDP does not implement handshak-
ing, packet ordering, or confirmation of packet delivery.
Special Considerations
Consider the following topics when implementing this library in a project.
Versions of SNMP
This version of the library only supports SNMPv2c, which is an unsecured implementation
that transmits all data on the wire without encryption or security.
// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_SnmpObject"
mySnmpObject := otherSnmpObject;
// This is fine
someVariable := mySnmpObject.value;
// As is this
pt_mySnmpObject := ADR(mySnmpObject);
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
NOTE: See
enum_InterfaceStatus http://tools.ietf.org/html/rfc2863 for
more information about the interface
states.
This enumeration provides a textual representation of the statuses possible for any individ-
ual port.
Enumeration Description
NONE Interface specified is out of range for this device.
UP Interface status is up.
DOWN Interface status is down.
TESTING Interface is in test configuration.
UNKNOWN Port link status is unknown.
DORMANT The interface is ready to transmit and receive network traffic, but
is waiting on some external event.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Classes
class_SnmpManager (Class)
A single class_SnmpManager object is instantiated to manage the UDP traffic on Port 161
for SNMP get and set requests and responses to these requests. The same object listens on
Port 162, which is the SNMP trap listening port. If two or more class are instantiated, all
but one of the classes will fail to initialize and display an appropriate error state.
This object issues SNMP requests queued by instantiated SNMP agent classes. It sends
responses to these requests and forwards SNMP traps received from a given IP address to
the SNMP agent class associated with the sending IP. The agent class is responsible for the
processing of the message.
The manager issues no more than one SNMP request per call to the Run() method. This
constraint evenly distributes the load per scan and allows support for an arbitrary number
of agents. However, this constraint also means that the more devices that this manager
supervises, the more time it takes to cycle through the pending requests from all of the
agent classes. This result can be mitigated by configuring traps on the SNMP agent devices
because the manager also processes one trap per call to the Run() method; a trap event will
update the status of the SNMP device immediately and the delay in getting new information
is not affected by the number of devices being monitored. Instead, only the number of traps
received simultaneously affects the latency of updates to the agent monitoring classes.
Run (Method)
Call this method once every scan on a low-priority task where real-time performance is not
critical.
Processing
The Run() method does the following:
ä Issues a pending poll:
â Get the next registered agent class.
â Issue the queued request.
ä Dequeues a maximum of two SNMP traps from the Port 162 socket and then sends
the traps to the agent class designated to the IP address of the sender for parsing.
ä Dequeues a maximum of two SNMP responses from the Port 161 socket and then
send the responses to the agent class designated to the IP address of the sender for
parsing.
class_SnmpAgentMonitor (Class)
When instantiated, this class registers itself with the active class_SnmpManager. There is
no need to call methods on this class or to run it periodically because the manager class is
responsible for refreshing the state of all agent monitors.
This class monitors a generic SNMP agent device that has a list of network interfaces listed
under OID 1.3.6.1.2.1.2.2.1 1 . It also displays the number of interfaces the SNMP agent
provides in response to requesting the Integer32 value at OID 1.3.6.1.2.1.2.1 2 .
The list of interfaces is initially obtained by walking through all of the table objects. If
the number of interfaces returned by walking the interface table is less than the number of
interfaces OID 1.3.6.1.2.1.2.1 advertises, the device will not enable. If the interface infor-
mation from all interfaces can be obtained, then the object enables itself. Subsequently,
the agent only requests port statuses via OID 1.3.6.1.2.1.2.2.1.8.N 3 .
The port information obtained by GetInterfaceInfo() updates only during initializa-
tion, with the exception of ifOperStatus, which continually updates.
In the event that (a) the agent does not receive replies to requests for ifOperStatus, (b) the
quantity of interfaces changes, or (c) the indexing of the monitored interfaces changes, this
block sets ENO to FALSE and attempts to reinitialize.
1 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifTable(2) . ifEntry(1).
2 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifNumber(1).
3 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifTable(2) . ifEntry(1) . ifOperSta-
tus(8) . item(N).
This basic SNMP agent monitor discards SNMP traps it receives from the class_Snmp-
Manager object because the contents of SNMP traps are highly dependent on the MIB of
the particular device sending the traps.
Initialization Inputs
Name IEC 61131 Type Description
ipAddress STRING(15) The IP address of the monitored agent as a string.
communityString STRING(80) A string that designates the community this agent de-
vice has been assigned. This ID is included in every
packet the agent and manager send.
Outputs
Name IEC 61131 Type Description
IpAddress STRING(15) The IP address as a string.
ENO BOOL The class was initialized.
NumInterfaces UDINT The number of interfaces the agent device has.
MessagesReceived UDINT The total number of responses and traps re-
ceived from the manager object since ENO last
became true.
TimeSinceLastMessage TIME The elapsed time since the last message from
this device.
Error STRING(255) The last error encountered will be described
here. It will not be cleared.
GetInterfaceStatus (Method)
This method provides the status of the specified interface.
Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.
Return Value
IEC 61131 Type Description
enum_InterfaceStatus The state of the requested interface.
Processing
ä Check that interfaceIndex is within the specified range. Return NONE if it is not.
GetInterfaceInfo (Method)
This method returns the information obtained from walking OID 1.3.6.1.2.1.2.2.1 before
the ENO output was true. NOTE: iso(1) . org(3) . dod(6) .
internet(1) . mgmt(2) . mib-2(1) .
interfaces(2) . ifTable(2) . ifEntry(1)
Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.
Outputs
Name IEC 61131 Type Description
info struct_InterfaceInfo The structure containing the interface information.
Return Value
IEC 61131 Type Description
BOOL TRUE if the object is initialized and the interfaceIndex is in range.
Processing
ä Check that interfaceIndex is within the specified range. Return FALSE if it is not,
leaving the output in an undefined state.
ä Copy internal information to the output and return true.
Reinitialize (Method)
Returns the agent to an uninitialized state, resulting in the ENO output being set to false.
From this point, the agent automatically tries to re-initialize, refreshing all port information
in the process.
class_SEL2730MAgent (Class)
This class has all of the functionality of the class_SnmpAgentMonitor. However, because
the number of ports are known in advance, the class also displays the port statuses as pins.
Because this class contains knowledge of the device, future changes to SEL-2730M firmware
may change interface enumerations in SNMP. All versions of SEL-2730M firmware that
do not impact the assumptions in SEL-2730M Assumptions on page 38.8 will work.
SEL-2730M Assumptions
1. Port F up/down status is not accessible via SNMP get request. Where all other
ports default to NONE and then report the status of SNMP get requests, this port
defaults to UNKNOWN until a trap is received and then changes to UP or DOWN
as appropriate.
2. Ports 1–24 can be accessed through use of a GetNextRequest SNMP command.
The order of the ports is unimportant.
3. The description field of Ports 1–24 always ends with the port number. The OID
order is randomly defined at every boot, so the class uses the description to associate
the OID with the physical port index.
When instantiated, this class registers itself with the active class_SnmpManager. There is
no need to call methods on this class or to run it periodically because the manager class is
responsible for refreshing the state of all agent monitors.
This class monitors a generic SNMP agent device that has a list of network interfaces listed
under OID 1.3.6.1.2.1.2.2.1 4 . It also displays the number of interfaces the SNMP agent
provides in response to requesting the Integer32 value at OID 1.3.6.1.2.1.2.1 5 .
The list of interfaces is initially obtained by walking through all of the table objects. If
the number of interfaces returned by walking the interface table is less than the number of
interfaces OID 1.3.6.1.2.1.2.1 advertises, the device will not enable. If the interface infor-
mation from all interfaces can be obtained, then the object enables itself. Subsequently,
the agent only requests port statuses via OID 1.3.6.1.2.1.2.2.1.8.N 6 .
The port information obtained by GetInterfaceInfo() updates only during initializa-
tion, with the exception of ifOperStatus, which continually updates.
In the event that (a) the agent does not receive replies to requests for ifOperStatus, (b) the
quantity of interfaces changes, or (c) the indexing of the monitored interfaces changes, this
block sets ENO to FALSE and attempts to reinitialize.
Traps from SEL-2730M devices have a known structure, so traps sent to this agent monitor
from the class_SnmpManager are parsed. The textual message contained in a trap that is
displayed in the LastMessage output. If the trap indicates a port status change, the state of
the indicated port updates accordingly.
Whether by traps or periodic queries, the output pin statuses update automatically without
the implementer having to call any methods or the body of the class.
Initialization Inputs
Name IEC 61131 Type Description
ipAddress STRING(15) The IP address of the monitored agent as a string.
communityString STRING(80) A string that designates the community this agent de-
vice has been assigned. This ID is included in every
packet the agent and manager send.
tus(8) . item(N).
Outputs
Name IEC 61131 Type Description
IpAddress STRING(15) The IP address as a string.
ENO BOOL The class was initialized.
NumInterfaces UDINT The number of interfaces the agent de-
vice has.
MessagesReceived UDINT The total number of responses and
traps received from the manager ob-
ject since ENO last became true.
TimeSinceLastMessage TIME The elapsed time since the last mes-
sage from this device.
Error STRING(255) The last error encountered will be de-
scribed here. It will not be cleared.
LastMessage STRING(255) The first 255 characters of the last
string message from this device.
PortStatus ARRAY[0..24] OF The state of all ports. Index 0 is ETHF,
enum_InterfaceStatus Index 1 is Port 1, Index 24 is Port 24.
GetPortInfo (Method)
This method returns the information obtained from walking OID 1.3.6.1.2.1.2.2.1 before
the ENO output was true. The index provided is the port number for the SEL-2730M instead NOTE: iso(1) . org(3) . dod(6) .
internet(1) . mgmt(2) . mib-2(1) .
of an arbitrary order. interfaces(2) . ifTable(2) . ifEntry(1).
Inputs
Name IEC 61131 Type Description
portNumber UDINT(0..24) The port index on the switch. portNumber 0 is for ETHF,
1 is for Port 1, and 24 is for Port 24.
Outputs
Name IEC 61131 Type Description
info struct_InterfaceInfo The structure containing the interface information.
Return Value
IEC 61131 Type Description
BOOL TRUE if the object is initialized and the requested port number is in range.
GetInterfaceStatus (Method)
This method provides the status of the specified interface.
Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.
Return Value
IEC 61131 Type Description
enum_InterfaceStatus The state of the requested interface.
Processing
ä Check that interfaceIndex is within the specified range. Return NONE if it is not.
ä Return the state of the specified interface.
GetInterfaceInfo (Method)
This method returns the information obtained from walking OID 1.3.6.1.2.1.2.2.1 before
the ENO output was true. NOTE: iso(1) . org(3) . dod(6) .
internet(1) . mgmt(2) . mib-2(1) .
interfaces(2) . ifTable(2) . ifEntry(1)
Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.
Outputs
Name IEC 61131 Type Description
info struct_InterfaceInfo The structure containing the interface information.
Return Value
IEC 61131 Type Description
BOOL TRUE if the object is initialized and the interfaceIndex is in range.
Processing
ä Check that interfaceIndex is within the specified range. Return FALSE if it is not,
leaving the output in an undefined state.
ä Copy internal information to the output and return true.
Reinitialize (Method)
Returns the agent to an uninitialized state, resulting in the ENO output being set to false.
From this point, the agent automatically tries to re-initialize, refreshing all port information
in the process.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware
ä SEL-3530-4
â R133-V0 firmware
ä SEL-3505
â R133-V0 firmware
class_SnmpAgentMonitor.GetInterfaceStatus()
The posted time is the average execution time of 100 method calls.
class_SnmpAgentMonitor.GetInterfaceInfo()
The posted time is the average execution time of 100 method calls.
class_SnmpAgentMonitor.Reinitialize()
The posted time is the average execution time of 100 method calls.
class_SEL2730MAgent.GetPortInfo()
The posted time is the average execution time of 100 method calls.
class_SEL2730MAgent.GetInterfaceStatus()
The posted time is the average execution time of 100 method calls.
class_SEL2730MAgent.GetInterfaceInfo()
The posted time is the average execution time of 100 method calls.
class_SEL2730MAgent.Reinitialize()
The posted time is the average execution time of 100 method calls.
Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3555 SEL-3530-4 SEL-3505
class_SnmpManager.Run() 22 409 644
class_SnmpAgentMonitor.GetInterfaceStatus() 1 11 49
class_SnmpAgentMonitor.GetInterfaceInfo() 1 4 92
class_SnmpAgentMonitor.Reinitialize() 1 65 12
class_SEL2730MAgent.GetPortInfo() 1 8 47
class_SEL2730MAgent.GetInterfaceStatus() 1 8 37
class_SEL2730MAgent.GetInterfaceInfo() 1 6 18
class_SEL2730MAgent.Reinitialize() 1 19 21
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
ä The RTAC being programmed can access three SEL-2730M devices configured on
the network. These SEL-2730M devices have the following IP addresses:
â 10.203.50.1
â 10.203.50.101
â 10.203.50.201
ä The user has configured these switches to communicate with the RTAC via SNMP.
This means the following:
â The user has added a v2c profile to the switch with the community string
“Switches” and at least Read permissions.
â The user has added the RTAC to the switch as a trap server using the desired
profile.
ä The RTAC, configured as the SNMP manager, has an IP address 10.203.50.2.
ä The Main task of the RTAC is not used for real-time critical purposes, making it
appropriate to instantiate the SNMP manager object on the Main task.
ä The RTAC has two access points configured to allow UDP traffic as follows:
â UDP incoming on Port 161 for normal SNMP
â UDP incoming on Port 162 for SNMP traps
Solution
On the Main task, the user can create a program as shown in Code Snippet 38.1.
// Run the SnmpManager, which is responsible for doing all the required
work.
SnmpManager.Run();
SyslogCollector
Introduction
This library allows the RTAC to receive syslog messages from other devices. Once the
RTAC receives a syslog message, the contents of the message are available to the IEC 61131
logic engine. Logic can be performed on the syslog messages to accomplish the following:
ä Store syslog messages into the SOE log of the RTAC.
ä Create a custom syslog file with the FileIO library.
ä Map syslog data into protocol servers.
ä Display syslog messages on RTAC HMI screens.
ä Generate an email or text message.
ä Generate syslog messages based on received syslog messages with modified content.
The syslog message is presented to the logic engine as a string data type. Anything that
can be done with a string in the logic engine can be done with the received syslog message.
This library offers the ability to filter received syslog messages based on its origin IP ad-
dress. It also allows for automatically logging the received syslog messages into the RTAC
SOE.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
struct_syslogMessageFormat
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
enum_severity
This enumeration lists the different severity levels allowed in syslog.
enum_facility
This enumeration lists the different facility levels allowed in syslog.
Function Blocks
fb_syslogCollector (Function Block)
This function block makes syslog messages that were received on one of the IP addresses
of the RTAC available to the IEC 61131 logic engine.
Inputs
Name IEC 61131 Type Description
LocalIPAddress STRING(15) Specify an RTAC IP address on which to
listen. Default is 0.0.0.0, which listens
on all interfaces.
LocalPortNumber UINT Defaults to 514, which is the standard
syslog port.
LogReceivedSyslog BOOL If TRUE, received syslog data will be en-
tered into the RTAC SOE log.
FilterOnSeverity enum_Severity If set to a value other than NONE, the
RTAC will only log syslog messages that
have a severity of NONE or higher. De-
fault value is NONE.
UseSeverityInSyslogMessage enum_Severity If set to a value other than NONE, re-
ceived syslog messages will use this
severity when logged. If set to NONE,
logged syslog messages will use the
severity received in message. Default
value is NONE.
IPAddressFilterList STRING(1600) Enter a comma-separated list of IP ad-
dresses for the RTAC to process syslog
messages from. If left empty, the RTAC
processes all received syslog messages.
Outputs
Name IEC 61131 Type Description
RecSyslogMessage ARRAY[1..50] OF struct_SyslogMessageFormat Received syslog
messages.
InvalidInputPin STRING Lists an incorrectly
configured input pin.
Processing
ä This function block will log received syslog messages in the RTAC SOE if the Lo-
gReceivedSyslog input is set to TRUE. If the syslog message is longer than 255
characters, the logged message will be truncated and MessageTruncated will be
appended to the end of the SOE message.
ä This function block filters received syslog messages based upon the originating IP
address. These addresses can be entered into the IPAddressFilterList input. If this
value is left empty or set to 0.0.0.0 (which is the default setting), the function block
will process all received syslog messages.
ä This function block will process as many as 50 received syslog messages per process-
ing cycle. If the RTAC receives more than 50 syslog messages in a single processing
cycle, the excess messages will be buffered and processed in a subsequent process-
ing interval. The function block displays processed messages for a single processor
cycle.
ä By default, Port 514 is used to listen for syslog messages. This can be changed by
configuring the LocalPortNumber input to a desired port to listen for syslog mes-
sages.
ä This function block only processes UDP-based syslog messages. No TCP syslog
messages are processed with this function block.
ä This function block must be used in conjunction with an Ethernet listening UDP
incoming access point that matches the LocalPortNumber input. Unless the input pin
is configured to a nondefault value, this port must be 514 on the Ethernet listening
UDP incoming access point.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
A UPD incoming access point needs to be included in the project configuration. The Local
Port Number setting input of the port must match the LocalPortNumber setting on the
syslog function block, as shown in Figure 39.1 and Code Snippet 39.1.
Solution
The syslog function block can be used as shown in Code Snippet 39.1. This example shows
the function block processing all received syslog messages on a specified interface (by
entering the IP address used on that interface). This example also shows the function block
storing all received messages with their received severity levels into the SOE log of the
RTAC.
_syslogCollector(LocalIPAddress := '192.168.1.2',
LocalPortNumber := 514,
LogReceivedSyslog := TRUE,
FilterOnSeverity := SyslogCollector.enum_severity.None,
UseSeverityInSyslogMessage := SyslogCollector.enum_severity.None,
IPAddressFilterList := '');
TrendRecorder
Introduction
This library provides flexible and scalable analog trend recording capability to the RTAC. It
can provide ACSELERATOR TEAM® SEL-5045 Software Load Data Profile (LDP) records,
which are viewable via ACSELERATOR Meter Reports SEL-5630 Software.
By using intuitive function blocks, users can configure as many as 12 different recorders,
each capable of recording 16 analog values. Two types of recorders are available: an inter-
val recorder and a monitor recorder. The interval recorder uses a recording interval setting
and records all 16 analog values each interval. The monitor recorder has a record time and
a trigger input. Recording occurs when the rising edge of the trigger is observed and the
time provided by the record time input is associated with the record (instead of the internal
time source of the RTAC). Each recorder records the value of each analog at the time the
record occurs (also known as an end-of-Interval recorder).
This document provides detailed information about the purpose and functionality of each
function block (along with its inputs and outputs). It also provides a configuration example.
Special Considerations
Record Storage Space
The TrendRecorder library uses files stored on the RTAC file system to record data. The
amount of data that can be retained is dependent on the available hard drive space as well
as the recording interval configured for each recorder.
// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type
class_ProfileRecorderObject"
myProfileRecorderObject := otherProfileRecorderObject;
// This is fine
someVariable := myProfileRecorderObject.value;
// As is this
pt_myProfileRecorderObject := ADR(myProfileRecorderObject);
Usage
The purpose of this library is to provide analog trend recording capability to the RTAC in a
way that requires as little configuration as possible. All settings required for recorder setup
are completed with only three function blocks (see Function Blocks on page 40.4 for more
detail). This section provides information about the intended usage of the TrendRecorder
library as well as some details about operations that occur in the background.
Theory of Operation
The TrendRecorder library is designed to interface with TEAM. TEAM collects the recorded
data in LDP format and saves it into the ACSELERATOR Database. The collected data is
then available for other software solutions, such as ACSELERATOR Meter Reports SEL-
5630 Software.
It is important to note that the TrendRecorder library can record analog values from any
capable source—it is not limited only to typical load profile or even electrical) values. As
long as the analog is of type REAL, it can be recorded.
The core of the TrendRecorder library user interface consists of two profile recorder func-
tion blocks: ProfileIntervalRecorder and ProfileTriggerRecorder. Contained within these
two function blocks is everything the RTAC needs to collect and record analog data. Simply
instantiate one or more of them in a Continuous Function Chart (CFC) program, connect
each recorder to the ProfileManager function block, create a Telnet Access Point, and start
collecting recorded data. Each recorder records 16 analogs, and as many as 12 recorder
function blocks can be instantiated (192 total analogs can be recorded in a single RTAC).
Function Blocks
This library provides three function blocks for use in setting up trend recorders: ProfileIn-
tervalRecorder, ProfileTriggerRecorder, and ProfileManager. You only need these function
blocks to configure fully functional profile recording in the RTAC.
Inputs
Name IEC 61131 Type Description
ConnectToProfileManager This pin must be connected to the ProfileM-
anager. This connection is required for the
recorder to save data and for the manager to
retrieve data when TEAM requests it.
RecorderNumber UINT The recorder number (1–12) to assign to
the recorder. Any recorder with a recorder
number outside of this range will not record
data. Any recorders that duplicate a recorder
number will not record data.
RecordingInterval UINT The interval (1–7200, in seconds) at which
to record data. If no RecordingInterval is
provided, the recorder will default to a set-
ting of 60 seconds. Any interval value less
than one will be forced to a setting of one.
Any interval value greater than 7200 will be
forced to a setting of 7200.
Channel[n]_Data REAL The analog inputs to be recorded, where n
is the channel number from 1–16. Zeros are
recorded for all disconnected channel data
inputs.
Channel[n]_Name STRING(15) The names of analogs to be recorded, where
n is the channel number from 1–16. Chan-
nel names longer than 15 characters will be
truncated to the first 15 characters. If no
value is assigned, the channel name will be
set to Chan [n] Rec [x], where n is the chan-
nel number and x is the recorder number.
Outputs
Name IEC 61131 Type Description
SettingsError BOOL This output asserts if the recorder has a settings error. If
this output is asserted, the recorder will not function.
Inputs
Name IEC 61131 Type Description
ConnectToProfileManager This pin must be connected to the ProfileM-
anager. This connection is required for the
recorder to save data and for the manager to
retrieve data when TEAM requests it.
RecorderNumber UINT The recorder number (1–12) to assign to
the recorder. Any recorder with a recorder
number outside of this range will not record
data. Any recorders that duplicate a recorder
number will not record data.
RecordTrigger UINT The recording trigger. Asserting this trigger
at a rate as high as once per second will re-
sult in data being recorded.
RecordTime DT The record time that will be used when
recording data. If this input is not provid-
ing a valid time or is left disconnected, the
internal time of the RTAC will be used in-
stead.
Channel[n]_Data REAL The analog inputs to be recorded, where n
is the channel number from 1–16. Zeros are
recorded for all disconnected channel data
inputs.
Channel[n]_Name STRING(15) The names of analogs to be recorded, where
n is the channel number from 01–16. Chan-
nel names longer than 15 characters will be
truncated to the first 15 characters. If no
value is assigned, the channel name will be
set to Chan [n] Rec [x], where n is the chan-
nel number and x is the recorder number.
Outputs
Name IEC 61131 Type Description
SettingsError BOOL This output asserts if the recorder has a settings er-
ror. If this output is asserted, the recorder will not
function.
RecordingBlocked BOOL This output asserts immediately following an asser-
tion of the RecordTrigger input and remains asserted
for one second. When asserted, no recording occurs,
and any assertion of the RecordTrigger input is ig-
nored.
Inputs
Name IEC 61131 Type Description
DeviceID STRING(22) The RTAC device description. Inputs greater than 22 char-
acters are truncated to 22 characters.
TerminalID STRING(22) A description of the function or location of the RTAC. In-
puts greater than 22 characters are truncated to 22 charac-
ters.
FID STRING The Firmware ID of the RTAC. SystemTags.FID must be
connected to this input. If this input is not connected, no
recording occurs.
Outputs
Name IEC 61131 Type Description
ConnectToRecorders The connection point for the ConnectToProfileM-
anager pins on each configured recorder. Each
recorder must be connected to this pin in order to
function.
DataStorageWarning BOOL This output asserts when not enough storage
space is available to meet the requirements of the
current recorder configurations. When this out-
put asserts recorders will run out of storage space
within 30 days. To resolve this issue either free
up hard drive space on the RTAC or reduce the
number of configured recorders.
DataStorageError BOOL This output asserts when no storage space is avail-
able, indicating no new data are being saved.
SettingsError BOOL This output asserts if the manager has a settings
error. If asserted, none of the recorders will func-
tion.
Telnet Communications
The ProfileManager function block uses Telnet to provide trend data to external clients
such as TEAM. To be able to communicate via Telnet on the RTAC, an Access Point with
Network Connection Type of Telnet and Local Port Number of 23 must be added to the
RTAC project.
Recorder Operation
Recording Interval Functionality
The ProfileIntervalRecorder attempts to time-align the recording interval with the top of
minute, top of hour, or top of day. This makes for cleaner chart generation and data visu-
alization. The following table describes how each interval setting is adjusted.
Settings Changes
When the settings of a recorder are changed, all of the saved data for that recorder is re-
moved from the RTAC. A loss of data in other recorders could also occur because of storage
reallotment caused by the addition of a new recorder.
Changes to settings elsewhere in the RTAC (i.e., not recorder settings) will not result in
deleted data. The only data loss that may occur would be caused by a missed recording
interval during the sending of the new settings to the RTAC.
The Trend Recorder function blocks require 60 seconds to initialize after startup, regardless
of settings change.
Do not remove or modify the files stored in the LDP folder on the RTAC. These files contain
settings and record data. Tampering with or removing these files may result in recorder data
loss or deletion.
SOE Logging
Trend Recorder logs settings errors and storage space errors to the RTAC SOE log.
Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R136-V0
ä SEL-3530
â R136-V0
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R136-V0
Benchmark Results
Note: The benchmarks were not found to be different in any statistically significant way
from those for the previous release, so the numbers have not been updated.
Web_Client_SL
Introduction
The Web_Client_SL library provides mechanisms to act as an HTTP client and make ap-
propriate requests.
Implementation Note
This library is provided as a member of the CODESYS® IIoT package as a special offer-
ing available in the SEL RTAC. The functionality provided by this resource is generally
intended to operate in generic CODESYS® environments. As such, some limitations may
be encountered when implementing these resources in the SEL RTAC. Any POUs or POU
inputs that may be subject to these limitations are marked accordingly in this document.
Global Constants
This section lists the global constants provided for interacting with the web client.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
Enumerations defined in this, the Web Client SL library, provide control of the various
HTTP request mechanisms.
CONTENT_TYPE
Enumeration Description
APPLICATION_FORM HTML-Form
APPLICATION_JSON JSON data
NONE Do not set the “content type” in the HTTP header.
REQUEST_TYPE
Enumeration Description
GET Use HTTP “GET” verb.
POST Use HTTP “POST” verb (needs input pwsPostValue).
DELETE Use HTTP “DELETE” verb.
PUT Use HTTP “PUT” verb (needs input pwsPostValue).
HEAD Use HTTP “HEAD” verb.
PATCH Use HTTP “PATCH” verb.
ERROR
Enumeration Description
NO_ERROR No error.
TIME_OUT Time out.
UNEXPECTED_ERROR Unexpected error.
TCP_INIT_ERROR Unable to initialize the TCP
socket.
TCP_READ_ERROR Error while reading response.
TCP_WRITE_ERROR Error while sending the request.
MISSING_POST_VALUE Current request type needs a post
value.
RESULT_PARSE_ERROR Error while parsing the re-
sponse.
MAXIMUM_SIZE_EXCEEDED Maximum size of buffer ex-
ceeded.
CONVERT_ERROR Converting error (UTF-8 to
UTF-16 or UTF-16 to UTF-8).
POST_VALUE_IS_NULL Post value is null.
UNSUPPORTED_OAUTH2_CREDENTIAL_INTERFACE Supported interfaces:
IOAuth2ClientCredentials
and IOAuth2ResourceOwner-
Credentials.
OAUTH2_AUTHENTICATION_SERVER_ERROR Error while sending request to
authentication server.
OAUTH2_REQUEST_ERROR Error while sending request to
resource server.
OAUTH2_REFRESH_ACCESS_TOKEN_ERROR Error while refreshing access to-
ken.
INVALID_LICENSE RTAC firmware does not ad-
equately provide IIoT informa-
tion.
RESOLVE_HOSTNAME_FAILED The hostname cannot be re-
solved.
NOT_FOUND Value or key not found.
MAXIMUM_TOKEN_SIZE_EXCEEDED Maximum size of access token
or refresh token exceeded.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Structures defined in this, the Web Client SL library, are positioned to be provide functional
access for the various web requests being made.
KeyValue
Name IEC 61131 Type Description
sKey STRING(255) Key of key-value pair.
sValue STRING(255) Value of key-value pair.
HttpResult
Name IEC 61131 Type Description
iStatus INT HTTP status
wsHeader WSTRING(g_udiMaxHeaderSize) HTTP header as WSTRING
wsContent WSTRING(g_udiMaxResponseSize) result of the request as WSTRING
sHeader STRING(g_udiMaxHeaderSize) HTTP header as STRING
sContent STRING(g_udiMaxResponseSize) result of the request as STRING
diContentLength DINT length of wsContent
Functions
This library provides functions to perform various operations in relation to URL encod-
ing/decoding and byte-encoding conversions.
ConvertUTF16toUTF8 (Function)
This function converts a WSTRING (UTF16) to a STRING (UTF8).
Inputs
Name IEC 61131 Type Description
sourceStart POINTER TO WORD Pointer to WSTRING.
targetStart POINTER TO BYTE Pointer to STRING.
dwTargetBufferSize DWORD Size of STRING.
bStrictConversion BOOL Require strict conversion technique.
Return Value
IEC 61131 Type Description
UDINT Number of WORD characters converted.
ConvertUTF8toUTF16 (Function)
This function converts a STRING (UTF8) to a WSTRING (UTF16).
Inputs
Name IEC 61131 Type Description
sourceStart POINTER TO BYTE Pointer to STRING.
targetStart POINTER TO WORD Pointer to WSTRING.
dwTargetBufferSize DWORD Size of WSTRING.
bStrictConversion BOOL Require strict conversion technique.
Return Value
IEC 61131 Type Description
UDINT Number of BYTE characters converted.
BASE64_DECODE (Function)
This function decodes a Base-64 string.
Inputs
Name IEC 61131 Type Description
diSizeIn DINT Size of “in”.
in POINTER TO BYTE Input: Pointer to the source STRING.
out POINTER TO BYTE Output: Pointer to destination STRING.
Outputs
Name IEC 61131 Type Description
diSizeOut DINT Number of BYTE characters decoded.
BASE64_ENCODE (Function)
This function encodes a Base-64 string.
Inputs
Name IEC 61131 Type Description
diSizeIn DINT Size of “in”.
in POINTER TO BYTE Input: Pointer to the source STRING.
out POINTER TO BYTE Output: Pointer to destination STRING.
Outputs
Name IEC 61131 Type Description
diSizeOut DINT Number of BYTE characters encoded.
FindJSONValue (Function)
Finds the corresponding value of a key in a JSON WSTRING. Objects and arrays are NOT
supported.
Inputs
Name IEC 61131 Type Description
pwsIn POINTER TO WORD Pointer to the source JSON WSTRING.
udiSizeIn DINT Size of “pwsIn”.
pwsKey POINTER TO WORD Pointer to key WSTRING.
diSearchStartPos DINT Start position of the search.
Inputs/Outputs
Name IEC 61131 Type Description
wsValue WSTRING(255) Identified value corresponding to key.
Return Value
IEC 61131 Type Description
DINT Index of the value in the JSON STRING.
FindJSONValue2 (Function)
Finds the corresponding value of a key in a JSON WSTRING. Objects and arrays are NOT
supported.
Inputs
Name IEC 61131 Type Description
pwsIn POINTER TO WORD Pointer to the source JSON WSTRING.
udiSizeIn UDINT Size of “pwsIn”.
pwsKey POINTER TO WORD Pointer to key WSTRING.
diSearchStartPos DINT Start position of the search.
pwsValue POINTER TO WSTRING Pointer to the result value.
udiValueSize UDINT Size of “pwsValue”.
Outputs
Name IEC 61131 Type Description
eError ERROR Error generated during search.
Return Value
IEC 61131 Type Description
DINT Index of the value in the JSON STRING.
URL_ENCODE_STRING (Function)
Encodes a STRING into a format appropriate for URLs.
Inputs
Name IEC 61131 Type Description
pbIn POINTER TO BYTE Pointer to the source STRING.
Return Value
IEC 61131 Type Description
STRING(Param.g_udiMaxRequestSize) Index of the value in the JSON STRING.
URL_ENCODE_STRING2 (Function)
Encodes a STRING into a format appropriate for URLs.
Inputs
Name IEC 61131 Type Description
pbIn POINTER TO BYTE Pointer to the source STRING.
pbOut POINTER TO BYTE Pointer to the destination URL-encoded STRING.
udiSizeOut UDINT Maximum size of the destination buffer.
URL_ENCODE_WSTRING (Function)
Encodes a WSTRING into a format appropriate for URLs.
Inputs
Name IEC 61131 Type Description
pbIn POINTER TO BYTE Pointer to the source WSTRING.
Return Value
IEC 61131 Type Description
WSTRING(Param.g_udiMaxRequestSize) Index of the value in the JSON WSTRING.
URL_ENCODE_WSTRING2 (Function)
Encodes a WSTRING into a format appropriate for URLs.
Inputs
Name IEC 61131 Type Description
pbIn POINTER TO BYTE Pointer to the source WSTRING.
pbOut POINTER TO BYTE Pointer to the destination URL-encoded WSTRING.
udiSizeOut UDINT Maximum size of the destination buffer.
Interfaces
This library provides the following interfaces.
IOAuth2Credentials
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
IOAuth2ClientCredentials
This interface extends IOAuth2Credentials.
IOAuth2ClientCredentials
This interface extends IOAuth2Credentials and provisions additional interface properties.
Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).
Function Blocks
The Web Client SL library provides various function block to interact with the respective
web client functionalities.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä IOAuth2ClientCredentials
Inputs
Name IEC 61131 Type Description
wsClientId WSTRING(255) Client ID as a WSTRING.
wsClientSecret WSTRING(255) Client secret as a WSTRING.
wsScope WSTRING(255) Client scope as a WSTRING.
Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä IOAuth2ResourceOwnerCredentials
Inputs
Name IEC 61131 Type Description
wsClientId WSTRING(255) Client ID. Leave blank if not used.
wsClientSecret WSTRING(255) Client Secret. Leave blank if not used.
wsPassword WSTRING(255) Resource owner password.
wsUsername WSTRING(255) Username of the resource owner.
wsScope WSTRING(255) Scope. Leave blank if not used.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
HTTPResult HttpResult The result of the request.
Inputs
Name IEC 61131 Type Description
wsLogin WSTRING(255) Login username.
wsPassword WSTRING(255) Login password.
xExecute BOOL Rising edge: Send request.
udiTimeOut UDINT Timeout in microseconds.
sURL STRING(1024) URL of the web server (resource server).
eRequestType REQUEST_TYPE Type of the request: POST or GET.
eContentType CONTENT_TYPE HTTP Content-Type of the request.
pwsAdditionalHeader POINTER TO WSTRING Additional HTTP header.
pwsPostValue POINTER TO WSTRING Post parameter.
xCloseConnection BOOL Close the connection after each request.
hCert RTS_IEC_HANDLE Handle to a certificate (optional).
itfTLSContext NBS.ITLSContext Encapsulates all the data necessary to
handle encrypted TCP connections.
itfAsyncProperty NBS.IAsyncProperty Runs the connect process in a own back-
ground task, usage see library Net Base
Services.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
HTTPResult HttpResult The result of the request.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Sends request.
udiTimeOut UDINT Timeout in microseconds.
sURL STRING(1024) URL of the web server (resource server).
eRequestType REQUEST_TYPE Type of the request: POST or GET.
eContentType CONTENT_TYPE HTTP Content-Type of the request.
pwsAdditionalHeader POINTER TO WSTRING Additional HTTP header.
pwsPostValue POINTER TO WSTRING Post parameter.
xCloseConnection BOOL Close the connection after each request.
sOAuthConsumerKey STRING(255) OAuth1: Consumer key.
sOAuthToken STRING(255) OAuth1: Token.
sConsumerSecret STRING(255) OAuth1: Consumer secret.
sOAuthTokenSecret STRING(255) OAuth1: Token secret.
itfTLSContext NBS.ITLSContext Encapsulates all the data necessary to
handle encrypted TCP connections.
itfAsyncProperty NBS.IAsyncProperty Runs the connect process in a own back-
ground task, usage see library Net Base
Services.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
HTTPResult HttpResult The result of the request.
Classes
The Web Client SL library provides the following class in order to facilitate OAuth2 con-
nections.
OAuth2WebClient (Class)
Function block to a send a request via 2 legged OAuth2 authentication. Supported request
types (flows): client_credentials and password.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Sends re-
quest.
udiTimeOut UDINT Timeout in microseconds.
sURL STRING(1024) URL of the web server (re-
source server).
eRequestType REQUEST_TYPE Type of the request: POST
or GET.
eContentType CONTENT_TYPE HTTP Content-Type of the
request.
pwsAdditionalHeader POINTER TO WSTRING Additional HTTP header.
pwsPostValue POINTER TO WSTRING Post parameter.
sAuthorizationServerURL STRING(1024) URL of authorization
server.
pwsAdditionalAuthenticationHeader POINTER TO WSTRING Additional Auth HTTP
header.
xCloseConnection BOOL Close the connection after
each request.
itfTLSContext NBS.ITLSContext Encapsulates all the data
necessary to handle en-
crypted TCP connections.
itfAsyncProperty NBS.IAsyncProperty Runs the connect process
in a own background task,
usage see library Net Base
Services.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
HTTPResult HttpResult The result of the request.
ResetToken (Method)
Resets the access and refresh token. This method does not require any inputs, and provides
no return type. ResetToken should be called when the token should be refreshed.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
The following assumptions are made:
1. The RTAC is configured to use DNS, either by static configuration or by use of
DNS configuration over DHCP.
2. An httpbin service is accessible by the URL http://httpbin.org.
Solution
Code Snippet 41.1 prg_MakeAGETRequest
PROGRAM prg_MakeAGETRequest
VAR CONSTANT
c_HostURL : STRING := 'http://httpbin.org';
END_VAR
VAR
// Function block to perform HTTP requests.
client : WEB_CLIENT.WebClient;
Assumptions
The following assumptions are made:
1. The RTAC is configured to use DNS, either by static configuration or by use of
DNS configuration over DHCP.
2. An httpbin service is accessible by the URL http://httpbin.org.
3. The httpbin service will respond with a status code equivalent to that requested
with the endpoint /status/{code}; e.g., a request to http://httpbin.org/status/200 will
provide a status code of 200.
Solution
Code Snippet 41.2 prg_ExamineHttpStatusCode
PROGRAM prg_ExamineHttpStatusCode
VAR CONSTANT
c_HostURL : STRING := 'http://httpbin.org';
c_StatusEndpoint : STRING := '/status/';
END_VAR
VAR
// Function block to perform HTTP requests.
client : WEB_CLIENT.WebClient;
fullyQualifiedURL : STRING(255);
CONCAT (
c_StatusEndpoint ,
TO_STRING ( status )
)
);
// fullyQualifiedURL := http :// httpbin . org / status /200
Assumptions
The following assumptions are made:
1. The RTAC is configured to use DNS, either by static configuration or by use of
DNS configuration over DHCP.
2. An httpbin service is accessible by the URL http://httpbin.org.
3. The httpbin service will respond with echoed data POSTed to the endpoint /any-
thing.
Solution
Code Snippet 41.3 prg_EchoDataFromPOST
PROGRAM prg_EchoDataFromPOST
VAR CONSTANT
c_HostURL : STRING := 'http://httpbin.org';
c_EchoEndpoint : STRING := '/anything';
END_VAR
VAR
// Function block to perform HTTP requests.
client : WEB_CLIENT.WebClient;
fullyQualifiedURL : STRING(255);
result : WEB_CLIENT.HttpResult;
Web_Socket_Client_SL
Introduction
The Web_Socket_Client_SL library provides mechanisms to act as an HTTP client and
make appropriate requests.
Implementation Note
This library is provided as a member of the CODESYS® IIoT package as a special offer-
ing available in the SEL RTAC. The functionality provided by this resource is generally
intended to operate in generic CODESYS® environments. As such, some limitations may
be encountered when implementing these resources in the SEL RTAC. Any POUs or POU
inputs that may be subject to these limitations are marked accordingly in this document.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
Enumerations defined in this, the Web Socket Client SL library, provide control of the
various HTTP request mechanisms.
ERROR
Enumeration Description
NO_ERROR No error.
TIME_OUT Time out.
INVALID_LICENSE RTAC firmware does not adequately pro-
vide IIoT information.
URI_PARSE_ERROR Error while parsing the URI.
RESOLVE_HOSTNAME_FAILED Cannot resolve hostname.
CONNECTION_REFUSED Connection refused by server.
TLS_CONTEXT_ERROR Error while creating the TLS context.
FRAME_TYPE
Enumeration Description
TEXT The payload contains a text message.
BINARY The payload contains a binary message.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Structures defined in this, the Web Socket Client SL library, are positioned to be provide
functional access for the various web requests being made.
KeyValue
Name IEC 61131 Type Description
sProxyServer STRING(255) Hostname or IP address of the proxy server. Leave
blank if no proxy server is used.
uiProxyPort UINT Port of the proxy server.
sProxyUser STRING Name of the proxy user. Leave blank if no authentica-
tion is required.
sProxyPassword STRING Password of the proxy user.
Interfaces
This library provides the following interface.
IWebSocketClient
Interface of the WebSocket client.
Read (Method)
Read incoming messages.
Inputs
Name IEC 61131 Type Description
pData __XWORD Pointer to the payload data.
udiSize UDINT Maximum size of the payload.
Outputs
Name IEC 61131 Type Description
udiCount UDINT Size of the received data.
xReceived BOOL TRUE if data received.
eFrameType FRAME_TYPE Type of the payload.
xIsFinalFragment BOOL FALSE if the payload is incomplete and is sent via
multiple packets.
TRUE if the payload is complete or if the payload
was incomplete and this packet is the last packet of a
message.
Return Value
IEC 61131 Type Description
NBS.ERROR Generated error.
Write (Method)
Send messages to a WebSocket server.
Inputs
Name IEC 61131 Type Description
pData __XWORD Pointer to the payload data.
udiSize UDINT Maximum size of the payload.
eFrameType FRAME_TYPE Type of the payload data.
Return Value
IEC 61131 Type Description
NBS.ERROR Generated error.
Function Blocks
The Web Socket Client SL library provides various function block to interact with the
respective web client functionalities.
Inputs
Name IEC 61131 Type Description
xEnable BOOL TRUE: Activates the defined operation.
FALSE: Aborts/resets the defined operation.
itfWebSocketClient IWebSocketclient Reference to the WebSocketClient.
pData __XWORD Pointer to the payload data.
udiSize UDINT Maximum size of the payload.
Outputs
Name IEC 61131 Type Description
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
xReady BOOL TRUE: TRUE if data received.
udiCount UDINT Size of the received data.
eFrameType FRAME_TYPE Type of the payload.
xIsFinalFragment BOOL FALSE if the payload is incomplete and is sent via
multiple packets.
TRUE if the payload is complete or if the payload
was incomplete and this packet is the last packet of a
message.
Inputs
Name IEC 61131 Type Description
xEnable BOOL TRUE: Activates the defined operation.
FALSE: Aborts/resets the defined operation.
udiTimeOut UDINT Max. operating time for executing [ţs], 0: No op-
erating time limit.
itfWebSocketClient IWebSocketclient Reference to the WebSocketClient.
pData __XWORD Pointer to the payload data.
udiSize UDINT Size of the payload.
eFrameType FRAME_TYPE Type of the payload data. NOTE: It can take more than one
cycle to send a message if the payload
is greater than the maximum buffer
size.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
udiCount UDINT Size of the received data.
Classes
The Web Socket Client SL library provides the following class in order to facilitate web
socket connections.
WebSocketClient (Class)
Function block to establish a connection to a WebSocket server.
Inputs
Name IEC 61131 Type Description
xEnable BOOL TRUE: Activates the defined operation.
FALSE: Aborts/resets the defined operation.
itfTLSContext NBS.ITLSContext User-defined TLS context for encrypted TCP con-
nections (only for wss-URIs). If the TLS context
is 0 then a default TLS context will be created for
wss-URIs.
itfAsyncProperty NBS.IAsyncProperty Runs the connect process in a background task.
Use this property if the connection setup takes
longer than one task cycle (e.g., TLS connections).
udiTimeOut UDINT Defines the time (ţs) after which the connection
setup aborts with xError.
sProtocol STRING Sec-WebSocket-Protocol. The underlaying sub-
protocols like “mqtt”. Default: “chat”.
sExtensions STRING Sec-WebSocket-Extensions. Note: The extension
data must be added manually to the payload data.
Default: “”, no extension.
tPingInterval TIME Ping interval, T#0s: no ping.
httpProxySettings HttpProxySettings Optional HTTP proxy settings.
udiBufferSize UDINT The maximum size of the send and receive buffer.
Changes during an online change have no effect on
the buffer size.
Inputs/Outputs
Name IEC 61131 Type Description
sUri STRING(1024) The URI of the server, e.g., “ws://localhost:8080” ws-URI =
“ws:” “//” host [ “:” port ] path [ “?” query ] wss-URI = “wss:”
“//” host [ “:” port ] path [ “?” query ].
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
udiCount UDINT Size of the received data.
xActive BOOL TRUE if a connection is established.
eError ERROR Output error.
sSupportedProtocols STRING Supported protocols (server side).
sSupportedExtensions STRING Supported extensions (server side).
Read (Method)
Read incoming messages. If a message was received, then the message is copied to pData
and xReceived is set to TRUE. udiCount corresponds to the size of the received data.
Outputs
Name IEC 61131 Type Description
udiCount UDINT Size of the received data.
xReceived BOOL TRUE if data received.
eFrameType FRAME_TYPE Type of the payload.
xIsFinalFragment BOOL FALSE if the payload is incomplete and is sent via
multiple packets.
TRUE if the payload is complete or if the payload
was incomplete and this packet is the last packet of a
message.
Return Value
IEC 61131 Type Description
NBS.ERROR Resultant status.
Write (Method)
Sends messages to a WebSocket server. This method sends the payload pData with the size
udiSize to the server.
Inputs
Name IEC 61131 Type Description
pData __XWORD Pointer to the payload data.
udiSize UDINT Size of the payload.
eFrameType FRAME_TYPE Type of the payload data.
Return Value
IEC 61131 Type Description
NBS.ERROR Resultant status.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
The following assumptions are made:
1. The RTAC is configured to use DNS, either by static configuration or by use of
DNS configuration over DHCP.
2. An echo-server service is accessible by the URL http://echo.websocket.events/.
Solution
Code Snippet 42.1 prg_MakeAGETRequest
PROGRAM prg_MakeAGETRequest
VAR CONSTANT
c_HostURL : STRING := 'http://echo.websocket.events/';
END_VAR
VAR
// Function block to establish WS connection.
client : WEB_SOCKET.WebSocketClient;
// Results
result_write, result_read : WEB_SOCKET.NBS.ERROR;
// WS Interval
sendInterval : SELUtils.TI := (PT:=T#2S);
// Payload data
payload : STRING(1024)
response : STRING(1024)
END_VAR
sendInterval () ;
IF sendInterval . Q THEN
// Write to the websocket
result_write := client . Write (
pData := ADR ( payload ) ,
udiSize := TO_UDINT ( LEN ( payload ) )
);
END_IF
XML_Utility_SL
Introduction
The XML_Utility_SL library provides mechanisms to generate and parse XML (Extensible
Markup Language) data structures from any structure whose characters are accessible by
byte-wise operations (example structures include Dynamic Vectors, STRINGs, and arrays
of BYTEs). The library can read and write UTF-8 and UTF-16 coded well-formed XML
files.
Supported XML elements are as follows:
1. Standard element <xxx>aaa</xxx> and <xxx />
2. Attributes yyy="zzz"
3. Comments <!– Comment –>
4. CDATA elements
Each element of the file is stored in a structure of the type XMLElement. A complete XML
file or parts of it will be stored in an array of structures.
Parameters
Reading data is buffered. The size of the buffer must greater than the size of the largest
XML element. The size of the buffer and the maximum WSTRING size of the structure
XMLElement can be changed in the parameter list (param) of the library manager. The
size of the data array can be declared individually outside the function blocks.
Implementation Note
This library is provided as a member of the CODESYS® IIoT package as a special offer-
ing available in the SEL RTAC. The functionality provided by this resource is generally
intended to operate in generic CODESYS® environments. As such, some limitations may
be encountered when implementing these resources in the SEL RTAC. Any POUs or POU
inputs that may be subject to these limitations are marked accordingly in this document.
Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.
Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.
Enumerations defined in this, the XML Utility SL library, provide control of the various
JSON parser/serializer mechanisms.
ERROR
Enumeration Description
NO_ERROR No error.
TIME_OUT Time out.
FILE_OPEN_ERROR Could not open file.
INVALID_HANDLE Open file retuned invalid handle.
READ_ERROR Could not read file.
WRITE_ERROR Could not write file.
SET_POS_FAILED Invalid file position.
NOT_FOUND Element not found.
START_TAG_NOT_FOUND Start tag of the element not found.
NEXT_START_TAG_NOT_FOUND Next start element not found.
ELEMENT_EXCEEDS_BUFFERSIZE Element size exceeds buffer size. Increment the
value of gc_udiBufferSize.
COMMENT_EXCEEDS_BUFFERSIZE Comment size exceeds buffer size. Increment the
value of gc_udiBufferSize.
BLANK_NOT_FOUND Missing blank between attributes.
MAX_ELEMENT_SIZE_EXCEEDED Maximum array size of XMLElements exceeded.
DATA_ARRAY_POINTER_IS_NULL Data pointer is null.
EMPTY_DATASET Empty dataset.
MAX_VALUE_SIZE_EXCEEDED Maximum value size exceeded. Increment the value
of gc_udiMaxValueSize.
INVALID_LICENSE RTAC firmware does not adequately provide IIoT in-
formation.
Encoding
Enumeration Description
UTF8 UTF-8 encoding.
UTF16 UTF-16 encoding.
ElementType
Enumeration Description
Element Marks an element.
CDATAElement Marks an element with CDATA.
Attribute Marks an attribute of an element.
Comment Marks an comment.
NotSet Marks an empty element.
READ_MODE
Enumeration Description
ONE_ELEMENT Reads only the specified element.
CHILDREN_ONLY Reads all child elements of the specified element.
RECURSIVE Reads all underlying elements of the specified element.
Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Structures defined in this, the XML Utility SL library, are positioned to be provide func-
tional access to JSON data.
XMLElement
Name IEC 61131 Type Description
diParentIndex DINT The index of the parent XMLElement.
wsName WSTRING(gc_udiMaxValueSize) The name of the XML element.
wsValue WSTRING(gc_udiMaxValueSize) The value of the XML element.
udiPosition UDINT Position of the start tag in XML file.
elementType ElementType Type of the element (Element, Attribute,
Comment, etc.).
Function Blocks
The XML Utility SL library provides various function block to construct and parse data
into respective structures.
Inputs
Name IEC 61131 Type Description
sFileName STRING(255) Path to an XML file. This function-
ality is not presently supported on
the RTAC.
wsElement WSTRING(gc_udiMaxValueSize) The element to find. If blank, the root
element will be returned.
attribute XMLElement Attributes of the XML element to
find.
readMode READ_MODE Read mode.
paElements POINTER TO XMLElement Pointer to the result set.
udiMaxElements UDINT Maximum size of paElements.
udiStartPosition UDINT Start position in bytes.
xTruncateValues BOOL TRUE: All values that exceed the
maximum value size will be trun-
cated.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
Outputs
Name IEC 61131 Type Description
eError ERROR Output error.
udiCountElements UDINT Number of elements in paElements.
udiNextReadPos UDINT Position in file (in bytes) of the next XML element,
0 if last element.
eEncoding Encoding Encoding of the XML file.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the
function block has completed its ac-
tion. The outputs operate in the usual
manner and are only reset if either the
action is completed or in the event of
an error. In this case, the correspond-
ing output values (xDone, xError) are
present at the outputs for exactly one
cycle.
sFileName STRING(255) Path to an XML file. This function-
ality is not presently supported on
the RTAC.
wsElement WSTRING(gc_udiMaxValueSize) The element to find. If blank, the root
element will be returned.
attribute XMLElement Attributes of the XML element to
find.
readMode READ_MODE Read mode.
paElements POINTER TO XMLElement Pointer to the result set.
udiMaxElements UDINT Maximum size of paElements.
udiStartPosition UDINT Start position in bytes.
xTruncateValues BOOL TRUE: All values that exceed the
maximum value size will be trun-
cated.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
eLastError ERROR The last error.
udiCountElements UDINT Number of elements in paElements.
udiNextReadPos UDINT Position in file (in bytes) of the next XML element,
0 if last element.
eEncoding Encoding Encoding of the XML file.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the
function block has completed its ac-
tion. The outputs operate in the usual
manner and are only reset if either the
action is completed or in the event of
an error. In this case, the correspond-
ing output values (xDone, xError) are
present at the outputs for exactly one
cycle.
sFileName STRING(255) Path to an XML file. This function-
ality is not presently supported on
the RTAC.
wsElement WSTRING(gc_udiMaxValueSize) The element to find. If blank, the root
element will be returned.
attributeName WSTRING(gc_udiMaxValueSize) Name of the attribute, BLANK if not
required.
attributeValue WSTRING(gc_udiMaxValueSize) Value of the attribute.
readMode READ_MODE Read mode.
paElements POINTER TO XMLElement Pointer to the result set.
udiMaxElements UDINT Maximum size of paElements.
udiStartPosition UDINT Start position in bytes.
xTruncateValues BOOL TRUE: All values that exceed the
maximum value size will be trun-
cated.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
eLastError ERROR The last error.
udiCountElements UDINT Number of elements in paElements.
udiNextReadPos UDINT Position in file (in bytes) of the next XML element,
0 if last element.
eEncoding Encoding Encoding of the XML file.
Inputs
Name IEC 61131 Type Description
sFileName STRING(255) Path to an XML file. This functionality
is not presently supported on the RTAC.
udiStartPosition UDINT Start position in bytes. Use XMLEle-
ment.udiPosition.
readMode READ_MODE Read mode.
paElements POINTER TO XMLElement Pointer to the result set.
udiMaxElements UDINT Maximum size of paElements.
xTruncateValues BOOL TRUE: All values that exceed the maxi-
mum value size will be truncated.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
Outputs
Name IEC 61131 Type Description
eError ERROR Output error.
udiCountElements UDINT Number of elements in paElements.
udiNextReadPos UDINT Position in file (in bytes) of the next XML element,
0 if last element.
eEncoding Encoding Encoding of the XML file.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the function
block has completed its action. The out-
puts operate in the usual manner and are
only reset if either the action is completed
or in the event of an error. In this case, the
corresponding output values (xDone, xEr-
ror) are present at the outputs for exactly
one cycle.
sFileName STRING(255) Path to an XML file. This functionality
is not presently supported on the RTAC.
udiStartPosition UDINT Start position in bytes. Use XMLEle-
ment.udiPosition.
readMode READ_MODE Read mode.
paElements POINTER TO XMLElement Pointer to the result set.
udiMaxElements UDINT Maximum size of paElements.
xTruncateValues BOOL TRUE: All values that exceed the maxi-
mum value size will be truncated.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
eLastError ERROR The last error.
udiCountElements UDINT Number of elements in paElements.
udiNextReadPos UDINT Position in file (in bytes) of the next XML element,
0 if last element.
eEncoding Encoding Encoding of the XML file.
Inputs
Name IEC 61131 Type Description
sFileName STRING(255) Path to an XML file. This functionality
is not presently supported on the RTAC.
paElements POINTER TO XMLElement Pointer to the result set.
udiCountElements UDINT Number elements in paElements.
eEncoding Encoding Encoding of the XML data.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
xAddDeclaration BOOL Adds XML declaration with encoding info
like “<?XML version=1.0 encoding=..”,
default: TRUE.
Outputs
Name IEC 61131 Type Description
eError ERROR Output error.
Inputs
Name IEC 61131 Type Description
xExecute BOOL Rising edge: Action starts.
Falling edge: Resets outputs.
If a falling edge occurs before the function
block has completed its action. The out-
puts operate in the usual manner and are
only reset if either the action is completed
or in the event of an error. In this case, the
corresponding output values (xDone, xEr-
ror) are present at the outputs for exactly
one cycle.
sFileName STRING(255) Path to an XML file. This functionality
is not presently supported on the RTAC.
paElements POINTER TO XMLElement Pointer to the result set.
udiCountElements UDINT Number elements in paElements.
eEncoding Encoding Encoding of the XML data.
paDataArray POINTER TO BYTE Pointer to XML data array.
udiDataArraySize UDINT Size of paDataArray.
xAddDeclaration BOOL Adds XML declaration with encoding info
like “<?XML version=1.0 encoding=..”,
default: TRUE.
Outputs
Name IEC 61131 Type Description
xDone BOOL TRUE: Ready condition reached.
xBusy BOOL TRUE: Operation is running.
xError BOOL TRUE: Error condition reached.
eError ERROR Output error.
eLastError ERROR The last error.
Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.
Assumptions
This example assumes that an XML data structure defined globally as a variable by the user
is to be parsed. The data is to be defined as follows, and its length (in number of characters)
is also defined as a global variable.
Solution
Code Snippet 43.1 prg_ParseArrayintoElements
PROGRAM prg_ParseArrayintoElements
VAR
// Parser object which will interpret serialized XML
parser : XML.XMLFindElement;
// Storage object which will manage all XML elements
elements : ARRAY[1..100] OF XML.XMLElement;
runOnce := FALSE;
END_IF
Release Notes
The following tables list the versions, revision descriptions, and corresponding Program-
ming Reference Manual date codes for ACSELERATOR RTAC Extensions, and IEC 61131-3
Libraries.
Libraries
IEC-61131 libraries are pre-packed logic that are authored by SEL for IEC-61131 appli-
cations like data recording, email, and generation control. Below are release notes for the
various different library solutions which are available for selection in ACSELERATOR RTAC
RTAC.
Starting with revisions published after March 1, 2022, changes that address security vulner-
abilities are marked with "[Cybersecurity]". Improvements to cybersecurity functionality
that should be evaluated for potential cybersecurity importance are marked with "[Cyber-
security Enhancement]".
AnalogCond
Version Summary of Revisions Date Code
3.5.2.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC type “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.1.1 ä Added class_ArmaFilter_LREAL. 20150722
3.5.1.0 ä Changed I_LimitedSplpf to inherit from I_Filter. 20141107
ä Modified class_LimitedSplpfStepToDefault to implement updated
I_LimitedSplpf.
ä Modified class_LimitedSplpfRampToDefault to implement up-
dated I_LimitedSplpf.
ä Added advanced ARMA filter.
ä Added dummy class_PassThroughFilter.
3.5.0.1 ä Initial release. 20140701
ChannelMonitoring
Version Summary of Revisions Date Code
3.5.3.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.3.0 are not supported for project versions
R148 and later.
3.5.2.0 ä Added class_TimeAlignment. 20200826
3.5.1.2 ä Modified behavior of fb_ChannelIntegral EN input to allow inte- 20191024
gration pausing.
ä Made ExcursionThreshold dynamically settable for fb_Chan-
nelAlert and fb_MultiChannelAlert.
ä Added LatchAlarm input to fb_ChannelAlert and fb_MultiChan-
nelAlert.
ä Addressed an issue that could cause an unexpected Integral result
after a manual reset to fb_ChannelIntegral while the PeriodicPro-
cessing input is true.
3.5.1.1 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
ä Added fb_ChannelDerivative.
ä Added fb_ChannelIntegral.
ä Added fb_IndicatorTimeDelta.
3.5.0.0 ä Initial release. 20151223
ConditionMonitoring
Version Summary of Revisions Date Code
3.5.2.2 ä Addressed an issue that causes an ’Invalid use of restricted 20221216
SEL library’ compile error on ACSELERATOR RTAC versions
1.35.151.6000 and later.
3.5.2.1 ä Added AlertEdge boolean to struct_CTPTGroupStatus. Pulses 20221104
for one task cycle on the rising edge of any monitored channel
Alert.stVal
ä Normalized input/output naming convention to favor Alert over
Alarm.
ä Replaced MonitorGroup with NodeGroup within struct_CTPTSta-
tusOutput.
ä Addressed an issue where struct_-
CTPTGroupStatus.StatusDescription does not clear a
warning message if a warning condition is cleared while in an
alert state.
ä Addressed an issue where phase angle wrapping is not accounted
for when MonitorMode = DEFINED_REFERENCE.
ä Addressed an issue where a deassertion of Initialize.EN is not
logged to the SOE/Summary file.
ä Addressed an issue where the MonitorGroup column of the SOE/-
Summary file can show an inaccurate list of CtPt IDs.
ä Addressed an issue where struct_-
CTPTStatusOutput.ReferenceMeasurement for
InputTypeIsAngle = TRUE loses decimal resolution for
angles in quadrants two and three of the unit circle.
3.5.2.0 ä Added support for topology processing, angle monitoring, and 20220909
chatter tracking.
3.5.1.2 ä Addressed issue in the CtPt Monitor Extension that could prevent 20211216
the project from going online with an RTAC in certain configura-
tions.
ä Addressed an issue in class_IedReportConverter where calls to
Bootstrap_ReportRegexRule with ContentType of SEQUENCE
and Instances of one result in a corrupt label string.
ä Addressed an issue in class_IedReportConverter where the last line
of sequence data may not be written to the output file.
ä Allows compatibility with project versions R150 and later.
3.5.1.1 ä Added additional phase options and outputs to the CtPt monitor 20210504
class and extension.
ä Removed monitored channel magnitude comparison to Minimum-
Magnitude as a qualification for monitor enabling.
3.5.1.0 ä Added CtPt Monitor Extension. 20210212
3.5.0.0 ä Initial release. 20200826
CrossTaskData
Version Summary of Revisions Date Code
3.5.1.1 ä Addressed an issue that will cause logic engine restart when using 20220526
duplicate writer mutex IDs.
ä Must be used with R150 firmware or later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Copy operations between tasks have been optimized to be more 20160708
efficient for large cross task data sets.
3.5.0.2 ä Corrected catching of SysMem internal errors. 20140828
3.5.0.1 ä Initial release. 20140701
DescriptiveData
Version Summary of Revisions Date Code
3.5.2.2 ä Added SerializeRow method to class_CsvManager as well as Per- 20220909
centSerialized and PercentParsed outputs.
ä Converted the duration-vs-content size relationship for class_Csv-
Manager CSV parse operations from exponential to linear.
ä Resolved an issue in class_CsvManager where parsing files larger
than 10 MB asserts the class output error.
3.5.2.1 ä Added AddKeyValuePairSELString and GetSELString methods to 20220331
class_JsonManager to allow SELString values to be assigned to
and retrieved from values stored in key-value pairs.
3.5.2.0 ä Added ExtractCell and OverwriteCell methods to class_CsvMan- 20211216
ager.
ä Resolved an issue in class_CsvManager where calling the Serialize
method could cause a logic engine restart.
ä Resolved an issue in class_JsonManager where serializing empty
key or value strings would cause logic engine restart.
ä Allows compatibility with project versions R150 and later.
3.5.1.0 ä Added class_CsvManager. 20210826
ä Added the SerializeJson() method to class_JsonManager to allow
serializing JSON structure contents to a byte array.
ä Added the GetNextValue() method to class_JsonManager to auto-
mate the process of retrieving the next item in a list or map.
ä Added the GoToIndex() method to class_JsonManager to allow
navigation to a specified JSON element.
ä Added the AddKeyValuePair() method to class_JsonManager to al-
low the addition of user-specified key-value pairs to a blank JSON
structure.
3.5.0.0 ä Initial Release. 20200826
Dictionaries
Version Summary of Revisions Date Code
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.1 ä Initial release. 20140811
DynamicDisturbanceRecorder
Version Summary of Revisions Date Code
3.5.4.3 ä Resolved an issue where generated COMTRADE files could con- 20230310
tain invalid data when configured for TIME_CHANGE mode with
MaxFileSize set such that records are generated frequently.
ä Resolved an issue introduced in 3.5.4.2 where class_Comtrade-
Float32 causes a logic engine restart.
ä Resolved an issue introduced in 3.5.3.0 where preparing zipped
COMTRADE records may exceed configured task cycle time con-
straints.
ä Resolved an issue where FilePostfix was not recorded when using
TRIGGER_EVENT as the DataLogType for class_TimeAligned-
Csv.
3.5.4.2 ä Restored COMTRADE file generation performance to pre-3.5.3.0 20220909
levels. See description of class_ComtradeFloat32 for expected
performance.
ä Added runtime license check verification after project download.
3.5.4.1 ä Resolved an issue introduced in 3.5.4.0 where the DynamicDistur- 20220526
banceRecorder configured with a record type of SOE Harvester
CSV eventually fails to generate CSV files and prevents further
file system writes from other libraries attempting to create files.
3.5.4.0 ä Resolved an issue introduced in 3.5.3.0 where class_SoeHar- 20220331
vesterCsv is unable to detect new SOE records when a previously
tracked record is removed from the RTAC SOE Log.
ä Modified class_SoeHarvesterCsv to remove the fixed internal 10-
second SOE query interval and added the QueryRecords input to
allow external triggering.
ä Allows compatibility with project versions R150 and later.
3.5.3.1 ä Resolved an issue introduced in 3.5.3.0 where generation of COM- 20210826
TRADE files is significantly slower than previous versions.
3.5.3.0 ä Added SOE Harvesting functionality via class_SoeHarvesterCsv 20210504
ä Resolved an issue where COMTRADE .dat files could contain out
of order samples.
ä Must be used with R148 firmware or later.
3.5.2.3 ä Resolved an issue where no data is recorded when only data types 20210212
without associated time stamps are configured.
ä Resolved an issue where CMV magnitude and angle channel
names, as written in the COMTRADE .cfg file, were out of com-
pliance with IEEE-C37.111-2013.
ä Resolved an issue where digital channels in the COMTRADE .cfg
file were not assigned an IEEE-C37.111-2013 compliant normal
state indicator.
ä Increased phase description string length to a maximum of two
characters for COMTRADE recordings and provided selectable
phase presets as per IEEE C37.111-2013.
3.5.2.2 ä Resolved an issue where COMTRADE files could be deleted pre- 20191122
maturely.
3.5.2.1 ä Resolved an issue where boolean data types could not be recorded 20190726
in a COMTRADE file.
ä Optimized the COMTRADE class so that files greater than 10 MB
can be created.
ä Must be used with R144 firmware or later.
3.5.2.0 ä Adds support for simple data types. 20190218
ä Increases maximum triggered COMTRADE file size from 1 MB
to 10 MB.
ä Extends COMTRADE pre- and post-trigger sample counts to
18,000.
ä Updates class_ComtradeFloat32 and class_TimeAlignedCsv to al-
low the LoggingInterval setting to change during runtime.
ä COMTRADE files are now compressed to reduce file size.
ä Must be used with R144 firmware or later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release of class_ComtradeFloat32. 20170601
ä Initial release of class_SoeClass.
ä Initial release of class_TimeAlignedCsv.
DynamicVectors
Version Summary of Revisions Date Code
3.5.3.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.3.0 are not supported for project versions
R148 and later.
3.5.2.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.1.0 ä Added typed vectors for REAL, LREAL, LWORD, and POINTER. 20150511
3.5.0.2 ä Initial release. 20140811
Email
Version Summary of Revisions Date Code
3.5.2.0 ä Allows compatibility with project versions R150 and later. 20220331
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.6 ä Full SMTP client/server handshaking implemented. 20150722
ä Added fb_SimpleEmailClient2 and class_EmailClient2. These
items extend the basic objects, providing destination and source
port initialization parameters.
ä Attachment functionality added for multiple files and raw data.
ä Very large emails, over 10 KB in size, send correctly.
3.5.0.3 ä Added correct HELO syntax when using local ip “0.0.0.0”. 20141212
ä Allow up to 10 seconds to connect with a mail server instead of a
single scan.
3.5.0.2 ä Improved sending of long emails. 20141110
3.5.0.1 ä Initial release. 20141010
EmailPlus
Version Summary of Revisions Date Code
3.5.2.0 ä Added Monitored Alarms functionality to class_EmailClient. Pre- 20220909
vious functionality is now referred to as Triggered Report config-
uration.
ä Added MaintenanceMode input.
3.5.1.0 ä Allows compatibility with project versions R150 and later. 20220331
3.5.0.2 ä Updated extension for compatibility with ACSELERATOR RTAC 20200826
versions newer than 1.30.146.3437.
3.5.0.1 ä Initial release. 20200220
FTPSync
Version Summary of Revisions Date Code
3.5.2.1 ä Documentation-only change. 20220909
3.5.2.0 ä Allows compatibility with project versions R150 and later. 20220331
ä Added visibility of licensing error to RuntimeErrors
3.5.1.4 ä Added a setting for defining the file transfer timeout period. 20210826
ä Added the ability to disable periodic synchronization.
3.5.1.3 ä Added public key authentication example (documentation-only 20200826
change).
3.5.1.2 ä Added the ability to specify the TCP port used during connection 20200403
to the FTP or SFTP server.
ä Added the ability to sync Recording Group events and any other
events in the file system not previously accessible by the library.
ä Must be used with R146-V0 firmware or later.
3.5.0.1 ä Resolved an issue that may cause a logic engine restart. 20200214
3.5.0.0 ä Initial release. 20190830
FallingConductorProtection
Version Summary of Revisions Date Code
3.5.0.4 ä Added new FUSE_SOURCE switch type. 20220909
ä Enhanced dI0/dt spike alarming and blown fuse detection to use
the configurable breaker status transition time period during which
detection is suppressed.
ä Enhanced blocking fault and faulty sensor detection to evaluate
switch availability before performing logic checks for these con-
ditions.
ä Modified faulty sensor detection to only apply with switches con-
figured as type BREAKER_SWITCH.
ä Modified blown fuse detection logic to only process when the
associated 52A contact status with the FUSE_TAP switch is
closed. This status should be associated with the closest upstream
BREAKER_SWITCH or SUBSTATION_BREAKER 52A status.
ä Modified blown fuse detection logic to no longer flag a parent zone
as having a possible blown fuse.
3.5.0.3 ä Enhanced switch availability status to support a configurable 20220526
pickup and dropout time.
ä Enhanced Faulty Sensor detection to support a configurable pickup
time as well as a configurable breaker status transition time period
during which detection is suppressed.
ä Modified per-switch RoundTripTime value calculation to handle
condition where switch is no longer communicating.
ä Modified dI0/dt spike alarming to only apply with switches con-
figured as type SUBSTATION_BREAKER.
ä Modified V0-Angle and V2-Angle method calculations to remove
ABS value condition. This was previously applied against the an-
gle values before they were subtracted from one another.
ä Modified per-switch FCDetectionFlag logic to only latch in the
flag if a trip is issued to the switch that detects a falling conductor
method.
3.5.0.2 ä Added new Substation Breaker switch type. 20220331
ä Added tracking of the availability status of switches providing
zone reference voltages. If this switch becomes unavailable, other
switches in the zone using those voltages are prevented from exe-
cuting falling conductor method detection.
ä Added AlgorithmsEnabled status to struct_SwitchStatus structure
to provide per-switch indication of the enabled status of falling
conductor method calculations.
ä Added new blocking condition for external disturbances that are
determined to be out of the zone of protection of falling conductor
protection.
3.5.0.1 ä Initial release. 20211216
FaultLocation
Version Summary of Revisions Date Code
3.5.1.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.1.0 are not supported for project versions
R148 and later.
3.5.0.1 ä Removed licensing requirement. 20200826
3.5.0.0 ä Initial release. 20200702
FileIO
Version Summary of Revisions Date Code
3.5.7.2 ä Added runtime license check verification after project download. 20220909
ä Added inputs to class_ComtradeParser and class_FileReader2
ReadEventFromDB methods to allow for reading a window of data
from the database (.dat) files.
3.5.7.1 ä Added new class_PersistentData to store logic engine variable val- 20220331
ues on the RTAC file system and automatically restore them upon
system restart.
3.5.7.0 ä Added GetAnalogChannelNumber, GetDigitalChannelNumber 20211216
ConvertComtradeTStoUTC, and GetEventFromFS methods to
class_ComtradeParser.
ä Added NumSamples element to struct_ComtradeInfo.
ä Addressed an issue in class_ComtradeParser where data samples
cannot be retrieved from events whose .cfg file defines nrates =
0 and samp = 0.
ä Allows compatibility with project versions R150 and later.
3.5.6.2 ä Addressed an issue in class_ComtradeParser where calls to Get- 20210826
DigitalSample() could fail for events with more digital channels
than analog channels.
ä Addressed an issue in class_DirectoryListing where it would con-
tinuously consume memory when used with firmware versions
R144 through R147.
3.5.6.1 ä Added GetBoolVector method to class_ComtradeParser. 20210504
ä Added GetEventFromDBDirect method to class_ComtradeParser.
ä Addressed an issue in class_ComtradeParser where an event with a
number of digital channels that are equally divisible by 16 leads to
invalid results returned from the various get-vector and get-sample
methods.
3.5.6.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.6.0 are not supported on project versions
R148 and later.
ä Resolved an issue where calls to fun_SoeAscending fail while the
ReturnAlarmSoeOnly input is True.
3.5.5.0 ä Added new class_ComtradeParser to read COMTRADE .dat and 20190401
.cfg event data into the RTAC’s logic engine.
3.5.4.1 ä Added facility to filter a directory listing to only return files newer 20190201
than or equal to the date and time specified.
ä Added new class_BasicDirectoryManager, which rotates the con-
tents of a given directory based on maximum size constraints.
ä Must be used with R144-V1 firmware or later.
GridConnect
Version Summary of Revisions Date Code
3.5.6.1 ä Modified Advanced PLimitMode to reduce or eliminate overshoot 20221216
after inverters leave power clamp mode.
3.5.6.0 ä Note: Updating to version 3.5.6.0 will require re-tuning for 20220909
configurations that operate in Advanced PLimitMode.
ä Added support to fb_masterPlantController for charging storage
assets during solar smoothing while PV increases.
ä Added support to fb_masterPlantController for anti-windup in re-
active closed-loop control modes including Var Control, Voltage
Control, and Voltage Compensation.
ä Added input pin AutomaticChargingSource to fb_masterPlant-
Controller to select a power source for automatic charging algo-
rithm.
ä Added input pin OptionalLowerVDeadband to fb_masterPlant-
Controller to allow for unique upper and lower deadbands for volt-
age control.
ä Added support for frequency regulation in PCC Metering mode.
ä Added simulator function blocks for testing and exploration of
GridConnect.
ä Resolved an issue in fb_masterPlantController that resulted from a
PSetpoint change occurring in Advanced mode while PDeadband
was larger than PLimitRampRate. The process value was driven
in the opposite direction of PSetpoint until the target ramp value
was driven outside the range of PDeadband from PlantP.
1.1.7 ä Modified set point bias logic during voltage or powerfactor excur- 20130506
sions beyond critical limits.
ä Decoupled PF control deadband and lag/lead alarm generation
from voltage limits.
1.1.6 ä Decrease power limit ramp rate output deadband to 0.01%/Sec. 20130412
ä Corrected predictive aggregate inverter response logic.
ä Limit power limit control output between 0 and 100% in open loop
and closed loop mode.
1.1.5 ä GC_INV - Corrected trigger logic to allow PF_TRIG output to 20130206
reset between control intervals.
1.1.4 ä GC_MSPC - Corrected closed loop cycle time pulse generation. 20130206
1.1.3 ä GC_MSPC Function Block Bug Fixes: 20130201
âCorrected Retry pulse generation.
âCorrected Closed loop cycle time pulse generation.
âCorrected Version output pin.
1.1.2 ä Added RTAC MOT support. 20121126
1.1.1 ä Initial release. 20120906
IPAliasRedundancy
Version Summary of Revisions Date Code
3.5.3.0 ä Allows compatibility with project versions R150 and later. 20220331
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
3.5.1.1 ä Resolved an issue that could cause a logic engine restart if com- 20200626
munications were not processed for five seconds or more.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Initial release. 20180427
JSON_Utilities_SL
Version Summary of Revisions Date Code
1.0.4.0 ä Initial release. 20221104
MQTT_Client_SL
Version Summary of Revisions Date Code
1.1.0.0 ä Initial release. 20221104
MathComplex
Version Summary of Revisions Date Code
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.2 ä Corrected bug in struct_ComplexRect_TO_vector_t() that 20150925
returned a value of NaN due to rounding errors.
ä Defined the range of the angle returned by struct_-
ComplexRect_TO_vector_t() to be [–180, 180] degrees. Pre-
vious to this release, this was undefined but returning [0, 360].
3.5.0.1 ä Fixed negative return values in fun_ComplexAbs(). This also 20150722
corrected issues in fun_ComplexCmp() and fun_ComplexLn().
3.5.0.0 ä Initial release. 20150511
MathMatrix
Version Summary of Revisions Date Code
3.5.2.1 ä Addressed an issue that causes an ’Invalid use of restricted 20221216
SEL library’ compile error on ACSELERATOR RTAC versions
1.35.151.6000 and later.
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
3.5.1.1 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.1 ä Initial release. 20150722
PacketEncoding
Version Summary of Revisions Date Code
3.5.2.0 ä Allows compatibility with project versions R150 and later. 20220331
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Replaced the deprecated “POINTER_TO_ANY” type with
POINTER_TO_BYTE”.
ä Must be used with R143 firmware or later.
3.5.0.4 ä Added base64-MIME encoding and decoding functionality. 20150722
PowerMetering
Version Summary of Revisions Date Code
3.5.2.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.1.0 ä Added fb_KYZ. 20160415
ä Added fb_KY.
ä Resolved an issue that could cause the fb_Demand block to discard
the initialValue after the first five minutes, resulting in the Demand
calculation being reset.
ä Updated examples using retain values for clarity.
3.5.0.5 ä Initial release. 20140714
PowerSystemAutomation
Version Summary of Revisions Date Code
3.5.1.1 ä Resolved an issue where local controls are processed in fb_Dis- 20220909
connectSwitchControl, fb_BreakerOpenControl, and fb_Breaker-
CloseControl when the LocalMode input is false.
3.5.1.0 ä Added function blocks for disconnect switch and circuit breaker 20210826
control.
3.5.0.0 ä Initial Release. 20201029
PowerSystemModel
Version Summary of Revisions Date Code
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20150924
PowerSystemProtection
Version Summary of Revisions Date Code
3.5.1.1 ä Removed licensing check, making PowerSystemProtection a free- 20191018
to-use library.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180619
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release of time-overcurrent function block. 20170517
ä Initial release of instantaneous-overcurrent function block.
ä Initial release of loss-of-potential function block.
ä Initial release of overvoltage function block.
ä Initial release of undervoltage function block.
ä Initial release of bus-line voltage check function block.
ä Initial release of conductor thermal overload function block.
Queue
Version Summary of Revisions Date Code
3.5.3.1 ä Added the Resize2 method that is identical to Resize but addition- 20230310
ally updates the Size property.
3.5.3.0 ä Added support to dynamically generate queues at run-time. 20210504
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Replaced the deprecated POINTER_TO_ANY type with
POINTER_TO_BYTE.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20150511
Quicksort
Version Summary of Revisions Date Code
3.5.1.1 ä Addressed an issue that causes an ’Invalid use of restricted 20221216
SEL library’ compile error on ACSELERATOR RTAC versions
1.35.151.6000 and later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Replaced the deprecated POINTER_TO_ANY type with
POINTER_TO_BYTE.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20140812
RecordingTriggers
Version Summary of Revisions Date Code
3.5.1.2 ä Documentation-only change. 20220909
3.5.1.1 ä Addressed an issue that causes a compile warning when entering 20200702
more than 100 triggers.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.2 ä Initial release of high-threshold function block. 20170908
ä Initial release of low-threshold function block.
ä Initial release of rate-of-change function block.
ä Initial release of digital trigger function block.
ReportGenerator
Version Summary of Revisions Date Code
3.5.0.5 ä Documentation-only change. 20220909
3.5.0.4 ä Resolved an issue that prevents going online while using the Re- 20211216
portGenerator extension and FileIo library in the same project.
ä Allows compatibility with project versions R150 and later.
3.5.0.3 ä Updated extension for compatibility with ACSELERATOR RTAC 20200702
versions newer than 1.30.146.3437.
3.5.0.2 ä Resolved an issue that may cause a logic engine restart. 20200214
3.5.0.1 ä Updated class_ReportGenerator for compatibility with SEL Server 20191024
FILE SHOW command.
ä Addressed an issue with the Report Generator extension that may
cause a logic engine restart when referencing REAL or LREAL
variables with the value NaN, +inf, or -inf.
ä Addressed an issue with the Report Generator extension that may
keep timeStamp_t data types from being rendered in the report.
3.5.0.0 ä Initial release. 20190830
SELEthernetController
Version Summary of Revisions Date Code
3.5.2.0 ä Allows compatibility with project versions R150 and later. 20220526
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.6 ä Allow the class to recover instead of closing the socket when at- 20160501
tempting to send large amounts of data all at once.
3.5.0.5 ä Added queues as input and output mechanisms for socket data. 20150511
ä Allow TCP client ports to connect to a server without binding to a
specific local port.
3.5.0.3 ä Made TCP sockets not throw error when outgoing data buffer is 20141107
full.
3.5.0.2 ä Initial release. 20141010
SELRand
Version Summary of Revisions Date Code
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20140811
SELServerSimulators
Version Summary of Revisions Date Code
3.5.3.1 ä Resolved an issue that caused a compile error when using class_- 20220909
TelnetServer or class_SessionManager in R150 projects.
ä SELServerSimulators support is deprecated for firmware revisions
R151 and later.
3.5.3.0 ä Allows compatibility with project versions R150 and later. 20220331
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.1 ä Initial release. 20150511
SELString
Version Summary of Revisions Date Code
3.5.3.1 ä Resolved an issue in class_SELString LeftJustify and RightJustify 20220909
methods where use of the same padding length as the SELString
caused a logic engine restart.
3.5.3.0 ä Resolved an issue in the class_SELString FindString method 20220331
where evaluating an IEC 61131 string of the same length as the
SELString would return an incorrect result.
ä Added support to append from an array of bytes.
ä Added functions fun_ByteIsAlpha, fun_ByteIsNumeric, fun_-
ByteIsAlphanumeric.
ä Added functions fun_LowercaseByte, fun_UppercaseByte.
ä Added class_SELString methods Count, StartsWith, EndsWith,
LeftJustify, RightJustify, Strip, LeftStrip, RightStrip.
ä Added support to copy class_SELString contents to another class_-
SELString.
ä Added support to convert raw byte content to and from ASCII-
encoded hexadecimal strings.
ä Added property to access a pointer to the first byte in a class_-
SELString.
ä Allows compatibility with project versions R150 and later.
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
ä Added support for simultaneous use in both main and automation
tasks.
ä Modified class_SELString and class_SELStringList to have max-
imum size determined by available system memory.
ä Modified class_SELStringList.Join method to accept class_SEL-
String as an argument and return pointer to STRING to indicate
any errors encountered.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Added FromByteArray and ToByteArray methods. 20140811
ä Added AppendString and PrependString methods.
ä Added FindString method.
ä Protected classes against assignment.
3.5.0.1 ä Initial release. 20140701
SELUtils
Version Summary of Revisions Date Code
3.5.4.2 ä Added default values for offset, ceiling, and floor inputs of 20221104
SCALE_MV, SCALE_CMV, and SCALE_INS making these pa-
rameters optional. Note, R150+ is required to use default values.
ä Added additional global constants for data type maximum and min-
imum value.
ä Updated description of global constant FLOAT_MIN.
ä Added function SCALE_BCR to scale BCR values.
ä Added function block Logger_ACD to log ACD data types to
RTAC’s sequence of event log.
ä Added function block Logger_ACT to log ACT data types to
RTAC’s sequence of event log.
ä Added function REAL_APPROX_EQUAL to check if two REAL
or two LREAL values are effectively equal (+/- 1 bit) accounting
for floating point precision limitations.
3.5.4.1 ä Added functions to convert between hexadecimal digits and 20220909
a DWORD (HEX_STRING_TO_DWORD and DWORD_TO_-
HEX_STRING).
3.5.4.0 ä Added functions to get and set individual bits within BYTE, 20220331
WORD, DWORD, and LWORD datatypes.
ä Added functions to convert between hexadecimal digits and a
WORD or BYTE(HEX_STRING_TO_BYTE, HEX_STRING_-
TO_WORD, BYTE_TO_HEXSTRING)).
ä Added function to validate hexadecimal digits in a STRING and
BYTE (fun_isValidHEXString, fun_isValidHEXChar).
ä Resolved an issue with angle calculation in ComposePF, Compose-
Watts, and ComposeVAR.
3.5.3.2 ä Added functions to convert CMV, MV, SPS, INS, and BCR to for- 20211216
matted STRING.
ä Added functions to convert hex STRING characters to the numeric
representation of BYTE, and WORD.
ä Added function to obtain the Power Factor from W, VA and VAR.
3.5.3.1 ä Added string checksum evaluation function (fun_Checksum). 20210504
ä Added functions to convert numeric representation of BYTE and
WORD to STRING of hex characters.
3.5.3.0 ä Added phasor angle difference monitor (fb_PADM). 20210212
ä Added string padding function.
ä Added filename validation function and supporting structure.
3.5.2.0 ä Added power calculation functions. 20201029
ä Added functions to add or subtract time to a dateTime_t structure.
ä Added functions for converting dateTime_t to ULINT and ULINT
to dateTime_t.
3.5.1.4 ä Added functions for converting a variety of data types 20200826
ä Added structures to support regular expression usage in logic en-
gine
3.5.1.3 ä Added functions for converting a variety of data types 20200403
3.5.1.2 ä Modified behavior to make empty strVal passed to Logger_STR 20200214
clear the associated alarm.
ä Resolved an issue that may cause a logic engine restart.
3.5.1.1 ä Added validation functions for IP addresses, REALs, and LRE- 20191024
ALs.
ä Must be used with R145-V0 firmware or later.
3.5.1.0 ä Added functions for converting REAL, LREAL, timestamp_t, and 20180917
quality_t to STRING.
3.5.0.1 ä Initial release. 20180703
SVPplus
Version Summary of Revisions Date Code
3.5.2.4 ä Addressed an issue that causes an ’Invalid use of restricted 20221216
SEL library’ compile error on ACSELERATOR RTAC versions
1.35.151.6000 and later.
3.5.2.3 ä Added runtime license check verification after project download. 20220909
3.5.2.2 ä Addressed an issue where the class_ModalAnalysis percent-of- 20220331
completion, indicated by the return of the Run() method, could
remain at 64 when the execution time of the Run() method nears
the stepTime initialization input value.
3.5.2.1 ä Literature update only. Removed recommendation for SNR of 80. 20211216
3.5.2.0 ä Allows compatibility with project versions R148 and later. 20210212
ä Versions prior to 3.5.2.0 are not supported for project versions
R148 and later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Improved precision of entire algorithm. 20150718
ä Improved performance for large matrices.
ä Hid internal variables of all function blocks.
3.5.0.0 ä Initial release. 20141101
SnmpLite
Version Summary of Revisions Date Code
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 through R149 firmware. SNMPLite sup-
port is deprecated for firmware revisions R150 and later.
3.5.0.6 ä Improved management of Ethernet socket failure. 20150511
3.5.0.5 ä Removed limitation that number and SNMP ID of ports cannot 20150213
change.
3.5.0.4 ä Initial release. 20141010
SyslogCollector
Version Summary of Revisions Date Code
3.5.1.0 ä Allows compatibility with project versions R150 and later. 20221104
3.5.0.0 ä Initial release. 20180928
TrendRecorder
Version Summary of Revisions Date Code
3.5.3.1 ä Added runtime license check verification after project download. 20220909
3.5.3.0 ä Allows compatibility with project versions R150 and later. 20220526
3.5.2.0 ä Resolved an issue in the Profile Manager where inputs no longer 20210826
accepted direct string assignments in projects using R148 or later
firmware.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Resolved an issue where, under certain conditions, recorded data 20170412
were not provided to ACSELERATOR TEAM software.
ä Removed library version 3.5.0.2 from the installer.
3.5.0.2 ä Initial release. 20161216
Web_Client_SL
Version Summary of Revisions Date Code
1.1.2.0 ä Initial release. 20221104
Web_Socket_Client_SL
Version Summary of Revisions Date Code
1.1.0.0 ä Initial release. 20221104
XML_Utility_SL
Version Summary of Revisions Date Code
1.0.4.0 ä Initial release. 20221104
Extensions
Extensions are pre-packaged solutions (e.g., data recording and email) that offer settings-
form-based configuration of IEC 61131-3 logic in ACSELERATOR RTAC. Below are release
notes for various different extensions which are available via ACSELERATOR RTAC.
Some extensions work closely with features of ACSELERATOR RTAC, or specific versions
of an associated library, as such, these minimum versions are also documented in the “Ver-
sion” column of the table below.
Starting with revisions published after March 1, 2022, changes that address security vulner-
abilities are marked with "[Cybersecurity]". Improvements to cybersecurity functionality
that should be evaluated for potential cybersecurity importance are marked with "[Cyber-
security Enhancement]".
CtPt Monitor
Version Summary of Revisions Date Code
1.33.0.2 ä Library update only. 20221216
Associated Library: 3.5.2.2
ACSELERATOR RTAC: 1.34.150.18000
1.33.0.1 ä Allows disabling 20221104
Associated Library: 3.5.2.1 summary logging by setting the
ACSELERATOR RTAC: 1.34.150.18000 Summary Logging Interval of the
Report Settings tab to zero.
ä Addressed an issue where CMV
channels are not validated for
group inclusion when Angle Mon-
itoring is enabled.
1.33.0.0 ä Added CtPt Monitor support for 20220909
Associated Library: 3.5.2.0 topology processing, angle
ACSELERATOR RTAC: 1.34.150.18000 monitoring, chatter tracking, re-
port generation, RTAC SOE inte-
gration, and SCADA tag mapping.
1.31.0.2 ä Allows compatibility with project 20211216
Associated Library: 3.5.1.2 versions R150 and later.
ACSELERATOR RTAC: 1.32.148.7000 ä Addressed issue that could prevent
the project from going online with
an RTAC in certain configurations.
1.31.0.1 ä Added additional phase options. 20210504
Associated Library: 3.5.1.1
ACSELERATOR RTAC: 1.32.148.7000
1.31.0.0 ä Initial release. 20210212
Associated Library: 3.5.1.0
ACSELERATOR RTAC: 1.32.148.7000
Email Plus
Version Summary of Revisions Date Code
1.33.0.1 ä Added Monitored Alarms. 20220909
Associated Library: 3.5.2.0 functionality.
ACSELERATOR RTAC: 1.34.150.15000 ä Added setting for Maintenance
Mode.
1.33.0.0 ä Allows compatibility with project 20220331
Associated Library: 3.5.1.0 versions R150 and later.
ACSELERATOR RTAC: 1.34.150.15000
1.29.0.1 ä Updated extension for 20200826
Associated Library: 3.5.0.2 compatibility with ACSELERATOR
ACSELERATOR RTAC: 1.30.146.3437 RTAC versions newer than
1.30.146.3437.
1.29.0.0 ä Initial release. 20200220
Associated Library: 3.5.0.1
ACSELERATOR RTAC: 1.30.146.3437
FTP Sync
Version Summary of Revisions Date Code
1.29.0.4 ä Documentation-only change. 20220909
Associated Library: 3.5.2.1
ACSELERATOR RTAC: 1.34.150.15000
1.29.0.3 ä Allows compatibility with project 20220331
Associated Library: 3.5.2.0 versions R150 and later.
ACSELERATOR RTAC: 1.34.150.15000
1.29.0.2 ä Added setting for Sync Timeout. 20210826
Associated Library: 3.5.1.4 ä Allow Sync Interval of 0.
ACSELERATOR RTAC: 1.30.146.3437
1.29.0.1 ä Documentation-only change. 20200826
Associated Library: 3.5.1.3
ACSELERATOR RTAC: 1.30.146.3437
1.29.0.0 ä Added settings for FTP Server 20200403
Associated Library: 3.5.1.2 Port and Monitored Events
ACSELERATOR RTAC: 1.30.146.3437 by Path.
1.28.0.1 ä Library update only. 20200214
Associated Library: 3.5.0.1
ACSELERATOR RTAC: 1.29.145.20391
1.28.0.0 ä Initial release. 20190830
Associated Library: 3.5.0.0
ACSELERATOR RTAC: 1.29.145.20391
Indirect Tagging
Version Summary of Revisions Date Code
1.33.0.0 ä Added support for mapping of 20220909
ACSELERATOR RTAC: 1.34.150.15000 structured client tag names con-
taining multiple periods, such as
those present on MMS clients.
These tags will be mapped to sim-
ilarly named virtual tag list tags
containing underscores in place of
the periods.
1.28.0.1 ä Added per-client option to only 20210504
ACSELERATOR RTAC: 1.32.148.7000 map the .status sub-attribute of
Modbus Holding Register tags of
type APC/INC/MDBC to corre-
sponding tags of type MV/IN-
S/SPS located in the Shared Tag
Map.
1.28.0.0 ä Initial release. 20210212
ACSELERATOR RTAC: 1.32.148.7000
Recording Triggers
Version Summary of Revisions Date Code
1.26.0.2 ä Documentation-only change. 20220909
Associated Library: 3.5.1.2
ACSELERATOR RTAC: 1.26.143.16172
1.26.0.1 ä Addressed warnings when more 20200702
Associated Library: 3.5.1.1 than 100 triggers are configured.
ACSELERATOR RTAC: 1.26.143.16172
1.26.0.0 ä Updated extension for 20180921
Associated Library: 3.5.1.0 compatibility with ACSELERATOR
ACSELERATOR RTAC: 1.26.143.16172 RTAC versions newer than
1.26.143.16172.
1.20.0.0 ä Initial release. 20170908
Associated Library: 3.5.0.2
ACSELERATOR RTAC: 1.23.140.12272
Report Generator
Version Summary of Revisions Date Code
1.28.0.5 ä Resolved an issue where the 20220909
Associated Library: 3.5.0.5 DataStorageWarning output did
ACSELERATOR RTAC: 1.34.150.15000 not assert when warning conditions
existed.
1.28.0.4 ä Allows compatibility with project 20211216
Associated Library: 3.5.0.4 versions R150 and later.
ACSELERATOR RTAC: 1.34.150.15000 ä Resolved an issue that prevented
going online while using the
ReportGenerator extension and
FileIO library in the same project.
1.28.0.3 ä Updated extension for 20200702
Associated Library: 3.5.0.3 compatibility with ACSELERATOR
ACSELERATOR RTAC: 1.30.146.3437 RTAC versions newer than
1.30.146.3437.
1.28.0.2 ä Library update only. 20200214
Associated Library: 3.5.0.2
ACSELERATOR RTAC: 1.29.145.20391
1.28.0.1 ä Resolved an issue that 20191024
Associated Library: 3.5.0.1 prevented timeStamp_t data types
ACSELERATOR RTAC: 1.29.145.20391 from being rendered in the report.
1.28.0.0 ä Initial release. 20190830
Associated Library: 3.5.0.0
ACSELERATOR RTAC: 1.29.145.20391
Developer Mode
Introduction
Developer Mode can be enabled by going to the following location: SEL > Options >
Preferences.
Once the check box is selected and the RTAC software has been restarted, projects R135
and later will support developer mode.
"Developer Mode" is an option that can be turned on in ACSELERATOR RTAC to allow
users to develop their own libraries directly in the ACSELERATOR RTAC software. Libraries
allow for code to be easily shared between projects and potentially allows for code to be
secured in a compiled library.
To start creating your own libraries, you need to create RTAC projects specifically intended
to be converted to a library format. Do this by starting a new SEL RTAC Project and
checking the Create As Library option.
With this new project created and opened, you can now begin adding POU’s to the POUs
tab which is minimized to the left-hand side of AcRTAC by default. Code added in the
POUs tab can be accessed by user logic in the project tab. Protocol connections or RTAC
firmware features cannot be added into the POUs tab.
Library Manager
The library manager is a tool which can be added to the POUs tab. This tool allows code
from other libraries to be referenced in the POUs tab. These libraries may be from SEL or
from users. Add a library manager by right-clicking on the baseline object from the POUs
tree and select Add Object > Library Manager... from the context menu.
Library Placeholders
Library Manager objects in ACSELERATOR RTAC can use explicit library references that
point directly to a library of a specific version. That is to say that if you reference a library
such as SEL IEC Types, you’ll be specifying a library exactly as the particular version (e.g.,
3.5.2.0) and when that dependency library (SEL IEC Types) is upgraded to a newer version,
the dependent library (your new library) will still reference the original dependency refer-
ence (3.5.2.0) and will require a new library build to reference the newer library. This poses
a long-term issue in terms of library dependencies, and it can cause a variety of issues.
The simple resolution of this problem is the application of Library Placeholders. Instead
of referencing a library directly by its version, a developer can reference a library by place-
holder, and allow ACSELERATOR RTAC software to resolve the dependency in real time and
select the best (most applicable) library version at compile time. This is the recommended
practice for library development. Especially for libraries released by SEL.
Inserting Placeholders
Start by selecting the Add library option, and from the popup window, select Advanced
to open the advanced library reference view.
From the advanced view, select the Placeholder tab, and find the library you’re interested
in adding a placeholder for. In this example SEL IEC Types is selected from the Miscel-
laneous section. All RTAC related from SEL will appear in the Miscellaneous section. It
is recomended to also include the Standard library from the Common section. The library
gives access to many common data types and timers that are often utilized.
Finally, type a Placeholder name with the exact same name as the Library name, and select
OK to add the library placeholder to the Library Manager.
You should now see the placeholder library reference listed among the other library refer-
ences that you’ve added to the Library Manager.
Example: SEL_IEC_TYPES.SPS
ä Properties tab:
Step 1. Set Key to Public.
Once project information is filled out properly, click POU > Save POUs as .compiled-
library.
ä The inherited function block contains all data and methods that are defined by the
basic function block. You can use an instance of the basic function block in every
context in which ACSELERATOR RTAC expects a function block of the type of the
basic function block.
ä The inherited function block is permitted to overwrite the methods that you have
defined in the basic function block. This means that the inherited function block
can define a method with the same name, the same inputs and the same output as is
defined by the basic function block.
ä The inherited function block is not permitted to have any function block variables
with the same name as used for the base function block. The compiler reports this
as an error.
ä You can directly address the variables and methods of the basic function block within
the scope of the inherited function block by using the SUPER pointer.
In the example below a function block is created with the basic functionality common to
all relays in a project.
After adding a second function block, this can extend the previously added function block.
This function block can be extended to have additional functionality that is common only to
a new subset of relays, for instance, overcurrent relays. This is done by using the keyword
EXTENDS.
This derived function block has all the variables that the base class has plus any other
variable defined in itself. The derived function block can also access the base class func-
tionality with the special pointer SUPER. When SUPER^() is called it will execute the
code in the main function block of the extended function block. It important to note that
a derived function block can also be extended so this process could be repeated further to
create new objects (function blocks) that have all the variables and functionalities of the its
base class.
Methods
Methods are an extension of the IEC 61131-3 standard and a tool for object-oriented pro-
gramming that is used for data encapsulation. A method contains a sequence of instruc-
tions, but unlike a function it is not an independent POU and it must be assigned to a
function block or program. A method has access to the data in the function block it be-
longs to, as well as to the variables in any function block its derived from. All variables
defined in methods are reinitialized on every call, similar to a Function.
ä All data of a method are temporary data and are valid only during the execution of a
method. This means that the RTAC engine re-initializes all variables local variables
in the method each time the method is called.
ä Like functions, methods can have additional outputs. You must assign these addi-
tional outputs in the method call.
ä Methods have access to the variables in the parent function block, this includes in-
puts, outputs, and local variables of the parent function block.
ä Use the THIS pointer to point to the function blocks own instance.
ä You cannot access VAR_TEMP variables of the function block from a method.
Access Modifiers
Many POU objects can be declared with the access specifiers of PUBLIC, PRIVATE, or
INTERNAL. These specifiers indicate to the library what namespace(s) should be granted
access to see, leverage, and use these objects. In many cases, if your library should uti-
lize structures, class methods, enumerations, or other select POU types that should not be
viewable after the library is exported to a compiled library, these objects should use either
the PRIVATE or INTERNAL specifier to designate such privacy.
PUBLIC Specifier
PUBLIC access specifier (or no specifier) will inform the logic engine that the logic can
be instantiated, leveraged, and used outside its own Library (namespace).
INTERNAL Specifier
Function Blocks, methods, structures, and enumerations with INTERNAL access specifier
can only be accessed within its library (i.e., the same namespace). INTERNAL specifier is
commonly used in conjunction with the Hidden Attribute (see Attribute Pragmas) to filter
what objects will be accessible from users of the library.
Attribute Pragmas
Hide
This pragma prevents variables from being displayed when using an instantiated instance
of the code. For example, they are not visible in the input assistant or in the declaration
section in online mode.
When attribute ’hide’ is added in the line above a variable declaration, that variable wont
be shown with the others during development or online mode. In the example above OutA
wont be shown during development or Online Mode.
Figure B.21 Hide Attribute usage during logic engine runtime: implementation sec-
tion
Figure B.22 Hide Attribute Usage During Logic Engine Runtime: Declaration Sec-
tion
If attribute ’hide’ is added in the line before the POU declaration, then the entire POU is
hidden.
Even if the variables are hidden, they can still be accessed by using the correct variable and
POU name. If the pragma hide is used in compiled libraries for variables and signatures,
these variables and signatures are also not displayed in the library manager.
hide_all_locals
This pragma prevents all local variables of a POU from being visible in the display of the
List components function, in the input assistant or in the declaration part in online mode.
When attribute ’hide_all_locals’ is added in the first of the POU declaration area, all local
variables (VAREND_VAR) wont be shown during online mode. In the example above
LocalA and LocalB wont be shown during Online Mode.