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