0% found this document useful (0 votes)
28 views896 pages

Programming Reference

Uploaded by

Paul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views896 pages

Programming Reference

Uploaded by

Paul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 896

Programming Reference

© 2018 by Schweitzer Engineering Laboratories, Inc. All rights reserved.


All brand or product names appearing in this document are the trademark or registered trademark of their respective holders.
No SEL trademarks may be used without written permission. SEL products appearing in this document may be covered by U.S.
and Foreign patents.
EtherCAT® is a registered trademark and patented technology, licensed by Beckhoff Automation GmbH, Germany.
Schweitzer Engineering Laboratories, Inc. reserves all rights and benefits afforded under federal and international copyright
and patent laws in its products, including without limitation software, firmware, and documentation.
The information in this document is provided for informational use only and is subject to change without notice. Schweitzer
Engineering Laboratories, Inc. has approved only the English language document.
This product is covered by the standard SEL 10-year warranty. For warranty details, visit selinc.com or contact your customer
service representative.

Programming Reference Instruction Manual Date Code 20190830


Table of Contents

List of Tables

List of Figures

Section 1: Command Line Interface


Command Line Interface Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1
Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1
Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2
Command List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3
Command Line Example Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.41

Section 2: Library Extensions Installer


Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1
Installing AcSELerator RTAC Extension Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1
Bulk Installation of .library, .compiled-library, and .rext Files . . . . . . . . . . . . . . . . . . . . . . . 2.2
Logging and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3
Return Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3
Notes and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3

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.14

Section 4: ChannelMonitoring
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.5
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.16
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.21

Section 5: CrossTaskData
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.4
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.5

Date Code 20190830 Instruction Manual Programming Reference


ii Table of Contents

Section 6: Dictionaries
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.8
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.10

Section 7: DynamicDisturbanceRecorder
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.4
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.35
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.37

Section 8: DynamicVectors
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.4
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.7
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.25
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.29

Section 9: Email
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.2
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.4
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.14
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.22
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.26

Section 10: FTPSync


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.1
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.5

Section 11: FileIo


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.5
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.8
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.21

Programming Reference Instruction Manual Date Code 20190830


Table of Contents iii

Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.71
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.80

Section 12: GridConnect


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.3
Master Plant Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.3
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.11
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.12
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.21

Section 13: IPAliasRedundancy


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.4
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.5
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.8

Section 14: MathComplex


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.1
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.1
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.1
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.7
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.9

Section 15: MathMatrix


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.2
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.11
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.50
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.53

Section 16: PacketEncodings


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.2
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.3
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.3
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.18
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.21
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.24

Section 17: PowerMetering


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.1
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.1
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.8
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.9
Retain Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.21

Section 18: PowerSystemModel


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.4
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.5

Date Code 20190830 Instruction Manual Programming Reference


iv Table of Contents

Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.5
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.6
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.44
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.45
Log File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.70

Section 19: PowerSystemProtection


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.1
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.2
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.16
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.18

Section 20:Queue
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.2
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.6
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.56
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.62

Section 21: Quicksort


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.1
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.1
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.9
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.10
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.12

Section 22: RecordingTriggers


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.1
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.2
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.8
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.9

Section 23: ReportGenerator


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23.3

Section 24: SELEthernetController


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.2
Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.2
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.4
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.20
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24.24

Section 25: SELRand

Programming Reference Instruction Manual Date Code 20190830


Table of Contents v

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.1
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.1
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.3
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25.4

Section 26: SELServerSimulators


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.2
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.2
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.2
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.3
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.7
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.14

Section 27: SELString


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.2
Global Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.2
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.2
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.3
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.24
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.32

Section 28: SELUtils


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.3
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.3
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.8
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.18
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.20

Section 29: SVPplus


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.3
Global Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.3
Structure Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.4
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.4
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.7
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.8

Section 30: SnmpLite


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.3
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.3
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.4
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.5
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.11
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30.13

Section 31: SyslogCollector


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3

Date Code 20190830 Instruction Manual Programming Reference


vi Table of Contents

Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.5

Section 32: TrendRecorder


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.1
Special Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.1
Supported Firmware Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.2
Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.2
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.4
Recorder Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.8
Benchmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.9

Section A: Release Notes


AnalogCond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.1
ChannelMonitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.1
CrossTaskData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.2
Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.2
DynamicDisturbanceRecorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.3
DynamicVectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.3
Email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.4
FTPSync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.4
FileIo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.5
GridConnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.6
IPAliasRedundancy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.8
MathComplex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.8
MathMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.8
PacketEncodings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.9
PowerMetering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.9
PowerSystemModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.9
PowerSystemProtection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.10
Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.10
Quicksort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.10
RecordingTriggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.11
ReportGenerator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.11
SELEthernetController. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.11
SELRand. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.12
SELServerSimulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.12
SELString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.12
SELUtils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.12
SVPplus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.13
SnmpLite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.13
SyslogCollector. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.13
TrendRecorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.13

Section B: Developer Mode

Programming Reference Instruction Manual Date Code 20190830


List of Tables

Table 1.1 Exit Code Statuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3


Table 1.2 Advanced Sending Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.8
Table 1.3 Convert RTAC Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.11
Table 1.4 importxml RTAC Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.24
Table 1.5 Advanced Reading Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.33

Table 12.1 Master Plant Controller Control Mode Parameters . . . . . . . . . . . . . . . . . . 12.3


Table 12.2 Closed-Loop Power Factor Control Parameters . . . . . . . . . . . . . . . . . . . . . . 12.4
Table 12.3 Closed-Loop VAR Control Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.4
Table 12.4 Closed-Loop Voltage Control Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.5
Table 12.5 Open-Loop Power Factor Control Parameters . . . . . . . . . . . . . . . . . . . . . . . . 12.5
Table 12.6 Power Factor Compensation Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.6
Table 12.7 Voltage Compensation Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.7
Table 12.8 Advanced Power Output Limit Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.9
Table 12.9 Frequency Regulation Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.10

Table 19.1 IEC Equations Associated With Predefined Inverse-


Time Overcurrent Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.6
Table 19.2 U.S. Equations Associated With Predefined Inverse-
Time Overcurrent Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.6

Table 28.1 PID Equations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.3


Table 28.2 Parameters of the PID Equations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.3
Table 28.3 Error Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.12
Table 28.5 Cascade Operating Modes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.25

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
List of Figures

Figure 3.1 A Digital Filter Using Three (3) Coefficients for A(z)
and Five (5) for B(z) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.5
Figure 3.2 class_LimitedSplpfStepToDefault With a Time Con-
stant of 1000 ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.15
Figure 3.3 class_LimitedSplpfRampToDefault With a Time Con-
stant of 1000 ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.16
Figure 3.4 Plot of Total Signal and Filtered Output of the Low-
Pass Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.19

Figure 4.1 An Excursion Defined by the Absolute Channel Dif-


ference Equaling or Exceeding the Threshold Value
for the Excursion Time Generates an Alert . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1
Figure 4.2 An Excursion Defined by the Indicator Equaling a TRUE
Value for the Excursion Time Generates an Alert . . . . . . . . . . . . . . . . . . . . 4.2
Figure 4.3 Multiple Excursions Defined by the Absolute Chan-
nel Difference Equaling or Exceeding the Threshold
Value Within the Excursion Time Generates an Alert
(Chatter Count = 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2
Figure 4.4 Multiple Excursion Defined by the Indicator Equaling
a TRUE Value Within the Excursion Time Generates
an Alert (Chatter Count = 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2

Figure 6.1 A Binary Search Tree Holding Integer Values . . . . . . . . . . . . . . . . . . . . . . . 6.3


Figure 6.2 An Unbalanced Binary Search Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3
Figure 6.3 A Balanced Binary Search Tree Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4

Figure 12.1 Voltage Compensation Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.7


Figure 12.2 Frequency Regulation Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.10
Figure 12.3 Solar Facility One-Line Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.21

Figure 13.1 Ethernet Listening Access Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.9


Figure 13.2 Interface Control in CFC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.10
Figure 13.3 Ethernet Listening Access Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.10
Figure 13.4 Interface Control in CFC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.11
Figure 13.5 Ethernet Listening Access Point for PortControlRTAC1 . . . . . . . . . . . . 13.12
Figure 13.6 Ethernet Listening Access Point for PortControlRTAC2 . . . . . . . . . . . . 13.12
Figure 13.7 InterfaceControlWithSerialCheck in CFC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.14

Figure 18.1 Differing Levels of Observability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.1


Figure 18.2 High-Voltage End of a Substation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.2
Figure 18.3 High-Voltage Components Identified . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.3
Figure 18.4 Model Tied Together With Connectivity Nodes. . . . . . . . . . . . . . . . . . . . . . 18.3
Figure 18.5 Tied Model With Measurement Points Identified . . . . . . . . . . . . . . . . . . . . 18.4
Figure 18.6 All Objects Defined for One Side of the Substation . . . . . . . . . . . . . . . . . 18.4

Date Code 20190830 Instruction Manual Programming Reference


x List of Figures

Figure 18.7 Example Substation Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.45


Figure 18.8 Distribution Network of Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.54
Figure 18.9 ring of Network of Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.63

Figure 19.1 Loss-of-Potential Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.9


Figure 19.2 Overvoltage Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.10
Figure 19.3 Undervoltage Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.11

Figure 28.1 Block Diagram of a PID Control System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.2


Figure 28.2 Manual/Automatic and Ramp-to-Set Point Operation . . . . . . . . . . . . . . . 28.11
Figure 28.3 Direct-Acting and Reverse-Acting Processes . . . . . . . . . . . . . . . . . . . . . . . . . 28.12
Figure 28.4 Integral Windup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.14
Figure 28.5 Block Diagram of the PID Instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.16
Figure 28.6 CascadeControl Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.16
Figure 28.7 PID Configuration in CFC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.21
Figure 28.8 Cascade Control Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.23
Figure 28.9 Cascade Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28.26

Figure 29.1 Ring Buffer Used To Store Samples In Modal Analy-


sis Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29.2

Figure 31.1 UDP Incoming Access Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.5


Figure 31.2 prg_SyslogCollector in CFC Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.6

Figure 32.1 Example Recorder Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.4

Figure B.1 Summary Tab for Project Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.1


Figure B.2 Properties Tab for Project Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.2
Figure B.3 Save POUs as .compiled-library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.2

Programming Reference Instruction Manual Date Code 20190830


SECTION 1

Command Line Interface


Command Line Interface Basics
The ACSELERATOR RTAC® SEL-5033 Software command line interface (CLI) is a built-
in feature providing both interactive and script-based automation of core functionalities of
ACSELERATOR RTAC via a text-based console.

Uses of the command line interface includes the following:


ä Automated deployment and auditing of ACSELERATOR RTAC projects and firmware
upgrades
ä Automated build verification testing of firmware releases on networked RTAC de-
vices
ä Programmatic functional test execution
ä Mechanisms to restrict users to subsets of ACSELERATOR RTAC functionality
The command console is a simple command interpreter, accepting text commands that are
then dispatched to ACSELERATOR RTAC.

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

Date Code 20190830 Instruction Manual Programming Reference


1.2 Command Line Interface
Behavior

AcRtacCmd command
sets the -v option to FALSE.
The following would be an invalid setting for a Boolean option:
AcRtacCmd command -v true
Options can be placed in any order (even between unbound values).
values are another type of argument you can use. There are two types of values: bound
and unbound.
ä Bound values are specifying arguments that follow a non-Boolean option flag. They
must be given directly following the corresponding flag. For example, in the com-
mand AcRtacCmd command -f <file>, -f is the option flag and <file> is its bound
value. If the -f option is followed by anything other than a valid file name, the com-
mand would be invalid.
ä Unbound values are arguments that are required for the command to work. They must
be given in the order shown in the synopsis because they are processed from left to
right.

Mutually Exclusive Options and Values


Some values and options either conflict or have a similar meaning and therefore only one
is needed for the command to work. Option and values separated by ‘|’ (vertical line) are
mutually exclusive, and providing both options to the command results in a bad syntax
error.
For example:
[-a <alias> | -i <pid>]
denotes that only one of the list options can be specified in a single 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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.3
Command List

ä 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.

Table 1.1 Exit Code Statuses


Exit Code Description
0 success
1 failure
2 bad syntax
127 command not found

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.36 for more information.

Command List
The syntax of available commands are as follows.

Date Code 20190830 Instruction Manual Programming Reference


1.4 Command Line Interface
Command List

Commands
check
close
connect
convert
delete
disconnect
exportexp
exportlibrary
exportxml
help
importexp
importxml
info
list
login
lsproc
open
read
rename
start
stop
unlock
upgradefirmware

check
Initiates a build run of all objects in the POUs window.

Synopsis
AcRtacCmd check [-a <alias> | -i <pid>] [-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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.5
Command List

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 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"


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:0:success" can be found in the output
And the error level returned is: "0"

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>]

Date Code 20190830 Instruction Manual Programming Reference


1.6 Command Line Interface
Command List

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

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.7
Command List

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"

Scenario: Attempt to open a project without entering the project name


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 "open" is passed to AcRtacCmd.exe
Then "open:1:failure" can be found in the output
And the error level returned is: "1"

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>

Date Code 20190830 Instruction Manual Programming Reference


1.8 Command Line Interface
Command List

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.

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.

Table 1.2 Advanced Sending Options


Name Description
all All available project settings
Ethernet-settings Project Ethernet settings
user-accounts Project user account setting
event-logs Project sequence of events report
website-settings Project website settings
x509-certs Project x509 certificate
LDAP Project lightweight directory access protocol settings

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.9
Command List

Table 1.2 Advanced Sending Options (Continued)


Name Description
Hosts Project Host settings
CA-certs Project certificate authority settings
HMI-diagrams Project HMI diagrams
event-collection Project event collection logs
SSH-authorized-keys Project SSH-authorized-keys
SSH-host-keys Project SSH host key settings

Examples
Feature: Connecting, disconnecting, and sending projects.
The connect and disconnect commands are used to send settings to a device.

Scenario: Send the project 'Connectexample' with a process using the


alias 'ConnectTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "ConnectTest"
And admin has logged in with password TAIL
And the project "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
When the argument string "connect 197.201.80.255 SEL -p SEL -s -a
ConnectTest" is passed to AcRtacCmd.exe
Then "connect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Disconnect from "RTAC Identifier" connected with the project


'Connectexample' with a process using the alias 'ConnectTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "ConnectTest"
And admin has logged in with password TAIL
And the project "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
And the project "Connectexample" is sent to the provided RTAC
When the argument string "disconnect -a ConnectTest" is passed to
AcRtacCmd.exe
Then "disconnect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Send the project 'Connectexample' with a process 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
And the project "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked

Date Code 20190830 Instruction Manual Programming Reference


1.10 Command Line Interface
Command List

And the project "Connectexample" is open


And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
When the argument string "connect 197.201.80.255 SEL -p SEL -s" is
passed to AcRtacCmd.exe
Then "connect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Disconnect from "RTAC Identifier" connected with the project


'Connectexample' with a process using the alias 'ConnectTest'
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 "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
And the project "Connectexample" is sent to the provided RTAC
When the argument string "disconnect" is passed to AcRtacCmd.exe
Then "disconnect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to send a project without opening or specifying the


project name
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 "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
When the argument string "connect 197.201.80.255 SEL -p SEL -s" is
passed to AcRtacCmd.exe
Then "connect:1:failure" can be found in the output
And the error level returned is: "1"

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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.11
Command List

ä 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.

Table 1.3 Convert RTAC Types


Type Description
3530, 2241 RTAC type for a SEL-3530, SEL-3530-4, or SEL-2241.
3505 RTAC type for a SEL-3505 or SEL-3505-3 Communications
Gateway.
3532, 3354, 3351, 3332, 1102 This RTAC type is for a SEL-3532, SEL-3354, SEL-3351,
SEL-3332 or SEL-1102 Embedded Automation Computing
Platform.
3555 RTAC type for a SEL-3555 Real-Time Automation Controller.

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: Coverting 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: Convert an existing project from 3530 to 3555 device


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

Date Code 20190830 Instruction Manual Programming Reference


1.12 Command Line Interface
Command List

And the project "Xmlexample" exists as a 3530 project in the db


And the project "Xmlexample" is unlocked
When the argument string "convert Xmlexample 3555" is passed to
AcRtacCmd.exe
Then "convert:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Convert an existing project from R135 to R136 version


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 "Xmlexample" exists as a R135 project in the db
And the project "Xmlexample" is unlocked
When the argument string "convert Xmlexample R136" is passed to
AcRtacCmd.exe
Then "convert:0:success" can be found in the output
And the error level returned is: "0"

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"

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>

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.13
Command List

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.

Scenario: Send the project 'Connectexample' with a process using the


alias 'ConnectTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "ConnectTest"
And admin has logged in with password TAIL
And the project "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
When the argument string "connect 197.201.80.255 SEL -p SEL -s -a
ConnectTest" is passed to AcRtacCmd.exe
Then "connect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Disconnect from "RTAC Identifier" connected with the project


'Connectexample' with a process using the alias 'ConnectTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "ConnectTest"
And admin has logged in with password TAIL
And the project "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
And the project "Connectexample" is sent to the provided RTAC
When the argument string "disconnect -a ConnectTest" is passed to
AcRtacCmd.exe
Then "disconnect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Send the project 'Connectexample' with a process 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
And the project "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
When the argument string "connect 197.201.80.255 SEL -p SEL -s" is
passed to AcRtacCmd.exe
Then "connect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Disconnect from "RTAC Identifier" connected with the project

Date Code 20190830 Instruction Manual Programming Reference


1.14 Command Line Interface
Command List

'Connectexample' with a process using the alias 'ConnectTest'


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 "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And the project "Connectexample" is open
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
And the project "Connectexample" is sent to the provided RTAC
When the argument string "disconnect" is passed to AcRtacCmd.exe
Then "disconnect:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to send a project without opening or specifying the


project name
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 "Connectexample" exists as a 3530 project in the db
And the project "Connectexample" is unlocked
And a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
When the argument string "connect 197.201.80.255 SEL -p SEL -s" is
passed to AcRtacCmd.exe
Then "connect: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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.15
Command List

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

Scenario: Delete the project 'DeleteTest' with a process 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
And the project "DeleteTest" exists as a 3530 project in the db
And the project "DeleteTest" is unlocked
When the argument string "delete OpenTest" 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

Scenario: Attempt to delete a project without entering the project name


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 "delete" is passed to AcRtacCmd.exe
Then "delete:2:syntax error" can be found in the output
And the error level returned is: "2"

exportexp
Export a project with <name> as a .exp file.

Date Code 20190830 Instruction Manual Programming Reference


1.16 Command Line Interface
Command List

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

Scenario: Import a new project from .exp file using an alias


Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "expTest"
And admin has logged in with password TAIL
When the argument string "importexp ../../FTProjects/expexample.exp -a
expTest" is passed to AcRtacCmd.exe
Then "importexp:0:success" can be found in the output
And the error level returned is: "0"

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.17
Command List

Scenario: Export an existing project named expexample to .exp file using


an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "expTest"
And admin has logged in with password TAIL
And the project "expexample" exists as a 3530 project in the db
And the project "expexample" is unlocked
When the argument string "exportexp expexample -a expTest" is passed to
AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Import a new project from .exp file 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 "importexp ../../FTProjects/expexample.exp" is
passed to AcRtacCmd.exe
Then "importexp:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Export an existing project named expexample to .exp file


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
And the project "expexample" exists as a 3530 project in the db
And the project "expexample" is unlocked
When the argument string "exportexp expexample" is passed to
AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to import and xml structure without using parameters


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 "importexp" is passed to AcRtacCmd.exe
Then "importxml:1:failure" can be found in the output
And the error level returned is: "1"

Scenario: Attempt to export and xml structure without using parameters


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 "exportexp" is passed to AcRtacCmd.exe
Then "exportxml:1:failure" can be found in the output
And the error level returned is: "1"

Date Code 20190830 Instruction Manual Programming Reference


1.18 Command Line Interface
Command List

exportlibrary
Export a project with <name> as a .compiledlibrary.

Synopsis
AcRtacCmd exportlibrary [-a <alias> | -i <pid>] [-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.
-n, --name <name>
The name of the project to export.

Examples
Feature: Export a project to a .compiled-library file

Scenario: Export an existing project named Xmlexample to .compiled-library

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.19
Command List

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 "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "exportlibrary -n Xmlexample" is passed to
AcRtacCmd.exe
Then "exportlibrary:0:success" can be found in the output
And the error level returned is: "0"
And a .compiled-library is created in "the calling directory"

Scenario: Export an existing project named Xmlexample to


.compiled-library to a specific directory
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 "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "exportlibrary -n Xmlexample -f
c:\test\testlibrary" is passed to AcRtacCmd.exe
Then "exportlibrary:0:success" can be found in the output
And the error level returned is: "0"
And a .compiled-library is created in "c:\test\testlibrary"

Scenario: Attempt to export a nonexisting project to .compiled-library


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 "exportlibrary -n nonexisting" is passed to
AcRtacCmd.exe
Then "exportlibrary:1:failure" can be found in the output
And the error level returned is: "1"

exportxml
Export the current project as an XML directory structure at <directory>.

Synopsis
AcRtacCmd exportxml [-a <alias> | -i <pid>] [-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.

Date Code 20190830 Instruction Manual Programming Reference


1.20 Command Line Interface
Command List

ä 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.

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: Export an existing project named Xmlexample to 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
And the project "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "exportxml -n Xmlexample -a XmlTest
../../FTProjects/exportxml" is passed to AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.21
Command List

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"

Scenario: Export an existing project named Xmlexample to 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
And the project "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "exportxml -n Xmlexample
../../FTProjects/exportxml" is passed to AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to import and xml structure without using parameters


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" is passed to AcRtacCmd.exe
Then "importxml:1:failure" can be found in the output
And the error level returned is: "1"

Scenario: Attempt to export and xml structure without using parameters


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 "exportxml" is passed to AcRtacCmd.exe
Then "exportxml:1:failure" can be found in the output
And the error level returned is: "1"

help
Prints out a list of commands

Synopsis
AcRtacCmd help

Examples

Date Code 20190830 Instruction Manual Programming Reference


1.22 Command Line Interface
Command List

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>] <file>

Remarks
ä The .exp file name is not what determines the project name. The .exp contains the
project name and cannot be set by the user. Note that this name may be an incre-
mented version of the .exp project if the project name already exists.
ä This command will print the name of the project created to stdout.

Values
<file>
Path to file to import.

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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.23
Command List

Examples
Feature: Importing and Exporting projects as .exp file

Scenario: Import a new project from .exp file using an alias


Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "expTest"
And admin has logged in with password TAIL
When the argument string "importexp ../../FTProjects/expexample.exp -a
expTest" is passed to AcRtacCmd.exe
Then "importexp:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Export an existing project named expexample to .exp file using


an alias
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "expTest"
And admin has logged in with password TAIL
And the project "expexample" exists as a 3530 project in the db
And the project "expexample" is unlocked
When the argument string "exportexp expexample -a expTest" is passed to
AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Import a new project from .exp file 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 "importexp ../../FTProjects/expexample.exp" is
passed to AcRtacCmd.exe
Then "importexp:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Export an existing project named expexample to .exp file


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
And the project "expexample" exists as a 3530 project in the db
And the project "expexample" is unlocked
When the argument string "exportexp expexample" is passed to
AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to import and xml structure without using parameters


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 "importexp" is passed to AcRtacCmd.exe
Then "importxml:1:failure" can be found in the output
And the error level returned is: "1"

Date Code 20190830 Instruction Manual Programming Reference


1.24 Command Line Interface
Command List

Scenario: Attempt to export and xml structure without using parameters


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 "exportexp" is passed to AcRtacCmd.exe
Then "exportxml:1:failure" can be found in the output
And the error level returned is: "1"

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>] <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.

Table 1.4 importxml RTAC Types


Type Description
3530, 2241 RTAC type for a SEL-3530, SEL-3530-4, or SEL-2241.
3505 RTAC type for a SEL-3505 or SEL-3505-3 Communications
Gateway.
3532, 3354, 3351, 3332, 1102 This RTAC type is for a SEL-3532, SEL-3354, SEL-3351,
SEL-3332 or SEL-1102 Embedded Automation Computing
Platform.
3555 RTAC type for a SEL-3555 Real-Time Automation Controller.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.25
Command List

<version>
The r-number / RTAC firmware version.

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: Export an existing project named Xmlexample to 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
And the project "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "exportxml -n Xmlexample -a XmlTest
../../FTProjects/exportxml" is passed to AcRtacCmd.exe
Then "exportxml: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"

Date Code 20190830 Instruction Manual Programming Reference


1.26 Command Line Interface
Command List

Scenario: Export an existing project named Xmlexample to 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
And the project "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "exportxml -n Xmlexample
../../FTProjects/exportxml" is passed to AcRtacCmd.exe
Then "exportxml:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to import and xml structure without using parameters


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" is passed to AcRtacCmd.exe
Then "importxml:1:failure" can be found in the output
And the error level returned is: "1"

Scenario: Attempt to export and xml structure without using parameters


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 "exportxml" is passed to AcRtacCmd.exe
Then "exportxml:1:failure" can be found in the output
And the error level returned is: "1"

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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.27
Command List

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 with an alias


Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "InfoTest"
And admin has logged in with password TAIL
When the argument string "info -a InfoTest" 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

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

Scenario: Get the status of an AcSELerator RTAC process without logging in


Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
When the argument string "info" is passed to AcRtacCmd.exe
Then "NONE:NONE:offline" can be found in the output
And "info:0:success" can be found in the outputs
And the error level returned is: "0"

list
List all projects in an ACSELERATOR RTAC database.

Date Code 20190830 Instruction Manual Programming Reference


1.28 Command Line Interface
Command List

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.

Scenario: Show all projects in database


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 "list" is passed to AcRtacCmd.exe
Then "list:0:success" can be found in the output
And the error level returned is: "0"
And A list of projects can be found in the output in the format
"name:type:version"

Scenario: Attempt to list the projects stored in the database without


being logged into the database
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create an unnamed worker
process
When the argument string "list" is passed to AcRtacCmd.exe
Then "list:1:failure" can be found in the output
And the error level returned is: "1"

login
Log into the ACSELERATOR RTAC database.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.29
Command List

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.

Scenario: Login to the AcSELerator RTAC database with default account


Given "AcRtacCmd.exe start" has been executed to create an unnamed
worker process
When the argument string "login admin -p TAIL" is passed to
AcRtacCmd.exe
Then "login:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to login without providing a correct username and


password
Given "AcRtacCmd.exe start" has been executed to create an unnamed
worker process

Date Code 20190830 Instruction Manual Programming Reference


1.30 Command Line Interface
Command List

When the argument string "login notarealuser -p badpassword" is passed


to AcRtacCmd.exe
Then "login:1:failure" can be found in the output
And the error level returned is: "1"

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

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.31
Command List

open
Opens a project in ACSELERATOR RTAC database with name <name>.

Synopsis
AcRtacCmd open [-a <alias> | -i <pid>] <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.

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

Date Code 20190830 Instruction Manual Programming Reference


1.32 Command Line Interface
Command List

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"

Scenario: Attempt to open a project without entering the project name


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 "open" is passed to AcRtacCmd.exe
Then "open:1:failure" can be found in the output
And the error level returned is: "1"

read
Reads a project into the active local database from a remote RTAC.

Synopsis
AcRtacCmd read [-a <alias> | -i <pid>] [-p <password>] [-d] <ipaddress>
<username>

Remarks
ä Upon successfully reading the project, the project name is printed to the console.
Note that this name may be an incremented version of the remote project if the project
name already exists.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.33
Command List

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.
-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.

Table 1.5 Advanced Reading Options


Name Description
all All available project settings
Ethernet-settings Project Ethernet settings
user-accounts Project user account setting
event-logs Project sequence of events report
website-settings Project website settings
x509-certs Project x509 certificate
LDAP Project lightweight directory access protocol settings
Hosts Project Host settings
CA-certs Project certificate authority settings
HMI-diagrams Project HMI diagrams
event-collection Project event collection logs
SSH-authorized-keys Project SSH-authorized-keys

Date Code 20190830 Instruction Manual Programming Reference


1.34 Command Line Interface
Command List

Table 1.5 Advanced Reading Options (Continued)


Name Description
SSH-host-keys Project SSH host key settings

Examples
Feature: Reading project settings from a RTAC.

Scenario: Read project settings from a RTAC


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 a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
And the RTAC is running "SampleProject"
When the argument string "read 197.201.80.255 SEL -p SEL" is passed to
AcRtacCmd.exe
Then "read:0:success" can be found in the output
And the error level returned is: "0"
And "SampleProject" can be found as a project in the local database

Scenario: Attempt to read project settings from a RTAC with invalid


credentials
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 a RTAC at "197.201.80.255" with username "SEL" and password "SEL"
is available
And the RTAC is running "SampleProject"
When the argument string "read 197.201.80.255 SEL -p badpassword" is
passed to AcRtacCmd.exe
Then "read:1:failure" can be found in the output
And the error level returned is: "1"

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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.35
Command List

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.

Scenario: Rename an existing project from "Xmlexample" to "RenameProject"


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 "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "rename RenameProject -n Xmlexample " is
passed to AcRtacCmd.exe
Then "rename:0:success" can be found in the output
And the error level returned is: "0"
And the project "RenameProject" exists as a project in the db

Scenario: Attempt to Rename a project without opening or giving the


project name
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 "Xmlexample" exists as a 3530 project in the db
And the project "Xmlexample" is unlocked
When the argument string "rename Xmlexample" is passed to AcRtacCmd.exe
Then "rename:1:failure" can be found in the output
And the error level returned is: "1"

Date Code 20190830 Instruction Manual Programming Reference


1.36 Command Line Interface
Command List

start
Starts a new RTAC.exe process.

Synopsis
AcRtacCmd start [-a <alias>] [--switch <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
Opens the ACSELERATOR RTAC GUI when starting RTAC.exe. Commands
will still be accepted through the command line and the open window will re-
flect changes made by commands.

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

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.37
Command List

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

Scenario: Run AcRtacCmd to stop a process without any processes running


Given AcRtacCmd is in the system path
When the command "AcRtacCmd stop" is issued in a console
Then "stop:1:failure" can be found in the output
And the error level returned is: "1"

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.

Date Code 20190830 Instruction Manual Programming Reference


1.38 Command Line Interface
Command List

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

Scenario: Run AcRtacCmd to stop a process without any processes running


Given AcRtacCmd is in the system path
When the command "AcRtacCmd stop" is issued in a console
Then "stop:1:failure" can be found in the output
And the error level returned is: "1"

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.

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.39
Command List

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.

Scenario: Unlock the project 'ExampleProject' with a process using the


alias 'UnlockTest'
Given AcRtacCmd is in the system path
And "AcRtacCmd.exe start" has been executed to create a worker process
named "UnlockTest"
And admin has logged in with password TAIL
And the project "ExampleProject" exists as a 3530 project in the db
And the project "ExampleProject" is locked
When the argument string "unlock ExampleProject -a UnlockTest" is
passed to AcRtacCmd.exe
Then "unlock:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Unlock the project 'ExampleProject' 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 "ExampleProject" exists as a 3530 project in the db
And the project "ExampleProject" is locked
When the argument string "unlock ExampleProject" is passed to
AcRtacCmd.exe
Then "unlock:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to unlock a project that 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 "unlock nonExistent" is passed to AcRtacCmd.exe
Then "unlock:1:failure" can be found in the output

Date Code 20190830 Instruction Manual Programming Reference


1.40 Command Line Interface
Command List

And the error level returned is: "1"

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.

Examples
Feature: Upgrade firmware on an RTAC

Scenario: Change "3555" RTAC firmware to "R135"


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 a "3555" RTAC at "197.201.80.255" with username "SEL" and password
"SEL" is available

Programming Reference Instruction Manual Date Code 20190830


Command Line Interface 1.41
Command Line Example Usage

And an RTAC firmware image is available at "c:\RTAC\3555_R135.upg"


When the argument string "upgradefirmware 197.201.80.255 SEL -p SEL
c:\RTAC\3555_R135.upg" is passed to AcRtacCmd.exe
Then "upgradefirmware:0:success" can be found in the output
And the error level returned is: "0"

Scenario: Attempt to Change "3555" RTAC firmware to "R135" with "3530"


firmware image
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 a "3555" RTAC at "197.201.80.255" with username "SEL" and password
"SEL" is available
And an RTAC firmware image is available at "c:\RTAC\3530_R135.upg"
When the argument string "upgradefirmware 197.201.80.255 SEL -p SEL
c:\RTAC\3530_R135.upg" is passed to AcRtacCmd.exe
Then "upgradefirmware:1:failure" can be found in the output
And the error level returned is: "1"

Command Line Example Usage


Convert .exp to .xml from Command Line
This example provides step-by-step instructions on how to import a project from a .exp file
and export it to a .xml file/folder system.

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

Date Code 20190830 Instruction Manual Programming Reference


1.42 Command Line Interface
Command Line Example Usage

Step 3. The command will respond as follows (note that the PID may be different
than shown in this example):

AcRtacCmd start -a session1


session1:1234
start:0:success
Step 4. Log into the Database with the command AcRtacCmd login admin -p
TAIL
Note that your username and password should be used in place of “admin”
and “TAIL” above.
Step 5. The command will respond as follows:

AcRtacCmd login admin -p TAIL


login:0:success
Step 6. Now, to import a .exp file, use the command AcRtacCmd importexp "C:\TestConvertExpToXml\MyProject.exp"
Step 7. The command will respond as follows:

AcRtacCmd importexp C:\TestConvertExpToXml\MyProject.exp


importexp:MyProject
importexp:0:success
Step 8. Then enter the command below to export to .xml the project that was just
imported. Note that because you did not open the project first, this command
will open, export, and then close the project.

AcRtacCmd exportxml "C:\TestConvertExpToXml\MyProject" -n MyProject


Step 9. When complete, the command should return as follows:

AcRtacCmd exportxml "C:\TestConvertExpToXml\MyProject" -n MyProject


.
.
.
exportxml:0:success
Step 10. Ensure the RTAC process is stopped before completing the session as follows:

AcRtacCmd stop -a session1


stop:0:success

Expected Result
The project definition should now exist in the following folder: C:\TestConvertExpToXml\MyProject\

Programming Reference Instruction Manual Date Code 20190830


SECTION 2

Library Extensions Installer


This section details the expected usage and outputs of the Library Extension Installer ex-
ecutable distributed with ACSELERATOR RTAC® SEL-5033 Software. This interface is
provided such that additional functionality can be deployed to the ACSELERATOR RTAC
software to extend the feature set.

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)/).

Installing AcSELerator RTAC Extension


Packages
In addition to installing CODESYS libraries, this command line interface can be used to
install all of the content required for a new ACSELERATOR RTAC Extension. This content
is expected to be in a .rext file, which is a zipped folder with the following layout:
.rext
<folder with a version of the extension X.X.X.X>
<ExtensionPy>.py
<ExtensionXML>.xml
<ExtensionPy>.sig
<ExtensionXML>.sig
<CODESYSLibraryA>.compiled-library (optional)
<CODESYSLibraryB>.library (optional)
Note that each ACSELERATOR RTAC Extension can contain zero or more .compiled-library
or .library files.
The .xml files in the .rext file will be parsed, and the content of the first tag:
<RTACModule><CustomApplicationDefinition><Name>
is used as the name of the ACSELERATOR RTAC Extension.

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:

Date Code 20190830 Instruction Manual Programming Reference


2.2 Library Extensions Installer
Bulk Installation of .library, .compiled-library, and .rext Files

> cd /Program Files (x86)/SEL/AcSELerator/RTAC


> LibraryExtensionInstaller.exe C:/Users/Alice/Desktop/myExtensions/Extension1.rext

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.

Bulk Installation of .library, .compiled-library,


and .rext Files
In order to expedite the installation of many libraries or extensions, you can pass into the
service a folder containing a combination of .library, .compiled-library, and .rext files.

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.

Programming Reference Instruction Manual Date Code 20190830


Library Extensions Installer 2.3
Logging and Debugging

Logging and Debugging


The installer outputs to the human-readable log file LibraryExtensionInstaller.txt,
which is contained in the directory C:/Users/<username>/Documents/AcSELerator
RTAC/Logs. The file is not structured, but will indicate complete for each successful
library installation, listing the name of the library on the same line. A successful installation
of all libraries will be indicated by All libraries installed successfully near the
end of the file. Errors and failures may be found by searching for the words “fail” or “error”.

Code Snippet 2.1 Example Log File Output


[Begin] Initializing logic engine
[End] Initializing logic engine
Installing DynamicVectorsFT... complete.
Installing CompiledMathMatrixFT... complete.
All libraries installed successfully.
[Begin] Shutting down logic engine
[End] Shutting down logic engine

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.

Notes and Exceptions


LibraryExtensionInstaller.exe currently requires the LibraryExtensionInstaller.exe .config
XML file, which directs the executable where to probe for certain required assemblies. The
.config file should have been installed along with ACSELERATOR RTAC and should not be
modified.

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 3

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.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.1.1 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.

Name IEC 61131 Type Value Description


g_p_MaxFilterOrder UINT 4 The maximum order of the filter for
class_ArmaFilter. This determines the
maximum number of coefficients and
the maximum delay, in samples, for the
filter.

Interface Definitions
This section outlines the various interfaces defined within this library.

I_Filter
Classes implementing this interface provide a filter for analog values.

Date Code 20190830 Instruction Manual Programming Reference


3.2 AnalogCond
Interface Definitions

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.

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.3
Public Class Definitions

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).

Name IEC 61131 Type Access Description


Alarm BOOL R/W Sets an alarm when true. Clears the alarm state if
false.

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.

Public Class Definitions


This section contains the basic definitions, descriptions, and public methods for the public
classes that can be instantiated by the user.

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.

Date Code 20190830 Instruction Manual Programming Reference


3.4 AnalogCond
Public Class Definitions

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.

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.5
Public Class Definitions

−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.4, but it retains greater precision internally. This allows for greater stability.

Date Code 20190830 Instruction Manual Programming Reference


3.6 AnalogCond
Public Class Definitions

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.

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.7
Public Class Definitions

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.

Date Code 20190830 Instruction Manual Programming Reference


3.8 AnalogCond
Public Class Definitions

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.

Processing of Interface Methods


This section provides specifics regarding the implementation of the methods required by
the implemented interface(s).

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

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.9
Public Class Definitions

ä 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.

Date Code 20190830 Instruction Manual Programming Reference


3.10 AnalogCond
Public Class Definitions

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.

Processing of Interface Methods


This section provides specifics regarding the implementation of the methods required by
the implemented interface(s).

I_LimitedSplpf—ConditionValue
This describes the behavior of this class when the ConditionValue() method is called.

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.11
Benchmarks

ä 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

Date Code 20190830 Instruction Manual Programming Reference


3.12 AnalogCond
Benchmarks

â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware
ä SEL-3505
â R134 firmware

Benchmark Test Descriptions


Any time less than one microsecond was rounded up to one microsecond for this report.

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

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.13
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
class_ArmaFilter 1 1 1
class_ArmaFilter_LREAL 1 1 1
class_PassThroughFilter 1 1 1

Date Code 20190830 Instruction Manual Programming Reference


3.14 AnalogCond
Examples

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.

Filtering with class_LimitedSplpfStepToDefault


The example code shown in Code Snippet 3.1 demonstrates a very simple use of this library.
This code instantiates a simple filter with the following attributes:
1. The filter output has a range of 0–100 inclusive.
2. If the filter input goes out of range or the Alarm property is set, the output steps to
the default value of 50.
3. The filter time constant is 1000 ms.
4. The filter has an initial value of zero.
This code filters rawValue normally for 100 time steps. After 100 time steps, Alarm is set
to true.

Code Snippet 3.1 prg_FilterStepToDefault


PROGRAM pr g_ F il t er St e pT o De f au lt
VAR
initialized : BOOL := FALSE ;
filter : c l a s s _ L i m i t e d S p l p f S t e p T o D e f a u l t ;
rawValue : REAL := 75;
filteredValue : REAL ;
step : UINT ;
END_VAR

IF NOT initialized THEN // Only initialize the filter once.


// Initialize the filter with a range of 0-100, a default output
// of 50, and a time constant of 1000 ms.
filter.LimitedSplpfStepToDefault(highLimit := 100, lowLimit := 0,
defaultOutput := 50, timeConstant := 1000);
// Start the filter with an initial value of zero.
filter.bootstrap_SetInitialValue(0);
initialized := TRUE;
END_IF

IF step < 100 THEN


// Filter normally for 100 time steps.
filter.ConditionValue(rawValue, conditionedValue => filteredValue);
step := step + 1;
ELSE
// After 100 time steps, set the Alarm property.
filter.Alarm := TRUE;
filter.ConditionValue(rawValue, conditionedValue => filteredValue);
END_IF

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.15
Examples

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.

Figure 3.2 class_LimitedSplpfStepToDefault With a Time Constant of 1000 ms

Filtering with class_LimitedSplpfRampToDefault


The example code shown in Code Snippet 3.2 demonstrates a simple use of this library.
This code instantiates a simple filter with the following attributes:
1. The filter output has a range of 0–100 inclusive.
2. If the filter input goes out of range or the Alarm property is set, the output will ramp
to the default value of 50.
3. The filter time constant is 1000 ms.
4. The filter has an initial value of zero.
This code filters rawValue normally for 100 time steps. After 100 time steps, Alarm is set
to true.

Code Snippet 3.2 prg_FilterRampToDefault


PROGRAM pr g_ F il t er Ra m pT o De f au lt
VAR
initialized : BOOL := FALSE ;
filter : c l a s s _ L i m i t e d S p l p f R a m p T o D e f a u l t ;
rawValue : REAL := 75;
filteredValue : REAL ;
step : UINT ;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


3.16 AnalogCond
Examples

Code Snippet 3.2 prg_FilterRampToDefault (Continued)


IF NOT initialized THEN // Only initialize the filter once .
// Initialize the filter with a range of 0 -100 , a default
output
// of 50 , and a time constant of 1000 ms .
filter . L i mi t e d S p l p f R a m p T o D e f a u l t ( highLimit := 100 ,
lowLimit := 0 ,
defaultOutput := 50 , timeConstant := 1000) ;
// Start the filter with an initial value of zero .
filter . b o ot s t r a p _ S e t I n i t i a l V a l u e (0) ;
initialized := TRUE ;
END_IF

IF step < 100 THEN


// Filter normally for 100 time steps .
filter . ConditionValue ( rawValue , conditionedValue = >
filteredValue ) ;
step := step + 1;
ELSE
// After 100 time steps , set the Alarm property .
filter . Alarm := TRUE ;
filter . ConditionValue ( rawValue , conditionedValue = >
filteredValue ) ;
END_IF

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.

Figure 3.3 class_LimitedSplpfRampToDefault With a Time Constant of 1000 ms

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.17
Examples

Filtering with class_ArmaFilter


The ARMA filter is best suited to filtering oscillating signals, and depending on the coef-
ficients used, provides a high-pass, low-pass, band-pass, or band-stop filter. This example
shows a specific implementation of the ARMA filter, but the basic approach described is
general, and can be used to provide whatever filtering the user of this library requires.

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:

Sample1n = 0.25 × COS((1/10) × 2πn)

Sample2n = 2 × SIN ((1/100) × 2πn)


Sample3n = SIN ((1/1000) × 2πn)
where n is the sample number.
These equations will provide one sample each time n is increased, and these discrete sam-
ples are described as follows:
period
Sample1n will have a period of 10 samples (high-frequency), a sample ratio of 0.1, be
offset by 90 degrees from the other two waves and a magnitude of 1/8 of the primary
frequency.
Sample2n is the primary frequency. It will have a period of 100 samples (mid-frequency)
period
and a sample ratio of 0.01.
period
Sample3n will have a period of 1000 samples (low-frequency), a sample ratio of 0.001
and a magnitude that is half of the primary frequency.
The sum of these three sine waves is fed into the low-pass filter.

F ilterInputn = Sample1n + Sample2n + Sample3n

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.

Date Code 20190830 Instruction Manual Programming Reference


3.18 AnalogCond
Examples

Code Snippet 3.3 OCTAVE Code to Design a Butterworth Filter


octave :1 >[ B , A ] = butter (3 , 0.05)
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, all
ans = 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.

Code Snippet 3.5 prg_LowpassFilter


PROGRAM prg_LowPassFilterDemo
VAR CONSTANT
c_Steps : UDINT := 1000;
c_Acoeff : ARRAY[1..g_p_MaxFilterOrder] OF REAL := [
-2.68616, 2.41966, -0.73017];
c_Bcoeff : ARRAY[0..g_p_MaxFilterOrder] OF REAL := [
4.1655e-04, 1.2496e-03, 1.2496e-03, 4.1655e-04];
END_VAR
VAR
Filter : class_ArmaFilter(c_Acoeff, c_Bcoeff, 3, 4);
Signals : ARRAY[1..3] OF ARRAY[1..c_Steps] OF REAL;
DesiredSignals : ARRAY[1..c_Steps] OF REAL;
TotalSignal : ARRAY[1..c_Steps] OF REAL;
FilterOutput : ARRAY[1..c_Steps] OF REAL;
Stage : UDINT := 0;
END_VAR
VAR_TEMP
i : UDINT;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


AnalogCond 3.19
Examples

Code Snippet 3.5 prg_LowpassFilter (Continued)


CASE Stage OF
0:
;// Do nothing on the first scan
1:
FOR i := 1 TO c_Steps DO
(* Calculate the samples used to create a compound signal *)
Signals[1][i] := 0.25 * COS(0.1*UDINT_TO_REAL(i)*2*PI);
Signals[2][i] := 2 * SIN(0.01*UDINT_TO_REAL(i)*2*PI);
Signals[3][i] := SIN(0.001*UDINT_TO_REAL(i)*2*PI);

(* Add the low and mid frequency components together to compare


against filtered output for accuracy. *)
DesiredSignals[i] := Signals[2][i] + Signals[3][i];

(* Add the high-frequency component to this signal to observe that


the Butterworth low-pass filter removes it, leaving just the
desired signal. *)
TotalSignal[i] := DesiredSignals[i] + Signals[1][i];

(* Pass the entire signal into the filter. *)


Filter.ConditionValue(TotalSignal[i],
conditionedValue => FilterOutput[i]);
END_FOR
2:
;// Add a way to print out the results to a file here if desired
ELSE
;// Done
END_CASE
Stage := Stage + 1;

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

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 4

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.1 An Excursion Defined by the Absolute Channel Difference Equaling or


Exceeding the Threshold Value for the Excursion Time Generates an Alert

Date Code 20190830 Instruction Manual Programming Reference


4.2 ChannelMonitoring
Introduction

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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type
class_fb_MultiChannelAlertObject"
myfb_MultiChannelAlertObject :=
otherfb_MultiChannelAlertObject;

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.3
Enumerations

// This is fine
someVariable := myfb_MultiChannelAlertObject.value;
// As is this
pt_myfb_MultiChannelAlertObject :=
ADR(myfb_MultiChannelAlertObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.0 and older can be used on RTAC firmware version R132 and higher.

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.

Enumeration Value Description


NO_DEVIATION 0 No alerts detected
CHATTER 1 Multiple excursions occurred within the excursion time
EXPIRATION 2 A sustained excursion equaled or exceeded the excursion time
EXCURSION 3 An instantaneous excursion. Used where ExcursionTime input is
not applicable.
BAD_QUALITY 4 Minimum number of inputs do not have good quality
RESET 5 Reset input is currently asserted
ERROR 6 Function block was unable to activate because of limited memory
resources
COMPLETE 7 Operation complete

Date Code 20190830 Instruction Manual Programming Reference


4.4 ChannelMonitoring
Functions

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.

Enumeration Value Description


NO_ALERTS 0 No alerts detected
CHANNEL_1_ALERT 1 Channel 1 is the responsible channel
CHANNEL_2_ALERT 2 Channel 2 is the responsible channel
CHANNEL_1_2_ALERT 3 Channel 1 and 2 are the responsible channels
CHANNEL_3_ALERT 4 Channel 3 is the responsible channel
CHANNEL_1_3_ALERT 5 Channel 1 and 3 are the responsible channels
CHANNEL_2_3_ALERT 6 Channel 2 and 3 are the responsible channels
MULTIPLE_CHANNEL_ALERT 7 All available channels are responsible

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.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.5
Function Blocks

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

Date Code 20190830 Instruction Manual Programming Reference


4.6 ChannelMonitoring
Function Blocks

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.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.7
Function Blocks

ä 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.

Date Code 20190830 Instruction Manual Programming Reference


4.8 ChannelMonitoring
Function Blocks

ä 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.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.9
Function Blocks

ä 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.

Date Code 20190830 Instruction Manual Programming Reference


4.10 ChannelMonitoring
Function Blocks

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.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.11
Function Blocks

ä 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 incremental derivative is defined as the change
in Channel.instMag between the k and k - 1 samples divided by the Period input.
The incremental derivative is assigned a time stamp equal to the RTAC system time
of processing the k sample. This mode can be useful for real-time processing of
deadbanded data sources where no Channel update is meant to be interpreted as
a derivative of zero. When using this mode, the applied Period setting should be
greater than or equal to, and equally divisible by, the RTAC task time.
ä The function block maintains a buffer of the ConditionedFilterLength most recent
incremental derivative results. The Derivative output represents the average of the
buffered results. The Derivative output updates only when the buffer is full. The
buffer is full once ConditionedFilterLength plus one Channel samples are processed.
ä While EN = FALSE, Channel is not processed. The cached k - 1 sample is not
updated.
ä While Channel.instMag represents a floating point value of NAN, Inf, or -Inf, Chan-
nel is not processed. The Status is set to ERROR. The cached k - 1 sample is not
updated.
ä Negative time-stamp differences between consecutive Channel samples are ignored
when PeriodicProcessing = FALSE. Channel is not processed. However, the
cached k - 1 sample is updated to avoid a negative calculated sample interval on
the next incremental derivative calculation. Status equals ERROR until a positive
time-stamp difference is detected or Reset is asserted.
ä While Channel is not being processed, the output Derivative value and time stamp
are held at the last calculated result.
ä As previously noted, Channel is not processed when EN = FALSE, Channel.instMag
represents an invalid REAL quantity, or when a negative time-stamp difference is de-
tected while PeriodicProcessing = FALSE. However, the buffer is not cleared in
these cases. The next Channel sample that is processed causes the buffer to be up-
dated with the derivative between the current sample and the cached k - 1 sample.
While the resultant Derivative update in this case still represents the average deriva-
tive over ConditionedFilterLength plus one samples, it may not accurately portray
the average derivative over ConditionedFilterLength plus one expected sample in-
tervals. It is the responsibility of the user to clear the buffer by asserting Reset if
Channel processing is inhibited for a duration deemed unacceptable.
ä The output Derivative.t structure is set equal to the time stamp of the incremen-
tal derivative result at the center position of the buffer. This is done for derivative
approximation accuracy.
ä The output Derivative is assigned a quality that represents the lowest quality indi-
cators of all Channel samples processed in the calculation of the output derivative
value.
ä If the Derivative.q.validity does not equal good then the output QualityAlert
is asserted.
ä If the absolute value of the output Derivative.instMag exceeds the absolute value
of DerivativeThreshold, Alert.stVal is asserted. Alert.t is set equal to the
RTAC system time. Status is set to EXCURSION.

Date Code 20190830 Instruction Manual Programming Reference


4.12 ChannelMonitoring
Function Blocks

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.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.13
Function Blocks

ä 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:

Date Code 20190830 Instruction Manual Programming Reference


4.14 ChannelMonitoring
Function Blocks

â Channel.instMag at Channel.t time for the most recently processed sample


(k).
â Channel.instMag at the Channel.t time for the previously processed sam-
ple (k - 1).
ä Negative time-stamp differences between consecutive Channel samples are ignored.
In this scenario, the Channel sample is not used in the integral approximation. How-
ever, the cached k - 1 sample is updated to avoid a negative calculated sample in-
terval on the next incremental update to the Integral output. Status equals ERROR
until a positive time-stamp difference is detected or Reset is asserted.
ä The integration period begins when Channel.instMag is in excess of SetPoint. At
this time Status is set to EXCURSION.
ä Channel.instMag must exceed SetPoint for a minimum time equal to Debounce-
Time in order for integration to complete.
ä If Channel.instMag is in excess of SetPoint, but becomes equal to or less than
SetPoint before DebounceTime is reached, the function block is reset on the first task
cycle for which Channel.instMag is not in excess of SetPoint.
ä If Channel.instMag exceeds SetPoint for a duration equal to DebounceTime, Status
is set to EXPIRATION and ExcursionTimeOn is assigned as described below.
ä While Status is set to EXPIRATION integration will continue until Channel.instMag
falls below SetPoint for time equal to DebounceTime.
ä If the preceding debounce time condition is met, Alert.stVal asserts, Alert.t.value
is set equal to the RTAC system time. Status is set to COMPLETE and Excursion-
TimeOff is assigned as described below.
ä ExcursionTimeOn and ExcursionTimeOff, respectively, are assigned a derived time-
stamp that is between the time stamp values associated with the two processed Chan-
nel samples that straddle SetPoint. More specifically, this time stamp coincides with
the intersection of the line drawn between the .instMag values of these two samples
and SetPoint.
ä Integral.t.value is set equal to ExcursionTimeOn and will not be updated until
the function block is reset.
ä The Integral output represents the area under Channel.instMag and over Lower-
Bound between ExcursionTimeOn and ExcursionTimeOff as shown in Equation 4.1
.

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.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.15
Function Blocks

ä 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 can not be changed during runtime.
ä ENO is true when EN = TRUE and the function block initialization is completed
successfully.

Date Code 20190830 Instruction Manual Programming Reference


4.16 ChannelMonitoring
Benchmarks

ä 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.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.17
Benchmarks

ä 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

Benchmark Test Descriptions


Each benchmarking test is performed 1000 times and the average run time is recorded here.
Each test is intended to give insight into the expected cost of running the given command.

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_MultiChannelAlert 1 Channel Timed


The cost of a call to fb_MultiChannelAlert when all channels are active and one channel
differs from the others long enough to generate an alert. This is the run time on the scan
the alert begins.

fb_MultiChannelAlert All Channel Timed


The cost of a call to fb_MultiChannelAlert when all channels are active and all three chan-
nels differ from each other long enough to generate an alert. This is the run time on the
scan the alert begins.

Date Code 20190830 Instruction Manual Programming Reference


4.18 ChannelMonitoring
Benchmarks

fb_MultiChannelAlert 1 Channel Chatter


The cost of a call to fb_MultiChannelAlert when all channels are active and one channel
differs from the others often enough to generate an alert. This is the run time on the scan
the alert begins.

fb_MultiChannelAlert All Channel Chatter


The cost of a call to fb_MultiChannelAlert when all channels are active and all three chan-
nels differ from each other often enough to generate an alert. This is the run time on the
scan the alert begins.

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 Active Periodic


The cost of a call to fb_ChannelDerivative during active derivative calculation on a Channel
input while in periodic processing mode (PeriodicProcessing = TRUE).

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.19
Benchmarks

fb_ChannelDerivative Active Not Periodic


The cost of a call to fb_ChannelDerivative during active derivative calculation on a Channel
input while in not in periodic processing mode (PeriodicProcessing = FALSE). In this
mode sample processing is triggered by Channel time-stamp changes.

fb_ChannelDerivative Alert
The cost of a call to fb_ChannelDerivative while Status = EXCURSION and Alert.stVal
= TRUE.

fb_ChannelIntegral No Deviation Periodic


The cost of a call to fb_ChannelIntegral while it is in an idle state, and while it is in periodic
processing mode (PeriodicProcessing = TRUE).

fb_ChannelIntegral No Deviation Not Periodic


The cost of a call to fb_ChannelIntegral during an idle state while not in periodic processing
mode (PeriodicProcessing = FALSE). In this mode sample processing is triggered by
Channel time-stamp changes.

fb_ChannelIntegral Active Periodic


The cost of a call to fb_ChannelIntegral during an active integration state while in periodic
processing mode (PeriodicProcessing = TRUE).

fb_ChannelIntegral Active Not Periodic


The cost of a call to fb_ChannelIntegral during an active integration state while not in peri-
odic processing mode (PeriodicProcessing = FALSE). In this mode sample processing
is triggered by Channel time-stamp changes.

fb_ChannelIntegral Complete Periodic


The cost of a call to fb_ChannelIntegral during a Status = COMPLETE state while in pe-
riodic processing mode (PeriodicProcessing = TRUE).

fb_ChannelIntegral Complete Not Periodic


The cost of a call to fb_ChannelIntegral during a Status = COMPLETE state while not in
periodic processing mode (PeriodicProcessing = FALSE). In this mode sample pro-
cessing is triggered by Channel time-stamp changes.

Date Code 20190830 Instruction Manual Programming Reference


4.20 ChannelMonitoring
Benchmarks

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).

fb_IndicatorTimeDelta Bad Quality


The cost of a call to fb_IndicatorTimeDelta during a Status = BAD_QUALITY state (either
indicator input has .q.validity that is not equal to good).

fb_IndicatorTimeDelta Waiting For Second Indicator


The cost of a call to fb_IndicatorTimeDelta while one indicator input is asserted and the
function block is waiting for the second indicator input to assert.

fb_IndicatorTimeDelta Alert State


The cost of a call to fb_IndicatorTimeDelta during a Alert.stVal = TRUE state (time
difference has exceeded the threshold. Alert is held high until a user reset).

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
fb_MultiChannelAlert All Channel Chatter 24 39 4
fb_ChannelAlert No Alert 10 14 2
fb_ChannelAlert Timed 16 22 3
fb_ChannelAlert Chatter 18 26 3
fb_IndicatorAlert No Alert 8 10 2
fb_IndicatorAlert Timed 14 19 3
fb_IndicatorAlert Chatter 16 22 3
fb_ChannelDerivative Active Periodic 56 123 10
fb_ChannelDerivative Active Not Periodic 105 138 18
fb_ChannelDerivative Alert 6 8 1
fb_ChannelIntegral No Deviation Periodic 26 90 5
fb_ChannelIntegral No Deviation Not Periodic 22 41 3
fb_ChannelIntegral Active Periodic 31 111 4
fb_ChannelIntegral Active Not Periodic 28 78 3

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.21
Examples

Platform (time in µs)


Operation Tested
SEL-3530 SEL-3505 SEL-3555
fb_ChannelIntegral Complete Periodic 7 40 1
fb_ChannelIntegral Complete Not Periodic 7 8 1
fb_IndicatorTimeDelta No Deviation 9 12 1
fb_IndicatorTimeDelta Bad Quality 7 35 1
fb_IndicatorTimeDelta Waiting For Second Indicator 11 44 2
fb_IndicatorTimeDelta Alert State 5 6 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.

Monitor Phase-A Measurements for a Maintenance


Condition
Objective
Create a program to monitor and verify the measurements obtained from three protective
relays to determine if the components are functioning within expected limits.

Solution
This solution uses the fb_ChannelAlert function block to monitor for difference between
CTs. The Phase A measurements are obtained from the relays and compared against a
reference measurement (see Code Snippet 4.1).

Date Code 20190830 Instruction Manual Programming Reference


4.22 ChannelMonitoring
Examples

Code Snippet 4.1 prg_MonitorPhaseA_Components


PROGRAM prg_MonitorPhaseA_Components
VAR
(*Function block monitoring IED 1-3*)
IED_1_PhA : fb_ChannelAlert;
IED_2_PhA : fb_ChannelAlert;
IED_3_PhA : fb_ChannelAlert;
(*Function block parameters*)
PhA_Reference : MV; Allowed_Deviation : REAL; Allowed_Chatter : UDINT;
AlertTime : TIME; MonitorReset : BOOL;
(*Criterion to enable the monitoring block*)
EnableMonitoring : BOOL;
(*Alert status*)
IED_1_Enabled : BOOL; IED_2_Enabled : BOOL; IED_3_Enabled : BOOL;
(*Placeholder for a data communications tag*)
IED_1_Data : MV; IED_2_Data : MV; IED_3_Data : MV;
(*Alert status*)
IED_1_Alert : SPS; IED_2_Alert : SPS; IED_3_Alert : SPS;
(*Alert condition*)
IED_1_Status : DINT; IED_2_Status : DINT; IED_3_Status : DINT;
(*Quality status*)
IED_1_Quality : BOOL; IED_2_Quality : BOOL; IED_3_Quality : BOOL;
END_VAR

(*Check the quality of the reference signal*)


EnableMonitoring := (PhA_Reference.q.validity = good);

(*Configure and monitor the function block parameters*)


IED_1_PhA(EN := EnableMonitoring, Channel := IED_1_Data,
ChannelReference := PhA_Reference.instMag,
ExcursionThreshold := Allowed_Deviation,
ChatterCount := Allowed_Chatter, ExcursionTime := AlertTime,
LatchAlarm := TRUE, Reset := MonitorReset,
ENO => IED_1_Enabled, Alert => IED_1_Alert,
Status => IED_1_Status, QualityAlert => IED_1_Quality);

IED_2_PhA(EN := EnableMonitoring, Channel := IED_2_Data,


ChannelReference := PhA_Reference.instMag,
ExcursionThreshold := Allowed_Deviation,
ChatterCount := Allowed_Chatter, ExcursionTime := AlertTime,
LatchAlarm := TRUE, Reset := MonitorReset,
ENO => IED_2_Enabled, Alert => IED_2_Alert,
Status => IED_2_Status, QualityAlert => IED_2_Quality);

IED_3_PhA(EN := EnableMonitoring, Channel := IED_3_Data,


ChannelReference := PhA_Reference.instMag,
ExcursionThreshold := Allowed_Deviation,
ChatterCount := Allowed_Chatter, ExcursionTime := AlertTime,
LatchAlarm := TRUE, Reset := MonitorReset,
ENO => IED_3_Enabled, Alert => IED_3_Alert,
Status => IED_3_Status, QualityAlert => IED_3_Quality);

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.23
Examples

Creating an Object to Verify and Monitor IED Operation


Objective
Create a program to monitor for deviations between phases on the generator and load sides
of a breaker.

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.

Code Snippet 4.2 prg_MonitorBreakerHighLoadSideComponents


PROGRAM prg_MonitorBreakerHighLoadSideComponents
VAR
(*Function block monitoring generator side of breaker*)
Gen_Monitor : fb_MultiChannelAlert;
(*Function block monitoring bus side of breaker*)
Bus_Monitor : fb_MultiChannelAlert;
(*Generator nominal current*)
GenNominal : REAL;
(*Actual generator output*)
GenOutput : REAL;
(*Set the limit the channels are allowed to deviate by*)
AllowedDeviation : REAL;
(*Criterion to enable the monitoring block*)
Enable_FB : BOOL;
(*Placeholder for a data communications tag*)
PhaseA_X_Terminal : MV; PhaseB_X_Terminal : MV; PhaseC_X_Terminal : MV;
(*Placeholder for a data communications tag*)
PhaseA_Y_Terminal : MV; PhaseB_Y_Terminal : MV; PhaseC_Y_Terminal : MV;
(*Clear the alert condition and restore block to default condition*)
FB_Reset : BOOL;
(*Function block successfully enabled*)
GenFB_Enabled : BOOL; BusFB_Enabled : BOOL;
(*Gen_FB alert information*)
GenAlert : SPS; GenFB_Status : enum_AlertType; GenAlertCause :
enum_ChannelAlert;
GenQualityAlert : BOOL; GenQualityCause : enum_ChannelAlert;
(*Bus_FB alert information*)
BusAlert : SPS; BusFB_Status : enum_AlertType; BusAlertCause :
enum_ChannelAlert;
BusQualityAlert : BOOL; BusQualityCause : enum_ChannelAlert;
(*Detect an alert condition*)
Gen_Alert_Generated : R_TRIG; Bus_Alert_Generated : R_TRIG;
Gen_Status_Message : STRING; Bus_Status_Message : STRING;
Gen_Channel_Message : STRING; Bus_Channel_Message : STRING;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


4.24 ChannelMonitoring
Examples

Code Snippet 4.2 prg_MonitorBreakerHighLoadSideComponents (Continued)


(*If the generator output exceeds 5% of nominal, enable the monitoring
blocks*)
Enable_FB := (GenOutput >= 0.05 * GenNominal);

(*Function block monitoring the X terminal - high side*)


Gen_Monitor(EN := Enable_FB, Channel_1 := PhaseA_X_Terminal,
Channel_2 := PhaseB_X_Terminal, Channel_3 := PhaseC_X_Terminal,
ExcursionThreshold := AllowedDeviation, ChatterCount := 3,
ExcursionTime := T#1M, LatchAlarm := TRUE, Reset := FB_Reset,
ENO => GenFB_Enabled,
Alert => GenAlert, Status => GenFB_Status, ChannelStatus =>
GenAlertCause,
QualityAlert => GenQualityAlert, QualityStatus =>
GenQualityCause);

(*Function block monitoring the Y terminal - load side*)


Bus_Monitor(EN := Enable_FB, Channel_1 := PhaseA_Y_Terminal,
Channel_2 := PhaseB_Y_Terminal, Channel_3 := PhaseC_Y_Terminal,
ExcursionThreshold := AllowedDeviation, ChatterCount := 3,
ExcursionTime := T#1M, LatchAlarm := TRUE, Reset := FB_Reset,
ENO => BusFB_Enabled,
Alert => BusAlert, Status => BusFB_Status, ChannelStatus =>
BusAlertCause,
QualityAlert => BusQualityAlert, QualityStatus =>
BusQualityCause);

//If an alert condition is detected, generate a message for logging


Gen_Alert_Generated(CLK := GenAlert.stVal);
Bus_Alert_Generated(CLK := BusAlert.stVal);

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

Creating an Object to Verify and Monitor


Communications Channels and Hardware Alarms
Objective
Monitor and verify that a communications channel is functioning properly and that no hard-
ware failures are detected for an IED.

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.25
Examples

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.

Code Snippet 4.3 prg_MonitorIED_Components


PROGRAM prg_MonitorIED_Components
VAR
(*Monitor the HALARM Rely Word bit*)
IED_1_HardwareMonitor : fb_IndicatorAlert;
(*Monitor a Mirrored Bits or GOOSE communications channel*)
ProtectionChannelMonitor : fb_IndicatorAlert;
(*Criterion to enable the monitoring block*)
EnableHardwareMonitoring : BOOL;
(*Reset after results are recorded*)
DailyReset : BOOL;
(*Placeholder for a data tag*)
HALARM : BOOL;
Communication_Client_Offline : BOOL;
ProtectionChannelDiagnostic : BOOL;
(*HALARM monitoring status*)
IED_1_HALARM_MonitorEnabled : BOOL;
IED_1_HALRM_Alert : SPS;
IED_1_HALRM_Status : DINT;
(*Protection monitoring status*)
ProtectionChannelMonitor_Enabled : BOOL;
(*Alert status*)
ProtectionChannel_Alert : SPS;
(*Alert condition*)
ProtectionChannel_Status : DINT;
END_VAR

(*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;

(*Configure and monitor the function block parameters*)


IED_1_HardwareMonitor(EN := EnableHardwareMonitoring, Indicator := HALARM,
ChatterCount := 1, ExcursionTime := T#10S,
Reset := DailyReset, ENO => IED_1_HALARM_MonitorEnabled,
Alert => IED_1_HALRM_Alert, Status =>
IED_1_HALRM_Status);

ProtectionChannelMonitor(EN := TRUE, Indicator :=


ProtectionChannelDiagnostic,
ChatterCount := 2, ExcursionTime := T#5S,
Reset := DailyReset,
ENO=>ProtectionChannelMonitor_Enabled,
Alert => ProtectionChannel_Alert,
Status => ProtectionChannel_Status);

Date Code 20190830 Instruction Manual Programming Reference


4.26 ChannelMonitoring
Examples

Creating an Object to Calculate Kilowatt-Hours Delivered


During a Peak Demand Period
Objective
Calculate kilowatt-hours delivered during a period of peak demand.

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

Code Snippet 4.4 prg_KWH_Track


(*This example demonstrates the calculation of Kilowatt-hours over a
period of high demand, given a power measurement in units of Kilowatts.

This program sets the PeriodicProcessing input of the fb_ChannelIntegral


instance to TRUE since the Modbus source will not update the
Channel.t.value time-stamp on its own. The Period input is set to
two seconds which corresponds with the Modbus holding register poll
interval.

Kilowatts integrated over time will produce a result in units of Joules.


Where one Joule = one Watt-Second. To convert Joules to Kilowatt-Hours,
the result must be divided by (3600 seconds/hour * 1000Watts/KiloWatts)
= 3,600,000 Watt-Seconds/Kilowatt-Hour.*)

PROGRAM prg_KWH_Track
VAR
Enable : BOOL;
Aggregator : fb_ChannelIntegral;

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.27
Examples

Joules_to_KWH : REAL := 3600000;


KWH_During_Peak : REAL;
Peak_Start_Time : dateTime_t;
Peak_End_Time : dateTime_t;
QualityAlert : BOOL;
END_VAR

//Determine Enable condition


Enable := NOT SEL_351_1_MODBUS_POU.Offline
AND SEL_351_1_MODBUS.KW3DI.status.q.validity = good;

//Run the Integrator function block


Aggregator( EN := Enable,
Reset := HMI_Controls.Aggregator_Reset.operSet.ctlVal,
Channel := SEL_351_1_MODBUS.KW3DI.status,
SetPoint := HMI_Controls.Demand_Threshold.oper.setMag,
PeriodicProcessing := TRUE,
Period := T#2S, //Set to 2 seconds to match the
//Holding Register poll interval.
LowerBound := 0,
DebounceTime := T#10S);

//Load monitor status variables


HMI_Controls.Monitor_Enabled.stVal := Aggregator.ENO;
HMI_Controls.Monitor_Quality_Alert.stVal := Aggregator.QualityAlert;
HMI_Controls.Peak_Time_Active.stVal := Aggregator.Status = EXPIRATION
OR Aggregator.Status = EXCURSION;
HMI_Controls.Aggregation_Complete := Aggregator.Alert;

//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;

//Update Peak demand on and Peak demand off time-stamps


HMI_Controls.Peak_Start_Time.strVal :=
DT_TO_STRING(Aggregator.ExcursionTimeOn.dateTime);
HMI_Controls.Peak_End_Time.strVal :=
DT_TO_STRING(Aggregator.ExcursionTimeOff.dateTime);

//Force good quality on tags with no other quality source.


HMI_Controls.Peak_End_Time.q.validity := good;
HMI_Controls.Peak_Start_Time.q.validity := good;
HMI_Controls.Aggregator_Reset.status.q.validity := good;
HMI_Controls.Demand_Threshold.status.q.validity := good;
HMI_Controls.Monitor_Enabled.q.validity := good;
HMI_Controls.Monitor_Quality_Alert.q.validity := good;
HMI_Controls.Peak_Time_Active.q.validity := good;

Date Code 20190830 Instruction Manual Programming Reference


4.28 ChannelMonitoring
Examples

Creating an Object to Monitor a Client's Go-Online Time


Delay
Objective
Calculate the time delta between RTAC runtime initiation and the deassertion of a com-
munication client Offline POU pin. Assert an alert if the time delta exceeds a user-settable
threshold.

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.

Code Snippet 4.5 prg_Go_Online_Timer


PROGRAM Go_online_timer
VAR
TimeTracker : fb_IndicatorTimeDelta;
Control : SPS;
OfflineTrack : SPS;
MaxAllowedTime : REAL := 30; //In seconds
TimeToGoOnline : REAL;
GoOnlineTimerAlert : BOOL;
END_VAR

//Set control variable


Control.q.validity := good;
Control.t := SYS_TIME();
Control.stVal := TRUE; //Control should always be true to ensure that the
timer starts
//on the first cycle.

//Load variable to be monitored


OfflineTrack.q.validity := good;
OfflineTrack.stVal := NOT SEL_735_2_SEL_POU.Offline;
OfflineTrack.t := SYS_TIME();

//Run fb_IndicatorTimeDelta function block


TimeTracker(EN := TRUE,
RESET := FALSE,
Indicator1 := Control,
Indicator2 := OfflineTrack,
TimeDiffThreshold := MaxAllowedTime,
WaitTime := T#5M); //If OfflineTrack.stVal hasn't asserted after 5 minutes
//assume something else is wrong and stop the timer.

//If client has gone online, load the outputs


IF NOT SEL_735_2_SEL_POU.Offline THEN
TimeToGoOnline := TimeTracker.TimeDifference;
GoOnlineTimerAlert := TimeTracker.Alert.stVal;
END_IF

Programming Reference Instruction Manual Date Code 20190830


ChannelMonitoring 4.29
Examples

Creating an Object to Monitor the Rate of Remote


Access Failures
Objective
Monitor the number of failed attempts to log-in to the RTAC and assert an HMI alarm if
there have been more than five failed attempts within one minute.

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

Code Snippet 4.6 prg_AuthenticationAlarm


PROGRAM prg_AuthenticationAlarm
VAR
LoginErrorRateTracker : fb_ChannelDerivative;
ErrorAccumulator : MV;
Threshold : REAL := 0.08333; // In units of login
//failures per second. Equals 5 login
//failures divided by 60 seconds.
END_VAR

//Load the input Channel MV


ErrorAccumulator.q.validity := good;
ErrorAccumulator.instMag :=
UDINT_TO_REAL(SystemTags.Number_Of_Logon_Errors.stVal);

//Run the fb_ChannelDerivative block


LoginErrorRateTracker(EN := TRUE,
Reset := HMI_Controls.RemoteAccessTracker_Reset.status.stVal,
Channel := ErrorAccumulator,
DerivativeThreshold := Threshold,
PeriodicProcessing := TRUE,
Period := T#60S,
FilterLength := 1
Alert => HMI_Controls.RemoteAccessAlarm);

//Display alarm details while in alarm state, otherwise, clear alarm


details.
IF LoginErrorRateTracker.Alert.stVal THEN
HMI_Controls.RemoteAccessAlarmDetails :=
SystemTags.Unsuccessful_Log_On_Attempt;
ELSE
HMI_Controls.RemoteAccessAlarmDetails.strVal := '';

Date Code 20190830 Instruction Manual Programming Reference


4.30 ChannelMonitoring
Examples

END_IF

Programming Reference Instruction Manual Date Code 20190830


SECTION 5

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.

Date Code 20190830 Instruction Manual Programming Reference


5.2 CrossTaskData
Function Blocks

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.3 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.

Name IEC 61131 Type Value Description


g_p_N_CrossTaskIDs UDINT 10 The number of mutexes available for
writer function blocks.

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.

Programming Reference Instruction Manual Date Code 20190830


CrossTaskData 5.3
Function Blocks

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.

Date Code 20190830 Instruction Manual Programming Reference


5.4 CrossTaskData
Benchmarks

ä 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

Benchmark Test Descriptions


fb_CrossTaskWrite10
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 10 UDINTs.

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.

Programming Reference Instruction Manual Date Code 20190830


CrossTaskData 5.5
Examples

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
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fb_CrossTaskWrite10 13 8 1
fb_CrossTaskRead10 17 9 1
fb_CrossTaskWrite10000 800 450 4
fb_CrossTaskRead10000 780 450 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.

Moving Data From a High-Priority Task to a Low-Priority


Task
Objective
You have a structure called dt_myAStruct containing data from a high-speed, high-priority
task. You want to copy this data to a slow-speed, low-priority task.

Assumptions
You have declared your IEC 61131 datatype, dt_myAStruct; here we use the declaration
found in Code Snippet 5.1.

Code Snippet 5.1 dt_myAStruct


TYPE dt_myAStruct :
STRUCT
a : UDINT;
b : BOOL;
END_STRUCT
END_TYPE

Date Code 20190830 Instruction Manual Programming Reference


5.6 CrossTaskData
Examples

Solution
Create a writing program on the high-speed task, as shown in Code Snippet 5.2.

Code Snippet 5.2 prg_FastTask


PROGRAM prg_FastTask
VAR
_FastA : dt_myAStruct;
_FastWriter : fb_CrossTaskWrite (ID := 1, sizeOfStruct :=
SIZEOF(dt_myAStruct));
_ErrorA : STRING(80);
END_VAR

// Populate the variable "_FastA" here.


_FastA.a := 20;
_FastA.b := TRUE;
// Send the data to the mutex.
_FastWriter(pt_Struct := ADR(_FastA), Error => _ErrorA);

Create a reading program on the slow-speed task, as shown in Code Snippet 5.3.

Code Snippet 5.3 prg_SlowTask


PROGRAM prg_SlowTask
VAR
_SlowA : dt_myAStruct;
_SlowReader : fb_CrossTaskRead (ID := 1);
_ErrorA : STRING(80);
_TheAvar : UDINT;
_TheBvar : BOOL;
END_VAR

// 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;

Moving Data From a Low-Priority Task to a High-Priority


Task
Objective
You have a structure called dt_myBStruct containing data from a low-speed, low-priority
task. You want to copy these data to a high-speed, high-priority task.

Assumptions
You have declared your IEC 61131 datatype, dt_myBStruct; here we use the declaration
found in Code Snippet 5.4.

Programming Reference Instruction Manual Date Code 20190830


CrossTaskData 5.7
Examples

Code Snippet 5.4 dt_myBStruct


TYPE dt_myBStruct :
STRUCT
a : STRING(32);
b : INT;
c : REAL;
END_STRUCT
END_TYPE

Solution
Create a writing program on the slow-speed task, as seen in Code Snippet 5.5.

Code Snippet 5.5 prg_SlowTask


PROGRAM prg_SlowTask
VAR
_SlowB : dt_myBStruct;
_SlowWriter : fb_CrossTaskWrite(ID := 2, sizeOfStruct :=
SIZEOF(dt_myBStruct));
_ErrorB : String(80);
END_VAR

// Populate the variable "_SlowB" here.


_SlowB.a := 'helloFastTask';
_SlowB.b := -5;
_SlowB.c := 6.25;

// Send the data to the mutex.


_SlowWriter(pt_Struct := ADR(_SlowB), Error => _ErrorB);

Create a reading program on the high-speed task, as seen in Code Snippet 5.6.

Code Snippet 5.6 prg_FastTask


PROGRAM prg_FastTask
VAR
_FastB : dt_myBStruct;
_FastReader : fb_CrossTaskRead(ID := 2);
_ErrorB : STRING(80);
_TheAvar : STRING(32);
_TheBvar : INT;
_TheCvar : REAL;
END_VAR

// First, read in all the data from the mutex to the local variable.
_FastReader(pt_Struct := ADR(_FastB), Error => _ErrorB);

// Now use _SlowB structure information as you wish.


_TheAvar := _FastB.a;
_TheBvar := _FastB.b;
_TheCvar := _FastB.c;

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 6

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 6.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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type class_Object"
myObject := otherObject;

// This is fine
someVariable := myObject.value;
// As is this
pt_myObject := ADR(myObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.

Date Code 20190830 Instruction Manual Programming Reference


6.2 Dictionaries
Structure Definitions

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.1 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.

Name IEC 61131 Type Value Description


g_p_KeyStringLength UINT 80 The maximum string length for a key.

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.

Name IEC 61131 Type Description


Key STRING(g_p_KeyStringLength) A key associated with a value.
Data DATA_VAL Data storage.

Programming Reference Instruction Manual Date Code 20190830


Dictionaries 6.3
Classes

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 6.1).

Figure 6.1 A Binary Search Tree Holding Integer Values

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 6.2).

Figure 6.2 An Unbalanced Binary Search Tree

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 6.3).

Date Code 20190830 Instruction Manual Programming Reference


6.4 Dictionaries
Classes

Figure 6.3 A Balanced Binary Search Tree Node

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).

Name IEC 61131 Type Access Description


Size UDINT R The number of key-value pairs stored in this tree.

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.

Programming Reference Instruction Manual Date Code 20190830


Dictionaries 6.5
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


6.6 Dictionaries
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


Dictionaries 6.7
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


6.8 Dictionaries
Benchmarks

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

Benchmark Test Descriptions


Each of these tests is run on a tree of 1024 entries. The test attempts to make an unbalanced
tree by inserting values in order, forcing the tree to continually rebalance itself. Each of
the following tests is repeated 100 times, and the total average of all samples is recorded.
For example, the test in Insert records the average of the 1024 • 100 insertions.

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.

Programming Reference Instruction Manual Date Code 20190830


Dictionaries 6.9
Benchmarks

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.

Platform (time in µs)


Operation Tested
SEL-3530 SEL-3354 SEL-3555
GetData 14 2 1
Insert 796 59 47
Delete 799 53 42
Clear 779128 51891 42171
Begin 3 1 1
Next 2 1 1

Date Code 20190830 Instruction Manual Programming Reference


6.10 Dictionaries
Examples

Platform (time in µs)


Operation Tested
SEL-3530 SEL-3354 SEL-3555
NextKey 4 1 1
NextValue 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.

Ordered Data Retrieval


A user has data that she needs to present in an ordered fashion. She can define the order she
needs through the keys, update the values as needed, and then present the data, all while
maintaining the same order.

Solution
First the user initializes the full tree. Later, she can iterate across the entire structure to
receive those data in key alphabetical order.

Code Snippet 6.1 prg_SortedLookup


PROGRAM prg_SortedLookup
VAR
MyBinaryLookupTree : class_BinaryTreeDictionary;
CurrentData : struct_KeyValuePair;
Initializing : BOOL := TRUE;
Check : BOOL := TRUE;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


Dictionaries 6.11
Examples

Code Snippet 6.1 prg_SortedLookup (Continued)


IF Initializing THEN
//First put the data into the tree as key value pairs
MyBinaryLookupTree.Insert('Boxes', 1250);
MyBinaryLookupTree.Insert('TapeRolls', 200);
MyBinaryLookupTree.Insert('Pallets', 13);
MyBinaryLookupTree.Insert('BubbleWrap', 75);
Initializing := FALSE;
ELSE
MyBinaryLookupTree.Begin();
WHILE Check DO
Check := MyBinaryLookupTree.Next(entry => CurrentData);
IF CurrentData.data <> 0 THEN
; // Do some meaningful work
END_IF
END_WHILE
END_IF

Creating a Quick Lookup Table


Objective
A user has a collection of data he desires to look up quickly based on unique description
strings. He needs to store it now and use parts of it later based on system state.

Assumptions
This example assumes that there is a user-specified IEC 61131 data type that is defined as
shown in Code Snippet 6.2 and a function using that particular structure as shown in Code
Snippet 6.3.

Code Snippet 6.2 struct_JobDefinition


TYPE struct_JobDefinition:
STRUCT
JobName : STRING(32);
Duration : UDINT;
Input : REAL;
END_STRUCT
END_TYPE

Code Snippet 6.3 fun_DoWork


FUNCTION fun_DoWork : BOOL
VAR_IN_OUT
pt_currentCommand : POINTER TO struct_JobDefinition;
END_VAR

; //Program the work that should be done here

Date Code 20190830 Instruction Manual Programming Reference


6.12 Dictionaries
Examples

Solution
First the user initializes the full tree. Later, based on some request, the required data can
be retrieved.

Code Snippet 6.4 prg_BinaryTree


PROGRAM prg_BinaryTree
VAR
CurrentData : BOOL;
JobSelector : INT;
Initializing : BOOL := TRUE;
Working : BOOL := FALSE;

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

Programming Reference Instruction Manual Date Code 20190830


SECTION 7

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 three 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. 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.

Date Code 20190830 Instruction Manual Programming Reference


7.2 DynamicDisturbanceRecorder
Introduction

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 and COMTRADE. This trigger method monitors the boot-
strapped points for changes in the dateTime_t data structure. A detected 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 because 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. 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 reference, 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
and COMTRADE. This trigger method periodically samples all points at the spec-
ified 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.
ä 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

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.3
Supported Firmware Versions

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.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R144 or higher.
Versions 3.5.2.0 and later can be used on RTAC firmware version R144 and later.
Versions 3.5.0.0 and later can be used on RTAC firmware version R139 and later.
To enable DynamicDisturbanceRecorder library support, the device number of your RTAC
must include the feature in its model option table (MOT). You cannot download projects
that include this library to RTACs that do not support the library. Use the SEL website
MOT configuration (https://selinc.com/products/) to ensure that a particular part number
has DynamicDisturbanceRecorder support enabled.

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.

Enumeration Value Description


TIME_CHANGE 0 When a change is detected in the dateTime_t data structure of
a bootstrapped point, a log is generated.
DATA_CHANGE 1 When a change is detected in the respective data status value of
a bootstrapped point, a log entry generated.

Date Code 20190830 Instruction Manual Programming Reference


7.4 DynamicDisturbanceRecorder
Classes

PERIODIC 2 On a periodic interval, a log entry is generated.


TRIGGER_EVENT 3 When a trigger condition is detected, a log is generated.

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 calcu-
lation.
RefTime timestamp_t Provides a time-stamp reference for log creation; ig-
nored unless DataLogType TIME_CHANGE trig-
ger.
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 DataLogType TIME_-
CHANGE trigger.
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 gen-
erated file name.
MaxFolderSize LINT The maximum size, in bytes, for the specified direc-
tory path.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.5
Classes

MaxFileSize DINT 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 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 DataLogType PERIODIC trigger.
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 of 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 after the trigger event
for which data will be recorded; ignored unless Dat-
aLogType TRIGGER_EVENT trigger. Minimum of
1 post-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.

Date Code 20190830 Instruction Manual Programming Reference


7.6 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.7
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.8 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.9
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.10 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.11
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.12 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.13
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.14 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.15
Classes

ä 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.

Date Code 20190830 Instruction Manual Programming Reference


7.16 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.17
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.18 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.19
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.20 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.21
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.22 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.23
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.24 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.25
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.26 DynamicDisturbanceRecorder
Classes

ä For DataLogType DATA_CHANGE, points are considered changed if the respective


data status value has changed since the previous scan.
ä Scan all data points. If they have changed, then prepare the points for logging.
ä Write one line containing a time value with millisecond precision, time code, station
name, device name, and the data status value.
ä Manage the total size of the directory path folder and the number of files in the
respective data path based on MaxDirectorySize.
ä Start a new file if the active log file exceeds the maximum file size, if NewFilePerDay
is TRUE at the start of a new day, or if project settings change.
ä The logs will be maintained for MaxNumDays if the MaxDirectorySize is not ex-
ceeded.
ä 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.
ä Start a new file if the active log file exceeds the maximum file size, if the project
settings are changed, or at the beginning of a new day if StartNewFilePerDay is
TRUE.
ä 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 EN toggling
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_ComtradeFloat32 (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 COMTRADE record, which is composed of a CFG and DAT file. The log is
then written into the directory specified by DirectoryPath. A subfolder is created that has
the date and time of the record to the millisecond, as well as FilePostFix. The date, time,
and postfix are separated by the “,” character. A new log will start after MaxFileSize is
reached.
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 will store logs for MaxNumDays. If the cumulative number
of logs exceeds MaxFolderSize, the directory manager will delete one day of records until
the cumulative log directory size is less than MaxFolderSize. File names will be in the same
format as the subfolder with either a CFG or DAT extension appended. Two additional
folders may be present in the directory. Do not delete or alter the contents of these folders.
Doing so may cause errors in the logging object.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.27
Classes

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 DataLogType TIME_CHANGE trig-
ger.
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 DataLogType TIME_-
CHANGE trigger.
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 DataLogType PERIODIC trigger.
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.

Date Code 20190830 Instruction Manual Programming Reference


7.28 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.29
Classes

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(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 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.

Date Code 20190830 Instruction Manual Programming Reference


7.30 DynamicDisturbanceRecorder
Classes

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(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 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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.31
Classes

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(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 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.

Date Code 20190830 Instruction Manual Programming Reference


7.32 DynamicDisturbanceRecorder
Classes

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 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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.33
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


7.34 DynamicDisturbanceRecorder
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.35
Benchmarks

ä 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.

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

Date Code 20190830 Instruction Manual Programming Reference


7.36 DynamicDisturbanceRecorder
Benchmarks

Benchmark Test Descriptions


class_TimeAlignedCSVManager Performance tests
ä Time-Aligned CSV TIME_CHANGE trigger: This test instantiates one manager
class, bootstraps it with two data points of each type, and changes the time stamps
of these data points ten times per second. The RTAC has a task cycle time of 10 ms
and the time required for the Run() method is recorded. The average, maximum,
minimum, and standard deviation are recorded here.
ä Time-Aligned CSV PERIODIC trigger: This test instantiates one manager class,
bootstraps it with two data points of each type, and sets the period to 100 ms. The
RTAC has a task cycle time of 10 ms and the time required for the Run() method
is recorded. The average, maximum, minimum, and standard deviation are recorded
here.
ä Time-Aligned CSV TRIGGERED trigger: This test instantiates one manager class,
bootstraps it with two data points of each type, and triggers once per second. The
block is configured to store four pre-trigger cycles and five post-trigger cycles. The
RTAC has a task cycle time of 10 ms and the time required for the Run() method
is recorded. The average, maximum, minimum, and standard deviation are recorded
here.

class_SoeCsv Performance tests


ä Per-Point CSV DATA_CHANGE trigger: This test instantiates one manager class,
bootstraps it with two data points of each type, and changes the data of these points
ten times per second. The RTAC has a task cycle time of 10 ms and the time required
for the Run() method is recorded. The average, maximum, minimum, and standard
deviation are recorded here.

class_Float32COMTRADE Performance tests


ä COMTRADE TIME_CHANGE trigger: This test instantiates one manager class,
bootstraps it with two data points of each type, and changes the time stamps of these
data points ten times per second. The RTAC has a task cycle time of 10 ms and the
time required for the Run() method is recorded. The average, maximum, minimum,
and standard deviation are recorded here. This test waits for the first transition from
temporary data to CFG and DAT files to commence before running.
ä COMTRADE PERIODIC trigger: This test instantiates one manager class, boot-
straps it with two data points of each type, and sets the period to 100 ms. The RTAC
has a task cycle time of 10 ms and the time required for the Run() method is recorded.
The average, maximum, minimum, and standard deviation are recorded here. This
test waits for the first transition from temporary data to CFG and DAT files to com-
mence before running.
ä COMTRADE TRIGGERED trigger: This test instantiates one manager class,
bootstraps it with two data points of each type, and triggers once per second. The
block is configured to store four pre-trigger cycles and five post-trigger cycles. The
RTAC has a task cycle time of 10 ms and the time required for the Run() method
is recorded. The average, maximum, minimum, and standard deviation are recorded
here.

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.37
Examples

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
PERIODIC Average 1032.3 574.5 24.3
Maximum 6433.2 4206.8 398.1
Minimum 88.5 65.5 2.6
Std Deviation 734.2 369.9 35.2
TRIGGERED Average 1564.2 819.3 29.5
Maximum 5968.8 4456.6 341.6
Minimum 1000.0 667.5 21.1
Std Deviation 334.2 243.3 22.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.

Date Code 20190830 Instruction Manual Programming Reference


7.38 DynamicDisturbanceRecorder
Examples

Log Data Cyclically to a Time-Aligned CSV File


Objective
A user wishes to record three data points in a time-aligned CSV file format at a one second
periodic basis and does not want any log to exceed 100 KB. The user wants to maintain the
logs for a maximum of 10 days.

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 7.1. The
sample log output is shown in Code Snippet 7.2.

Code Snippet 7.1 prg_CyclicCsvLogger


PROGRAM prg_CyclicCsvLogger
VAR
//Initialization variable
INIT : BOOL;
//Class initialization
MyCSVCyclic : class_TimeAlignedCsv := (EN := TRUE,
RecordTimeInUtc := FALSE,
TimeVariance := 0,
DataLogType := PERIODIC,
DirectoryPath := 'CSV_Cyclic_1',
FilePostfix := 'SubC.csv',
MaxFolderSize := 500000000,
MaxFileSize := 100000,
MaxNumDays := 10,
LoggingInterval := T#1S);
END_VAR

//Bootstrap the points for logging


IF NOT INIT THEN
MyCSVCyclic.bootstrap_MonitorCMV(channel := 'Point_CMV0',
station := 'PMU10', data := DataRecorderTags.Status_0000);
MyCSVCyclic.bootstrap_MonitorINS(channel := 'Point_INS1',
station := 'PMU10', data := DataRecorderTags.Status_0001);
MyCSVCyclic.bootstrap_MonitorSPS(channel := 'Point_SPS3',
station := 'PMU10', data := DataRecorderTags.Status_0002);

INIT := TRUE;
END_IF

//It is required to call the Run method every scan


MyCSVCyclic.Run();

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.39
Examples

Code Snippet 7.2 Sample of a Time-Aligned Cyclic Log


PMU10:Point_INS1,PMU10:Point_SPS3
2017/03/14 22:14:25.899,3172.46,12.1414,123456,1
2017/03/14 22:14:26.900,9.11965E11,3330840.0,654321,0
2017/03/14 22:14:27.901,3172.46,12.1414,123456,1
2017/03/14 22:14:28.902,9.11965E11,3330840.0,654321,0
2017/03/14 22:14:29.903,3172.46,12.1414,123456,1
2017/03/14 22:14:30.904,9.11965E11,3330840.0,654321,0

Log Data SOE data to a CSV File


Objective
A user wishes to monitor and record any data status changes to four data points in a SOE
CSV file format and does not want any log to exceed 100 KB. The user wants to maintain
the logs for a maximum of 30 days.

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 7.3. The sample
log output is shown in Code Snippet 7.4.

Date Code 20190830 Instruction Manual Programming Reference


7.40 DynamicDisturbanceRecorder
Examples

Code Snippet 7.3 prg_SoeCsvLogger


PROGRAM prg_SoeCsvLogger
VAR
//Initialization variable
INIT : BOOL;
//Class initialization
MySOE : class_SoeCsv := (EN := TRUE,
RecordTimeInUtc := FALSE,
DirectoryPath := 'SOE Events 1',
FilePostfix := 'SubA.csv',
MaxFolderSize := 500000000,
MaxFileSize := 100000,
MaxNumDays := 30,
StartNewFilePerDay := FALSE);
END_VAR

//Bootstrap the points for logging


IF NOT INIT THEN
MySOE.bootstrap_MonitorCMV(channel := 'Point_CMV0', station :=
'Breaker1',
data := DataRecorderTags.Status_0000);
MySOE.bootstrap_MonitorINS(channel := 'Point_INS1', station :=
'Breaker1',
data := DataRecorderTags.Status_0001);
MySOE.bootstrap_MonitorMV(channel := 'Point_MV2', station := 'Breaker1',
data := DataRecorderTags.Status_0003);
MySOE.bootstrap_MonitorSPS(channel := 'Point_SPS3', station :=
'Breaker1',
data := DataRecorderTags.Status_0002);
INIT := TRUE;
END_IF

//It is required to call the Run method every scan


MySOE.Run();

Code Snippet 7.4 Sample of an SOE Log


Date,Time,Time Code,Station,Device,Value
03/15/2017,10:28:49.528,-7.0,Breaker1,Point_CMV0,9.11965E11@3330840.0
03/15/2017,10:28:49.528,-7.0,Breaker1,Point_INS1,654321
03/15/2017,10:28:49.528,-7.0,Breaker1,Point_MV2,2.99882E-38
03/15/2017,10:28:49.528,-7.0,Breaker1,Point_SPS3,0
03/15/2017,10:28:50.529,-7.0,Breaker1,Point_CMV0,3172.46@12.1414
03/15/2017,10:28:50.529,-7.0,Breaker1,Point_INS1,123456
03/15/2017,10:28:50.529,-7.0,Breaker1,Point_MV2,1.07596E33
03/15/2017,10:28:50.529,-7.0,Breaker1,Point_SPS3,1

Programming Reference Instruction Manual Date Code 20190830


DynamicDisturbanceRecorder 7.41
Examples

Log Data to a COMTRADE File


Objective
A user wishes to monitor and record any data updates for two data points, as determined
by the time stamp of the data point, in a COMTRADE file format. The user does not want
any log to exceed 10 MB and wants to maintain the logs for a maximum of 10 days.

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 7.5. The sample log output is shown in Code Snippet 7.6.

Code Snippet 7.5 prgCOMTRADELogger


PROGRAM prg_COMTRADELogger
VAR
//Initialization variable
INIT : BOOL;
//Class initialization
MyCOMTRADETimeChange : class_ComtradeFloat32 := (EN := TRUE,
RecordTimeInUtc := FALSE,
TimeVariance := 0,
DataLogType := TIME_CHANGE,
DirectoryPath := 'CTRADE_Station1',
FilePostfix := 'Bay1',
MaxFolderSize := 500000000,
MaxFileSize := 1000000,
MaxNumDays := 10,
SystemFrequency := 60);
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


7.42 DynamicDisturbanceRecorder
Examples

Code Snippet 7.5 prgCOMTRADELogger (Continued)


//Bootstrap the points for logging
IF NOT INIT THEN
MyCOMTRADETimeChange.bootstrap_MonitorCMV(channel := 'Point_CMV0',
station := 'PMU10', ph := 'A',
Component := 'Breaker1', Unit := 'V', data :=
DataRecorderTags.Status_0000);
MyCOMTRADETimeChange.bootstrap_MonitorSPS(channel := 'Point_SPS39',
station := 'PMU10', ph := 'A',
Component := 'Breaker1', defaultState := FALSE, data :=
DataRecorderTags.Status_0002);
INIT := TRUE;
END_IF

//It is required to call the Run method every scan


MyCOMTRADETimeChange.RUN();

Code Snippet 7.6 Sample of a COMTRADE 2013 CFG File


Bay1,RTAC_Archive,2013
5,4A,1D
1,PMU10:Point_CMV0_m,Am,Breaker1,V,1,0,0,-3.4028235E38,3.4028235E38,1,1,P
2,PMU10:Point_CMV0_a,Aa,Breaker1,V,1,0,0,-3.4028235E38,3.4028235E38,1,1,P
1,PMU10:Point_SPS39,A,Breaker1,0
60
1
1,40
15/03/2017,11:51:37.674722
15/03/2017,11:51:37.674722
float32
1000
-7,-7
F,3

Programming Reference Instruction Manual Date Code 20190830


SECTION 8

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.
See the ACSELERATOR RTAC Library Extensions Instruction Manual (LibraryExtension-
sIM) for an explanation of the concepts used by the object-oriented extensions to the IEC 61131-3
standard.

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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type class_VectorObject"
myVectorObject := otherVectorObject;

// This is fine
someVariable := myVectorObject.value;
// As is this
pt_myVectorObject := ADR(myVectorObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.
ä 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).

Date Code 20190830 Instruction Manual Programming Reference


8.2 DynamicVectors
Enumerations

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
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.

Name IEC 61131 Type Value Description


g_p_DefaultVectorSize UDINT 32 The default number of elements that
a vector can hold.

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.3
Functions

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.

Date Code 20190830 Instruction Manual Programming Reference


8.4 DynamicVectors
Interfaces

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.5
Interfaces

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).

Name IEC 61131 Type Access Description


pt_BaseVector POINTER TO class_BaseVector R Pointer to the class_BaseVec-
tor used internally by this vec-
tor.
pt_Data POINTER TO BYTE R Pointer to the raw memory ar-
ray used internally by this vec-
tor.
ElementSize UDINT R The number of bytes required
for each element in the vector.
MaxSize UDINT R The number of elements this
vector can currently hold be-
fore a reallocation for addi-
tional memory is required.
pt_Self POINTER TO BYTE R The THIS pointer for the class.
Size UDINT R The number of elements in the
vector.

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.

Date Code 20190830 Instruction Manual Programming Reference


8.6 DynamicVectors
Interfaces

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.7
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


8.8 DynamicVectors
Classes

GetCopyOfElement (Method)
This method copies the element at the 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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.9
Classes

ä 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, 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.

Date Code 20190830 Instruction Manual Programming Reference


8.10 DynamicVectors
Classes

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 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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.11
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


8.12 DynamicVectors
Classes

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 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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.13
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


8.14 DynamicVectors
Classes

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.

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 index.

Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.15
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


8.16 DynamicVectors
Classes

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.

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 index.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.17
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


8.18 DynamicVectors
Classes

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.

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

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.19
Classes

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector

GetAt (Method)
Provides a copy of the element at the specified index.

Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.

Outputs
Name IEC 61131 Type Description
element 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.

Date Code 20190830 Instruction Manual Programming Reference


8.20 DynamicVectors
Classes

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.

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.21
Classes

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 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.

Date Code 20190830 Instruction Manual Programming Reference


8.22 DynamicVectors
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.23
Classes

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 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.

Date Code 20190830 Instruction Manual Programming Reference


8.24 DynamicVectors
Classes

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.25
Benchmarks

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.

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

Date Code 20190830 Instruction Manual Programming Reference


8.26 DynamicVectors
Benchmarks

Benchmark Test Descriptions


As benchmarks are designed to provide more information about speed of operation in
known environments, only tests on the five pre-configured vectors are recorded here. Vec-
tors on objects of varying sizes may have varying performance.
All benchmark tests shall be performed 100 times with the average result recorded here.
In an attempt to allow other usage of system memory, only one iteration of each test is run
per scan.

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.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.27
Benchmarks

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
Platform (time in µs)
Operation Tested
SEL-3530 SEL-3354 SEL-3555
Append
Byte 67 9 6
Dword 58 6 3
Lreal 88 10 4
Lword 63 9 4
Pointer 44 5 3
Real 57 5 3
Word 43 5 3
Clear
Byte 41 4 3
Dword 40 4 2
Lreal 40 4 2
Lword 43 4 2
Pointer 39 4 2
Real 39 4 2
Word 37 4 2
GetAt
Byte 17 2 1
Dword 6 2 1
Lreal 7 2 1
Lword 9 1 1
Pointer 6 1 1
Real 8 1 1
Word 6 2 1
New
Byte 73 23 10
Dword 43 6 4
Lreal 40 6 4
Lword 41 6 4
Pointer 37 6 4

Date Code 20190830 Instruction Manual Programming Reference


8.28 DynamicVectors
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3530 SEL-3354 SEL-3555
Real 37 5 4
Word 42 6 4
Pop
Byte 4 1 1
Dword 5 1 1
Lreal 4 1 1
Lword 4 1 1
Pointer 4 1 1
Real 5 1 1
Word 4 1 1
Push1024
Byte 22 4 3
Dword 23 4 3
Lreal 36 5 3
Lword 33 5 3
Pointer 23 4 3
Real 22 4 3
Word 27 4 3
Push32
Byte 32 5 3
Dword 33 5 3
Lreal 33 5 3
Lword 35 5 3
Pointer 31 5 3
Real 30 5 3
Word 31 4 3
Recycle
Byte 2 1 1
Dword 2 1 1
Lreal 3 1 1
Lword 2 1 1
Pointer 2 1 1
Real 2 1 1
Word 2 1 1
ResizeDown
Byte 23 4 3
Dword 23 4 3
Lreal 23 4 3
Lword 21 4 3
Pointer 20 4 3
Real 22 4 3
Word 23 4 3
ResizeUp
Byte 35 5 3
Dword 35 4 3
Lreal 28 4 3

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.29
Examples

Platform (time in µs)


Operation Tested
SEL-3530 SEL-3354 SEL-3555
Lword 24 4 3
Pointer 24 4 3
Real 24 4 3
Word 30 5 3
SetAt
Byte 5 2 1
Dword 6 2 1
Lreal 7 1 1
Lword 5 2 1
Pointer 6 2 1
Real 7 1 1
Word 8 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.

Creating and Using a class_ByteVector


Objective
This example shows how a basic class_ByteVector is instantiated and used. Code Snip-
pet 8.1 shows some simple manipulations of a byte vector. These include appending an
array to the vector, popping bytes off the end of the vector, and checking the size of the
vector.

Date Code 20190830 Instruction Manual Programming Reference


8.30 DynamicVectors
Examples

Solution

Code Snippet 8.1 prg_ByteVector


PROGRAM prg_ByteVector
VAR
// Flag to only run the program once.
initialized : BOOL := FALSE;
// A dynamically sized vector of bytes.
byteVector : DynamicVectors.class_ByteVector();
// A fixed size array of bytes to append to the vector.
appendArray : ARRAY[1..5] OF BYTE := [1, 2, 3, 4, 5];
// A fixed size array of bytes to pop off the vector.
popArray : ARRAY[1..5] OF BYTE;
// The size of the vector after appending.
sizeAfterAppend : UDINT;
// The size of the vector after popping.
sizeAfterPop : UDINT;
// Loop counter.
i : UINT;
END_VAR

Code Snippet 8.1 prg_ByteVector (Continued)


// Only run the program once.
IF NOT initialized THEN
initialized := TRUE;

// Append the array to the empty vector.


byteVector.Append(ADR(appendArray), 5);
// The size after appending five bytes is five.
sizeAfterAppend := byteVector.Size;

// 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

Creating a class_ByteVector with fun_NewByteVector()


Objective
This example shows how a basic class_ByteVector is created when using the factory func-
tion fun_NewTypeVector(). Code Snippet 8.2 shows some simple manipulations of a
byte vector created with a factory. These include appending an array to the vector, popping
bytes off the end of the vector, and checking the size of the vector.

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.31
Examples

Solution

Code Snippet 8.2 prg_ByteVectorFactory


PROGRAM prg_ByteVectorFactory
VAR
// Flag to only run once.
initialized : BOOL := FALSE;
// A pointer to a dynamically sized vector of bytes.
pt_byteVector : POINTER TO DynamicVectors.class_ByteVector();
// A fixed size array of bytes to append to the vector.
appendArray : ARRAY[1..5] OF BYTE := [1, 2, 3, 4, 5];
// A fixed size array of bytes to pop off the vector.
popArray : ARRAY[1..5] OF BYTE;
// The size of the vector after appending.
sizeAfterAppend : UDINT;
// The size of the vector after popping.
sizeAfterPop : UDINT;
// Loop counter.
i : UINT;
END_VAR

Code Snippet 8.2 prg_ByteVectorFactory (Continued)


// Only run the program once.
IF NOT initialized THEN
initialized := TRUE;

(* Create the byte vector with the factory. fun_NewTypeVector creates a


* byte vector and returns a pointer to the new vector. *)
pt_byteVector := fun_NewTypeVector(BYTE_VECTOR);

// Append the array to the empty vector.


pt_byteVector^.Append(ADR(appendArray), 5);
// The size after appending five bytes is five.
sizeAfterAppend := pt_byteVector^.Size;

// 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;
END_IF

Creating and Using a class_BaseVector


Objective
This example shows how a class_BaseVector is instantiated and used. Code Snippet 8.4
shows some simple manipulations of a base vector. These include appending an array to
the vector, popping elements off the end of the vector, and checking the size of the vector.

Date Code 20190830 Instruction Manual Programming Reference


8.32 DynamicVectors
Examples

Assumptions
This example assumes that there is a user-specified IEC 61131 data type defined as shown
in Code Snippet 8.3.

Code Snippet 8.3 struct_UserObject


TYPE struct_UserObject :
STRUCT
name : STRING;
value : INT;
END_STRUCT
END_TYPE

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.33
Examples

Solution

Code Snippet 8.4 prg_BaseVector


PROGRAM prg_BaseVector
VAR
// Flag to only run once.
initialized : BOOL := FALSE;
(* A dynamically sized vector of struct_UserObects. This instantiates a
* vector of elements, where each element requires
* SIZEOF(struct_UserObject) bytes of memory and to reserve memory for
* 32 elements before a memory allocation is required. *)
baseVector : DynamicVectors.class_BaseVector(SIZEOF(struct_UserObject),
32);
// A fixed size array to append to the vector.
appendArray : ARRAY[1..5] OF struct_UserObject := [
(name := 'number 1', value := 1),
(name := 'number 2', value := 2),
(name := 'number 3', value := 3),
(name := 'number 4', value := 4),
(name := 'number 5', value := 5)
];
// A fixed size array to pop off the vector.
popArray : ARRAY[1..5] OF struct_UserObject;
// The size of the vector after appending.
sizeAfterAppend : UDINT;
// The size of the vector after popping.
sizeAfterPop : UDINT;
// Loop counter.
i : UINT;
END_VAR

// Only run the program once.


IF NOT initialized THEN
initialized := TRUE;

// Append the array to the empty vector.


baseVector.Append(ADR(appendArray), 5);
// The size after appending five bytes is five.
sizeAfterAppend := baseVector.Size;

// 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

Date Code 20190830 Instruction Manual Programming Reference


8.34 DynamicVectors
Examples

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 8.5 shows the resizing of a vector to return memory to the system.

Solution

Code Snippet 8.5 prg_VectorResize


PROGRAM prg_VectorResize
VAR
// Flag to only run once.
initialized : BOOL := FALSE;
// A dynamically sized vector of bytes.
byteVector : DynamicVectors.class_ByteVector();
// A fixed size array of bytes to append to the vector.
appendArray : ARRAY[1..5] OF BYTE := [1, 2, 3, 4, 5];
// A fixed size array of bytes to pop off the vector.
popArray : ARRAY[1..5] OF BYTE;
// The size of the vector after appending.
sizeAfterAppend : UDINT;
// The size of the vector after popping.
sizeAfterPop : UDINT;
// The maximum vector size before resizing.
maxSizeBeforeResize : UDINT;
// The maximum vector size after resizing.
maxSizeAfterResize : UDINT;
// Loop counter.
i : UINT;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


DynamicVectors 8.35
Examples

Code Snippet 8.5 prg_VectorResize (Continued)


// Only run the program once.
IF NOT initialized THEN
initialized := TRUE;
// Append the array to the empty vector.
byteVector.Append(ADR(appendArray), 5);
// The size after appending five bytes is five.
sizeAfterAppend := byteVector.Size;
// 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;
// The maximum size before resizing is 32 elements.
maxSizeBeforeResize := byteVector.MaxSize;
// Resize the vector so it can hold 10 bytes before a memory allocation
// is required.
byteVector.Resize(10);
(* The maximum size after resizing is 10 elements. The memory required
* for 22 elements is returned to the system, but if the vector needs
* to store more than 10 elements in the future, it will need to
* allocate additional memory. *)
maxSizeAfterResize := byteVector.MaxSize;
END_IF

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 9

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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type
class_EmailClientObject"
myEmailClientObject := otherEmailClientObject;

// This is fine
someVariable := myEmailClientObject.value;
// As is this
pt_myEmailClientObject := ADR(myEmailClientObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.
ä 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).

Date Code 20190830 Instruction Manual Programming Reference


9.2 Email
Function Blocks

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.6 and older can be used on RTAC firmware version R132 and higher.

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.

fb_SimpleEmailClient (Function Block)


This function block provides a simple triggered interface for sending email to one or two
recipients. It reads all inputs immediately upon receiving a request that data be sent and
ignores any further changes until the next trigger is received.

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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.3
Function Blocks

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.

Date Code 20190830 Instruction Manual Programming Reference


9.4 Email
Classes

fb_SimpleEmailClient2 (Function Block)


This function block provides functionality and behavior that is identical to fb_SimpleEmail-
Client (Function Block) on page 9.2, with the exception that the user may define the out-
going and destination ports of the email client at declaration. These inputs are described
below.

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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.5
Classes

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).

Name IEC 61131 Type Access Description


Busy BOOL R Indication that the class is sending an email.
SentMsg STRING(255) R The first 255 characters of the last message the
class sent to the SMTP server.
ErrorStr STRING(80) R A description of any state that would prevent the
attempt to send an email.

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.

Date Code 20190830 Instruction Manual Programming Reference


9.6 Email
Classes

ä 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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.7
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


9.8 Email
Classes

ä 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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.9
Classes

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.

Date Code 20190830 Instruction Manual Programming Reference


9.10 Email
Classes

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.

NOTE: See the DynamicVectors


Library documentation for more
Inputs details on the I_Vector interface.

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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.11
Classes

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.

NOTE: See the SELString Library


documentation for more details on
class_SELString objects.

Date Code 20190830 Instruction Manual Programming Reference


9.12 Email
Classes

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
email.

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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.13
Classes

ä 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 9.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.

Date Code 20190830 Instruction Manual Programming Reference


9.14 Email
Benchmarks

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

Programming Reference Instruction Manual Date Code 20190830


Email 9.15
Benchmarks

Benchmark Test Descriptions


fb_SimpleEmailClient Average Busy Time
The posted time is the average execution time of 100 calls of the function block body while
the Busy output is high. This benchmark is run with all inputs using maximum length
strings.

fb_SimpleEmailClient Average Longest Scan Busy Time


It takes multiple calls to the function block to send an email and each call while the function
block is busy will take a varying length of time. The posted time is the average time of the
longest call of the function block body while the function block is busy. The average is
taken over 100 emails with all inputs using maximum length strings.

fb_SimpleEmailClient2 Average Busy Time


The posted time is the average execution time of 100 calls of the function block body while
the Busy output is high. This benchmark is run with all inputs using maximum length
strings.

fb_SimpleEmailClient2 Average Longest Scan Busy Time


It takes multiple calls to the function block to send an email and each call while the function
block is busy will take a varying length of time. The posted time is the average time of the
longest call of the function block body while the function block is busy. The average is
taken over 100 emails with all inputs using maximum length strings.

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.

Date Code 20190830 Instruction Manual Programming Reference


9.16 Email
Benchmarks

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.Run() Average Busy Time


The posted time is the average execution time of 100 method calls while the Busy output is
high. The email message contains an 80-character subject with a message body containing
255 characters.

class_EmailClient.Run() Average Busy Time With Event Report


The posted time is the average execution time of 100 method calls while the Busy output is
high. The email message contains an 80-character subject with a message body containing
a large event report.

class_EmailClient.Run() Average Longest Scan Time


It requires multiple calls to the Run() method to send an email and each call while the
class is busy will take a varying length of time. The posted time is the average time of the
longest call of the method while the method is busy. The average is taken over 100 emails
with an 80-character subject and a message body containing 255 characters.

class_EmailClient.Run() Average Longest Scan Time With Event


Report
It requires multiple calls to the Run() method to send an email and each call while the
class is busy will take a varying length of time. The posted time is the average time of the
longest call of the method while the method is busy. The average is taken over 100 emails
with an 80-character subject and a message body containing a large event report.

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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.17
Benchmarks

class_EmailClient.SetBodyBytes() With Event Report


The posted time is the average execution time of 100 method calls when setting the email
body to the contents of a large event report. 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.SetBodySELString With Event Report


The posted time is the average execution time of 100 method calls when setting the email
body to the contents of a large event report. 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.SetBodyVector() With Event Report


The posted time is the average execution time of 100 method calls when setting the email
body to the contents of a large event report. 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.

Date Code 20190830 Instruction Manual Programming Reference


9.18 Email
Benchmarks

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.Run() Average Busy Time


The posted time is the average execution time of 100 method calls while the Busy output is
high. The email message contains an 80-character subject with a message body containing
255 characters.

Programming Reference Instruction Manual Date Code 20190830


Email 9.19
Benchmarks

class_EmailClient2.Run() Average Busy Time With Event Report


The posted time is the average execution time of 100 method calls while the Busy output is
high. The email message contains an 80-character subject with a message body containing
a large event report.

class_EmailClient2.Run() Average Longest Scan Time


It requires multiple calls to the Run() method to send an email and each call while the
class is busy will take a varying length of time. The posted time is the average time of the
longest call of the method while the method is busy. The average is taken over 100 emails
with an 80-character subject and a message body containing 255 characters.

class_EmailClient2.Run() Average Longest Scan Time With Event


Report
It requires multiple calls to the Run() method to send an email and each call while the
class is busy will take a varying length of time. The posted time is the average time of the
longest call of the method while the method is busy. The average is taken over 100 emails
with an 80-character subject and a message body containing a large event report.

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.SetBodyBytes() With Event Report


The posted time is the average execution time of 100 method calls when setting the email
body to the contents of a large event report. 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.

Date Code 20190830 Instruction Manual Programming Reference


9.20 Email
Benchmarks

class_EmailClient2.SetBodySELString With Event Report


The posted time is the average execution time of 100 method calls when setting the email
body to the contents of a large event report. 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.SetBodyVector() With Event Report


The posted time is the average execution time of 100 method calls when setting the email
body to the contents of a large event report. 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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.21
Benchmarks

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
class_EmailClient2.SetBodyBytes() 842 518 55
class_EmailClient2.SetBodyBytes() w/ER 95720 52103 5609
class_EmailClient2.SetBodySELString() 988 537 49
class_EmailClient2.SetBodySELString w/ER 118489 62911 5864

Date Code 20190830 Instruction Manual Programming Reference


9.22 Email
Examples

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
class_EmailClient2.SetBodyString() 890 506 58
class_EmailClient2.SetBodyVector() 854 497 52
class_EmailClient2.SetBodyVector() w/ER 95879 52390 5596
class_EmailClient2.SetSender() 95 59 14
class_EmailClient2.SetSubjectBytes() 48 31 8
class_EmailClient2.SetSubjectSELString() 1306 531 48
class_EmailClient2.SetSubjectString() 68 43 11
class_EmailClient2.SetSubjectVector() 17 10 2

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.

Sending an Alert Email After a Failure


Objective
A user wants to notify correct team members of events occurring in the field.

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 9.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).

Programming Reference Instruction Manual Date Code 20190830


Email 9.23
Examples

Code Snippet 9.1 prg_EmailAlerts


PROGRAM prg_EmailAlerts
VAR
Emailer : fb_SimpleEmailClient( localIPAddr := '0.0.0.0',
mailServerIP := '192.168.176.99');
FromEmail : STRING(254) := 'rtac6@myCompany.com';
FromName : STRING(255) := 'The automation RTAC';
//The number of the on call phone for an SMS message
OncallPhone : STRING(255) := '5095552321@txt.att.net';
DayEmail : STRING(254) := 'day_managers@myCompany.com';
NightEmail : STRING(254) := 'night_managers@myCompany.com';
ManagerEmail : STRING(254);
SubjectLine : STRING(255) := 'Plant on Backup Power';
BodyString : STRING(255);

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);

Forwarding a Text Report From the RTAC


Objective
After the RTAC receives confirmation of the completion of an automated task, a user wants
to receive a notice from the RTAC, including a log file of actions taken.

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.

priate events occur and allow it to return false afterwards.


The user has included FileIo and DynamicVectors in their project.

Date Code 20190830 Instruction Manual Programming Reference


9.24 Email
Examples

Solution
The user can create a class_EmailClient to provide brief notifications as seen in Code Snip-
pet 9.2.
This example sends an email containing the text of the log file to the user and a manager.

Code Snippet 9.2 prg_DailyReport


PROGRAM prg_DailyReport
VAR
Emailer : class_EmailClient( localIPAddr := '0.0.0.0',
mailServerIP := '192.168.176.99');
FromEmail : STRING(254) := 'rtac6@myCompany.com';
FromName : STRING(255) := 'The automation RTAC';
//Email addresses to receive the information.
SecretEmail : STRING(254) := 'TheBoss@myCompany.com';
DeveloperEmail : STRING(254) := 'developerLead@myCompany.com';
SubjectLine : STRING(255) := 'The Numbers for the Day';

Initialized : BOOL := FALSE;


TaskDone : BOOL;
FileRead : BOOL;

FileBuffer : class_ByteVector;
LogFileReader : class_FileReader;
END_VAR

IF NOT Initialized THEN


Emailer.SetSender(FromEmail, FromName);
Emailer.AddRecipient(MAIL_BCC, SecretEmail, 'Head Honcho');
Emailer.AddRecipient(MAIL_TO, DeveloperEmail, '');
Emailer.SetSubjectString(SubjectLine);
Initialized := TRUE;
END_IF
IF TaskDone THEN
LogFileReader.ReadFile('/details.txt');
TaskDone := FALSE;
FileRead := FALSE;
END_IF
IF NOT FileRead AND LogFileReader.BytesInBuffer > 0 THEN
FileBuffer.Recycle();
LogFileReader.AppendToVector(startByte := 0, vector := FileBuffer);
Emailer.SetBodyVector(FileBuffer);
Emailer.Send();
FileRead := TRUE;
END_IF
Emailer.Run();
LogFileReader.Run();

Attaching Raw Data to Send


Objective
A user wishes to directly forward raw data on the RTAC device to various technicians.

Programming Reference Instruction Manual Date Code 20190830


Email 9.25
Examples

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 9.3.
This example sends an email with raw data attachments to various technicians or other field
personnel.

Code Snippet 9.3 prg_AttachData


PROGRAM prg_AttachData
VAR
Alarm : BOOL := FALSE;
Emailer : class_EmailClient( localIPAddr := '0.0.0.0',
mailServerIP := '192.168.176.7');
FromEmail : STRING(254) := 'rtac6@myCompany.com';
FromName : STRING(255) := 'The automation RTAC';
Email : STRING(254) := 'tech_leads@myCompany.com';
AttachmentName : STRING(255) := 'procData.raw';
ProcessControlData : STRING(255) := '01110110101010';
ControlData : class_ByteVector;
SubjectLine : STRING(255) := 'Current Process Control Data';
BodyString : STRING(255) := 'Raw process control data attached.';
Initialized : BOOL := FALSE;
trigger : R_TRIG;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


9.26 Email
Troubleshooting

Code Snippet 9.3 prg_AttachData (Continued)


trigger(clk := Alarm OR Emailer.Busy);
//Send email when an alarm occurs and we have vector data to send.
IF trigger.Q AND (LEN(ProcessControlData) > 0) THEN
//Initializes the email parameters; assumes these do not change.
IF NOT Initialized THEN
Emailer.AddRecipient(MAIL_TO, Email, 'Lead Process Technicians');
Emailer.SetSender(FromEmail,FromName);
Emailer.SetBodyBytes(ADR(BodyString),LEN(BodyString));
Emailer.SetSubjectBytes(ADR(SubjectLine),LEN(SubjectLine));
Initialized := TRUE;
END_IF

// Clear any previous information from the vector


ControlData.Recycle();
// Append the new process information
ControlData.Append(ADR(ProcessControlData),
INT_TO_UDINT(LEN(ProcessControlData)));
// Clear any previous attachments and add the new data.
Emailer.ClearAttachments();
Emailer.AttachVector(ControlData,AttachmentName);

//Initiates the email send operation.


IF NOT Emailer.Busy THEN
Emailer.Send();
END_IF
END_IF

// Call Run() every scan to complete the email.


Emailer.Run();

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.

Programming Reference Instruction Manual Date Code 20190830


Email 9.27
Troubleshooting

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

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 10

FTPSync
Introduction
The FTPSync library allows a user to specify content to be monitored and synced with a
File Transfer Protocol (FTP) server automatically. This library monitors specified folders
and IEDs to detect when files are added or modified and sends those files to the FTP server.

Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type class_FTPSyncObject"
myFTPSyncObject := otherFTPSyncObject;

// This is fine
someVariable := myFTPSyncObject.value;
// As is this
pt_myFTPSyncObject := ADR(myFTPSyncObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.
ä 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).
ä The FTP server must have a user defined for use by the RTAC with read, write, delete,
and append permissions for files in the specified remote folder.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R145-V0 or higher.

Date Code 20190830 Instruction Manual Programming Reference


10.2 FTPSync
Classes

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.

struct_SyncStatus
This structure contains the sync status for a single monitored IED or directory.

Name IEC 61131 Type Description


DirectoryName STRING(255) The directory being monitored.
LastSyncSuccessful BOOL TRUE if the last sync was successful.
LastError STRING The last error encountered for the directory.
LastSyncTime DT The time of the last successful sync.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_EventType
The type of event to monitor for a given IED.

Enumeration Description
CEV SEL Compressed ASCII format event report.
COMTRADE Binary COMTRADE format event report.
MMS_COMTRADE Binary COMTRADE format event report collected via MMS protocol.

Classes
class_FtpSync (Class)
This class monitors directories and collected CEV and COMTRADE events for new or
modified files and sends those files to an FTP server on the specified interval.

Programming Reference Instruction Manual Date Code 20190830


FTPSync 10.3
Classes

Inputs
Name IEC 61131 Type Description
EnableSFTP BOOL If TRUE, the client uses SFTP.
FtpServerAddress STRING(15) IP address of the FTP server. Must be in the
form XXX.XXX.XXX.XXX, where XXX is an in-
teger between 0 and 255.
UserName STRING(32) Username for the FTP server. Must be 1 to 32
characters and contain only alphanumeric char-
acters and underscore.
Password STRING(32) Password for the FTP Server. Must be 1 to 32
characters and may contain all printable ASCII
characters, excluding the single quote, double
quote, and backtick.
RemoteTargetDirectory STRING(100) The target directory where the RTAC repli-
cates the monitored RTAC directory structure
and places files and events. Must be 1 to 100
characters and may contain all printable ASCII
characters, excluding the single quote and dou-
ble quote.
SyncInterval TIME The interval at which monitored directories and
IEDs are checked for updates. The range is 1 to
60 minutes.
SyncTrigger BOOL Triggers a file sync in lieu of waiting for the
sync interval to expire. May be a Boolean vari-
able or Boolean expression, and is not required.
LogRuntimeErrors BOOL If TRUE, the library logs runtime errors in the
RTAC Sequence of Events (SOE) log.
SyncInfoDirectory STRING(100) Local directory for use by this class instance
only. If the directory does not exist, the RTAC
creates it. Do not modify the directory or its
contents. Must be 1 to 100 characters and may
contain all printable ASCII characters between
16#20 (Space) and 16#7E (~), excluding ", ’, :,
<, %, >, ?, \, and |. Cannot contain any file path
manipulation character sequences (//, /./, /../)

Outputs
Name IEC 61131 Type Description
Initialized BOOL This pin asserts when the class finishes initializa-
tion. The sync interval and SyncTrigger are ig-
nored while this pin is deasserted.
FileSyncInProgress BOOL This pin is TRUE while the FTP client is sending
files to the FTP server.
InvalidInputPin STRING Lists an incorrectly configured input pin.
RunTimeErrors STR Lists any runtime errors the FTP client encounters.
NumSyncFolders UINT The number of directories and IEDs being moni-
tored.

Date Code 20190830 Instruction Manual Programming Reference


10.4 FTPSync
Classes

Processing
ä Once Run() has been called, any further changes to the class inputs are ignored.
ä Upon the first call of Run(), the class begins the initialization process, which in-
cludes creating the monitored directory structure on the remote FTP server. If the
server does not allow directory creation, the sync fails. Once initialization has fin-
ished, the Initialized pin asserts.
ä On each sync interval expiration or sync trigger assertion, the RTAC uploads any
new or updated monitored content that has not been synced into the appropriate
remote target directory. For example, events from an IED named SEL_351S_1 on
the RTAC in the directory /EVENTS/CEV/SEL_351S_1 are placed in the directory
<RemoteTargetDirectory>/EVENTS/CEV/SEL_351S_1 on the server.
ä If a monitored directory contains additional subdirectories, these directories are ig-
nored. Only files in the specified directories are monitored.
ä File names beginning with a period are ignored.
ä If the FTP client cannot send a file to the FTP server, it populates the RunTimeErrors
output pin with the error message. The FTP client then attempts to sync any other
directories and IEDs to the server. The client tracks the state of the directory or IED
that could not be fully synced and tries again on the next sync interval.

bootstrap_AddMonitorDirectory (Method)
This method adds a directory to be monitored. This method only adds directories to be
monitored if called prior to the first Run() method call.

Inputs
Name IEC 61131 Type Description
directoryName STRING(100) The directory to be monitored. Must be 1 to 100 char-
acters and may contain all printable ASCII characters
between 16#20 (Space) and 16#7E (~), excluding ", ’, :,
<, %, >, ?, \, and |. Cannot contain any file path manip-
ulation character sequences (//, /./, /../)

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the directory is successfully listed for monitoring.

bootstrap_AddMonitorEvent (Method)
This method adds an IED to monitor for collected events to sync. This method only adds
IEDs to be monitored if called prior to the first Run() method call.

Programming Reference Instruction Manual Date Code 20190830


FTPSync 10.5
Examples

Inputs
Name IEC 61131 Type Description
iedName STRING(100) The IED to be monitored for events.
eventType enum_EventType The collected event format (CEV or COMTRADE).

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the IED is successfully listed for monitoring.

GetSyncStatus (Method)
This method returns the sync status for a given directory or IED.

Inputs
Name IEC 61131 Type Description
statusIndex UINT A number between 1 and NumSyncFolders, corresponding
to a directory or IED being monitored.

Return Value
IEC 61131 Type Description
struct_SyncStatus The current sync status for the indicated directory or IED.

Run (Method)
This method performs directory and IED monitoring. Call this method once each process-
ing cycle after configuration is complete.

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Date Code 20190830 Instruction Manual Programming Reference


10.6 FTPSync
Examples

Syncing Files and Events with class_FtpSync


Objective
You want to sync files in several directories and collected events from several IEDs to an
FTP server.

Assumptions
This example assumes the following:
ä The RTAC project contains an SEL client collecting CEV events called SEL_Client
and a Modbus client collecting COMTRADE events from a GE relay called GE_-
Client.
ä The RTAC has directory Dir1 with file File1.txt in it and directory Dir2 with file
File2.txt in it.
ä An FTP server exists with IP address 192.168.1.10, and the RTAC is networked to
communicate with it.
ä The FTP server has an existing user with username RTACUser and the password
TAIL, with read, write, delete, and append file permissions in the FTPFiles directory.

Solution
A program can be created to run an instance of class_FtpSync to sync the files and events,
as shown in Code Snippet 10.1.

Programming Reference Instruction Manual Date Code 20190830


FTPSync 10.7
Examples

Code Snippet 10.1 prg_FTPSync


PROGRAM prg_FTPSync
VAR
FtpSync : class_FtpSync;
FirstScan : BOOL := TRUE;
END_VAR

IF FirstScan THEN
FtpSync.EnableSFTP := FALSE;
FtpSync.FtpServerAddress := '192.168.1.10';
FtpSync.UserName := 'RTACUser';
FtpSync.Password := 'TAIL';
FtpSync.RemoteTargetDirectory := 'FTPFiles';
FtpSync.SyncInterval := T#5M;
FtpSync.LogRuntimeErrors := TRUE;
FtpSync.SyncInfoDirectory := 'FTPSync_1';

FtpSync.bootstrap_AddMonitorDirectory('/Dir1');
FtpSync.bootstrap_AddMonitorDirectory('/Dir2');
FtpSync.bootstrap_AddMonitorEvent('SEL_Client', enum_EventType.CEV);
FtpSync.bootstrap_AddMonitorEvent('GE_Client', enum_EventType.COMTRADE);

FirstScan := FALSE;
END_IF

FtpSync.Run();

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 11

FileIo
Introduction
The FileIO library includes the internal RTAC sel_file and sel_ftp_client libraries. This
library provides function blocks that simplify asynchronous file management for basic file
read and write operations. It also provides access to the underlying firmware interface
libraries.
Because the classes this library provides manage asynchronous file operations, the user
NOTE: See the ACSELERATOR RTAC
must call the Run() method of instantiated classes on every scan to ensure that all queued Library Extensions Instruction Manual
work is correctly performed and monitored. Each class provides various methods to initiate (LibraryExtensionsIM) for explanation
new read or write operations, collect data, or cause other changes in state. of the concepts used by the
object-oriented extensions to the
IEC 61131-3 standard.

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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type class_FileIOObject"
myFileIOObject := otherFileIOObject;

// This is fine
someVariable := myFileIOObject.value;
// As is this
pt_myFileIOObject := ADR(myFileIOObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.

Date Code 20190830 Instruction Manual Programming Reference


11.2 FileIo
Enumerations

ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
ä All file read operations are done completely into RAM. This means that the reading
of large files that exceed the available RAM will not work as expected.

Supported Firmware Versions


Versions 3.5.4.0 and later of this library must be used with an RTAC device that is running
firmware version R144-V1 firmware or later.
Versions 3.5.3.0 and later of this library must be used with an RTAC device that is running
firmware version R143-V0 firmware or later.
Versions 3.5.2.0 and later of this library must be used on an RTAC device that is running
firmware version R136-V2 or later.
Version 3.5.1.0 of this library must be used on an RTAC device that is running firmware
version R135.
Previous versions of this library can be used on firmware versions R132–R135.
To enable FileIO library support, the device number of your RTAC must include the correct
feature in its model option table (MOT). You cannot download projects that include this
library to RTACs that do not support the library. Use the SEL website MOT configuration
(https://selinc.com/products/) to ensure that a particular part number has FileIO support
enabled.

Global Parameters
The library applies the following values as maximums; they can be modified when the
library is included in a project.

Name IEC 61131 Type Value Description


g_p_FileIo_MaxBufferSize UDINT 1048576 The maximum internal buffer
size allowed for class_Fil-
eReader2 or class_FileWriter.
This value is the maximum
file size you can read in, and
the maximum amount you
can append to a file at one
time. The default value is
10242 • 10.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.3
Enumerations

enum_FtpSendSchedule
Enumeration Description
ON_CLOSE When the previous log file is closed, as part of starting a new log file with the
StartNewLog() method, synchronize the closed log to the FTP server.
ON_UPDATE Send active log file each time an additional log is added.

sel_file.Enum_protocol_id
This enumeration is defined in the underlying sel_file library. It lists the protocols that can
create an event.

Enumeration Value
NO_PROTOCOL_SPECIFIED 0
SEL_CLIENT 1
SEL_SERVER 2
MODBUS_CLIENT 3
MODBUS_SERVER 4
DNP_CLIENT 5
DNP_SERVER 6
SEL_MIRRORED_BITS 7
C37118_CLIENT 8
GOOSE_RX 9
ACCESS_POINT_CLIENT 10
ACCESS_POINT_SERVER 11
GOOSE_TX 12
ETHERCAT 13
DNP_SERVER_FAILOVER 14
IEC61850_CLIENT 15
IEC61850_SERVER 16
NGVL 17
LG8979_CLIENT 18
LG8979_SERVER 19
IEC60870_CLIENT 20
IEC60870_SERVER 21
C37118_SERVER 22
SES92_SERVER 23
PGE2179_CLIENT 24
FLEX_PARSE_CLIENT 25

Date Code 20190830 Instruction Manual Programming Reference


11.4 FileIo
Enumerations

sel_file.Enum_event_type
This enumeration is defined in the underlying sel_file library. This enumeration defines the
types of events the database can store. It is part of the event handle and should be used to
help decide which sel_file.Enum_event_data to use when opening an event.

Enumeration Description
NO_EVENT_TYPE There is no event type associated with this file.
CEV_FILE A plaintext file containing event data.
COMTRADE A zipped folder containing the event data as COMTRADE files.

sel_file.Enum_event_data
This enumeration is defined in the underlying sel_file library. It defines how that library
attempts to open events.

Enumeration Description
RAW_DATA Return the data exactly as it is stored in the database.
CFG_FILE Treat the data as an archive and extract the first file with a .cfg extension.
DAT_FILE Treat the data as an archive and extract the first file with a .dat extension.
HDR_FILE Treat the data as an archive and extract the first file with a .hdr extension.
INF_FILE Treat the data as an archive and extract the first file with a .inf extension.

sel_file.Enum_sel_file_errors
This enumeration is defined in the underlying sel_file library. It defines the status of file and
SOE requests. After a call to a function, variables of this type will display IN_PROGRESS
for a time, after which they will change to some other value. NO_ERROR implies that
the task completed successfully, and SYSTEM_BUSY means that the driver already has
too many jobs queued that it must complete before accepting any more jobs. In this case,
a subsequent request might succeed if one of the queued jobs has been completed. Any
other result should be descriptive of the error encountered.

Enumeration Description
NO_ERROR The request completed successfully.
FILE_NOT_FOUND The requested file was not found in the file system.
INVALID_FILE_NAME The file name provided was invalid.
INVALID_FH The file handle provided was not for an open file.
INVALID_FILTER The filter provided was invalid.
INVALID_TIMESTAMP The time stamp provided was invalid.
FS_OUT_OF_SPACE The file system did not have enough space to perform the action.
DIR_LIST_NOT_INIT The directory iterator has not be initialized.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.5
Structures

SYSTEM_BUSY The system is too busy to process the request.


TOO_MANY_TASKS The system has received requests from more than two tasks.
OPERATION_FAILED There was a system call failure while processing the request.
IN_PROGRESS The system is processing the request.

sel_ftp_client.Enum_sel_ftp_client_errors
This enumeration is defined in the underlying sel_ftp_client library. It defines the status of
FTP requests. After a call to a function, variables of this type will display IN_PROGRESS
for a time, after which they will change to some other value. NO_ERROR implies that
the task completed successfully, and SYSTEM_BUSY means that the driver already has
too many jobs queued that it must complete before accepting any more jobs. In this case,
a subsequent request might succeed if one of the queued jobs has been completed. Any
other result should be descriptive of the error encountered.

Enumeration Description
NO_ERROR The request successfully triggered an FTP attempt.
INIT_FAILED The FTP process is not responding.
INVALID_OPERATION There was a system call failure while processing the request.
INVALID_IP The IP address provided was not in the form XXX.XXX.XXX.XXX,
where XXX is an integer that is ≤ 255.
INVALID_USR_NAME The username provided contained invalid characters.
INVALID_PASSWORD The password provided contained invalid characters.
INVALID_FILE_NAME The file name provided contained invalid characters.
INVALID_MAX_TIME The time provided was less than or equal to 0.
FS_OUT_OF_SPACE The file system did not have enough space to perform the action.
SYSTEM_BUSY The system is too busy to process the request.
OPERATION_TIMEOUT The FTP attempt took longer than the provided time-out.
IN_PROGRESS The system is processing the request.

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.

Date Code 20190830 Instruction Manual Programming Reference


11.6 FileIo
Structures

struct_EventDetails
Name IEC 61131 Type Description
Handle Struct_event_handle The details required to access this event via the
database.
Device STRING(32) The name of the device the event was collected
from.
TimeStamp DT The time stamp of the event as seconds since epoch.
TimeMilliseconds UINT The millisecond at which the event occurred.
FileSize DINT The size of the event in the database in bytes.

sel_file.Struct_event_handle
This struct is defined in the underlying sel_file library. This struct contains all information
required to uniquely identify an event in the database.

Name IEC 61131 Type Description


EventID LINT An identifier of the event.
ProtocolID Enum_protocol_id An identifier of the protocol that gathered the event.
EventType Enum_event_type The type of the event file.

sel_file.Struct_soe_content
This struct is defined in the underlying sel_file library. This struct contains all value fields
returned by an SOE query.

Name IEC 61131 Type Description


DeviceName STRING(255) The name of the device that logged this event on the
RTAC.
TagName STRING(255) The tag that changed prompting this SOE to be logged.
Message STRING(255) The message of this SOE.
Category STRING(255) The category string provided for this SOE.
Priority STRING(255) The priority string provided for this SOE.
TimeStamp DT The time stamp of the event as seconds since epoch.
Millisecond UINT The time at which the event occurred with resolution to
the ms.
DSTOffset INT The daylight-saving time offset that should be applied to
the time stamp.
UTCOffset INT The timezone offset that should be applied to the time
stamp.
AlarmEnabled BOOL This SOE can trigger an alarm.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.7
Structures

sel_file.Struct_soe_content_id
This struct is defined in the underlying sel_file library. This struct contains all value fields
returned by an SOE query.

Name IEC 61131 Type Description


DeviceName STRING(255) The name of the device that logged this event on the
RTAC.
TagName STRING(255) The tag that changed prompting this SOE to be logged.
Message STRING(255) The message of this SOE.
Category STRING(255) The category string provided for this SOE.
Priority STRING(255) The priority string provided for this SOE.
TimeStamp DT The time stamp of the event as seconds since epoch.
Millisecond UINT The time at which the event occurred with resolution to
the ms.
DSTOffset INT The daylight-saving time offset that should be applied to
the time stamp.
UTCOffset INT The timezone offset that should be applied to the time
stamp.
AlarmEnabled BOOL This SOE can trigger an alarm.
RemoteSoe BOOL The SOE was generated by a device other than the local
RTAC.
ID STRING(80) A unique identifier for this SOE.

sel_file.Struct_soe_filter
This struct is defined in the underlying sel_file library. This struct contains all filters pos-
sible to apply to an SOE query. If left empty, no filter will be applied on that field.
The filter string must contain only letters (case-sensitive); numbers; the symbols _, -, and
“ ” (space); and the wildcard characters * and ?. The character * acts as a multicharacter
wildcard and the character ? acts as a single character wildcard when inside any string.

Name IEC 61131 Type Description


DeviceNameFilter STRING(255) The filter to place on the device name.
TagNameFilter STRING(255) The filter to use on the tag name.
MessageFilter STRING(255) The filter to use on the SOE message.
CategoryFilter STRING(255) The filter to use on the SOE category.
PriorityFilter STRING(255) The filter to use on the SOE priority.
ReturnAlarmSoeOnly BOOL Only return SOEs that can trigger an alarm.

Date Code 20190830 Instruction Manual Programming Reference


11.8 FileIo
Functions

Functions
This library provides the following functions, which allow single-operation asynchronous
actions. Each call has a status argument that must persist across multiple scans. Calling any
function does not complete the requested work, but rather queues the work to be performed
over multiple scans. This means you should only call a given function once per desired op-
eration. The system updates the status variable automatically when the operation completes
in either success or failure. Avoid reusing pointers or variables passed as VAR_IN_OUT
until the status variable used has changed from the value of IN_PROGRESS.

fun_FtpDownload
Use this function to download files to the local, sequestered file system from an FTP server.

Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
localPath STRING(255) The local path and file name to which you are writ-
ing. It must begin with “/” and contain the full file path.
It may contain all printable ASCII characters between
16#20(Space) and 16#7E(~) except for ", ', :, <, %, >, ?, \,
and |. It cannot contain any file path manipulation variables
(//, /./, /../).
remotePath STRING(255) The complete path and file name of the file to download
from the FTP server. It must contain only printable charac-
ters (ASCII values 0x32 to 0x7E inclusive), excluding sin-
gle and double quotation characters.
username STRING(32) The username to be used. This must only contain alphanu-
meric characters and “_”.
password STRING(32) The password for use on the FTP server. This may contain
any printable ASCII characters excluding the quote charac-
ters.
timeout UDINT The number of seconds for the FTP attempt to run before it
is canceled. This value must be greater than 0.

Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_ftp_client_errors The active status of this FTP event.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the FTP download request for processing.
ä Validates that the time-out exceeds zero seconds.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.9
Functions

ä Validates that all string characters meet the prescribed requirements.


ä Validates that at least 250 MB of space are available in the file system for the down-
load contents.
ä Attempts to FTP the file onto the RTAC as an asynchronous event.
ä A status of NO_ERROR implies that the FTP command was successfully issued, the
FTP service completed, and the service returned no error code.

fun_FtpEventUpload
Use this function to upload event files from the database to an FTP server.

Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
localEvent Struct_event_handle The event file to upload.
remotePath STRING(255) The complete path and file name of the file to save on
the FTP server. It must contain only printable characters
(ASCII values 0x32 to 0x7E inclusive), excluding single
and double quotation characters.
username STRING(32) The username to be used. This must only contain alphanu-
meric characters and “_”.
password STRING(32) The password for use on the FTP server. This may contain
any printable ASCII characters excluding the quote char-
acters.
timeout UDINT The number of seconds for the FTP attempt to run before
it is canceled. This value must be greater than 0.

Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_ftp_client_errors The active status of this FTP event.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the FTP upload request for processing.
ä Attempts to FTP the file from the RTAC as an asynchronous event.
ä A status of NO_ERROR implies that the FTP command was successfully issued, the
FTP service completed, and the service returned no error code.

Date Code 20190830 Instruction Manual Programming Reference


11.10 FileIo
Functions

fun_FtpUpload
Use this function to upload individual files from the local, sequestered file system to an
FTP server.

Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
localPath STRING(255) The complete local path and file name to upload. It must
begin with “/” and contain the full file path. It may contain
all printable ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot
contain any file path manipulation variables (//, /./, /../).
remotePath STRING(255) The complete path and file name of the file to write on
the FTP server. It must contain only printable characters
(ASCII values 0x32 to 0x7E inclusive), excluding single
and double quotation characters.
username STRING(32) The username to be used. This must only contain alphanu-
meric characters and “_”.
password STRING(32) The password for use on the FTP server. This may contain
any printable ASCII characters excluding the quote charac-
ters.
timeout UDINT The number of seconds for the FTP attempt to run before it
is canceled. This value must be greater than 0.

Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_ftp_client_errors The active status of this FTP event.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the FTP upload request for processing.
ä Attempts to FTP the file from the RTAC as an asynchronous event.
ä A status of NO_ERROR implies that the FTP command was successfully issued, the
FTP service completed, and the service returned no error code.

fun_DeleteFile
Use this function to delete any file or empty folder from the sequestered file system.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.11
Functions

Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path and file name of the file to delete. It may con-
tain all printable ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot contain
any file path manipulation variables (//, /./, /../).

Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_file_errors The variable where the state of the asynchronous task that is
deleting the file will be reported.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the file deletion request for processing.
ä If status later changes to NO_ERROR, the system successfully found and deleted the
file.
ä If status later changes to OPERATION_FAILED, the system failed to either find or
delete the file.
ä If status later changes to anything else, the system stopped the request before the
deletion command was issued.

fun_FileSize
Use this function to request the size of any file in the sequestered file system. If the size of
the file provided exceeds UDINT max (4,294,967,295) bytes, then the value that is returned
will roll over and equal the file size modulo 4,294,967,296.

Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path and file name for the size calculations. It may
contain all printable ASCII characters between 16#20(Space)
and 16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot
contain any file path manipulation variables (//, /./, /../).

Date Code 20190830 Instruction Manual Programming Reference


11.12 FileIo
Functions

Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_file_errors The variable where the state of the asynchronous task that
is obtaining the file size will be reported.
sizeInBytes UDINT After completion, this variable contains the size of the
file in bytes.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the file size request for processing.
ä If status later changes to NO_ERROR, sizeInBytes contains the file size.
ä If status later changes to OPERATION_FAILED, then the system failed to find the
file.
ä If status later changes to anything else, sizeInBytes is undefined.

fun_FilesystemFreeSpace
Use this function to validate how much usable space remains in the file system. FileIO
will not use all the space on the file system, and the value returned by this function reflects
that. When the value this function returns reaches zero, additional writes to the file system
through FileIO will fail.

Inputs/Outputs
Name IEC 61131 Type Description
status Enum_sel_file_errors The variable where the state of the asynchronous task
that is obtaining the file system free space will be re-
ported.
spaceAvailable ULINT After completion, this variable contains the space left
in the file system that the FileIO library can use, in
bytes.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the file system size request for processing.
ä If status later changes to NO_ERROR, spaceAvailable contains the file system free
space.
ä If status later changes to anything else, spaceAvailable is undefined.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.13
Functions

fun_SoeAscending
Use this function to request a limited number of SOEs from the database, beginning with
a specified time and moving toward the future.

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content The array provided must have at least maxSoe-
Count members, or memory corruption will occur.
startTime DT The earliest time to include in the results. This
value must be between the years 2000 and 2037,
or the call will result in an error.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the num-
ber of Struct_soe_content objects that can fit in the
memory space pt_soeBuffer points to, or memory
corruption will occur.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

fun_SoeDescending
Use this function to request a limited number of SOEs from the database, beginning with
a specified time and moving toward the past.

Date Code 20190830 Instruction Manual Programming Reference


11.14 FileIo
Functions

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content The array provided must have at least maxSoe-
Count members, or memory corruption will occur.
startTime DT The latest time to include in the results. This value
must be between the years 2000 and 2037, or the
call will result in an error.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the num-
ber of Struct_soe_content objects that can fit in the
memory space pt_soeBuffer points to, or memory
corruption will occur.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

fun_SoeWindow
Use this function to request a limited number of SOEs from the database, beginning with
a specified time and moving toward the specified, future end time.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.15
Functions

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content The array provided must have at least maxSoe-
Count members, or memory corruption will occur.
startTime DT The earliest time to include in the results. This
value must be between the years 2000 and 2037,
or the call will result in an error.
endTime DT The latest time to include in the results. This value
must be between the years 2000 and 2037, or the
call will result in an error.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the num-
ber of Struct_soe_content objects that can fit in the
memory space pt_soeBuffer points to, or memory
corruption will occur.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

fun_LocalSoeGetID
Use this function to request the data of a single SOE after a provided time stamp. If the
system finds no SOE after the time stamp, it provides the nearest SOE before the time
stamp. If the system finds no SOEs, then status reports an error. Any data returned are for
an SOE the local RTAC generated.

Date Code 20190830 Instruction Manual Programming Reference


11.16 FileIo
Functions

Inputs
Name IEC 61131 Type Description
soeTime DT The time near which to search for an SOE. This value must be
between the years 2000 and 2037, or the call will result in an
error.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable where the state of the asynchronous task that
is obtaining the SOE id will be reported.
soeData Struct_soe_content_id The location that will be populated with the information de-
scribing the returned SOE.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeData contains the pertinent information
for one local SOE.
ä If status later changes to anything else, the contents of soeData are undefined.

fun_LocalSoeAscending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the future. The order of the returned SOEs is the time
of their creation on the RTAC, not the time of the actual event. The local RTAC generated
all returned SOEs.

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE
Struct_soe_content_id data. The array provided must have at least
maxSoeCount members, or memory corruption
will occur.
startID STRING(80) The unique identifier of a local SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_-
soeBuffer. This number must exceed zero to ob-
tain a non-error result and it must not exceed the
number of Struct_soe_content_id objects that
can fit in the memory space pt_soeBuffer points
to, or memory corruption will occur.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.17
Functions

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE after startID. If startID represent an invalid
SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

fun_LocalSoeDescending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the past. The order of the returned SOEs is the time of
their creation on the RTAC, not the time of the actual event. The local RTAC generated all
returned SOEs.

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE
Struct_soe_content_id data. The array provided must have at least
maxSoeCount members, or memory corruption
will occur.
startID STRING(80) The unique identifier of a local SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_-
soeBuffer. This number must exceed zero to ob-
tain a non-error result and it must not exceed the
number of Struct_soe_content_id objects that
can fit in the memory space pt_soeBuffer points
to, or memory corruption will occur.

Date Code 20190830 Instruction Manual Programming Reference


11.18 FileIo
Functions

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE before startID. If startID represent an
invalid SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

fun_RemoteSoeGetID
Use this function to request the data of a single SOE after a provided time stamp. If the
system finds no SOE after the time stamp, it provides the nearest SOE before the time
stamp. If the system finds no SOEs, then status reports an error. Any data returned are an
SOE a device other than the local RTAC generated.

Inputs
Name IEC 61131 Type Description
soeTime DT The time near which to search for an SOE. This value must be
between the years 2000 and 2037, or the call will result in an
error.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable where the state of the asynchronous task that
is obtaining the SOE id will be reported.
soeData Struct_soe_content_id The location that will be populated with the information de-
scribing the returned SOE.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.19
Functions

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä If status later changes to NO_ERROR, soeData contains the pertinent information
for one remote SOE.
ä If status later changes to anything else, the contents of soeData are undefined.

fun_RemoteSoeAscending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the future. The order of the returned SOEs is the time of
their creation on the RTAC, not the time of the actual event. A device other than the local
RTAC generated all SOEs returned.

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content_- The array provided must have at least maxSoeCount
id members, or memory corruption will occur.
startID STRING(80) The unique identifier of a remote SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the number of
Struct_soe_content_id objects that can fit in the mem-
ory space pt_soeBuffer points to, or memory corrup-
tion will occur.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE after startID. If startID represent an invalid
SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.

Date Code 20190830 Instruction Manual Programming Reference


11.20 FileIo
Functions

ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

fun_RemoteSoeDescending
Use this function to request a limited number of SOEs from the database beginning with a
specified SOE and moving toward the past. The order of the returned SOEs is the time of
their creation on the RTAC, not the time of the actual event. A device other than the local
RTAC generated all SOEs returned.

Inputs
Name IEC 61131 Type Description
pt_soeBuffer POINTER TO Pointer to the array to populate with the SOE data.
Struct_soe_content_- The array provided must have at least maxSoeCount
id members, or memory corruption will occur.
startID STRING(80) The unique identifier of a remote SOE.
maxSoeCount UINT The maximum number of SOEs to place in pt_soe-
Buffer. This number must exceed zero to obtain a
non-error result and it must not exceed the number of
Struct_soe_content_id objects that can fit in the mem-
ory space pt_soeBuffer points to, or memory corrup-
tion will occur.

Inputs/Outputs
Name IEC 61131 Type Description
filters Struct_soe_filter The values defining the filter criteria.
status Enum_sel_file_errors The variable that reports the state of the asynchronous task
that is obtaining the SOE list.
soeCount UINT The location to report the number of SOEs placed in pt_-
soeBuffer.

Processing
ä Sets status to IN_PROGRESS.
ä Queues the SOE request for processing.
ä The selection of SOEs begins at the SOE after startID. If startID represent an invalid
SOE, the system returns no SOEs.
ä If status later changes to NO_ERROR, soeCount SOEs were placed at location pt_-
soeBuffer.
ä If status later changes to anything else, values at pt_soeBuffer remain unchanged.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.21
Classes

Classes
This library provides the following classes as extensions of the IEC 61131 function block.

class_DirectoryListing (Class)
This class calls the sel_file.sel_open_dir() function after a new listing is requested
by the call to CreateNewList(). On the task where this class is instantiated, Run() must
be called once on every scan to handle all of the asynchronous file system interactions.
While there are still items to list, Run() will call sel_file.sel_read_dir() once each
scan until the complete directory listing is built.

Outputs
Name IEC 61131 Type Description
InProgress BOOL Stays TRUE while the Run() method constructs the list-
ing. The class ignores any calls to CreateNewList()
while this output is TRUE.
Error BOOL TRUE if the directory listing could not be created.
ErrorDesc STRING(255) The last error encountered is described here.
NewListReady BOOL Once a list has been built, this output is set to TRUE.

CreateNewList (Method)
This is one of the methods that can be called each time a new directory listing is required.
If no filter is given, it will provide a complete listing of the directory.

Inputs
Name IEC 61131 Type Description
directoryName STRING(255) The directory path to get file list from. Path separators
should be the “/” character.
filter STRING(255) If not blank, only those files that contain this substring
will be appended to the list.

Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and destroys any internal lists.
ä Initiates the enumeration of the directory, carried out by the Run() method.

Date Code 20190830 Instruction Manual Programming Reference


11.22 FileIo
Classes

CreateNewerThanList (Method)
This is one of the methods that can be called each time a new directory listing is required.
This method causes a list to be generated that contains all files with a date code equal to or
newer than the value passed in.

Inputs
Name IEC 61131 Type Description
directoryName STRING(255) The directory path to get file list from. Path separators
should be the “/” character.
filter STRING(255) If not blank, only those files that contain this substring
will be appended to the list.
mtimeSec DT Last UTC modification time (DT#yyyy-mm-dd-
00:00:00)

Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and deletes any internal lists.
ä Initiates the enumeration of the directory, carried out by the Run() method.

GetList (Method)
The call to this method must occur after the NewListReady output is TRUE to obtain the
populated class_SELStringList. There can only be one call to this method per created list.

Inputs/Outputs
Name IEC 61131 Type Description
list SELString.class_SELStringList The class_SelStringList to write the directory list-
ing to. See the SELString library for more informa-
tion about the type class_SELStringList.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the class_SELStringList provided was populated success-
fully.

Processing
ä Returns FALSE if NewListReady is not TRUE.
ä Populates list with the prepared list.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.23
Classes

ä Sets the NewListReady class output to FALSE.


ä Destroys the internal list.

Run (Method)
Call this method on every scan. It supervises the asynchronous directory listing.

Processing
ä If a directory listing has been initiated:
â Ensure that the directory is opened, using the sel_file.sel_open_dir()
function.
â Repeatedly call the sel_file.sel_read_dir() and append a class_SEL-
String to list for each file name containing the filter substring, until no more
file names are returned.
ä Once the directory listing is complete, it closes the operation by setting NewListReady
to TRUE and calling sel_file.sel_close_dir().
ä If any error occurs, Error is set to TRUE and ErrorDesc is populated appropriately.

class_EventReportListing (Class)
This class has been completely removed from the library. If it was included in projects,
these projects will now provide compile-time errors. If you want event access, the class_-
EventListing provides access to those files along with non-obfuscated file names, the ability
to filter queries based on several criteria, and the ability to properly open COMTRADE file
collections to view individual files.
Please note that the class_EventListing class does have one limitation that this class did not.
All class_EventListing objects on a single RTAC task (e.g., Main or Automation) share an
internal iterator. It is best practice to only have one class_EventListing per task.

class_EventListing (Class)
This class calls sel_file.sel_begin_event_iterator_filtered() after a new list-
ing request activated by a call to CreateNewList() or CreateNewFilteredList(). On
the task in which this class is instantiated, Run() must be called once on every scan to han-
dle all of the asynchronous file system interactions. While there are still items to list, Run()
calls sel_file.sel_next_event() once each scan until the complete directory listing
is built.
All class_EventListing objects on a single RTAC task (e.g., Main or Automation) share an
internal iterator. It is best practice to only have one class_EventListing per task.

Date Code 20190830 Instruction Manual Programming Reference


11.24 FileIo
Classes

Outputs
Name IEC 61131 Type Description
InProgress BOOL Stays TRUE while the Run() method constructs the list-
ing. The class ignores any calls to CreateNewList()
while this output is TRUE.
Error BOOL TRUE if the directory listing could not be created.
ErrorDesc STRING(255) The last error encountered is described here.
NewListReady BOOL Once a list has been built, this output is set to TRUE.

CreateNewList (Method)
This method may be called each time a new listing of event reports is required. It filters by
device name only.

Inputs/Outputs
Name IEC 61131 Type Description
deviceName STRING(32) If not blank, only events from this device will be listed.

Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and destroys any internal lists.
ä Initiates the enumeration of the directory, carried out by the Run() method.

CreateNewFilteredList (Method)
This method may be called each time a new listing of event reports is required. It filters by
device name, time of creation, the reporting protocol, and the event type.

Inputs/Outputs
Name IEC 61131 Type Description
deviceName STRING(32) If not blank, only events from this device will be listed.

Inputs
Name IEC 61131 Type Description
startTime DT The earliest time stamp of a returned event as seconds since
epoch.
endTime DT The latest time stamp of a returned event as seconds since
epoch.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.25
Classes

protocol Enum_protocol_id The protocol that collected the events.


eventType Enum_event_type The type of the events to be presented.

Processing
ä Clears Error.
ä Sets the NewListReady value to FALSE and destroys any internal lists.
ä Initiates the enumeration of the events, carried out by the Run() method.
ä Values of NO_PROTOCOL_SPECIFIED, NO_EVENT_TYPE, or zero for start-
Time and endTime result in the associated filter not being used.

GetList (Method)
The call to this method must occur after the NewListReady output is TRUE to obtain the
vector of event handles. There can only be one call to this method per created list.

Inputs/Outputs
Name IEC 61131 Type Description
list DynamicVectors.class_BaseVector The vector to write the directory listing to.
This vector must have been initialized with an
element size SIZEOF(struct_EventDetails).

See the DynamicVectors library for more infor-


mation about the type class_BaseVector.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the class_BaseVector provided was populated success-
fully.

Processing
ä Returns FALSE if NewListReady is not TRUE.
ä Populates list with the prepared list.
ä Sets the NewListReady class output to FALSE.
ä Destroys the internal list.

Run (Method)
Call this method on every scan. It supervises the asynchronous event report listing.

Date Code 20190830 Instruction Manual Programming Reference


11.26 FileIo
Classes

Processing
ä If an event listing has been initiated:
â Ensure that the listing is opened by using sel_file.sel_begin_event_-
iterator().
â Repeatedly call sel_file.sel_next_event() and append a struct_Event-
Details to list for each of the returned files that were issued by deviceName, the
system returns no more files.
ä Once the directory listing is complete, it closes the operation by setting NewListReady
to TRUE.
ä If any error occurs, Error is set to TRUE and ErrorDesc is populated appropriately.

class_FileWriter (Class)
This class provides the ability to write files to the sequestered RTAC file system. This class
is instantiated with a specific file name. The return value of each method is based on the
success or failure of queuing the requested action. The final success or failure of each action
is not determined until processing completes after multiple calls to the Run() method,
which you must call every scan to perform whatever file-handling actions are buffered in
its internal queue.
The g_p_FileIo_MaxBufferSize parameter, detailed in Global Parameters on page 27.2,
dictates the maximum amount of data that can be buffered at one time before writing to the
specified file.

Initialization Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path of the file opened in append mode. The character
“/” delimits the folder path. This path must end with the full
file name, including extension. It may contain all printable
ASCII characters between 16#20(Space) and 16#7E(~) except
for ", ', :, <, %, >, ?, \, and |. It cannot contain any file path
manipulation variables (//, /./, /../). If the file does not exist, it
will be created.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.27
Classes

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).

Name IEC 61131 Type Access Description


BytesLeft UDINT R Number of unwritten bytes in the internal buffer.
Filename STRING(255) R/W Write to this property to set the next file to which
data are written. It may contain all printable
ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and
|. It cannot contain any file path manipulation
variables (//, /./, /../).

Writing to this property sets the FileRename


output true. If data are appended to this class
while FileRename is TRUE, subsequent attempts
to set Filename are ignored until FileRename
returns to FALSE.

After modifying Filename, any append method


call queues data for the new file.

Outputs
Name IEC 61131 Type Description
Error BOOL TRUE if the function block cannot write the contents of its
buffer to file.
ErrorDesc STRING(255) The last error encountered will be described here.
FileRename BOOL After the Filename property is set, this pin will remain
TRUE until all pending writes to the previous file name
have been completed.

AppendBytes (Method)
Call this method whenever bytes are to be appended to the write buffer. Every subsequent
call of the Run() method will write as many bytes as possible until nothing remains in the
write buffer.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the item to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, starting with pt_data.

Date Code 20190830 Instruction Manual Programming Reference


11.28 FileIo
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE for successful addition of the data to the output buffer.

Processing
ä Check that numBytes exceeds 0.
ä Check that the memory region specified has read access.
ä If both previous statements are true, copy the contents of the specified region into
the output buffer.
ä If the copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.

AppendSELString (Method)
Call this method to append the content of a class_SELString to the write buffer.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.

Processing
ä Copy the content of the supplied string to the output buffer.
ä If the copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.

AppendString (Method)
Call this method to append the content of a string to the write buffer.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.29
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to append.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.

Processing
ä Copy the content of the supplied string to the output buffer.
ä If copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.

AppendVector (Method)
Call this method to append the content of a vector to the write buffer.

Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the vector was successfully added to the output buffer.

Processing
ä Check that vector passed in is valid and has contents to copy.
ä Copy the content of the dynamic vector into the output buffer.
ä If the copy succeeded, return TRUE.
ä If any error occurs, the method sets Error to TRUE, populates ErrorDesc appropri-
ately, and returns FALSE.

Date Code 20190830 Instruction Manual Programming Reference


11.30 FileIo
Classes

Run (Method)
Call this method on every scan to supervise the asynchronous writing of the internal buffer
to the specified file.

Processing
ä If the file is not open, this method opens it in append mode and stores the file handle
internally.
ä If the file is open and there are data in the internal buffer, this method writes to the
opened file.
ä Monitors the asynchronous write process, clears the buffer of written data, and sub-
tracts number of bytes written from BytesLeft.
ä If any error occurs, this method sets Error to TRUE and fills ErrorDesc appropri-
ately.

class_FileReader2 (Class)
This class provides the ability to read files from the sequestered RTAC file system. Call
the Run() method every scan to perform whatever file-handling actions are buffered in the
internal queue.
The g_p_FileIo_MaxBufferSize parameter, detailed in Global Parameters on page 27.2,
dictates the maximum file size that can be read using this class.

Outputs
Name IEC 61131 Type Description
InProgress BOOL Stays TRUE while the Run() method reads a file. The
class ignores any calls to a read method while this output
is TRUE.
Error BOOL TRUE if the function block cannot read contents of the
file into buffer.
ErrorDesc STRING(255) The last error encountered is described here.
BytesInBuffer UDINT The number of bytes that were read from file. Set to 0
when a read method is called, and populated when read
is complete.

ReadFile (Method)
Call this method to read the content of a file into the internal buffer.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.31
Classes

Inputs
Name IEC 61131 Type Description
filename STRING(255) The full path to the file of interest within the sequestered file
system. The character “/” delimits the folder path. This path
must end with the full file name, including extension. It may
contain all printable ASCII characters between 16#20(Space)
and 16#7E(~) except for ", ', :, <, %, >, ?, \, and |. It cannot
contain any file path manipulation variables (//, /./, /../).

Processing
ä Checks that a read operation is not in progress.
ä Ensures that the first character of filename is “/”. This method prepends the character
if it is missing from the filename provided.
ä Initiates a read operation, which Run() performs.

ReadEventFromDB (Method)
Call this method to read the content of an event from the database into the internal buffer.

Inputs
Name IEC 61131 Type Description
handle Struct_event_handle The details required to request this event from the database.
fileType Enum_event_data The file extension to attempt to extract from this event.

Processing
ä Checks that a read operation is not in progress.
ä Initiates a read operation, which Run() performs.

CopyTo (Method)
Copies the contents of the buffer to a user-accessible location.

Inputs
Name IEC 61131 Type Description
startByte UDINT Indicates the first byte to copy as an offset from the begin-
ning of the internal buffer.
pt_byte POINTER TO BYTE The destination address to where the bytes should be
copied.
numBytes UDINT The maximum number of bytes to write out, starting with
startByte.

Date Code 20190830 Instruction Manual Programming Reference


11.32 FileIo
Classes

Return Value
IEC 61131 Type Description
UDINT Returns the number of bytes copied to the destination address.

Processing
ä Checks that startByte is less than BytesInBuffer and that pt_byte is a valid pointer
with write access. If the initial checks fail, return 0.
ä Copies contents of internal buffer to destination until all remaining bytes in buffer
have been copied or numBytes specified have been copied.
ä Returns the number of bytes copied.

AppendToSELString (Method)
Copies the contents of the internal buffer to a class_SELString.

Inputs
Name IEC 61131 Type Description
startByte UDINT Indicates the first byte to copy as an offset from the beginning
of the internal buffer.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to which the contents of the internal buffer
will be appended. See the SELString library documentation for
information about the class_SELString type.

Return Value
IEC 61131 Type Description
UDINT Returns the number of characters added to the SELString.

Processing
ä Checks that startByte is less than BytesInBuffer. If the initial check fails, returns 0.
ä Beginning with startByte, appends the bytes from the internal buffer to the strSel
supplied, until one of the following occurs:
1. The class_SELString throws an internal error.
2. No bytes remain in the buffer.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.33
Classes

ä Returns the number of characters added to strSel.

CopyToString (Method)
Copies the content of the internal buffer to a string.
NOTE: This method assumes that
the string str is of type STRING(255).
Smaller strings will cause undesired
Inputs behavior.

Name IEC 61131 Type Description


startByte UDINT Indicates the first byte to copy as an offset from the beginning
of the internal buffer.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to which the content of the internal buffer will be
written.

Return Value
IEC 61131 Type Description
UDINT Returns the number of characters added to the string.

Processing
ä Checks that startByte is less than BytesInBuffer. If the initial check fails, returns 0.
ä Copies the bytes from the internal buffer to str until either of the following occurs:
1. Two hundred and fifty-five (255) characters have been copied.
2. No bytes remain in the buffer.
ä Appends a null terminator onto the str.

AppendToVector (Method)
Allows the content of the buffer to be copied to the end of a user-accessible vector.

Inputs
Name IEC 61131 Type Description
startByte UDINT Indicates the first byte to copy as an offset from the beginning
of the internal buffer.
vector I_Vector The vector to which the internal buffer content is appended.
See the DynamicVectors library documentation for informa-
tion about the I_Vector interface.

Date Code 20190830 Instruction Manual Programming Reference


11.34 FileIo
Classes

Return Value
IEC 61131 Type Description
UDINT Returns the number of elements added to the vector.

Processing
ä Checks that startByte is less than BytesInBuffer. If the initial check fails, return 0.
ä Pushes the contents of the buffer into the supplied vector.
ä If the number of bytes specified for the copied output (BytesInBuffer minus startByte)
is not evenly divisible by the vector ElementSize, then pads the last element appended
to vector with trailing zeros.

Run (Method)
Call this method on every scan to supervise the asynchronous reading of the specified file
into the internal buffer.

Processing
ä Waits until the initiation of a file read operation by the ReadFile() or ReadEventReport()
methods.
ä If the file is not open, opens the file in read mode and stores the file handle internally.
ä If the file is open and a read has been signaled by the ReadFile() or ReadEventReport
methods, monitors the asynchronous task until complete.
ä Populates BytesInBuffer upon completion of the read.
ä If any error occurs, this method sets Error TRUE and fills ErrorDesc appropriately.

class_FileReader (Class)
This is a deprecated class that is now an exact copy of class_FileReader2. The ability to
view event files by name only has been removed from the file system. Projects that contain
the ReadEventReport method will now generate compile-time errors. Reading files should
be accomplished using full paths or Struct_event_handle objects.
The g_p_FileIo_MaxBufferSize parameter, detailed in Global Parameters on page 27.2,
dictates the maximum file size that can be read using this class.
If you use this class, consider refactoring to use class_FileReader2.

class_BasicDirectoryManager (Class)
This class manages files within a given directory by removing files based on the size of the
directory, the number of files in the directory, or the maximum number of days to hold a
file since modified.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.35
Classes

This class does not do the following:


ä Directly write any files.
ä Modify any files.
ä Monitor files within a subdirectory.
Before you can use class_BasicDirectoryManager to manage a directory, it must be pro-
vided the folder path to monitor, a maximum size for that directory, and either a maximum
number of files to hold or a maximum number of days for which to hold files.

File Blacklisting
File blacklisting allows for files to be ignored by the class_BasicDirectoryManager. A
blacklisted file cannot be deleted, and it is not counted in the total directory size or number
of files.
A file is blacklisted by having a period (.) as the first character in the file name.
For example, a file named “.somefile.txt” is ignored by class_BasicDirectoryManager,
while a file named “MySpecialFileData.txt” is managed by class_BasicDirectoryManager.

File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If only one file exists, no files are deleted. This allows the
single file to overfill the allotted maximum until the creation of a new file. This means that
if the maximum number of files is set to one, the manager never deletes files based on the
directory size or age of the file.

Outputs
Name IEC 61131 Type Description
Directory STRING(128) The directory being managed.
Error BOOL TRUE if the class encounters any error.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileCount UDINT The maximum number of files this directory stores. A
value of zero indicates that MaxFileCount is ignored.
MaxDaysHeld UDINT The maximum number of days this directory stores files
based on the time stamp. A value of zero indicates that
MaxDaysHeld is ignored.

Date Code 20190830 Instruction Manual Programming Reference


11.36 FileIo
Classes

bootstrap_SetDirectory (Method)
This method is called once, before any other method, to configure the class_BasicDirecto-
ryManager. It provides the values the class uses to determine what directory to watch and
when to delete files.

Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to use and manage. The character “/”
delimits the folder path. It may contain all print-
able ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |.
It cannot contain any file path manipulation vari-
ables (//, /./, /../). If the folder does not exist, the
class will show an error until the directory is cre-
ated by some other mechanism.
maximumFolderSize ULINT The size, in bytes, at which the directory begins
deleting files, starting at the oldest.
maximumNumFiles UDINT The maximum number of files this directory
stores. A value of zero indicates that maximum-
NumFiles is ignored.
maximumNumDays UDINT The maximum number of days this directory
stores files based on the time stamp. A value of
zero indicates that maximumNumDays is ignored.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors occured during bootstrapping.

Run (Method)
Call this method on every scan. It supervises the asynchronous deletion of old files. Dele-
tions occur only if the number of files in the directory, the size of the directory, or the
number of days to hold a file exceeds user-set limits.

Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the directory listing is exhausted:
a. Determine the cutoff file for deletions on the next scan by performing the fol-
lowing steps:
i. Collect a running total of space moving backward in time.
ii. Find the file that causes the space to be exceeded and store its time stamp.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.37
Classes

iii. Find the file that exceeds the file count and store its time stamp.
iv. Set the cutoff time to the newest of the two saved time stamps.
b. Restart the directory iterator.
2. If the directory listing is not exhausted, perform one of the following checks on the
next file:
a. If the file is blacklisted, ignore it.
b. If the file is managed and newer than the cutoff time from the previous directory
scan, leave it alone.
c. If the file is managed and older than the cutoff time from the previous directory
scan, delete it.

class_DirectoryManager (Class)
This class allows for the creation of managed files, over time, in a controlled directory. It
provides protection for the size of the directory, the number of files in the directory, and
the size of those files.
Before you can use this class to manage a directory, you must provide it the folder path
designating to where log files are written, a maximum size for that directory, a maximum
number of files to allow in that directory, and a postfix to add to log files.
This class uses class_FileWriter objects to perform the writing of log files and event logs.
See class_FileWriter (Class) on page 11.26 for more detailed information about the limi-
tations on the maximum size of log files or maximum number of buffered log entries.

File Entries
File entries take exactly the data provided and append this information to the active file.
No additional formatting is performed.

Event Logs
In addition to log files, you may want to create a separate file that records information
corresponding to some event, with custom formatting. These are referred to as “Event
Logs,” and should not be confused with the “Event Records” relays generate, containing
high-resolution waveforms. An event file is simply a custom log file written out to the
managed directory, rotated with the files (as described in File Rotation on page 11.38),
and sent to the same FTP server (if set) for this manager object.
Event Logs are stored with the time stamp of when they were created. The format for these
files is YYYY-MM-DD-HH-MM_eventPostfix, where eventPostfix is defined in the method
call to write the file.
It is important to recognize that, because the file name does not include seconds, two events
recorded within the same minute and defined with the same eventPostfix argument will
cause the contents of the second event to be appended to the end of the first file.

Date Code 20190830 Instruction Manual Programming Reference


11.38 FileIo
Classes

File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If no other files exist except the active file, no files are deleted.
This allows the single active file to overfill the allotted maximum until the creation of a
new file.

Outputs
Name IEC 61131 Type Description
Directory STRING(127) The directory being managed.
ActiveFile STRING(128) The rotating file presently waiting for write requests.
Error BOOL TRUE if the class cannot write the contents of its buffer
to file.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileSize UDINT The size, in bytes, at which this class rotates its auto-
matically generated files.
MaxFileCount UDINT The maximum number of files this directory stores. A
value of zero indicates that MaxFileCount is ignored.

bootstrap_SetDirectory (Method)
This method is called once, before any other method, to configure the class_Directory-
Manager. It provides the values the class uses to determine where to store files, what to
call them, and when to create and delete them.

Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to use and manage. The character “/”
delimits the folder path. It may contain all print-
able ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |.
It cannot contain any file path manipulation vari-
ables (//, /./, /../). If the folder does not exist, it
will be created the first time that a file is written.
Any files in this directory that are not managed
files will be deleted.
filenamePostfix STRING(16) A string that is added to the end of the time-
stamped file name on every file.
maximumFolderSize UDINT The size, in bytes, at which the directory manager
begins deleting files, starting at the oldest.
maximumFileSize UDINT The size, in bytes, at which this class rotates its
automatically generated files.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.39
Classes

maximumNumFiles UDINT The maximum number of files this directory


stores. A value of zero indicates that maximum-
NumFiles is ignored.
rollFileAtDay BOOL Close the working file each day at midnight and
start a new file.

SetFtpServerForArchiving (Method)
Call this method once to specify a remote FTP server to which generated files are sent and
how often the files should be sent.
Every FTP attempt generates a log file to assist with debugging (overwriting the previous
log file if it exists). The file includes success notifications as well as errors the ftp client
encounters (such as a bad username or password). View the following file, found at the
root of the sequestered file system, via a web browser after attempting an FTP file transfer:
ftplog.txt

Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
remotePath STRING(127) The folder on the FTP server to where the local files
are sent.
username STRING(32) The FTP username used to log into the server. This
must contain only alphanumeric or underscore char-
acters.
password STRING(32) The password associated with the FTP username used
to log into the server. This may contain any printable
ASCII characters, excluding the quote characters.
timeout UDINT The number of seconds for the FTP attempt to be run
before it is canceled. Must be greater than 0.
schedule enum_FtpSendSchedule Specify when local files should be sent to the remote
FTP server.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the arguments provided are within range.

Processing
ä Validates the input strings and confirms that a valid IP address is provided.
ä If the inputs provided are valid, sets internal variables so that the Run() method
attempts to send files, and returns TRUE.
ä If the inputs provided are invalid, returns FALSE.

Date Code 20190830 Instruction Manual Programming Reference


11.40 FileIo
Classes

SetFileHeaderBytes (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing header; new files will be started with the first data entry instead.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the header block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.

SetFileHeaderSELString (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A strSel
of Size zero clears any existing header; new files will be started with the first data entry
instead.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the header block.

SetFileHeaderString (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing header; new files will be started with the first data entry instead.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the header block.

SetFileHeaderVector (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A vector
of Size zero clears any existing header; new files will be started with the first data entry
instead.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.41
Classes

Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the header block. See the DynamicVectors
library documentation for information about the I_Vector inter-
face.

SetFileFooterBytes (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing footer.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the footer block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.

SetFileFooterSELString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A strSel of Size
zero clears any existing footer.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the footer block.

SetFileFooterString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing footer.

Date Code 20190830 Instruction Manual Programming Reference


11.42 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the footer block.

SetFileFooterVector (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A vector of Size
clears any existing footer.

Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the new footer block. See the DynamicVec-
tors library documentation for information about the I_Vector
interface.

StartNewFile (Method)
Use this method to close the active file and begin a new one. Unless you call this method,
a new file starts only if the conditions provided in bootstrap_SetDirectory() are met,
(i.e., rollFileAtDay is TRUE and a new day has begun or the active file size exceeded
maximumFileSize).

Processing
ä For an active log file and a non-empty footer string, this method places that string at
the end of the active file.
ä Closes the active file.
ä Creates a new file with the present time stamp.
ä For a non-empty header string, places that string at the top of the new file.

WriteToFileBytes (Method)
Call this method to append a raw byte array to the active file.

Inputs/Outputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.43
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of pt_data was successfully added to the out-
put buffer.

Processing
ä Appends numBytes characters, starting at address pt_data to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteToFileSELString (Method)
Call this method to append an SELString to the active file.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.

Processing
ä Appends the content of selStr to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteToFileString (Method)
Call this method to append a string to the active file.

Date Code 20190830 Instruction Manual Programming Reference


11.44 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to append to the file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.

Processing
ä Appends the value of str to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteToFileVector (Method)
Call this method to append a vector of data to the active file.

Inputs/Outputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of vector was successfully added to the output
buffer.

Processing
ä Appends the content of vector to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.45
Classes

EventLogFromBytes (Method)
Call this method to write a log file with contents defined in a contiguous set of memory.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.

Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromSELString (Method)
Call this method to write a log file with contents defined in a class_SELString.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Date Code 20190830 Instruction Manual Programming Reference


11.46 FileIo
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromString (Method)
Call this method to write a log file with contents defined in a string.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.47
Classes

EventLogFromVector (Method)
Call this method to write a log file with contents defined in an I_Vector.

Inputs
Name IEC 61131 Type Description
vector I_Vector The content of the event file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

Run (Method)
Call this method on every scan. It supervises the asynchronous writing of queued data to
active files and the asynchronous deletion of old files. Deletions occur only if the number
of files in the directory or size of the directory exceed user-set limits.
This method is also responsible for sending local files to a remote FTP server if the user
has configured FTP through a successful call to SetFtpServerForArchiving().

Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.

Date Code 20190830 Instruction Manual Programming Reference


11.48 FileIo
Classes

Subsequent calls to the Run() method perform the following sequence of operations:
1. If the system day of year has changed since the last time Run() was called and the
class is set to start a new file each day, the method starts a new log by calling the
StartNewFile() method.
2. Is this object already in one of the states described in Processing States on page 11.60?
ä Yes: Continues execution of that state.
ä No: Evaluates the job priority list described in Processing Jobs on page 11.59
and executes the next job.
3. Calls Run() on the internal class_FileWriter object that handles the writing of en-
tries.
4. Calls Run() on the internal class_FileWriter object that handles the writing of event
logs.

Processing Jobs
Only one job is performed per call to this method. The jobs are listed below in priority
order:
1. Enters the Send File state if a write operation has been completed since the last
Send File state completed (determined by looking for the falling edge of class_-
FileWriter.BytesLeft <> 0).
2. Enters the Directory Housekeeping state if there is no directory listing or the last
listing was exhausted.
3. Enters the Resend File state if there are unsent files that have not been synchronized
to the remote server .

Processing States
Some of the jobs in Processing Jobs on page 11.59 cause this object to enter a state. The
following describes these states and their exit criteria:
ä Send File: This state exits immediately if a valid FTP server was not provided using
the method SetFtpServerForArchiving().
If the FTP server was set appropriately, the behavior of this state varies depending on
the value of the schedule argument passed in using the SetFtpServerForArchiving()
method call. Enumerations on page 31.2 defines the enumeration for this argument.
â schedule = ON_CLOSE: If this write was initiated by the StartNewFile()
method, the closed file is sent to the FTP server using the sel_ftp_client.ftp_-
upload() function call.
The state is maintained until the file is sent and then successfully read back
using the sel_ftp.ftp_download() function call.
If any error occurs, this method sets Error to TRUE and fills ErrorDesc appro-
priately.
â schedule = ON_UPDATE: The active file is sent to the server using the method
call sel_ftp.ftp_upload().
ä Directory Housekeeping: The following sub-states exist in this state.
â Obtain the size of the active file.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.49
Classes

â If the active file size is greater than maximumFileSize, start a new file.
â If the file list is exhausted:
1. Determine the cutoff file for deletions on the next scan by performing
the following steps:
a. Collect a running total of space moving backward in time.
b. Find the file that causes space to be exceeded and store the time
stamp of that file.
c. Find the file that exceeds the file count moving backward in time
and store its time stamp.
d. Set the cutoff time to the newest of the two saved time stamps.
2. Restart the directory iterator.
â If the directory listing is not exhausted, perform one of the following checks on
the next file:
ã If unmanaged, delete it.
ã If the file is managed and newer than the cutoff time from the previous
directory scan, leave it alone.
ã If the file is managed and older than the cutoff time from the previous
directory scan, delete it.

class_TimeBasedDirectoryManager (Class)
This class allows for the creation of managed files, over time, in a controlled directory. It
provides protection for the size of the directory, the number of files in the directory, and
the size of those files.
Before you can use this class to manage a directory, you must provide it the folder path
designating to where log files are written, a maximum size for that directory, a maximum
number of days for which to hold files, and a postfix to add to log files.
This class uses class_FileWriter objects to perform the writing of log files and event logs.
See class_FileWriter (Class) on page 11.26 for more detailed information about the limi-
tations on the maximum size of log files or maximum number of buffered log entries.

File Entries
File entries take exactly the data provided and append this information to the active file.
No additional formatting is performed.

Event Logs
In addition to log files, you may want to create a separate file that records information
corresponding to some event, with custom formatting. These are referred to as “Event
Logs,” and should not be confused with the “Event Records” relays generate, containing
high-resolution waveforms. An event file is simply a custom log file written out to the
managed directory, rotated with the files (as described in File Rotation on page 11.50),
and sent to the same FTP server (if set) for this manager object.

Date Code 20190830 Instruction Manual Programming Reference


11.50 FileIo
Classes

Event Logs are stored with the time stamp of when they were created. The format for these
files is YYYY-MM-DD-HH-MM_eventPostfix, where eventPostfix is defined in the method
call to write the file.
It is important to recognize that, because the file name does not include seconds, two events
recorded within the same minute and defined with the same eventPostfix argument will
cause the contents of the second event to be appended to the end of the first file.

File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If no other files exist except the active file, no files are deleted.
This allows the single active file to overfill the allotted maximum until the creation of a
new file.

Outputs
Name IEC 61131 Type Description
Directory STRING(127) The directory being managed.
ActiveFile STRING(128) The rotating file presently waiting for write requests.
Error BOOL TRUE if the class cannot write the contents of its buffer
to file.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileSize UDINT The size, in bytes, at which this class rotates its auto-
matically generated files.
MaxDaysHeld UDINT The maximum number of days this directory stores files
based on the time stamp.

bootstrap_SetDirectory (Method)
This method is called once, before any other method, to configure the class. It provides
the values the class uses to determine where to store files, what to call them, and when to
create and delete them.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.51
Classes

Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to use and manage. The character “/”
delimits the folder path. It may contain all print-
able ASCII characters between 16#20(Space) and
16#7E(~) except for ", ', :, <, %, >, ?, \, and |.
It cannot contain any file path manipulation vari-
ables (//, /./, /../). If the folder does not exist, it
will be created the first time that a file is written.
Any files in this directory that are not managed
files will be deleted.
filenamePostfix STRING(16) A string that is added to the end of the time-
stamped file name on every file.
maximumFolderSize UDINT The size, in bytes, at which the directory begins
deleting files, starting at the oldest.
maximumFileSize UDINT The size, in bytes, at which this class rotates its
automatically generated files.
maximumNumDays UDINT The maximum number of days from today this di-
rectory stores files based on the time stamp.
rollFileAtDay BOOL Close the working file each day at midnight and
start a new file.

SetFileHeaderBytes (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing header; new files will be started with the first data entry instead.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the header block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.

SetFileHeaderSELString (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A strSel
of Size zero clears any existing header; new files will be started with the first data entry
instead.

Date Code 20190830 Instruction Manual Programming Reference


11.52 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the header block.

SetFileHeaderString (Method)
This method sets a block of text the class will place at the beginning of every non-event file
it creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing header; new files will be started with the first data entry instead.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the header block.

SetFileHeaderVector (Method)
This method sets a block of text the class will place at the beginning of every non-event
file it creates. If you desire a newline, you must include it in the provided data. A vector
of Size zero clears any existing header; new files will be started with the first data entry
instead.

Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the header block. See the DynamicVectors
library documentation for information about the I_Vector inter-
face.

SetFileFooterBytes (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A numBytes of
zero clears any existing footer.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to use as the footer block, as re-
turned by the ADR() function.
numBytes UDINT The number of bytes to store, beginning with pt_data.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.53
Classes

SetFileFooterSELString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A strSel of Size
zero clears any existing footer.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to use as the footer block.

SetFileFooterString (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A str of LEN
zero clears any existing footer.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to use as the footer block.

SetFileFooterVector (Method)
This method sets a block of text the class will place at the end of every non-event file it
creates. If you desire a newline, you must include it in the provided data. A vector of Size
clears any existing footer.

Inputs
Name IEC 61131 Type Description
vector I_Vector The vector to use as the new footer block. See the DynamicVec-
tors library documentation for information about the I_Vector
interface.

StartNewFile (Method)
Use this method to close the active file and begin a new one. Unless you call this method,
a new file starts only if the conditions provided in bootstrap_SetDirectory() are met,
(i.e., rollFileAtDay is TRUE and a new day has begun or the active file size exceeded
maximumFileSize).

Date Code 20190830 Instruction Manual Programming Reference


11.54 FileIo
Classes

Processing
ä For an active log file and a non-empty footer string, this method places that string at
the end of the active file.
ä Closes the active file.
ä Creates a new file with the present time stamp.
ä For a non-empty header string, places that string at the top of the new file.

WriteToFileBytes (Method)
Call this method to append a raw byte array to the active file.

Inputs/Outputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of pt_data was successfully added to the out-
put buffer.

Processing
ä Appends numBytes characters, starting at address pt_data to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteToFileSELString (Method)
Call this method to append an SELString to the active file.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.55
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.

Processing
ä Appends the content of selStr to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteToFileString (Method)
Call this method to append a string to the active file.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to append to the file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.

Processing
ä Appends the value of str to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteToFileVector (Method)
Call this method to append a vector of data to the active file.

Date Code 20190830 Instruction Manual Programming Reference


11.56 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of vector was successfully added to the output
buffer.

Processing
ä Appends the content of vector to the output buffer.
ä Does not append a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

EventLogFromBytes (Method)
Call this method to write a log file with contents defined in a contiguous set of memory.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, starting with pt_data.

Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.57
Classes

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromSELString (Method)
Call this method to write a log file with contents defined in a class_SELString.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromString (Method)
Call this method to write a log file with contents defined in a string.

Date Code 20190830 Instruction Manual Programming Reference


11.58 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromVector (Method)
Call this method to write a log file with contents defined in an I_Vector.

Inputs
Name IEC 61131 Type Description
vector I_Vector The content of the event file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.59
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

Run (Method)
Call this method on every scan. It supervises the asynchronous writing of queued data to
active files and the asynchronous deletion of old files. Deletions occur only if the number
of files in the directory or size of the directory exceed user-set limits.
This method is also responsible for sending local files to a remote FTP server if the user
has configured FTP through a successful call to SetFtpServerForArchiving().

Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the system day of year has changed since the last time Run() was called and the
class is set to start a new file each day, the method starts a new log by calling the
StartNewFile() method.
2. Is this object already in one of the states described in Processing States on page 11.60?
ä Yes: Continues execution of that state.
ä No: Evaluates the job priority list described in Processing Jobs on page 11.59
and executes the next job.
3. Calls Run() on the internal class_FileWriter object that handles the writing of en-
tries.
4. Calls Run() on the internal class_FileWriter object that handles the writing of event
logs.

Processing Jobs
Only one job is performed per call to this method. The jobs are listed below in priority
order:

Date Code 20190830 Instruction Manual Programming Reference


11.60 FileIo
Classes

1. Enters the Send File state if a write operation has been completed since the last
Send File state completed (determined by looking for the falling edge of class_-
FileWriter.BytesLeft <> 0).
2. Enters the Directory Housekeeping state if there is no directory listing or the last
listing was exhausted.
3. Enters the Resend File state if there are unsent files that have not been synchronized
to the remote server .

Processing States
Some of the jobs in Processing Jobs on page 11.59 cause this object to enter a state. The
following describes these states and their exit criteria:
ä Send File: This state exits immediately if a valid FTP server was not provided using
the method SetFtpServerForArchiving().
If the FTP server was set appropriately, the behavior of this state varies depending on
the value of the schedule argument passed in using the SetFtpServerForArchiving()
method call. Enumerations on page 31.2 defines the enumeration for this argument.
â schedule = ON_CLOSE: If this write was initiated by the StartNewFile()
method, the closed file is sent to the FTP server using the sel_ftp_client.ftp_-
upload() function call.
The state is maintained until the file is sent and then successfully read back
using the sel_ftp.ftp_download() function call.
If any error occurs, this method sets Error to TRUE and fills ErrorDesc appro-
priately.
â schedule = ON_UPDATE: The active file is sent to the server using the method
call sel_ftp.ftp_upload().
ä Directory Housekeeping: The following sub-states exist in this state.
â Obtain the size of the active file.
â If the active file size is greater than maximumFileSize, start a new file.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.61
Classes

â If the file list is exhausted:


1. Determine the cutoff file for deletions on the next scan by performing
the following steps:
a. Collect a running total of space moving backward in time.
b. Find the file that causes space to be exceeded and store the time
stamp of that file.
c. Calculate and save the time stamp that exceeds the maxNum-
Days value.
d. Set the cutoff time to the newest of the two saved time stamps.
2. Restart the directory iterator.
â If the directory listing is not exhausted, perform one of the following checks on
the next file:
ã If unmanaged, delete it.
ã If the file is managed and newer than the cutoff time from the previous
directory scan, leave it alone.
ã If the file is managed and older than the cutoff time from the previous
directory scan, delete it.

class_LogDirectoryManager (Class)
This class allows for the creation of managed files, over time, in a controlled directory. It
provides protection for the size of the directory, the number of files in the directory, and
the size of those files.
Before you can use this class to manage a directory, you must provide it the folder path
designating to where log files are written, a maximum size for that directory, a maximum
number of files to allow in that directory, and a postfix to add to log files.
This class uses class_FileWriter objects to perform the writing of log files and event logs.
See class_FileWriter (Class) on page 11.26 for more detailed information about the limi-
tations on the maximum size of log files or maximum number of buffered log entries.

Log Entries
Log entries are prefixed with a time stamp and added as a single-row entry to the active log
file.
The log file names are stored with the time stamp of when they were created. The format for
these files is YYYY-MM-DD-HH-MM_logPostfix, where logPostfix is set in the declaration
of the class.

Date Code 20190830 Instruction Manual Programming Reference


11.62 FileIo
Classes

Event Logs
In addition to log files, you may want to create a separate file that records information
corresponding to some event, with custom formatting. These are referred to as “Event
Logs,” and should not be confused with the “Event Records” relays generate, containing
high-resolution waveforms. An event file is simply a custom log file written out to the
managed directory, rotated with the log files (as described in File Rotation on page 11.62),
and sent to the same FTP server (if set) for this manager object.
Event Logs are stored with the time stamp of when they were created. The format for these
files is YYYY-MM-DD-HH-MM_eventPostfix, where eventPostfix is defined in the method
call to write the file.
It is important to recognize that, because the file name does not include seconds, two events
recorded within the same minute and defined with the same eventPostfix argument will
cause the contents of the second event to be appended to the end of the first file.

File Rotation
Periodically, the class compares the new directory size against the maximum permitted
directory size set in the object declaration. If the directory exceeds the maximum folder
size, the oldest file is deleted. If no other files exist except the active log file, no files are
deleted. This allows the single active log file to overfill the allotted maximum until the
creation of a new log file.

Initialization Inputs
Name IEC 61131 Type Description
folderName STRING(127) The folder to write logs to and manage. The
character “/” delimits the folder path. It may
contain all printable ASCII characters between
16#20(Space) and 16#7E(~) except for ", ', :, <,
%, >, ?, \, and |. It cannot contain any file path
manipulation variables (//, /./, /../). If the folder
does not exist, it will be created the first time
that a log is written. Any files in this directory
that are not log files will be deleted.
logPostfix STRING(16) A string that is added to the end of the time-
stamped file name on every log file.
maxFolderSize UDINT The size, in bytes, at which the directory begins
deleting files, starting at the oldest.
maxNumFiles UDINT The maximum number of files this directory
stores. A value of zero indicates that maxNum-
Files is ignored.
autoStartNewLogDaily BOOL If this is TRUE, a new log file is automatically
created on the first PLC scan of every day, re-
gardless of whether an entry is written that day.
If FALSE, a new log file will only be created at
the first log entry method call.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.63
Classes

Outputs
Name IEC 61131 Type Description
Directory STRING(127) The directory being managed.
ActiveFile STRING(128) The rotating file presently waiting for write requests.
Error BOOL TRUE if the class cannot write the contents of its buffer
to file.
ErrorDesc STRING(255) The last error encountered by this class.
SpaceUsed ULINT The size, in bytes, of all managed files in this directory.
MaxFolderSize ULINT The size, in bytes, at which the directory begins deleting
files, starting at the oldest.
MaxFileSize UDINT The size, in bytes, at which this class rotates its auto-
matically generated files.
MaxFileCount UDINT The maximum number of files this directory stores. A
value of zero indicates that MaxFileCount is ignored.

SetFtpServerForArchiving (Method)
Call this method once to specify a remote FTP server to which generated files are sent and
how often the files should be sent.
Every FTP attempt generates a log file to assist with debugging (overwriting the previous
log file if it exists). The file includes success notifications as well as errors the ftp client
encounters (such as a bad username or password). View the following file, found at the
root of the sequestered file system, via a web browser after attempting an FTP file transfer:
ftplog.txt

Inputs
Name IEC 61131 Type Description
ftpServer STRING(15) The IP address of the FTP server being contacted.
remotePath STRING(127) The folder on the FTP server to where the local files
are sent.
username STRING(32) The FTP username used to log into the server. This
must contain only alphanumeric or underscore char-
acters.
password STRING(32) The password associated with the FTP username used
to log into the server. This may contain any printable
ASCII characters, excluding the quote characters.
timeout UDINT The number of seconds for the FTP attempt to be run
before it is canceled. Must be greater than 0.
schedule enum_FtpSendSchedule Specify when local files should be sent to the remote
FTP server.

Date Code 20190830 Instruction Manual Programming Reference


11.64 FileIo
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the arguments provided are within range.

Processing
ä Validates the input strings and confirms that a valid IP address is provided.
ä If the inputs provided are valid, sets internal variables so that the Run() method
attempts to send files, and returns TRUE.
ä If the inputs provided are invalid, returns FALSE.

StartNewLog (Method)
Call this method to create a new log file. All new log entries are added to this file until this
method is called again or the system day of year changes. Do not call this method if you
desire exactly one log file per day.

Processing
ä If there was an active log file, adds a log entry with the text: --End log file--
ä Updates internal retained variable storing the active log time via the SYS_TIME()
function call.
ä Adds a log to this new file with the text: --Begin log file--

WriteLogEntryBytes (Method)
Call this method to append a raw byte array to the active log file.

Inputs/Outputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, beginning with pt_data.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of pt_data was successfully added to the out-
put buffer.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.65
Classes

Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends numBytes characters starting at address pt_data to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteLogEntrySELString (Method)
Call this method to append an SELString to the active log file.

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The class_SELString to append.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of strSel was successfully added to the output
buffer.

Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends the content of selStr to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteLogEntryString (Method)
Call this method to append a string to the active log file.

Date Code 20190830 Instruction Manual Programming Reference


11.66 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The string to add to the log.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of str was successfully added to the output
buffer.

Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.
ä Appends the value of str to the output buffer.
ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

WriteLogEntryVector (Method)
Call this method to append a vector of data to the active log file.

Inputs/Outputs
Name IEC 61131 Type Description
vector I_Vector The vector to append to the file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the content of vector was successfully added to the output
buffer.

Processing
ä Gets the current date from SYS_TIME().
ä Writes the time stamp of the log entry to the output buffer in the form YYYY-MM-
DD-HH-MM-SS.MiS, where MiS is milliseconds.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.67
Classes

ä Appends the content of vector to the output buffer.


ä Appends a newline to the output buffer.
ä If any error occurs, sets Error TRUE and populates ErrorDesc appropriately.

EventLogFromBytes (Method)
Call this method to write a log file with contents defined in a contiguous set of memory.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The address of the bytes to write to file, as returned by the
ADR() function.
numBytes UDINT The number of bytes to write, starting with pt_data.

Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromSELString (Method)
Call this method to write a log file with contents defined in a class_SELString.

Date Code 20190830 Instruction Manual Programming Reference


11.68 FileIo
Classes

Inputs/Outputs
Name IEC 61131 Type Description
strSel class_SELString The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromString (Method)
Call this method to write a log file with contents defined in a string.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(255) The content of the event file.
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.69
Classes

ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

EventLogFromVector (Method)
Call this method to write a log file with contents defined in an I_Vector.

Inputs
Name IEC 61131 Type Description
vector I_Vector The content of the event file. See the DynamicVectors library
documentation for information about the I_Vector interface.

Inputs/Outputs
Name IEC 61131 Type Description
eventPostfix STRING(16) A string that is added to the end of the time-stamped file
name of an event log file.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the data are successfully added to the output buffer.

Processing
ä Obtains the system time through the SYS_TIME() function call.
ä Constructs the new file name from the time and eventPostfix.
ä Sets the internal class_FileWriter object that handles event logs to use the new file
name.
ä Passes the provided data to the internal class_FileWriter that handles event logs.
ä If any error occurs, sets Error to TRUE, populates ErrorDesc appropriately, and
returns FALSE.

Date Code 20190830 Instruction Manual Programming Reference


11.70 FileIo
Classes

Run (Method)
Call this method on every scan. It supervises the asynchronous writing of queued data to
active files and the asynchronous deletion of old files. Deletions occur only if the number
of files in the directory or size of the directory exceed user-set limits.
This method is also responsible for sending local files to a remote FTP server if the user
has configured FTP through a successful call to SetFtpServerForArchiving().

Processing
This class maintains an internal state machine with a round-robin job scheduler, ensuring
that the amount of processing overhead per scan remains relatively constant.
Subsequent calls to the Run() method perform the following sequence of operations:
1. If the system day of year has changed since the last time Run() was called, the
method starts a new log by calling the StartNewLog() method.
2. Is this object already in one of the states described in Processing States on page 11.70?
ä Yes: Continues execution of that state.
ä No: Evaluates the job priority list described in Processing Jobs on page 11.70
and executes the next job.
3. Calls Run() on the internal class_FileWriter object that handles the writing of en-
tries.
4. Calls Run() on the internal class_FileWriter object that handles the writing of event
logs.

Processing Jobs
Only one job is performed per call to this method. The jobs are listed below in priority
order:
1. Enters the Send File state if a write operation has been completed since the last
Send File state completed (determined by looking for the falling edge of class_-
FileWriter.BytesLeft <> 0).
2. Enters the Directory Housekeeping state if there is no directory listing or the last
listing was exhausted.
3. Enters the Resend File state if there are unsent files that have not been synchronized
to the remote server .

Processing States
Some of the jobs in Processing Jobs on page 11.70 cause this object to enter a state. The
following describes these states and their exit criteria:
ä Send File: This state exits immediately if a valid FTP server was not provided using
the method SetFtpServerForArchiving().
If the FTP server was set appropriately, the behavior of this state varies depending on
the value of the schedule argument passed in using the SetFtpServerForArchiving()
method call. Enumerations on page 31.2 defines the enumeration for this argument.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.71
Benchmarks

â schedule = ON_CLOSE: If this write was initiated by the StartNewLog()


method, the closed file is sent to the FTP server using the sel_ftp_client.ftp_-
upload() function call.
The state is maintained until the file is sent and then successfully read back
using the sel_ftp.ftp_download() function call.
If any error occurs, this method sets Error to TRUE and fills ErrorDesc appro-
priately.
â schedule = ON_UPDATE: The active file is sent to the server using the method
call sel_ftp.ftp_upload().
ä Directory Housekeeping: The following sub-states exist in this state.
â Obtain the size of the active file.
â If the active file size is greater than 1/3 of the maxFolderSize, start a new file.
â If the file list is exhausted:
1. Determine the cutoff file for deletions on the next scan by performing
the following steps:
a. Collect a running total of space moving backward in time.
b. Find the file that causes space to be exceeded and store the time
stamp of that file.
c. Find the file that exceeds the file count moving backward in time
and store its time stamp.
d. Set the cutoff time to the newest of the two saved time stamps.
2. Restart the directory iterator.
â If the directory listing is not exhausted, perform one of the following checks on
the next file:
ã If unmanaged, delete it.
ã If the file is managed and newer than the cutoff time from the previous
directory scan, leave it alone.
ã If the file is managed and older than the cutoff time from the previous
directory scan, delete it.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R136-V0 firmware
ä SEL-3530
â R136-V0 firmware
ä SEL-3555

Date Code 20190830 Instruction Manual Programming Reference


11.72 FileIo
Benchmarks

â Dual-core Intel i7-3555LE processor


â 4 GB ECC RAM
â R136-V0 firmware

Benchmark Test Descriptions


It is important to note that all computation in the sel_file and sel_ftp_client libraries is
performed at a lower priority than any logic processing functionality. The time required to
perform a given action is proportional to the RTAC processing burden. The only values this
document records are the times for queuing that lower-priority work. The system performs
the lower-priority work asynchronously, so the Run() method of each class must be called
or the status variable passed to the functions must be monitored on every scan to supervise
the asynchronous operations.
Calculation of each time is the average of 100 iterations of the described computation.

class_DirectoryListing
CreateNewList
The time necessary to request a new list when provided a 255-character path.

GetList
The time necessary to copy a list containing 10 file names.

Run
The time necessary to call Run() on each scan when there is directory work pending.

Idle
The time necessary to call Run() on each scan when there is no directory work pending.

class_EventListing
CreateNewList
The time necessary to request a new list when provided a 255-character path.

GetList
The time necessary to copy a list containing 10 file names.

Run
The time necessary to call Run() on each scan when there is directory work pending.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.73
Benchmarks

Run (Idle)
The time necessary to call Run() on each scan when there is no directory work pending.

class_FileWriter
AppendBytes
The time necessary to request 255 bytes be written via AppendBytes().

AppendVector
The time necessary to request 255 bytes be written via AppendVector().

AppendString
The time necessary to request 255 bytes be written via AppendString().

AppendSELString
The time necessary to request 255 bytes be written via AppendSELString().

Run
The time necessary to call Run() on the scan it switches from idle to work pending. This
tests how long it takes to request a copy of 255 characters when switching from idle state.

Run (Idle)
The time necessary to call Run() on each scan when there is no work pending.

class_FileReader2
ReadFile
The time necessary to request that a file with a 255-byte-long file name be opened via
ReadFile().

CopyTo
The time necessary to copy 255 bytes from the internal buffer via CopyTo().

AppendToVector
The time necessary to append 255 bytes from the internal buffer by using AppendToVector().

CopyToString
The time necessary to copy 255 bytes from the internal buffer via CopyToString().

Date Code 20190830 Instruction Manual Programming Reference


11.74 FileIo
Benchmarks

AppendToSELString
The time necessary to append 255 bytes from the internal buffer by using AppendToSELString().

Run
The time necessary to call Run() on a class_FileReader2 on the scan it switches from work
pending to idle. This tests how long it takes to request a copy of 255 characters into the
internal buffer when switching to idle state.

Run (Idle)
The time necessary to call Run() on a class_FileReader each scan when there is no work
pending.

class_LogDirectoryManager
StartNewLog
The time necessary to call StartNewLog().

WriteLogEntryBytes
The time necessary to call WriteLogEntryBytes() with 255 bytes of input.

WriteLogEntryVector
The time necessary to call WriteLogEntryVector() with 255 bytes of content.

WriteLogEntryString
The time necessary to call WriteLogEntryString() with 255 characters of content.

WriteLogEntrySELString
The time necessary to call WriteLogEntrySELString() with 255 characters of content.

EventLogFromBytes
The time necessary to call EventLogFromBytes() with 255 bytes of input.

EventLogFromVector
The time necessary to call EventLogFromVector() with 255 bytes of input.

EventLogFromString
The time necessary to call EventLogFromString() with 255 bytes of input.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.75
Benchmarks

EventLogFromSELString
The time necessary to call EventLogFromSELString() with 255 bytes of input.

Run
The time necessary to call Run() with FTP configured.

class_DirectoryManager
StartNewFile
The time necessary to call StartNewLog().

WriteLogEntryBytes
The time necessary to call WriteLogEntryBytes() with 255 bytes of input.

WriteLogEntryVector
The time necessary to call WriteLogEntryVector() with 255 bytes of content.

WriteLogEntryString
The time necessary to call WriteLogEntryString() with 255 characters of content.

WriteLogEntrySELString
The time necessary to call WriteLogEntrySELString() with 255 characters of content.

EventLogFromBytes
The time necessary to call EventLogFromBytes() with 255 bytes of input.

EventLogFromVector
The time necessary to call EventLogFromVector() with 255 bytes of input.

EventLogFromString
The time necessary to call EventLogFromString() with 255 bytes of input.

EventLogFromSELString
The time necessary to call EventLogFromSELString() with 255 bytes of input.

Run
The time necessary to call Run() with FTP configured.

Date Code 20190830 Instruction Manual Programming Reference


11.76 FileIo
Benchmarks

class_TimeBasedDirectoryManager
StartNewFile
The time necessary to call StartNewLog().

WriteLogEntryBytes
The time necessary to call WriteLogEntryBytes() with 255 bytes of input.

WriteLogEntryVector
The time necessary to call WriteLogEntryVector() with 255 bytes of content.

WriteLogEntryString
The time necessary to call WriteLogEntryString() with 255 characters of content.

WriteLogEntrySELString
The time necessary to call WriteLogEntrySELString() with 255 characters of content.

EventLogFromBytes
The time necessary to call EventLogFromBytes() with 255 bytes of input.

EventLogFromVector
The time necessary to call EventLogFromVector() with 255 bytes of input.

EventLogFromString
The time necessary to call EventLogFromString() with 255 bytes of input.

EventLogFromSELString
The time necessary to call EventLogFromSELString() with 255 bytes of input.

Run
The time necessary to call Run() with FTP configured.

fun_FtpDownload
The time necessary to request a file download when provided a 255-character path.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.77
Benchmarks

fun_FtpEventUpload
The time necessary to request an event upload when provided a 255-character path.

fun_FtpUpload
The time necessary to request a file upload when provided a 255-character path.

fun_DeleteFile
The time necessary to request a file delete when provided a 255-character path.

fun_FileSize
The time necessary to request a file size when provided a 255-character path.

fun_FilesystemFreeSpace
The time necessary to request the available free space on the system.

fun_SoeAscending
The time necessary to request a list of 10 SOE reports without a filter.

fun_SoeDescending
The time necessary to request a list of 10 SOE reports without a filter.

fun_SoeWindow
The time necessary to request a list of 10 SOE reports without a filter.

fun_LocalSoeGetID
The time necessary to request a list of 10 SOE reports without a filter.

fun_LocalSoeAscending
The time necessary to request a list of 10 SOE reports without a filter.

Date Code 20190830 Instruction Manual Programming Reference


11.78 FileIo
Benchmarks

fun_LocalSoeDescending
The time necessary to request a list of 10 SOE reports without a filter.

fun_RemoteSoeGetID
The time necessary to request a list of 10 SOE reports without a filter.

fun_RemoteSoeAscending
The time necessary to request a list of 10 SOE reports without a filter.

fun_RemoteSoeDescending
The time necessary to request a list of 10 SOE reports without a filter.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
class_DirectoryListing.CreateNewList 327 202 11
class_DirectoryListing.GetList 72 45 4
class_DirectoryListing.Run 137 42 3
class_DirectoryListing.Run (Idle) 5 4 1
class_EventListing.CreateNewList 6 4 1
class_EventListing.GetNewList 353 218 73
class_EventListing.Run 18 12 2
class_EventListing.Run (Idle) 2 1 1
class_FileWriter.AppendBytes 27 20 2
class_FileWriter.AppendVector 37 17 1
class_FileWriter.AppendString 43 26 2
class_FileWriter.SELString 1170 678 53
class_FileWriter.Run 62 50 5
class_FileWriter.Run (Idle) 5 4 1
class_FileReader2.ReadFile 25 14 1
class_FileReader2.CopyTo 38 19 1
class_FileReader2.AppendToVector 824 459 19
class_FileReader2.AppendToString 13 6 1
class_FileReader2.AppendToSELString 460 287 17
class_FileReader2.Run 4 2 1
class_FileReader2.Run (Idle) 3 1 1
class_LogDirectoryManager.StartNewLog 552 285 13
class_LogDirectoryManager.WriteLogEntryBytes 113 127 4
class_LogDirectoryManager.WriteLogEntryVector 159 100 4
class_LogDirectoryManager.WriteLogEntryString 143 71 5

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.79
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
class_LogDirectoryManager.WriteLogEntrySELString 1934 1030 45
class_LogDirectoryManager.EventLogFromBytes 145 91 4
class_LogDirectoryManager.EventLogFromVector 149 68 3
class_LogDirectoryManager.EventLogFromString 172 116 4
class_LogDirectoryManager.EventLogFromSELString 1927 1024 44
class_LogDirectoryManager.Run 624 368 14
class_DirectoryManager.StartNewFile 237 104 5
class_DirectoryManager.WriteLogEntryBytes 92 27 1
class_DirectoryManager.WriteLogEntryVector 41 15 1
class_DirectoryManager.WriteLogEntryString 46 30 2
class_DirectoryManager.WriteLogEntrySELString 1770 952 44
class_DirectoryManager.EventLogFromBytes 286 135 4
class_DirectoryManager.EventLogFromVector 220 85 4
class_DirectoryManager.EventLogFromString 158 80 4
class_DirectoryManager.EventLogFromSELString 1966 1020 43
class_DirectoryManager.Run 574 309 14
class_TimeBasedDirectoryManager.StartNewFile 256 95 5
class_TimeBasedDirectoryManager.WriteLogEntryBytes 79 27 1
class_TimeBasedDirectoryManager.WriteLogEntryVector 46 17 1
class_TimeBasedDirectoryManager.WriteLogEntryString 47 21 2
class_TimeBasedDirectoryManager.WriteLogEntrySELString 1769 969 45
class_TimeBasedDirectoryManager.EventLogFromBytes 282 116 4
class_TimeBasedDirectoryManager.EventLogFromVector 236 84 3
class_TimeBasedDirectoryManager.EventLogFromString 165 82 4
class_TimeBasedDirectoryManager.EventLogFromSELString 198 1016 45
class_TimeBasedDirectoryManager.Run 592 348 16
fun_FtpDownload 112 76 4
fun_FtpEventUpload 75 45 5
fun_FtpUpload 88 88 5
fun_DeleteFile 73 50 4
fun_FileSize 93 53 5
fun_FilesystemFreeSpace 75 41 4
fun_SoeAscending 106 64 5
fun_SoeDescending 106 63 4
fun_SoeWindow 118 62 4
fun_LocalSoeGetID 122 60 5
fun_LocalSoeAscending 108 64 4
fun_LocalSoeDescending 118 65 4
fun_RemoteSoeGetID 113 61 4
fun_RemoteSoeAscending 116 65 5
fun_RemoteSoeDescending 106 63 4

Date Code 20190830 Instruction Manual Programming Reference


11.80 FileIo
Examples

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.

Writing From Changing String


Objective
You want to append the contents of a string to a file every time the value of that string
changes.

Assumptions
This example assumes that a user-specified IEC 61131 function called fun_StringDifferent
provides functionality similar to that in Code Snippet 11.1.

Code Snippet 11.1 fun_StringsDifferent


(* Compares str1 to str2. If they are identical until the null terminator
is encountered in both strings, then return FALSE. *)
FUNCTION fun_StringsDifferent : BOOL
VAR CONSTANT
c_maxStringSize : UDINT := 255;
END_VAR
VAR_IN_OUT
str1 : STRING(c_maxStringSize); // The first string to compare
str2 : STRING(c_maxStringSize); // The second string to compare
END_VAR
VAR
i : UDINT;
differenceFound : BOOL := FALSE;
END_VAR

FOR i := 0 TO c_maxStringSize - 1 DO
IF (0 = str1[i]) AND (0 = str2[i]) THEN
// Found null terminator on both strings at the same time.
EXIT;
ELSIF str1[i] <> str2[i] THEN
differenceFound := TRUE;
EXIT;
END_IF
END_FOR
(* Return True if difference found *)
fun_StringsDifferent := differenceFound;

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.81
Examples

Solution
Because we assume that a simple string comparison function exists, we can write out the
contents of a string to a file every time it changes by using just a few lines of code, as in
Code Snippet 11.2.

Code Snippet 11.2 prg_WriteStringOnChange


PROGRAM prg_WriteStringOnChange
VAR
TheStringToWrite : STRING(255) := '';
TheStringLastWritten : STRING(255) := '';
FileWriter : class_FileWriter('/OutputFolder/OutputFile.txt');
END_VAR

Code Snippet 11.2 prg_WriteStringOnChange (Continued)


IF fun_StringsDifferent(TheStringToWrite, TheStringLastWritten) THEN
FileWriter.AppendString(TheStringToWrite);
TheStringLastWritten := TheStringToWrite;
END_IF
FileWriter.Run(); // Run this every scan regardless.

Reading File Contents Into Byte Array


Objective
You want to read the contents of a file into a byte array.

Assumptions
The file “/FileToRead.txt” exists in the root of the RTAC public file system.

Solution
The file is read into an internal buffer and then copied into an empty user-supplied byte
array using the program in Code Snippet 11.3.

Date Code 20190830 Instruction Manual Programming Reference


11.82 FileIo
Examples

Code Snippet 11.3 prg_ReadToByteArray


PROGRAM prg_ReadToByteArray
VAR CONSTANT
c_ByteArraySize : UDINT := 10_000;
END_VAR
VAR
TheByteArray : ARRAY[1..c_ByteArraySize] OF BYTE;
Filename : STRING(255) := '/FileToRead.txt';
FileReader : class_FileReader2;
FirstScan : BOOL := TRUE;
Copied : BOOL := FALSE;
END_VAR

IF FirstScan THEN
//Initiate the File Read.
FileReader.ReadFile(Filename);
FirstScan := FALSE;
ELSIF 0 < FileReader.BytesInBuffer AND NOT Copied THEN
FileReader.CopyTo(startByte := 0,
pt_byte := ADR(TheByteArray),
numBytes := c_ByteArraySize);
Copied := TRUE;
END_IF
FileReader.Run(); // Run this every scan regardless.

Reading File Contents Into Dynamic Byte Vector


Objective
You want to read the contents of a file into a Dynamic Byte Vector.

Assumptions
1. You have included the DynamicVectors library in your project.
NOTE: See the DynamicVectors
2. The file “/FileToRead.txt” exists in the root of the RTAC public file system. library documentation for more
information about DynamicVectors.
See the ACSELERATOR RTAC Library
Extensions Instruction Manual
Solution (LibraryExtensionsIM) for explanation
about the concepts used by the
object-oriented extensions to the
The file will first be read into an internal buffer and then copied into an empty user-supplied IEC 61131-3 standard.
class_ByteVector using the program in Code Snippet 11.4.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.83
Examples

Code Snippet 11.4 prg_ReadToByteVector


PROGRAM prg_ReadToByteVector
VAR
TheByteVector : DynamicVectors.class_ByteVector;
Filename : STRING(255) := '/FileToRead.txt';
FileReader : class_FileReader2;
FirstScan : BOOL := TRUE;
Copied : BOOL := FALSE;
END_VAR

IF FirstScan THEN
//Initiate the File Read.
FileReader.ReadFile(Filename);
FirstScan := FALSE;
ELSIF 0 < FileReader.BytesInBuffer AND NOT Copied THEN
FileReader.AppendToVector(startByte := 0, vector := TheByteVector);
Copied := TRUE;
END_IF
FileReader.Run(); // Run this every scan regardless.

Reading File Contents Into Array of Strings


Objective
You want to read the contents of a file into an array of strings.

Assumptions
The file “/FileToRead.txt” exists in the root of the RTAC File Manager.

Solution
The file will first be read into an internal buffer and then it will be copied into an empty
user-supplied strings using the program in Code Snippet 11.5.

Date Code 20190830 Instruction Manual Programming Reference


11.84 FileIo
Examples

Code Snippet 11.5 prg_ReadToArrayOfStrings


PROGRAM prg_ReadToArrayOfStrings
VAR CONSTANT
c_NumStringsInArray : UDINT := 1_000;
c_StringSize : UDINT := 255;
END_VAR
VAR
TheStringArray : ARRAY[1..c_NumStringsInArray] OF STRING(c_StringSize);
Filename : STRING(255) := '/FileToRead.txt';
FileReader : class_FileReader2;
FirstScan : BOOL := TRUE;
Copied : BOOL := FALSE;
stringIter : UDINT;
bufferTracker : UDINT := 0;
END_VAR

IF FirstScan THEN
//Initiate the File Read.
FileReader.ReadFile(Filename);
FirstScan := FALSE;
ELSIF 0 < FileReader.BytesInBuffer AND NOT Copied THEN
FOR stringIter := 1 TO c_NumStringsInArray DO
IF bufferTracker <= FileReader.BytesInBuffer THEN
FileReader.CopyToString(startByte := bufferTracker,
str := TheStringArray[stringIter]);
ELSE
// All of the file contents has been copied into strings.
EXIT;
END_IF
bufferTracker := bufferTracker + c_StringSize;
END_FOR
Copied := TRUE;
END_IF
FileReader.Run(); // Run this every scan regardless.

Reading Event Reports Retrieved From Relays


Objective
You have set up the RTAC to automatically collect and buffer event records, and want to
read the contents of these records.

Assumptions
1. You have included the SELString and DynamicVectors libraries in your project.
NOTE: See the SELString library
2. The RTAC database contains events collected from the desired relays. documentation for more information
about class_SELStrings and
class_SELStringLists.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.85
Examples

Solution
You can locate qualifying files using a class_EventListing. Then you can select one as in
Code Snippet 11.6.

Code Snippet 11.6 prg_ReadEventReportFromRelay


PROGRAM prg_ReadEventReportFromRelay
VAR
EventReportListing : class_EventListing;
EventReportList : class_BaseVector(SIZEOF(struct_EventDetails), 32);
FileReader : class_FileReader2;
FileContents : class_ByteVector;
//A record of the first 255 characters of the read in file.
FirstFileChars : STRING(255);
EventReportFileDetails : struct_EventDetails;
StepNumber : UDINT := 1; // Start off by running.
EventIndexToRead : UDINT := 0; // The index of the file to read in
EventIndexRead : UDINT := 0;
Initiate : BOOL; // Force this value to TRUE in order to start reading
files.
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


11.86 FileIo
Examples

Code Snippet 11.6 prg_ReadEventReportFromRelay (Continued)


IF Initiate THEN
// Start the state machine to read the event.
StepNumber := 1;
Initiate := FALSE;
END_IF
CASE StepNumber OF
1:
// Request a list of all events on the system.
EventReportListing.CreateNewList(deviceName := '');
StepNumber := StepNumber + 1;
2:
// Wait for the list to be ready.
IF EventReportListing.NewListReady THEN
IF EventReportListing.GetList(list := EventReportList) THEN
StepNumber := StepNumber + 1;
END_IF
END_IF
3:
// Select a specific event if that many events exist on the system.
IF EventIndexToRead < EventReportList.Size THEN
EventReportList.GetCopyOfElement(EventIndexToRead,
ADR(EventReportFileDetails));
EventIndexRead := EventIndexToRead;
FileReader.ReadEventFromDB(EventReportFileDetails.Handle,
FileIo.sel_file.RAW_DATA);
StepNumber := StepNumber + 1;
END_IF
4:
// The file reader has read the data in. Do any required work.
IF 0 < FileReader.BytesInBuffer THEN
FileReader.AppendToVector(0, FileContents);
(*Update the output string by copying to it the first 255 bytes or
the complete file, whichever is less.*)
SysMemCpy(pDest := ADR(FirstFileChars),
pSrc := FileContents.pt_Data,
udiCount := MIN(FileContents.Size, 255));
StepNumber := StepNumber + 1;
END_IF
5:
// Wait for until Initiate = TRUE for next file read request.
StepNumber := 0;
END_CASE
EventReportListing.Run(); // Run this every scan regardless.
FileReader.Run(); // Run this every scan regardless.

Reading COMTRADE Events Retrieved From Relays


Objective
You have set up the RTAC to automatically collect COMTRADE events and want to read
the contents of these records.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.87
Examples

Assumptions
1. You have included the SELString and DynamicVectors libraries in your project.
NOTE: See the SELString library
2. Collected events from the desired relays exist in the RTAC database. documentation for more information
about class_SELStrings and
class_SELStringLists.

Solution
You can locate qualifying files using a class_EventListing. Then you can select one as in
Code Snippet 11.7.

Code Snippet 11.7 prg_ReadComtradeEventFromRelay


PROGRAM prg_ReadComtradeEventFromRelay
VAR
EventReportListing : class_EventListing;
EventReportList : class_BaseVector(SIZEOF(struct_EventDetails), 32);
cfgReader : class_FileReader2;
datReader : class_FileReader2;
//A record of the first 255 characters of the read in file.
EventReportFileDetails : struct_EventDetails;
StepNumber : UDINT := 1; // Start off by running.
EventIndexToRead : UDINT := 0;
Initiate : BOOL; // Force this value to TRUE in order to start reading
files.
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


11.88 FileIo
Examples

Code Snippet 11.7 prg_ReadComtradeEventFromRelay (Continued)


IF Initiate THEN
StepNumber := 1; // Start executing the state machine
Initiate := FALSE;
END_IF
CASE StepNumber OF
1:
EventReportListing.CreateNewList(deviceName := '');
StepNumber := StepNumber + 1;
2:
IF EventReportListing.NewListReady THEN
IF EventReportListing.GetList(list := EventReportList) THEN
StepNumber := StepNumber + 1;
END_IF
END_IF
EventIndexToRead := 0;
3:
WHILE EventIndexToRead < EventReportList.Size DO // An event was found
EventReportList.GetCopyOfElement(EventIndexToRead,
ADR(EventReportFileDetails));
EventIndexToRead := EventIndexToRead + 1;
IF EventReportFileDetails.Handle.EventType =
FileIo.sel_file.COMTRADE THEN
cfgReader.ReadEventFromDB(EventReportFileDetails.Handle,
FileIo.sel_file.CFG_FILE);
datReader.ReadEventFromDB(EventReportFileDetails.Handle,
FileIo.sel_file.DAT_FILE);
EXIT;
END_IF
END_WHILE
StepNumber := StepNumber + 1;
4:
IF NOT cfgReader.InProgress AND NOT datReader.InProgress THEN
//Extract data and perform desired actions on the data here.
//cfgReader and datReader contain the contents desired.
StepNumber := StepNumber + 1;
END_IF
5:
IF EventIndexToRead >= EventReportList.Size THEN
//This branch represents having accessed all COMTRADE files found.
StepNumber := 0;
ELSE
//This branch represents having more files to check.
StepNumber := 3;
END_IF
END_CASE
EventReportListing.Run(); // Run this every scan regardless.
cfgReader.Run(); // Run this every scan regardless.
datReader.Run();

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.89
Examples

Downloading File to Local File System From Remote FTP


Server
Objective
You want to read a file onto the local file system from a remote FTP server and call the
local file “FileFromFtpServer.csv”.

Assumptions
1. An FTP server is set up, configured, and accessible by the RTAC over the network.
2. The FTP server configuration is as follows:
ä IP address: 192.168.0.2
ä Username: FTPUSER
ä Password: TAIL
3. The file “FileToFtp.csv” exists in the root of the FTP server file system.

Solution
First, you must get the file from the remote server by performing an FTP download using
code similar to that shown in Code Snippet 11.8.
Then you can manipulate the file at will. For example, you could read the file into an
internal buffer, then copy it into an empty user-supplied class_ByteVector by using the
program shown previously in Code Snippet 11.4.

Code Snippet 11.8 prg_FtpDownload


PROGRAM prg_FtpDownload
VAR
FtpServerIP : STRING(15) := '192.168.0.2';
FtpServerUsername : STRING(32) := 'FTPUSER';
FtpServerPassword : STRING(32) := 'TAIL';
FtpServerFileToGet : STRING(255) := 'FileToFtp.csv';
RenameAsLocalFile : STRING(255) := '/FileFromFtpServer.csv';

FirstScan : BOOL := FALSE;


Timeout : UDINT := 10; // Time in seconds
DownloadStatus : FileIo.sel_ftp_client.Enum_sel_ftp_client_errors := 0;
CurrentStatus : FileIo.sel_ftp_client.Enum_sel_ftp_client_errors;
DownloadAttemptCompleted : BOOL := FALSE;
DownloadAttemptFailed : BOOL := FALSE;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


11.90 FileIo
Examples

Code Snippet 11.8 prg_FtpDownload (Continued)


CurrentStatus := DownloadStatus;
IF FirstScan THEN
//Initiate the FTP Read.
FileIo.sel_ftp_client.ftp_download(
ftp_server := FtpServerIP,
local_path := RenameAsLocalFile,
remote_path := FtpServerFileToGet,
username := FtpServerUsername,
password := FtpServerPassword,
timeout := Timeout,
status := DownloadStatus); // This is passed in as a VAR_IN_OUT
(* Note, making this call will cause the download status to be
initialized
to 'IN_PROGRESS'*)
FirstScan := FALSE;

(* Because DownloadStatus was passed in as a VAR_IN_OUT,


it can be written to by the external FTP task.
Check it regularly to see if the download status changed to 0 *)
ELSIF FileIo.sel_ftp_client.NO_ERROR = CurrentStatus THEN
DownloadAttemptCompleted := TRUE;
ELSIF CurrentStatus < FileIo.sel_ftp_client.IN_PROGRESS THEN
// The operation has hit an error because NO_ERROR was already checked.
DownloadAttemptFailed := TRUE;
END_IF

Uploading File From Local File System to Remote FTP


Server
Objective
You want to write a file from the local file system to a remote FTP server and call the local
file “FileFromRTAC.csv”.

Assumptions
1. An FTP server is set up, configured, and accessible by the RTAC over the network.
2. The FTP server configuration is as follows:
ä IP address: 192.168.0.2
ä Username: FTPUSER
ä Password: TAIL
3. The file “FileToSend.csv” exists in the root of the RTAC File Manager.

Solution
Get the file onto the remote server by performing an FTP upload.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.91
Examples

Code Snippet 11.9 prg_FtpUpload


PROGRAM prg_FtpUpload
VAR
FtpServerIP : STRING(15) := '192.168.0.2';
FtpServerUsername : STRING(32) := 'FTPUSER';
FtpServerPassword : STRING(32) := 'TAIL';
FileNameForFtpServer : STRING(255) := 'FileFromRTAC.csv';
LocalFileToSend : STRING(255) := '/FileToSend.csv';
FirstScan : BOOL := TRUE;
Timeout : UDINT := 10; // Time in seconds
UploadStatus : FileIo.sel_ftp_client.Enum_sel_ftp_client_errors
:= 0;
CurrentStatus : FileIo.sel_ftp_client.Enum_sel_ftp_client_errors;
UploadAttemptCompleted : BOOL := FALSE;
UploadAttemptFailed : BOOL := FALSE;
END_VAR

CurrentStatus := UploadStatus;
IF FirstScan THEN
//Initiate the FTP write.
FileIo.sel_ftp_client.ftp_upload(
ftp_server := FtpServerIP,
local_path := LocalFileToSend,
remote_path := FileNameForFtpServer,
username := FtpServerUsername,
password := FtpServerPassword,
timeout := Timeout,
status := UploadStatus); // This is passed in as a VAR_IN_OUT
(* Note, making this call will cause the upload status to be initialized
to 'IN_PROGRESS'*)
FirstScan := FALSE;

(* Because UploadStatus was passed in as a VAR_IN_OUT,


it can be written to by the external FTP task.
Check it regularly to see if the upload status changed to 0 *)
ELSIF FileIo.sel_ftp_client.NO_ERROR = CurrentStatus THEN
UploadAttemptCompleted := TRUE;
ELSIF CurrentStatus < FileIo.sel_ftp_client.IN_PROGRESS THEN
// The operation has hit an error because NO_ERROR was already checked.
UploadAttemptFailed := TRUE;
END_IF

Basic Directory Management With Persistent Log Files


Objective
Use the basic directory manager to implement a six-file circular buffer in a target directory
that is being populated by an independent FileIO class_FileWriter instance. Write applica-
tion errors to a persistent log file in the target directory so the log file is not subject to the
circular buffer.

Date Code 20190830 Instruction Manual Programming Reference


11.92 FileIo
Examples

Assumptions
1. A user-programmed application is writing files to a designated folder, Dir1, on the
RTAC file system by using FileIO class_FileWriter.
2. A Global Variable List, GVL1, has been defined to contain variables pertinent to
error tracking activities for the application. This example GVL is shown in Code
Snippet 11.10.
3. The user-programmed application populates the variables in GVL1.

Code Snippet 11.10 Error Tracking: GVL1


VAR_GLOBAL
//Flag indicating error condition on the given application
g_ApplicationError : BOOL;
//User-defined numeric error category
g_ApplicationErrorCode : DINT;
//Specific error message
g_ApplicationErrorDescription : STRING(255);
END_VAR

Solution
Instantiate a class_BasicDirectoryManager to fulfill the stated directory management ob-
jectives. Also use class_FileWriter to generate a persistent error log file. Recall that class_-
BasicDirectoryManager ignores files with file names beginning with a period (.).

Code Snippet 11.11 prg_ManageComplexDirectory


PROGRAM prg_ManageComplexDirectory
VAR
FirstScan : BOOL := TRUE;
FolderName : STRING := 'Dir1';
ErrorFileWriter : FileIO.class_FileWriter(filename :=
'Dir1/.ErrorLog.txt');
Manager : FileIO.class_BasicDirectoryManager;
ApplicationErrorTrigger : R_TRIG;
TempLogString : STRING(255);
END_VAR

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.93
Examples

Code Snippet 11.11 prg_ManageComplexDirectory (Continued)


IF FirstScan THEN
(*Initialize the basic directory manager
by calling the bootstrap_SetDirectory() method.
Limit target directory to 1MB, 6 files, and
no limit on the age of the files.*)
Manager.bootstrap_SetDirectory(folderName := FolderName,
maximumFolderSize := 1024*1024, maximumNumFiles := 6,
maximumNumDays := 0);
FirstScan := FALSE;
END_IF

//Look for the rising edge of the error flag.


ApplicationErrorTrigger(CLK := GVL1.g_ApplicationError);

(*IF error detected, write current state of GVL1 variables


to the persistent log file, preceded by the current system time.*)
IF ApplicationErrorTrigger.Q THEN
TempLogString :=
CONCAT(DT_TO_STRING(System_Time_Control_POU.System_Time_DateAndTime),
' Application error code:');
TempLogString := CONCAT(TempLogString,
DINT_TO_STRING(GVL1.g_ApplicationErrorCode));
TempLogString := CONCAT(TempLogString, '$nError message: ');
TempLogString := CONCAT(TempLogString,
GVL1.g_ApplicationErrorDescription);
TempLogString := CONCAT(TempLogString, '$n$r');
ErrorFileWriter.AppendString(TempLogString);
END_IF

//Run the persistent file writer


ErrorFileWriter.Run();
//Manage the target directory
Manager.Run();

Logging a History of Inputs and Outputs


Objective
You want to keep a week’s worth of input value history, as well as outputs from a protection
algorithm that has been implemented.

Assumptions
There exist some set of inputs and outputs to the work being done. Here these are delineated
by adding the prefix g_, indicating that they exist in a GVL as shown in Code Snippet 11.12.

Date Code 20190830 Instruction Manual Programming Reference


11.94 FileIo
Examples

Code Snippet 11.12 Global Variable List


VAR_GLOBAL
g_TriggerOne : BOOL;
g_TriggerTwo : BOOL;
g_WorkingVoltage : REAL;
g_WorkingCurrent : REAL;

g_OutputOne : BOOL;
g_OutputTwo : BOOL;
END_VAR

Solution
You can instantiate a class_LogDirectoryManager to manage rotation of the logs you want.

Code Snippet 11.13 prg_LogApplicationActions


PROGRAM prg_LogApplicationActions
VAR
LogManager : class_LogDirectoryManager( folderName := '/WeekOfLogs/',
logPostfix := 'InVsOuts.log',
maxFolderSize := 512000,
maxNumFiles := 7,
autoStartNewLogDaily := TRUE);
WorkspaceString : STRING(255);
END_VAR

IF g_TriggerOne THEN
WorkspaceString := CONCAT( 'Trigger One received with a input voltage
of ',
REAL_TO_STRING(g_workingVoltage));
LogManager.WriteLogEntryString(WorkspaceString);
END_IF
IF g_TriggerTwo THEN
WorkspaceString := CONCAT( 'Trigger Two received with a input current
of ',
REAL_TO_STRING(g_workingCurrent));
LogManager.WriteLogEntryString(WorkspaceString);
END_IF

(*At this point the user calls the application doing work so the outputs
update.*)

IF g_OutputOne THEN
LogManager.WriteLogEntryString('Action One requested');
END_IF
IF g_OutputTwo THEN
LogManager.WriteLogEntryString('Action Two requested');
END_IF

LogManager.Run();

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.95
Examples

Rotating Logs More Frequently


Objective
You want to keep a week’s worth of logs with creation of a new log file every eight hours.

Solution
You can instantiate a class_LogDirectoryManager to manage rotation of the logs you want.
To do this, you must track the time and issue StartNewLog() on the eight-hour shift
boundaries.

Code Snippet 11.14 prg_RotatingLogs


PROGRAM prg_RotatingLogs
VAR CONSTANT
c_ShiftChange1 : UDINT := 1;
c_ShiftChange2 : UDINT := 9;
c_ShiftChange3 : UDINT := 17;
END_VAR
VAR
//Note that maxNumFiles allows for three files and the automated
nightly rollover.
LogManager : class_LogDirectoryManager( folderName :=
'/WeekOfShiftLogs/',
logPostfix := 'Shift.log',
maxFolderSize := 512000,
maxNumFiles := 28,
autoStartNewLogDaily := TRUE);

FirstScan : BOOL := TRUE;

PresentTime : timestamp_t;
TimeOfDay : TIME_OF_DAY;

PreviousHours : UDINT;
PresentHours : UDINT;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


11.96 FileIo
Examples

Code Snippet 11.14 prg_RotatingLogs (Continued)


PresentTime := SYS_TIME();
TimeOfDay := DT_TO_TOD(PresentTime.value.dateTime);

PreviousHours := PresentHours;
//Divide by 1000 to remove milliseconds and 3600 to remove seconds and
minutes.
PresentHours := TOD_TO_UDINT(TimeOfDay)/3600000;

IF FirstScan THEN
PreviousHours := PresentHours;
FirstScan := FALSE;
END_IF

IF PreviousHours < c_ShiftChange1 AND PresentHours >= c_ShiftChange1 THEN


LogManager.StartNewLog();
ELSIF PreviousHours < c_ShiftChange2 AND PresentHours >= c_ShiftChange2
THEN
LogManager.StartNewLog();
ELSIF PreviousHours < c_ShiftChange3 AND PresentHours >= c_ShiftChange3
THEN
LogManager.StartNewLog();
END_IF

//Do any work and logging desired.

LogManager.Run();

Logging Events Via FTP


Objective
You want to record event logs on a remote server.

Assumptions
1. An FTP server is set up, configured, and accessible by the RTAC over the network.
2. The FTP server configuration is as follows:
ä IP address: 192.168.0.2
ä Username: FTPUSER
ä Password: TAIL
3. There are external variables g_EventOccurred and g_EventDescription, driven by
other code, that cause an event to be populated and sent.
4. There exists some set of inputs and outputs for the work being done. Here these are
delineated by adding the prefix g_, indicating that they exist in a GVL as shown in
Code Snippet 11.15.

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.97
Examples

Code Snippet 11.15 Global Variable List


VAR_GLOBAL
g_EventOccurred : BOOL;
g_EventDescription : STRING(255);
END_VAR

Solution
You can instantiate a class_LogDirectoryManager to accept the data for transmission and
to manage the storage required to facilitate the transaction.

Code Snippet 11.16 prg_RemoteEventLogs


PROGRAM prg_RemoteEventLogs
VAR
LogManager : class_LogDirectoryManager( folderName := '/RemoteLogs/',
logPostfix := '',
maxFolderSize := 10240,
maxNumFiles := 10,
autoStartNewLogDaily := FALSE);

EventPostfix : String(16) := 'RTAC1.event';


ServerIP : STRING(15) := '192.168.0.2';
RemotePath : STRING := '/RTAC1_Event_Files/';
FtpUser : STRING := 'FTPUSER';
FtpPassword : STRING := 'TAIL';

FirstScan : BOOL := TRUE;


Workbench : STRING(255);
END_VAR

IF FirstScan THEN
LogManager.SetFtpServerForArchiving( ftpServer := ServerIP,
remotePath := RemotePath,
username := FtpUser,
password := FtpPassword,
timeout := 5,
schedule := ON_UPDATE);
FirstScan := FALSE;
END_IF

//Do any work and logging desired.

IF g_EventOccurred THEN
LogManager.EventLogFromString( str := g_EventDescription,
eventPostfix := EventPostfix);
g_EventOccurred := FALSE;
END_IF
LogManager.Run();

Date Code 20190830 Instruction Manual Programming Reference


11.98 FileIo
Examples

Iterating Over All SOEs


Objective
You need to programmatically iterate over all SOEs from the RTAC and be sure that every
SOE after a certain time is addressed.

Assumptions
Your workload requires assurances that every SOE is seen and that duplication of responses
to SOEs is unacceptable. In this use case, the order of the events matters less than ensuring
that each event is seen and addressed. For this method to work, the SOEs must either be
all from the local RTAC or from external devices being logged on the RTAC. If both types
of SOEs exist, they would need to be handled independently.

Solution
You periodically query the system for the next c_MaxSoeCount SOEs that have not yet
been addressed.

Code Snippet 11.17 prg_SoeIterator


PROGRAM prg_SoeIterator
VAR CONSTANT
c_MaxSoeCount : UINT := 10;
END_VAR
VAR
// Variables to control the program flow
GetFirstSOE : BOOL := TRUE;
SoeQueried : BOOL := FALSE;
DoWork : BOOL := FALSE;
i : UINT;

// Input Filters
StartTime : DT := DT#2000-1-1-0:0:0;
Filters : FileIo.sel_file.Struct_soe_filter;

// Variables to store function output


Status : FileIo.sel_file.Enum_sel_file_errors;
Content : ARRAY [1..c_MaxSoeCount] OF
FileIo.sel_file.Struct_soe_content_id;
LastOutput : FileIo.sel_file.Struct_soe_content_id;
Count : UINT;
END_VAR

IF GetFirstSOE THEN
// We need to get a starting SOE.
IF NOT SoeQueried THEN
FileIo.fun_LocalSoeGetID(StartTime, Filters, Status, Content[1]);
SoeQueried := TRUE;
ELSE
IF Status = FileIo.sel_file.SYSTEM_BUSY THEN
// The system was too busy try again.
SoeQueried := FALSE;
ELSIF Status = FileIo.sel_file.NO_ERROR THEN

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.99
Examples

// We got a result, switch to group queries


GetFirstSoe := FALSE;
SoeQueried := FALSE;
LastOutput := Content[1];
StartTime := Content[1].TimeStamp;
// This function only ever returns one result.
Count := 1;
// Trigger processing for the SOE data returned
DoWork := TRUE;
ELSIF Status = FileIo.sel_file.OPERATION_FAILED THEN
;(* The database was unable to find any SOEs matching the
filters provided. *)
ELSIF Status <> FileIo.sel_file.IN_PROGRESS THEN
;(* If we arrive here configuration is bad and needs to be
manually adjusted to continue. *)
END_IF
END_IF
ELSE
IF NOT SoeQueried THEN
// Beginning from the last SOE received, query for the next set of
SOEs.
FileIo.fun_LocalSoeAscending( ADR(content[1]), LastOutput.ID,
c_MaxSoeCount,
Filters, Status, Count);
SoeQueried := TRUE;
ELSE
IF Status = FileIo.sel_file.SYSTEM_BUSY THEN
// The system was too busy try again.
SoeQueried := FALSE;
ELSIF Status = FileIo.sel_file.NO_ERROR THEN
DoWork := Count > 0;
SoeQueried := FALSE;
IF DoWork THEN
// Store next lookup information if there is any.
LastOutput := Content[Count];
StartTime := Content[Count].TimeStamp;
END_IF
ELSIF Status <> FileIo.sel_file.IN_PROGRESS THEN
(* If we arrive here configuration is probably OK, as we got
results above.
Something probably affected the ID we were using. Start
over. *)
SoeQueried := FALSE;
GetFirstSOE := TRUE;
END_IF
END_IF
END_IF

IF DoWork THEN
// Process any new data.
FOR i := 1 TO Count DO
;(* Insert your code here to do work on the SOEs encountered. *)
END_FOR
DoWork := FALSE;
END_IF

Date Code 20190830 Instruction Manual Programming Reference


11.100 FileIo
Examples

Querying a Subset of SOEs


Objective
You want to display the 10 most recent SOEs each minute.

Assumptions
You have some code for presenting or communicating the SOE content at some other loca-
tion. In this use case, the order of events is more important than hard guarantees of seeing
each event occur.

Solution
You periodically query the system for the most recent SOE data.

Code Snippet 11.18 prg_SoeUpdater


PROGRAM prg_SoeUpdater
VAR CONSTANT
c_MaxSoeCount : UINT := 10;
END_VAR
VAR
// This query has no filters, so leave all values as default empty
// strings.
Filters : FileIo.sel_file.Struct_soe_filter;
Status : FileIo.sel_file.Enum_sel_file_errors;

SoeData : ARRAY [1..c_MaxSoeCount] OF


FileIo.sel_file.Struct_soe_content;
SoesFound : UINT;

Timestamp : timestamp_t;
Now : DT;
Last : DT;

// These are the arrays populated with display data


Devices : ARRAY [1..c_MaxSoeCount] OF STRING(255);
Messages : ARRAY [1..c_MaxSoeCount] OF STRING(255);
Times : ARRAY [1..c_MaxSoeCount] OF DT;

// Flag indicating that SOE data has been requested and not copied.
Running : BOOL := FALSE;

i : UDINT;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


FileIo 11.101
Examples

Code Snippet 11.18 prg_SoeUpdater (Continued)


(*Check for the first run after the SOE query completes.*)
IF Running AND Status <> FileIo.sel_file.IN_PROGRESS THEN
(*Loop across all found SOEs. This is guaranteed to be less than our
array
*sizes c_MaxSoeCount because of the arguments passed to the function
below*)
FOR i := 1 TO SoesFound DO
Devices[i] := SoeData[i].DeviceName;
Messages[i] := SoeData[i].Message;
Times[i] := SoeData[i].TimeStamp;
END_FOR
Running := FALSE;
END_IF

Timestamp := Sys_Time();
Now := Timestamp.value.dateTime;

(*Only query for SOEs on even minute intervals*)


IF ((DT_TO_UDINT(Now) MOD 60) = 0) AND
(*Only query for SOEs if any previous request has completed.*)
Status <> FileIo.sel_file.IN_PROGRESS AND
(*Only allow one query per second even if the last one completed.*)
Now > Last THEN
fun_SoeDescending(ADR(SoeData), Now, c_MaxSoeCount, Filters, Status,
SoesFound);
Running := TRUE;
Last := Now;
END_IF

Listing the Content of a Directory


Objective
You want to list the the files contained in the /TestDirectory.
You want the listing to automatically occur when the project is uploaded. In addition, you
want the ability to refresh the directory listing after the project is downloaded by forcing a
value in the online editor.

Assumptions
The directory content to be listed is uploaded.

Solution
Create the file list using the FileIo.class_DirectoryListing, and write that content into an
array to make it easier to see.

Date Code 20190830 Instruction Manual Programming Reference


11.102 FileIo
Examples

Code Snippet 11.19 prg_ListDirectory


PROGRAM prg_ListDirectory
VAR CONSTANT
c_MaxFilesToList : UDINT := 10;
c_MaxFilenameLength : UDINT := 255;
END_VAR
VAR
Lister : FileIo.class_DirectoryListing;
DirList : FileIo.class_SELStringList;
ArrayList : ARRAY[1..c_MaxFilesToList] OF
STRING(c_MaxFilenameLength);
Stage : UDINT := 1; // Force to 1 with <Ctrl> <F6>
to run again
END_VAR
VAR_TEMP
i : UDINT;
pt_SelStr : POINTER TO FileIo.class_SELString;
END_VAR

CASE Stage OF
1: // Clear from last run, and request a new list
DirList.Clear();
FOR i := 1 TO c_MaxFilesToList DO
ArrayList[i] := ''; // Empty the array
END_FOR
Lister.CreateNewList(directoryName := '/TestDirectory',
filter := '');
Stage := Stage + 1;
2: // Wait until done
IF Lister.NewListReady THEN
Lister.GetList(DirList);
// Read the list into the array
DirList.Begin(); // Start at the beginning of the list
FOR i := 1 TO DirList.Size DO
IF (i > c_MaxFilesToList) THEN
EXIT; // No more room in the array
END_IF
pt_SelStr := DirList.Next();
IF 0 <> pt_SelStr THEN // Always check pointers aren't 0
ArrayList[i] := pt_SelStr^.ToString();
END_IF
END_FOR
Stage := 0; // Reset to start
END_IF
ELSE
; // Do nothing
END_CASE
Lister.Run(); // Always run the worker method

Programming Reference Instruction Manual Date Code 20190830


SECTION 12

GridConnect
Introduction
The GridConnect library is designed for use with the SEL Real-Time Automation Con-
troller (RTAC) family of products. It contains ready-to-use function blocks for controlling
the point of interconnection (POI) between the utility grid and a solar power generation
resource. The GridConnect library uses proportional integral (PI) controllers when in a
closed-loop mode to regulate output set points.

Overview
The GridConnect library contains the following four function blocks:
ä fb_MasterPlantController: Regulates POI between the utility and the solar facility.
ä fb_PvInverter: Interfaces with a photovoltaic inverter.
ä fb_StorageInverter: Interfaces with a battery storage inverter.
ä fb_Capacitor: Interfaces with a capacitor.
The user must map all necessary input/output (I/O) signals to interface the function blocks
to their various pieces of external equipment, but the GridConnect library automates all
data exchange between the function blocks themselves.

Feature Summary
This library contains the following features for interconnection of a solar facility to the
utility grid.

Reactive Control at POI


ä Closed-loop control of power factor
ä Closed-loop control of reactive power (constant VAR)
ä Closed-loop control of voltage
ä Closed-loop power factor compensation
ä Closed-loop voltage compensation
ä Open-loop control of power factor (POI set-point pass-through)

Date Code 20190830 Instruction Manual Programming Reference


12.2 GridConnect
Introduction

Power Limit Control at POI


ä Closed-loop control of power output (i.e., advanced power limit control)
ä Open-loop control of power output (i.e., simple power limit control)

Frequency Regulation at POI


ä Automatic adjustment of plant power output in response to system frequency changes
ä Automatic adjustment of storage device output in response to system frequency changes

Additional Features
ä POI voltage limit override when in power factor or reactive power control or com-
pensation modes
ä POI power factor limit override when in voltage control or compensation modes
ä Integrated control of PV inverters, storage inverters, and capacitors to provide precise
control at the POI

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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type
class_GridConnectObjectObject"
myGridConnectObjectObject := otherGridConnectObjectObject;

// This is fine
someVariable := myGridConnectObjectObject.value;
// As is this
pt_myGridConnectObjectObject := ADR(myGridConnectObjectObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.
ä 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).

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.3
Master Plant Controller

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.

Master Plant Controller


Overview
The master plant controller (hereafter referred to as the Controller) is operated in several
different control modes, each having the objective of controlling or compensating power
factor, reactive power, or voltage. The desired mode is provided as an input on the fb_-
MasterPlantController function block. The controller is enabled by asserting the Enable
input and is disabled by deasserting the Enable input. Top level mode and enable/disable
control inputs are described in Table 12.1.

Table 12.1 Master Plant Controller Control Mode Parameters


Parameter Description
ControlMode POI control mode:
ä 0 = Power Factor Control
ä 1 = VAR Control
ä 2 = Power Factor Compensation
ä 3 = Voltage Compensation
ä 4 = Voltage Control
ä 5 = Open-Loop Power Factor Control

Enable POI control enable


PLimitMode Power limit mode:
ä 0 = NoLimit
ä 1 = Simple
ä 2 = Advanced

When the controller is in open-loop power factor control mode it passes the power factor
set point to the power factor reference for all inverters in the facility. This mode is used as
a fall-back mode (when POI measurements are not reliable).
In closed-loop mode the controller automatically adjusts either the power, power factor, or
VAR reference signal of the inverter to perform control or compensation at the POI.
The controller automatically adjusts the power limit reference signal of the inverters to limit
the cumulative power output of the plant.

Date Code 20190830 Instruction Manual Programming Reference


12.4 GridConnect
Master Plant Controller

Control Modes
The GridConnect library supports six different control modes. This section provides details
about the following modes: power factor, voltage, VAR, and open-loop power factor. The
remaining two modes are compensation modes and are detailed in Compensation Modes
on page 12.5.

Power Factor Control


When the controller is in power factor control mode, it adjusts the power factor reference
of the inverter to provide precise adjustment of the power factor at the POI. The controller
uses a proportional integral (PI) controller for these adjustments. For this mode to function
properly, the inverter must be in power factor control mode (as opposed to VAR control
mode). If the inverter is not in power factor control mode, the controller will periodically
attempt to send a mode change control. The inverter is considered unavailable to the master
controller if it is unable to change modes.
Closed-loop behavior of power factor control is adjusted using the inputs defined in Ta-
ble 12.2.

Table 12.2 Closed-Loop Power Factor Control Parameters


Parameter Description
PFControlSetpoint POI power factor control set point (positive values = lagging, negative
values = leading)
PFControlDeadband POI power factor control dead band
PFKp Proportional tuning parameter for power factor control. Default is 1.
PFKi Integral tuning parameter for power factor control. Default is 0.

VAR Control
When the controller is in VAR control mode, it adjusts the VAR reference of the inverter to
provide precise adjustment of VAR flow at the POI. The controller uses a PI controller for
these adjustments. For this mode to function properly, the inverter must be in VAR control
mode (as opposed to power factor control mode). If the inverter is not in VAR control
mode, the controller will periodically attempt to send a mode change control. The inverter
is considered unavailable to the master controller if it is unable to change modes.
Closed-loop behavior of VAR control is adjusted using the inputs defined in Table 12.3.

Table 12.3 Closed-Loop VAR Control Parameters


Parameter Description
QSetpoint POI VAR control set point
QDeadband POI VAR control dead band
QKp Proportional tuning parameter for VAR control
QKi Integral tuning parameter for VAR control

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.5
Master Plant Controller

Voltage Control
When the controller is in voltage control mode, it adjusts the VAR reference of the inverter
to provide precise adjustment of the voltage magnitude at the POI. The controller uses a
PI controller for these adjustments, and separate tuning parameters (VKp and VKi) are
provided for this mode. For this mode to function properly, the inverter must be in VAR
control mode (as opposed to power factor control mode). If the inverter is not in VAR
control mode, the controller will periodically attempt to send a mode change control. The
inverter will be considered unavailable to the master controller if it is unable to change
modes.
Closed-loop behavior of voltage control is adjusted using the inputs defined in Table 12.4.

Table 12.4 Closed-Loop Voltage Control Parameters


Parameter Description
VSetpoint POI power voltage set point
VDeadband POI voltage control dead band
VKp Proportional tuning parameter for voltage control. Default is 1.
VKi Integral tuning parameter for voltage control. Default is 0.

Open-Loop Power Factor Control


When the controller is in open loop power factor control mode, it passes the power factor set
point to the power factor reference for all configured inverters. For this mode to function
properly, the inverter must be in power factor control mode (as opposed to VAR control
mode). If the inverter is not in power factor control mode, the controller will periodically
attempt to send a mode change control. The inverter will be considered unavailable to the
master controller if it is unable to change modes.
Power factor ramp rate changes are also passed to the inverters. Settings relating to power
factor control that are passed through to configured inverters are listed in Table 12.5.

Table 12.5 Open-Loop Power Factor Control Parameters


Parameter Description
PFControlSetpoint POI power factor control set point
InverterPFRampRate Power factor ramp rate

Compensation Modes
The GridConnect library supports both power factor and voltage compensation. These
modes regulate the controlled value (power factor or voltage) in a response proportional to
the percentage of plant output power or voltage.
It is important to note that these modes use different settings than other control modes, and
they do not observe the limits that constrain those other modes. Limits that do not apply to
compensation modes are as follows:
ä PFLagLimit and PFLeadLimit
ä VLimitHigh and VLimitLow

Date Code 20190830 Instruction Manual Programming Reference


12.6 GridConnect
Master Plant Controller

ä QLimitHigh and QLimitLow


These compensation modes should instead be limited by their own curve set points as de-
fined in the following sections.

Power Factor Compensation


When the controller is in power factor compensation mode, it regulates the power factor
at the POI based on how much power the plant is generating. This mode uses the same PI
controller tuning parameters as the Power Factor control mode. The relationship between
power factor and plant power output is a slope defined by a power factor compensation
gradient setting (its units are PF/%kW). Control of the POI power factor is limited by a
compensation limit setting, as well as a low power cutoff setting. Inputs that adjust the
operation of the controller when in power factor compensation mode are defined in Ta-
ble 12.6.
This mode requires that the inverters be in power factor control mode. Any inverter not in
power factor control mode is flagged as unavailable to the master controller and is period-
ically sent a mode change control signal.

Table 12.6 Power Factor Compensation Parameters


Parameter Description
PFCompensationSetpoint Power factor compensation set point
PFCompensationCutoff Power factor compensation cutoff
PFCompensationGradient Power factor compensation gradient
PFCompensationLimit Power factor compensation limit
PFKp Proportional tuning parameter for power factor control. Default is
1.
PFKi Integral tuning parameter for power factor control. Default is 0.

Voltage Compensation
When the controller is in voltage compensation mode, it regulates VAR flow at the POI
based on voltage at the POI. This mode uses the same PI controller tuning parameters as
the Voltage Control mode. In this mode the plant can provide VAR support for grid voltage,
even at night or when real power output is otherwise very low. The relationship between
VAR output and voltage magnitude follows a curve defined by voltage and VAR set points
(as illustrated in Figure 12.1 and Table 12.7). These inputs can be adjusted at any time,
which will change the curve being used by the controller for voltage compensation. If these
inputs are made variable, it is important to ensure that they have correct and intended values
at all times, including at controller startup.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.7
Master Plant Controller

V1,Q1

V3,Q3
V
V2,Q2

V4,Q4

Figure 12.1 Voltage Compensation Curve

This mode requires that the inverters be in VAR control mode. Any inverter not in VAR
control mode is flagged as unavailable to the master controller and is periodically sent a
mode change control signal.

Table 12.7 Voltage Compensation Parameters


Parameter Description
VCompensationV1 Voltage compensation voltage set point 1. Units are kV. Default is 0.
VCompensationV2 Voltage compensation voltage set point 2. Units are kV. Default is 0.
VCompensationV3 Voltage compensation voltage set point 3. Units are kV. Default is 0.
VCompensationV4 Voltage compensation voltage set point 4. Units are kV. Default is 0.
VCompensationQ1 Voltage compensation reactive power set point 1. Units are kVAR. Default
is 0.
VCompensationQ2 Voltage compensation reactive power set point 2. Units are kVAR. Default
is 0.
VCompensationQ3 Voltage compensation reactive power set point 3. Units are kVAR. Default
is 0.
VCompensationQ4 Voltage compensation reactive power set point 4. Units are kVAR. Default
is 0.
VKp Proportional tuning parameter for voltage control. Default is 1.
VKi Integral tuning parameter for voltage control. Default is 0.

Capacitor Control
The master controller calculates the reactive power required to achieve the active control
objective (i.e., VAR, voltage, or power factor at the POI). Additionally, the master con-
troller calculates the reactive power available to be added or removed using inverters and
capacitors. Generally, the active PI control pursues the control objective by operating ca-
pacitors first (if available) and complementing that operation by adjusting the power factor
reference to the inverters. If inverters collectively output more than 75 percent of the rating

Date Code 20190830 Instruction Manual Programming Reference


12.8 GridConnect
Master Plant Controller

of the next capacitor selected to operate for 60 seconds, the capacitor will close (as long
as the CapacitorOperationPeriod interval is not violated). In this manner, the master con-
troller will attempt to use capacitors to make coarse control adjustments at the POI, and
use the inverters to reach and maintain fine control at the POI.

Storage Inverter Control


The GridConnect library provides a storage inverter function block. It will use the storage
inverter’s ability to discharge energy to the POI in order to maintain POI real power ramp
rate as photovoltaic (PV) power output decreases. This is referred to as downramp control.

Power Output Limit


When the controller is enabled, it sets the power limit reference signals to the inverters
based on the power limit mode.

NoLimit Power Limit Mode


The controller sets the power limit reference signal to 100 percent for all inverters.

Simple Power Limit Mode


The power limit set point is calculated based on a percentage of the total power rating of
the inverters that are online and available to be controlled. While the real power set point
is in kW, the real power set point of each inverter will be the same in terms of the rating of
each inverter. For example, if there are 40 inverters at 500 kW rating each, the total power
rating is 20 MW. If the power limit set point is 15 MW, each inverter will be limited to 75
percent of 500 kW, or 375 MW. If some of the 40 inverters are not online, the total power
rating of will be less. For example, if two inverters are offline, each of the remaining online
inverters should be limited to 79 percent of 500 kW, or 395 kW.
In some cases, there may be inverters that are online and producing power but which are not
available to be controlled. For example, the controller does not attempt to control inverters
that are in one of the following states:
ä The inverter is in local mode and is excluded from operation.
ä The inverter indicates that a fault is present.
ä The inverter controller detects a communications failure alarm.
When one of these conditions is true, the controller assumes that the power output of these
inverters will remain constant and adjusts the power limit of the remaining inverters to com-
pensate. In the example below, if the two offline inverters were actually online, generating
250 kW each but not available to be controlled, then the controller will calculate the power
limit as shown in Equation 12.1 . Each inverter will then output this percentage multiplied
by its individual real power rating.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.9
Master Plant Controller

P OIP owerSetP oint − ConstantP ower 15M W − 2 ∗ 0.250M W


P owerLimit = = = 76.3% (Equation 12.1)
AvailableInverterRating 19M W
The simple power limit mode does not address any non-uniform cloud cover issues or the
presence of local load.

Advanced Power Limit Mode


The power output of an inverter is very sensitive to fluctuations in solar radiation. A dis-
turbance, such as a cloud, quickly reduces the power output of some inverters while other
inverters in the facility may have unused capacity. Additionally, a storage inverter may be
used to provide energy at the POI in these cases. The advanced power limit acts to aggre-
gate the fast-changing power output available at individual inverters to produce a steady
power output at the POI. Additionally, the changes to the power limit reference are limited
by the specified power limit ramp rate of the inverter.
If an inverter does not respond to the power set point, the master controller will limit the
inverter power set point to 115 percent of the present power output of the inverter. This
adaptive power limit reduces potential high-power excursions because of inverter wind up
when the available power increases quickly because of cloud cover clearing. A user-settable
time delay is employed to determine when the adaptive power limit should be applied. This
time delay should be set to at least twice the expected data update period for the inverter
power measurement. Because the advanced power limit mode uses data from the individual
inverters in a closed control loop, it is important that data from the inverters be updated to
the controller at least every 5 seconds.
The user may adjust the behavior of the advanced power output limit using the parameters
listed in Table 12.8.

Table 12.8 Advanced Power Output Limit Parameters


Parameter Description
PSetpoint POI power limit set point (kW)
PDeadBand POI power limit dead band (kW)
PKp Proportional tuning parameter for power control
PKi Integral tuning parameter for power control
PRating POI power output rating (kW)
InverterPLimitRampRate Inverter power limit ramp rate (% power rating/second)
InverterPLimitDelay Time between the last valid inverter response and application of the
adaptive power limit

Frequency Regulation
The following settings determine how the controller performs frequency regulation. It is
able to do so using either the non-storage generation assets (general PV plant output) or
by using storage devices. Frequency regulation is performed according to a curve defined
by inputs on the Master Plant Controller. These inputs can be adjusted at any time, which
will change the curve being used by the controller for frequency regulation. If these inputs
are made variable, it is important to ensure that they have correct and intended values at
all times, including at controller startup. These inputs are described in Table 12.9 and
Figure 12.2.

Date Code 20190830 Instruction Manual Programming Reference


12.10 GridConnect
Master Plant Controller

Table 12.9 Frequency Regulation Parameters


Parameter Description
FRegulationF1 Frequency regulation frequency set point 1. Units are Hz. Default is 0.
FRegulationF2 Frequency regulation frequency set point 2. Units are Hz. Default is 0.
FRegulationF3 Frequency regulation frequency set point 3. Units are Hz. Default is 0.
FRegulationF4 Frequency regulation frequency set point 4. Units are Hz. Default is 0.
FRegulationP1 Frequency regulation real power set point 1. Units are % of PlantPRating above
or below PSetpoint. Default is 0.
FRegulationP2 Frequency regulation real power set point 2. Units are % of PlantPRating above
or below PSetpoint. Default is 0.
FRegulationP3 Frequency regulation real power set point 3. Units are % of PlantPRating above
or below PSetpoint. Default is 0.
FRegulationP4 Frequency regulation real power set point 4. Units are % of PlantPRating above
or below PSetpoint. Default is 0.

F1, P1

F3, P3
F
F2, P2

F4, Q4

Figure 12.2 Frequency Regulation Curve

Disabled
When Frequency Regulation is disabled, the controller does not perform any adjustment
of real power set points in response to frequency input.

Plant
When Frequency Regulation is in Plant mode, the controller uses any available capacity
in configured non-storage generation devices to perform frequency regulation. The output
adjustment of these non-storage devices is changed at a rate according to the EvaluationIn-
terval setting on the controller in accordance with the PLimitRampSetpoint setting. This
mode uses the plant’s non-storage generation devices. If an increase in power output is
desired in response to a frequency event, some margin must be left (the plant needs to be
run at less than maximum capacity) proportional to the slope of the frequency regulation
curve and the expected severity of frequency events.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.11
Enumerations

HighSpeedStorage
When Frequency Regulation is in HighSpeedStorage mode, the controller uses any avail-
able capacity in configured storage devices to perform frequency regulation. The output
of these storage devices is adjusted every RTAC task cycle, which allows this feature to
quickly react to changes in frequency using stored energy. This mode does not apply any
ramp rate control to the set point delivered to storage devices.

Enumerations
Enumerations make code more readable by allowing a specific number to have a text equiv-
alent. Either the raw integer value can be assigned to a value that requires an enumeration
or the text of the enumeration itself can be assigned. When viewing the values online, the
enumeration text is displayed instead of the integer value.

enum_ReactiveControlMode
This enumeration is used to set and indicate the desired reactive power control mode of the
Master Plant Controller.

Enumeration Value Description


PFControl 0 Power factor control mode
VARControl 1 VAR control mode
PFCompensation 2 Power factor compensation mode
VoltageCompensation 3 Voltage compensation mode
VoltageControl 4 Voltage control mode
OpenLoopPFControl 5 Open-loop power factor control mode

enum_PLimitMode
This enumeration is used to set and indicate the real power control mode of the Master
Plant Controller.

Enumeration Value Description


NoLimit 0 Maximum power limit set to 100 percent of inverter capacity
Simple 1 Equally divide intertie power limit amongst all available inverters
(see Simple Power Limit Mode on page 12.8)
Advanced 2 Allows an individual inverter maximum power output to adapt based
on present power output. Allows use of storage inverter to maintain
ramp rate during cloud cover (see Advanced Power Limit Mode on
page 12.9).

Date Code 20190830 Instruction Manual Programming Reference


12.12 GridConnect
Function Blocks

enum_FrequencyRegulationMode
This enumeration is used to set and indicate the frequency regulation mode of the Master
Plant Controller.

Enumeration Value Description


Disabled 0 Frequency regulation is disabled
Plant 1 Frequency regulation is performed by automatically adjusting
PSetpoint, which controls the output of non-storage generation
assets
HighSpeedStorage 2 Frequency regulation is performed by automatically adjusting
StoragePSetpoint, which controls configured storage assets

Function Blocks
The library contains the function blocks required to build a GridConnect control system.

fb_MasterPlantController (Function Block)


The Master Plant Controller function block provides the control algorithms and I/O inter-
face for controlling the POI between the utility and a solar generating facility.

Inputs

Name IEC 61131 Type Description


ControlMode enum_ReactiveControlMode POI control mode. Default is OpenLoopPFCon-
trol. For more information see Enumerations on
page 12.11.
Frequency- enum_FrequencyRegulationMode Frequency Regulation mode. Default is Disabled. For
RegulationMode more information see Enumerations on page 12.11.
Enable BOOL POI control enable. Default is FALSE.
EnableStorageDownramp- BOOL Enable downramp control using storage inverters. De-
Control fault is FALSE.
QuickStop BOOL Stop signal. Sets power output to zero, disregarding
ramp rates. Disables master controller. This signal
will go through to connected inverters even if the mas-
ter controller is already disabled.
PlantP REAL POI real power measurement. Units are kW. Default
is 0. (Positive values = flow from plant to grid.)
PlantQ REAL POI reactive power measurement. Units are kVAR.
Default is 0. (Positive values = flow from plant to grid)
PlantPF REAL POI power factor measurement. Default is 1. Units
are PF. (Positive values = lagging, negative values =
leading.)
PlantV REAL POI voltage measurement. Units are kV. Default is 1.
PlantF REAL POI frequency. Units are in Hz. Default is 60.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.13
Function Blocks

Name IEC 61131 Type Description


PlantMeasurementsGood BOOL POI measurement quality indication. Default is
FALSE.
QSetpoint REAL POI reactive power control set point. Units are kVAR.
Default is 0.
QDeadband REAL POI reactive power control dead band. Units are
kVAR. Default is 250.
QKp REAL Proportional tuning parameter for VAR control. De-
fault is 1.
QKi REAL Integral tuning parameter for VAR control. Default is
0.
QLimitHigh REAL Reactive power high limit
QLimitLow REAL Reactive power low limit
PFSetpoint REAL POI power factor control set point. Units are PF. De-
fault is 1. (Positive values = lagging, negative values
= leading)
PFDeadband REAL POI power factor control dead band. Units are PF. De-
fault is 0.0002.
PFKp REAL Proportional tuning parameter for power factor con-
trol. Default is 1.
PFKi REAL Integral tuning parameter for power factor control.
Default is 0.
PFLagLimit REAL POI lagging power factor limit (positive). Units are
PF. Default is 0.95.
PFLeadLimit REAL POI leading power factor limit (negative). Units are
PF. Default is -0.95.
PFCompensationSetpoint REAL Power factor compensation nominal set point. Units
are PF. Default is 0.
PFCompensation- REAL Power factor compensation low-power cutoff. Units
LowPowerCutoff are in % (value should be between 0 and 100). Default
is 0.
PFCompensationGradient REAL Power factor compensation gradient. Units are in
PF/kW. Default is 0.
PFCompensation- REAL Power factor compensation low power factor limit.
LowPFLimit Units are PF. Default is 0.
VCompensationV1 REAL Voltage compensation voltage set point 1. Units are
kV. Default is 0.
VCompensationV2 REAL Voltage compensation voltage set point 2. Units are
kV. Default is 0.
VCompensationV3 REAL Voltage compensation voltage set point 3. Units are
kV. Default is 0.
VCompensationV4 REAL Voltage compensation voltage set point 4. Units are
kV. Default is 0.
VCompensationQ1 REAL Voltage compensation reactive power set point 1.
Units are kVAR. Default is 0.
VCompensationQ2 REAL Voltage compensation reactive power set point 2.
Units are kVAR. Default is 0.
VCompensationQ3 REAL Voltage compensation reactive power set point 3.
Units are kVAR. Default is 0.
VCompensationQ4 REAL Voltage compensation reactive power set point 4.
Units are kVAR. Default is 0.
VSetpoint REAL POI voltage control set point. Units are kV. Default is
1.

Date Code 20190830 Instruction Manual Programming Reference


12.14 GridConnect
Function Blocks

Name IEC 61131 Type Description


VDeadband REAL POI voltage control dead band. Units are kV. Default
is 0.02.
VKp REAL Proportional tuning parameter for voltage control. De-
fault is 1.
VKi REAL Integral tuning parameter for voltage control. Default
is 0.
VLimitHigh REAL POI high voltage limit. Units are kV. Default is 1.05.
VLimitLow REAL POI low voltage limit. Units are kV. Default is 0.95.
dV_dQ REAL POI ratio of the expected change in voltage to a change
in reactive power. Units are Volts/VAR. Default is
0.01.
FRegulationF1 REAL Frequency regulation frequency set point 1. Units are
Hz. Default is 0.
FRegulationF2 REAL Frequency regulation frequency set point 2. Units are
Hz. Default is 0.
FRegulationF3 REAL Frequency regulation frequency set point 3. Units are
Hz. Default is 0.
FRegulationF4 REAL Frequency regulation frequency set point 4. Units are
Hz. Default is 0.
FRegulationP1 REAL Frequency regulation real power set point 1. Units are
% of PlantPRating above or below PSetpoint (from 0
to 100). Default is 0.
FRegulationP2 REAL Frequency regulation real power set point 2. Units are
% of PlantPRating above or below PSetpoint (from 0
to 100). Default is 0.
FRegulationP3 REAL Frequency regulation real power set point 3. Units are
% of PlantPRating above or below PSetpoint (from 0
to 100). Default is 0.
FRegulationP4 REAL Frequency regulation real power set point 4. Units are
% of PlantPRating above or below PSetpoint (from 0
to 100). Default is 0.
PLimitMode enum_PLimitMode Power limit mode. Default is NoLimit. For more in-
formation, see Enumerations on page 12.11.
PSetpoint REAL POI power limit set point. Units are kW. Default is
50000.
PDeadband REAL POI power limit dead band. Units are kW. Default is
500.
PKp REAL Proportional tuning parameter for power control. De-
fault is 1.
PKi REAL Integral tuning parameter for power control. Default
is 0.
PFRampSetpoint REAL Plant power factor ramp rate (power factor change/sec-
ond). Units are PF/second. Default is 0.02. Setting to
0 will result in no ramp supervision.
QRampSetpoint REAL Plant reactive power ramp rate (reactive power
change/second). Units are kVAR/second. Default is
10. Setting to 0 will result in no ramp supervision.
PLimitRampSetpoint REAL Plant power limit ramp rate (real power change/sec-
ond) Units are kW/second. Default is 10. Setting to 0
will result in no ramp supervision.
PLimitDelay TIME Time between the last valid inverter response and ap-
plication of the adaptive power limit. Units are sec-
onds. Default is 120.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.15
Function Blocks

Name IEC 61131 Type Description


StoragePSetpoint REAL Storage real power set point. Units are kW. Default is
0.
PlantPRating REAL POI power output rating. Units are kW. Default is
50000.
PlantQRating REAL POI reactive power rating. Units are kVAR. Default is
50000.
PlantLowPowerCutoff REAL Power output below which no power factor control will
occur. Units are kW. Default is 25.
EvaluationPeriod TIME Time between closed-loop control algorithm execu-
tion. Default is T#5S.
ControlRetryPeriod TIME Time between control retries to field devices. Default
is T#20S.
CapacitorOperationPeriod TIME Minimum time between capacitor operations. Default
is T#5M.
InverterMode- TIME Time to delay sending set points after an inverter mode
ChangeControlDelay change. Default is T#10S.

Outputs

Name IEC 61131 Type Description


ConnectToPlantDevices POINTER Connect to all plant devices.
Enabled BOOL Master controller is enabled.
QuickStopAsserted BOOL QuickStop input pin is asserted.
PFControlMode BOOL Master controller is in power factor control mode.
QControlMode BOOL Master controller is in reactive power control mode.
PFCompensationMode BOOL Master controller is in power factor compensation mode.
VCompensationMode BOOL Master controller is in voltage compensation mode.
VControlMode BOOL Master controller is in voltage control mode.
OpenLoopPFCon- BOOL Master controller is in open loop power factor control mode.
trolMode
NoLimitPControl BOOL Master controller is in NoLimit power control mode.
SimplePControl BOOL Master controller is in Simple power control mode.
AdvancedPControl BOOL Master controller is in Advanced power control mode.
PlantFRegulationEnabled BOOL Plant frequency regulation mode is enabled.
StorageFRegulationEn- BOOL High speed storage frequency regulation mode is enabled.
abled
PFOutOfBand BOOL Power factor at the POI is outside the dead band.
QOutOfBand BOOL VAR flow at the POI is outside the dead band.
VOutOfBand BOOL Voltage at the POI is outside the dead band.
PFLagAlarm BOOL Power factor lagging beyond the limit at the POI (generating more
kVAR).
PFLeadAlarm BOOL Power factor leading beyond the limit at the POI (consuming more
kVAR).
VHighAlarm BOOL Voltage above the high limit at the POI.
VLowAlarm BOOL Voltage below the low limit at the POI.
ConditionedDVDQ REAL Conditioned DVDQ input. Conditioning checks to make sure the in-
put is greater than zero.
ConditionedPFCompensa- REAL Conditioned PF Compensation Cutoff. Conditioning checks to make
tionLowPowerCutoff sure the input is between 0 and 100.

Date Code 20190830 Instruction Manual Programming Reference


12.16 GridConnect
Function Blocks

Name IEC 61131 Type Description


ConditionedPFCompensa- REAL Conditioned PF Compensation Setpoint. Conditioning checks to
tionSetpoint make sure input is within PF lag and lead limits.
ConditionedPFSetpoint REAL Conditioned PF Setpoint. Conditioning checks to make sure input is
within PF lag and lead limits.
ConditionedPLimitSet- REAL Conditioned power limit set point. Conditioning checks to make sure
point input is between 0 and PRating.
ConditionedQSetpoint REAL Conditioned reactive power limit set point. Conditioning checks to
make sure input is between leading and lagging QRating.
ConditionedPFRampSet- REAL Conditioned power factor ramp rate set point. Conditioning checks
point to make sure input is between 0 and 1.
ConditionedQRampSet- REAL Conditioned reactive power ramp rate set point. Conditioning checks
point to make sure input is between 0 and ConditionedQRating.
ConditionedPLim- REAL Conditioned real power ramp rate set point. Conditioning checks to
itRampSetpoint make sure input is between 0 and ConditionedPRating.
ConditionedVSetpoint REAL Conditioned voltage set point. Conditioning checks to make sure in-
put is between the VLimitHigh and VLimitLow inputs.
ConditionedPRating REAL Conditioned real power rating. Conditioning checks to make sure
input is greater than 0.
ConditionedQRating REAL Conditioned reactive power rating. Conditioning checks to make sure
input is between lagging and leading reactive power limits.
DownrampEventActive BOOL This output asserts when a downramp event is active. This input will
only assert if the EnableStorageDownrampControl input is asserted.
FrequencyRegulation- BOOL This output asserts if a real power set point is being adjusted due to
EventActive an ongoing frequency regulation event.
StorageDownrampCon- BOOL Storage downramp control is enabled.
trolEnabled

fb_PvInverter (Function Block)


The PV Inverter function block provides the control algorithms and I/O interface for one
photovoltaic inverter in a solar generating facility.

Inputs

Name IEC 61131 Type Description


ConnectToMasterController POINTER Connect this input to a master controller instance.
Offline BOOL Communications channel to the inverter control device is offline (1
= Offline). Default is FALSE.
RemoteEnabled BOOL Inverter control device is available to remote master control. Default
is FALSE.
Fault BOOL Inverter control device is reporting a fault. Default is FALSE.
OnStatus BOOL On/off status of the inverter. Default is FALSE.
OnCommandInput BOOL Command to turn on the inverter control device. Default is FALSE.
OffCommandInput BOOL Command to turn off the inverter control device. Default is FALSE.
Include BOOL Latch to include inverter in the master control. Default is FALSE.
Exclude BOOL Latch to remove inverter from the control. Default is FALSE.
PFModeEnabled BOOL Inverter is in power factor control mode.
QModeEnabled BOOL Inverter is in reactive power control mode.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.17
Function Blocks

Name IEC 61131 Type Description


InverterP REAL Real power output from inverter. Units are kW.
InverterQ REAL Reactive power output from inverter. Units are kVAR.
InverterPF REAL Power factor at inverter (generative +, consumptive –). Units are PF.
InverterPFLagLimit REAL Inverter lagging power factor limit (positive). Default is 0.8. Units
are PF.
InverterPFLeadLimit REAL Inverter leading power factor limit (negative). Default is –0.8. Units
are PF.
PFSetpointFeedback REAL Power factor set point feedback. Units are PF.
QSetpointFeedback REAL Reactive power set point feedback. Units are kVAR.
PLimitSetpointFeedback REAL Power limit set point feedback. Units are kW.
PFRampFeedback REAL Power factor ramp feedback. Units are PF/sec.
QRampFeedback REAL Reactive power ramp feedback. Units are kVAR/sec.
PLimitRampFeedback REAL Power limit ramp feedback. Units are kW/sec.
PRating REAL Power rating for the inverter. Units are kW. Default is 0.
QRating REAL Reactive power rating for the inverter. Units are kVAR. Default is 0.

Outputs

Name IEC 61131 Type Description


IncludedInMasterControl BOOL Inverter is included in master control. Will assert when inverter is on,
included, and not excluded.
OnCommand BOOL Pulse to turn on inverter.
OffCommand BOOL Pulse to turn off inverter.
QuickStop BOOL Asserts to send stop signal to inverter. This output can assert when
required even if the master controller is not enabled.
PFModeCommand BOOL Command to put inverter in power factor mode.
QModeCommand BOOL Command to put inverter in reactive power mode.
PFSetMag REAL Power factor output. Units are PF.
PFTrigger BOOL Power factor trigger (1 = Write).
QSetMag REAL Reactive power output. Units are kVAR.
QTrigger BOOL Reactive power trigger (1 = Write).
PLimitSetMag REAL Power limit output. Units are kW.
PLimitTrigger BOOL Power limit trigger (1 = Write).
PFRampSetMag REAL Power factor ramp output. Units are PF/sec.
PFRampTrigger BOOL Power factor ramp trigger (1 = Write).
QRampSetMag REAL Reactive power ramp output. Units are kVAR/sec.
QRampTrigger REAL Reactive power trigger (1 = Write).
PLimitRampSetMag REAL Power limit ramp output. Units are kW/sec.
PLimitRampTrigger BOOL Power limit ramp trigger (1 = Write).
InputAlarm BOOL One or more inverter inputs are in an invalid state.

The InputAlarm indicates that one or more inverter inputs are in an invalid state. Providing
invalid inputs can result in undesired behavior. The InputAlarm output will assert if any of
the following are true:
ä PFModeEnabled and QModeEnabled are both TRUE.

Date Code 20190830 Instruction Manual Programming Reference


12.18 GridConnect
Function Blocks

ä Inverter is not in correct reactive power mode after three times the master controller’s
ControlRetryPeriod setting.
ä OnCommandInput and OffCommandInput are both TRUE.
ä IncludeCommand and ExcludeCommand are both TRUE.
ä InverterPF, PFSetpointFeedback, InverterPFLagLimit, or InverterPFLeadLimit are
less than –1 or greater than 1.
ä PRating is less than 0.
ä QRating is less than 0.

fb_StorageInverter (Function Block)


The Storage Inverter function block provides the control algorithms and I/O interface for
one storage inverter in a solar generating facility.

Inputs

Name IEC 61131 Type Description


ConnectToMasterCon- POINTER Connect this input to a master controller instance.
troller
Offline BOOL Communications channel to the inverter control device is offline (1 =
Offline). Default is FALSE.
RemoteEnabled BOOL Inverter control device is available to remote master control. Default
is FALSE.
Fault BOOL Inverter control device is reporting a fault. Default is FALSE.
OnStatus BOOL On/off status of the inverter. Default is FALSE.
OnCommandInput BOOL Command to turn on the inverter control device. Default is FALSE.
OffCommandInput BOOL Command to turn off the inverter control device. Default is FALSE.
IncludeCommand BOOL Command to include inverter in the master control. Default is
FALSE.
ExcludeCommand BOOL Command to remove inverter from the control. Default is FALSE.
PFModeEnabled BOOL Inverter is in power factor control mode.
QModeEnabled BOOL Inverter is in reactive power control mode.
InverterP REAL Real power output from inverter. Units are kW.
InverterQ REAL Reactive power output from inverter. Units are kVAR.
InverterPF REAL Power factor at inverter (generative +, consumptive –). Units are PF.
InverterPFLagLimit REAL Inverter lagging power factor limit (positive). Default is 0.8. Units
are PF.
InverterPFLeadLimit REAL Inverter leading power factor limit (negative). Default is –0.8. Units
are PF.
PFSetpointFeedback REAL Power factor set point feedback. Units are PF.
QSetpointFeedback REAL Reactive power set point feedback. Units are kVAR.
PSetpointFeedback REAL Real power set point feedback. 0 to +PRating indicate battery charg-
ing (consume kW), and 0 to –PRating indicate battery discharge (out-
put kW). Units are kW.
PFRampFeedback REAL Power factor ramp feedback. Units are PF/sec.
PRampFeedback REAL Real power ramp feedback. Units are kW/sec.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.19
Function Blocks

Name IEC 61131 Type Description


QRampFeedback REAL Reactive power ramp feedback. Units are kVAR/sec.
PRating REAL Power rating for the inverter. Units are kW. Default is 0.
QRating REAL Reactive power rating for the inverter. Units are kVAR. Default is 0.

Outputs

Name IEC 61131 Type Description


IncludedInMasterControl BOOL Inverter is included in master control. Will assert when inverter is on,
included, and not excluded.
OnCommand BOOL Pulse to turn on inverter.
OffCommand BOOL Pulse to turn off inverter.
QuickStop BOOL Asserts to send stop signal to inverter. This output can assert when
required even if the master controller is not enabled.
PFModeCommand BOOL Command to put inverter in power factor mode.
QModeCommand BOOL Command to put inverter in reactive power mode.
PFSetMag REAL Power factor output. Units are PF.
PFTrigger BOOL Power factor trigger (1 = Write).
QSetMag REAL Reactive power output. Units are kVAR.
QTrigger BOOL Reactive power trigger (1 = Write).
PLimitSetMag REAL Power limit output. Units are kW.
PLimitTrigger BOOL Power limit trigger (1 = Write).
PFRampSetMag REAL Power factor ramp output. Units are PF/sec.
PFRampTrigger BOOL Power factor ramp trigger (1 = Write).
QRampSetMag REAL Reactive power ramp output. Units are kVAR/sec.
QRampTrigger REAL Reactive power trigger (1 = Write).
PLimitRampSetMag REAL Power limit ramp output. Units are kW/sec.
PLimitRampTrigger BOOL Power limit ramp trigger (1 = Write).
InputAlarm BOOL One or more inverter inputs are in an invalid state.

The InputAlarm indicates that one or more inverter inputs are in an invalid state. Providing
invalid inputs can result in undesired behavior. The InputAlarm output will assert if any of
the following are true:
ä PFModeEnabled and QModeEnabled are both TRUE.
ä Inverter is not in correct reactive power mode after three times the master controller’s
ControlRetryPeriod setting.
ä OnCommandInput and OffCommandInput are both TRUE.
ä IncludeCommand and ExcludeCommand are both TRUE.
ä InverterPF, PFSetpointFeedback, InverterPFLagLimit, or InverterPFLeadLimit are
less than –1 or greater than 1.
ä PRating is less than 0.
ä QRating is less than 0.

Date Code 20190830 Instruction Manual Programming Reference


12.20 GridConnect
Function Blocks

fb_Capacitor (Function Block)


The Capacitor Control function block provides the control algorithms and I/O interface for
one capacitor in a solar generating facility.

Inputs

Name IEC 61131 Type Description


ConnectToMasterCon- POINTER Connect this input to a master controller instance.
troller
Offline BOOL Communications channel to the capacitor control device is offline (1
= Offline). Default is FALSE.
RemoteEnabled BOOL Capacitor control device is available to remote master control (1 =
Remote). Default is FALSE.
Fault BOOL Capacitor control device is reporting a fault (1 = Fault). Default is
FALSE.
OnStatus BOOL On/off status of the capacitor. Default is FALSE.
OnCommandInput BOOL Command to turn on the capacitor. Default is FALSE.
OffCommandInput BOOL Command to turn off the capacitor. Default is FALSE.
IncludeCommand BOOL Command to include capacitor in the master control. Default is
FALSE.
ExcludeCommand BOOL Command to remove capacitor from the master control. Default is
FALSE.
CapacitorV REAL Voltage at the capacitor terminals. Units are kV. Default is 0.
QRating REAL Reactive power rating of the capacitor. Units are kVAR. Default is 0.
VRating REAL Voltage rating of the capacitor. Units are kV. Default is 0.
SequenceNumber UINT Capacitor is dependent on another capacitor being closed first. De-
fault is 0.
ä 0 = Cap is not dependent on other Caps.
ä 1 = Cap is the first to be turned on and the last to be turned off.
ä 2 = Cap will only be turned on if Caps with a sequence number
of 1 is ON first.
ä 3 = Follows 2.
ä ...
ä g_c_CAP_MAX = Follows g_c_CAP_MAX – 1.

Outputs

Name IEC 61131 Type Description


IncludedInMasterControl BOOL Capacitor is included in master control. Will assert when capacitor
is included and not excluded.
OnCommand BOOL Pulse to turn on capacitor.
OffCommand BOOL Pulse to turn off capacitor.

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.21
Examples

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Modeling a Solar Generation Facility


Objective
A user has a solar facility that needs to be controlled. The facility is laid out as shown in
Figure 12.3.

Utility

POI

inverter 1

inverter 2 capacitor 1 capacitor 2

storage 1

storage 2
Figure 12.3 Solar Facility One-Line Diagram

Data Source Assumptions


Typically, all inputs to the function blocks used in this model would be connected to data
from an incoming communication channel. However, to make the illustration of this ex-
ample more clear, all inputs are contained in Global Variable Lists.

Date Code 20190830 Instruction Manual Programming Reference


12.22 GridConnect
Examples

Solution
Once the user has identified all the elements of the model and decided the source for all
required data, the only work remaining is to construct the model in a program as shown in
Code Snippet 12.1.

Code Snippet 12.1 prg_GridConnectMain


VAR
MasterController : fb_MasterPlantController;
Inverter1, Inverter2 : fb_PvInverter;
Storage1, Storage2 : fb_StorageInverter;
Capacitor1, Capacitor2 : fb_Capacitor;
hasRunOnce : BOOL;
END_VAR

(**** SETTINGS ****)


IF NOT hasRunOnce THEN
MasterController.QDeadband := 0; // kVAR
MasterController.QKp := 0.4;
MasterController.QKi := 0.04;
MasterController.QLimitHigh := 3000; // kVAR
MasterController.QLimitLow := -1300; // kVAR

MasterController.PFDeadband := 0.001; // PF
MasterController.PFKp := 0.2;
MasterController.PFKi := 0;
MasterController.PFLagLimit := 0.8; // PF
MasterController.PFLeadLimit := -0.8; // PF
MasterController.PFCompensationSetpoint := 1.0; // Unity PF
MasterController.PFCompensationLowPowerCutoff := 15; // 15%
MasterController.PFCompensationGradient := -0.002; // PF / %kW
MasterController.PFCompensationLowPFLimit := 0.8; // +- 0.8 PF

MasterController.VDeadband := 0.05; // kV
MasterController.VKp := 0.3;
MasterController.VKi := 0.03;
MasterController.VLimitHigh := 42; // kV
MasterController.VLimitLow := 38; // kV
MasterController.dV_dQ := 0.0002; // kW/kVAR
MasterController.VCompensationV1 := 38; // kV
MasterController.VCompensationV2 := 40;
MasterController.VCompensationV3 := 40;
MasterController.VCompensationV4 := 41;
MasterController.VCompensationQ1 := 2000; // kVAR
MasterController.VCompensationQ2 := 0;
MasterController.VCompensationQ3 := 0;
MasterController.VCompensationQ4 := -2000;

MasterController.FRegulationF1 := 59; // Hz
MasterController.FRegulationF2 := 59.7;
MasterController.FRegulationF3 := 60.3;
MasterController.FRegulationF4 := 61;
MasterController.FRegulationP1 := 10; // % of plant rated kW
MasterController.FRegulationP2 := 0;
MasterController.FRegulationP3 := 0;
MasterController.FRegulationP4 := -10;

MasterController.PDeadband := 2; // kW

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.23
Examples

MasterController.PKp := 0.4;
MasterController.PKi := 0.04;

MasterController.PFRampSetpoint := 0.02; // PF/sec


MasterController.QRampSetpoint := 20;
MasterController.PLimitRampSetpoint := 50;
MasterController.PLimitDelay := T#60S;

MasterController.PlantPRating := 1000; // 1MW


MasterController.PlantQRating := 8000; // 800 kVAR
MasterController.PlantLowPowerCutoff := 5; // kW
MasterController.EvaluationPeriod := T#1S;
MasterController.ControlRetryPeriod := T#2S;
MasterController.CapacitorOperationPeriod := T#120S;
MasterController.InverterModeChangeControlDelay := T#30S;

// Inverter 1 Settings
Inverter1.IncludeCommand := TRUE;
Inverter1.ExcludeCommand := FALSE;
Inverter1.InverterPFLagLimit := 0.8;
Inverter1.InverterPFLeadLimit := -0.8;
Inverter1.PRating := 500; // kW
Inverter1.QRating := 450; // kVAR

// Inverter 2 Settings
Inverter2.IncludeCommand := TRUE;
Inverter2.ExcludeCommand := FALSE;
Inverter2.InverterPFLagLimit := 0.8;
Inverter2.InverterPFLeadLimit := -0.8;
Inverter2.PRating := 500; // kW
Inverter2.QRating := 450; // kVAR

// Battery 1 settings
Storage1.IncludeCommand := TRUE;
Storage1.ExcludeCommand := FALSE;
Storage1.InverterPFLagLimit := 0.8;
Storage1.InverterPFLeadLimit := -0.8;
Storage1.PRating := 200; // kW
Storage1.QRating := 150; // kVAR

// Battery 2 settings
Storage2.IncludeCommand := TRUE;
Storage2.ExcludeCommand := FALSE;
Storage2.InverterPFLagLimit := 0.8;
Storage2.InverterPFLeadLimit := -0.8;
Storage2.PRating := 200; // kW
Storage2.QRating := 150; // kVAR

// Capacitor 1 Settings
Capacitor1.IncludeCommand := TRUE;
Capacitor1.ExcludeCommand := FALSE;
Capacitor1.QRating := 200; // kVAR
Capacitor1.VRating := 7.2; // kW
Capacitor1.SequenceNumber := 0; // First to turn on

// Capacitor 2 Settings
Capacitor2.IncludeCommand := TRUE;
Capacitor2.ExcludeCommand := FALSE;
Capacitor2.QRating := 200; // kVAR

Date Code 20190830 Instruction Manual Programming Reference


12.24 GridConnect
Examples

Capacitor2.VRating := 7.2; // kW
Capacitor2.SequenceNumber := 0; // First to turn on

hasRunOnce := TRUE;
END_IF

(**** MODE, STATUS, AND SET POINT CONTROLS ****)


MasterController.ControlMode :=
DINT_TO_INT(vtl_PlantControls.ReactiveControlMode.stVal);
MasterController.PLimitMode := DINT_TO_INT(vtl_PlantControls.RealPowerMode.stVal);
MasterController.Enable := vtl_PlantControls.Enable.stVal;
MasterController.EnableStorageDownrampControl := vtl_PlantControls.EnableDownrampControl.stVal;
MasterController.EmergencyStop := vtl_PlantControls.EmergencyStop.stVal;

MasterController.QSetpoint := vtl_PlantControls.QSetpoint.instMag;

MasterController.PFSetpoint := vtl_PlantControls.PFSetpoint.instMag;

MasterController.VSetpoint := vtl_PlantControls.VSetpoint.instMag;

MasterController.PSetpoint := vtl_PlantControls.PSetpoint.instMag;
MasterController.StoragePSetpoint := vtl_PlantControls.StoragePSetpoint.instMag;

(**** I/O ****)


// Master Controller I/O
MasterController.PlantP := vtl_POIData.PlantP.instCVal.mag;
MasterController.PlantQ := vtl_POIData.PlantQ.instCVal.mag;
MasterController.PlantPF := vtl_POIData.PlantPF.instCVal.mag;
MasterController.PlantV := vtl_POIData.PlantV.instCVal.mag;
MasterController.PlantF := vtl_POIData.PlantF.instCVal.mag;
MasterController.PlantMeasurementsGood := vtl_POIData.IsPoiDataGood.stVal;

// Inverter 1 I/O
Inverter1.Offline := vtl_InverterData.IsInverter1Offline.stVal;
Inverter1.RemoteEnabled := vtl_InverterData.IsInverter1RemoteEnabled.stVal;
Inverter1.Fault := vtl_InverterData.IsInverter1InFaultedState.stVal;
Inverter1.OnStatus := vtl_InverterData.IsInverter1On.stVal;
Inverter1.PFModeEnabled := vtl_InverterData.IsInverter1InPFMode.stVal;
Inverter1.QModeEnabled := vtl_InverterData.IsInverter1InQMode.stVal;
Inverter1.InverterP := DINT_TO_REAL(vtl_InverterData.Inverter1P.stVal);
Inverter1.InverterQ := DINT_TO_REAL(vtl_InverterData.Inverter1Q.stVal);
Inverter1.InverterPF := DINT_TO_REAL(vtl_InverterData.Inverter1PF.stVal)/1000;
Inverter1.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter1PFSetpointFeedback.stVal)/1000;
Inverter1.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter1QSetpointFeedback.stVal);
Inverter1.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter1PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Inverter1PackedControls.stVal.0 := Inverter1.OnCommand;
vtl_InverterData.Inverter1PackedControls.stVal.1 := Inverter1.OffCommand;
vtl_InverterData.Inverter1PackedControls.stVal.2 := Inverter1.EmergencyStop;
vtl_InverterData.Inverter1PackedControls.stVal.3 := Inverter1.PFModeCommand;
vtl_InverterData.Inverter1PackedControls.stVal.4 := Inverter1.QModeCommand;
vtl_InverterData.Inverter1PFSetpoint.oper.setMag := Inverter1.PFSetMag*1000; // Move significant
figures left of decimal
vtl_InverterData.Inverter1PFSetpoint.oper.trigger := Inverter1.PFTrigger;
vtl_InverterData.Inverter1QSetpoint.oper.setMag := Inverter1.QSetMag;
vtl_InverterData.Inverter1QSetpoint.oper.trigger := Inverter1.QTrigger;

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.25
Examples

vtl_InverterData.Inverter1PSetpoint.oper.setMag := Inverter1.PLimitSetMag;
vtl_InverterData.Inverter1PSetpoint.oper.trigger := Inverter1.PLimitTrigger;
vtl_InverterData.Inverter1PFRampSetpoint.oper.setMag := Inverter1.PFRampSetMag;
vtl_InverterData.Inverter1PFRampSetpoint.oper.trigger := Inverter1.PFRampTrigger;
vtl_InverterData.Inverter1QRampSetpoint.oper.setMag := Inverter1.QRampSetMag;
vtl_InverterData.Inverter1QRampSetpoint.oper.trigger := Inverter1.QRampTrigger;
vtl_InverterData.Inverter1PRampSetpoint.oper.setMag := Inverter1.PLimitRampSetMag;
vtl_InverterData.Inverter1PRampSetpoint.oper.trigger := Inverter1.PLimitRampTrigger;

// Inverter 2 I/O
Inverter2.Offline := vtl_InverterData.IsInverter2Offline.stVal;
Inverter2.RemoteEnabled := vtl_InverterData.IsInverter2RemoteEnabled.stVal;
Inverter2.Fault := vtl_InverterData.IsInverter2InFaultedState.stVal;
Inverter2.OnStatus := vtl_InverterData.IsInverter2On.stVal;
Inverter2.PFModeEnabled := vtl_InverterData.IsInverter2InPFMode.stVal;
Inverter2.QModeEnabled := vtl_InverterData.IsInverter2InQMode.stVal;
Inverter2.InverterP := DINT_TO_REAL(vtl_InverterData.Inverter2P.stVal);
Inverter2.InverterQ := DINT_TO_REAL(vtl_InverterData.Inverter2Q.stVal);
Inverter2.InverterPF := DINT_TO_REAL(vtl_InverterData.Inverter2PF.stVal)/1000;
Inverter2.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter2PFSetpointFeedback.stVal)/1000;
Inverter2.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter2QSetpointFeedback.stVal);
Inverter2.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Inverter2PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Inverter2PackedControls.stVal.0 := Inverter2.OnCommand;
vtl_InverterData.Inverter2PackedControls.stVal.1 := Inverter2.OffCommand;
vtl_InverterData.Inverter2PackedControls.stVal.2 := Inverter2.EmergencyStop;
vtl_InverterData.Inverter2PackedControls.stVal.3 := Inverter2.PFModeCommand;
vtl_InverterData.Inverter2PackedControls.stVal.4 := Inverter2.QModeCommand;
vtl_InverterData.Inverter2PFSetpoint.oper.setMag := Inverter2.PFSetMag * 1000; // Move significant
figures left of decimal
vtl_InverterData.Inverter2PFSetpoint.oper.trigger := Inverter2.PFTrigger;
vtl_InverterData.Inverter2QSetpoint.oper.setMag := Inverter2.QSetMag;
vtl_InverterData.Inverter2QSetpoint.oper.trigger := Inverter2.QTrigger;
vtl_InverterData.Inverter2PSetpoint.oper.setMag := Inverter2.PLimitSetMag;
vtl_InverterData.Inverter2PSetpoint.oper.trigger := Inverter2.PLimitTrigger;
vtl_InverterData.Inverter2PFRampSetpoint.oper.setMag := Inverter2.PFRampSetMag;
vtl_InverterData.Inverter2PFRampSetpoint.oper.trigger := Inverter2.PFRampTrigger;
vtl_InverterData.Inverter2QRampSetpoint.oper.setMag := Inverter2.QRampSetMag;
vtl_InverterData.Inverter2QRampSetpoint.oper.trigger := Inverter2.QRampTrigger;
vtl_InverterData.Inverter2PRampSetpoint.oper.setMag := Inverter2.PLimitRampSetMag;
vtl_InverterData.Inverter2PRampSetpoint.oper.trigger := Inverter2.PLimitRampTrigger;

// Battery 1 I/O
Storage1.Offline := vtl_InverterData.IsStorage1Offline.stVal;
Storage1.RemoteEnabled := vtl_InverterData.IsStorage1RemoteEnabled.stVal;
Storage1.Fault := vtl_InverterData.IsStorage1InFaultedState.stVal;
Storage1.OnStatus := vtl_InverterData.IsStorage1On.stVal;
Storage1.PFModeEnabled := vtl_InverterData.IsStorage1InPFMode.stVal;
Storage1.QModeEnabled := vtl_InverterData.IsStorage1InQMode.stVal;
Storage1.InverterP := DINT_TO_REAL(vtl_InverterData.Storage1P.stVal);
Storage1.InverterQ := DINT_TO_REAL(vtl_InverterData.Storage1Q.stVal);
Storage1.InverterPF := DINT_TO_REAL(vtl_InverterData.Storage1PF.stVal)/1000;
Storage1.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage1PFSetpointFeedback.stVal)/1000;
Storage1.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage1QSetpointFeedback.stVal);

Date Code 20190830 Instruction Manual Programming Reference


12.26 GridConnect
Examples

Storage1.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage1PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Storage1PackedControls.stVal.0 := Storage1.OnCommand;
vtl_InverterData.Storage1PackedControls.stVal.1 := Storage1.OffCommand;
vtl_InverterData.Storage1PackedControls.stVal.2 := Storage1.EmergencyStop;
vtl_InverterData.Storage1PackedControls.stVal.3 := Storage1.PFModeCommand;
vtl_InverterData.Storage1PackedControls.stVal.4 := Storage1.QModeCommand;
vtl_InverterData.Storage1PFSetpoint.oper.setMag := Storage1.PFSetMag * 1000; // Move significant
figures left of decimal
vtl_InverterData.Storage1PFSetpoint.oper.trigger := Storage1.PFTrigger;
vtl_InverterData.Storage1QSetpoint.oper.setMag := Storage1.QSetMag;
vtl_InverterData.Storage1QSetpoint.oper.trigger := Storage1.QTrigger;
vtl_InverterData.Storage1PSetpoint.oper.setMag := Storage1.PLimitSetMag;
vtl_InverterData.Storage1PSetpoint.oper.trigger := Storage1.PLimitTrigger;
vtl_InverterData.Storage1PFRampSetpoint.oper.setMag := Storage1.PFRampSetMag;
vtl_InverterData.Storage1PFRampSetpoint.oper.trigger := Storage1.PFRampTrigger;
vtl_InverterData.Storage1QRampSetpoint.oper.setMag := Storage1.QRampSetMag;
vtl_InverterData.Storage1QRampSetpoint.oper.trigger := Storage1.QRampTrigger;
vtl_InverterData.Storage1PRampSetpoint.oper.setMag := Storage1.PLimitRampSetMag;
vtl_InverterData.Storage1PRampSetpoint.oper.trigger := Storage1.PLimitRampTrigger;

// Battery 2 I/O
Storage2.Offline := vtl_InverterData.IsStorage2Offline.stVal;
Storage2.RemoteEnabled := vtl_InverterData.IsStorage2RemoteEnabled.stVal;
Storage2.Fault := vtl_InverterData.IsStorage2InFaultedState.stVal;
Storage2.OnStatus := vtl_InverterData.IsStorage2On.stVal;
Storage2.PFModeEnabled := vtl_InverterData.IsStorage2InPFMode.stVal;
Storage2.QModeEnabled := vtl_InverterData.IsStorage2InQMode.stVal;
Storage2.InverterP := DINT_TO_REAL(vtl_InverterData.Storage2P.stVal);
Storage2.InverterQ := DINT_TO_REAL(vtl_InverterData.Storage2Q.stVal);
Storage2.InverterPF := DINT_TO_REAL(vtl_InverterData.Storage2PF.stVal)/1000;
Storage2.PFSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage2PFSetpointFeedback.stVal)/1000;
Storage2.QSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage2QSetpointFeedback.stVal);
Storage2.PLimitSetpointFeedback :=
DINT_TO_REAL(vtl_InverterData.Storage2PLimitSetpointFeedback.stVal);
//NOTE: No ramp feedback available from inverters
vtl_InverterData.Storage2PackedControls.stVal.0 := Storage2.OnCommand;
vtl_InverterData.Storage2PackedControls.stVal.1 := Storage2.OffCommand;
vtl_InverterData.Storage2PackedControls.stVal.2 := Storage2.EmergencyStop;
vtl_InverterData.Storage2PackedControls.stVal.3 := Storage2.PFModeCommand;
vtl_InverterData.Storage2PackedControls.stVal.4 := Storage2.QModeCommand;
vtl_InverterData.Storage2PFSetpoint.oper.setMag := Storage2.PFSetMag * 1000; // Move significant
figures left of decimal
vtl_InverterData.Storage2PFSetpoint.oper.trigger := Storage2.PFTrigger;
vtl_InverterData.Storage2QSetpoint.oper.setMag := Storage2.QSetMag;
vtl_InverterData.Storage2QSetpoint.oper.trigger := Storage2.QTrigger;
vtl_InverterData.Storage2PSetpoint.oper.setMag := Storage2.PLimitSetMag;
vtl_InverterData.Storage2PSetpoint.oper.trigger := Storage2.PLimitTrigger;
vtl_InverterData.Storage2PFRampSetpoint.oper.setMag := Storage2.PFRampSetMag;
vtl_InverterData.Storage2PFRampSetpoint.oper.trigger := Storage2.PFRampTrigger;
vtl_InverterData.Storage2QRampSetpoint.oper.setMag := Storage2.QRampSetMag;
vtl_InverterData.Storage2QRampSetpoint.oper.trigger := Storage2.QRampTrigger;
vtl_InverterData.Storage2PRampSetpoint.oper.setMag := Storage2.PLimitRampSetMag;
vtl_InverterData.Storage2PRampSetpoint.oper.trigger := Storage2.PLimitRampTrigger;

Programming Reference Instruction Manual Date Code 20190830


GridConnect 12.27
Examples

// Capacitor 1 I/O
Capacitor1.Offline := vtl_CapacitorData.IsCapacitor1Offline.stVal;
Capacitor1.RemoteEnabled := vtl_CapacitorData.IsCapacitor1RemoteEnabled.stVal;
Capacitor1.Fault := vtl_CapacitorData.IsCapacitor1InFaultedState.stVal;
Capacitor1.OnStatus := vtl_CapacitorData.IsCapacitor1On.stVal;
Capacitor1.CapacitorV :=
DINT_TO_REAL(vtl_CapacitorData.Capacitor1Voltage.stVal);
vtl_CapacitorData.Capacitor1On.operPulse.ctlVal := Capacitor1.OnCommand;
vtl_CapacitorData.Capacitor1Off.operPulse.ctlVal := Capacitor1.OffCommand;

// Capacitor 2 I/O
Capacitor2.Offline := vtl_CapacitorData.IsCapacitor2Offline.stVal;
Capacitor2.RemoteEnabled := vtl_CapacitorData.IsCapacitor2RemoteEnabled.stVal;
Capacitor2.Fault := vtl_CapacitorData.IsCapacitor2InFaultedState.stVal;
Capacitor2.OnStatus := vtl_CapacitorData.IsCapacitor2On.stVal;
Capacitor2.CapacitorV :=
DINT_TO_REAL(vtl_CapacitorData.Capacitor2Voltage.stVal);
vtl_CapacitorData.Capacitor2On.operPulse.ctlVal := Capacitor2.OnCommand;
vtl_CapacitorData.Capacitor2Off.operPulse.ctlVal := Capacitor2.OffCommand;

(**** FUNCTION BLOCK EXECUTION ****)


MasterController();
Inverter1(ConnectToMasterController := MasterController.ConnectToPlantDevices);
Inverter2(ConnectToMasterController := MasterController.ConnectToPlantDevices);
Storage1(ConnectToMasterController := MasterController.ConnectToPlantDevices);
Storage2(ConnectToMasterController := MasterController.ConnectToPlantDevices);
Capacitor1(ConnectToMasterController := MasterController.ConnectToPlantDevices);

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 13

IPAliasRedundancy
Introduction
This library provides functionality to manage an additional IP alias (a second IP address)
added to a specified interface on an SEL Real-Time Automation Controller (RTAC). The
function blocks in this library are designed to work in a redundancy scheme by using an IP
alias to be shared between two RTAC units. The two RTAC units will communicate with
each other via the logic in this library to decide when the IP alias should and should not be
active on the specified interface. The primary IP address for interfaces on the RTAC are
still configured via the web interface.
The two RTACs managing the IP alias communicate via an Ethernet or serial connection.
The library only supports the use of one or the other connection type (do not use both si-
multaneously). If the RTACs communicate via Ethernet, it is recommended that a separate
interface than the managed interface is used for communications. (This is not an absolute
requirement—the two RTACs can communicate via the same interface that is being man-
aged—see Frequently Asked Questions on page 13.2 for details.) Information between the
two RTACs is updated at least once a second regardless of which connection is used.
The redundancy logic operates in two modes. The first is a primary-primary mode, in which
the detection of a failover condition causes the IP alias to activate on the inactive unit. In this
mode, the previously inactive unit will become the primary unit. If the previous primary
unit becomes available again, it will be the inactive unit and must wait for a condition to
occur in which the IP alias will become active. The second mode is a primary-backup
mode, in which the backup unit is designated on the function block. In this mode, if the
primary unit is no longer available, the backup unit will activate the IP alias. When the
primary unit is available again and reestablishes communication to the backup unit, the IP
alias on the backup unit will be deactivated and that IP alias will be returned to the primary
unit.
The function blocks in this library offer a maintenance mode in which the unit will no longer
participate in the IP alias redundancy logic. If the IP alias is currently active on the unit
when maintenance mode is activated, it will be transferred to the other unit. Maintenance
mode persists through project settings changes and power cycles. This mode allows for
configuration changes or testing to be performed without affecting communication on the
other unit participating in the redundancy scheme.
The following conditions will cause the IP address to activate on the standby unit:
ä Managed Ethernet interface loss of link
ä Loss of communication between RTACs (note that a unit with a broken communi-
cations cable looks the same to the standby unit as a unit that has lost power)
ä Maintenance mode is activated

Date Code 20190830 Instruction Manual Programming Reference


13.2 IPAliasRedundancy
Introduction

Frequently Asked Questions


Where do I configure the IP alias?
The IP alias is configured as an input on the function block. The IP alias cannot be added
through the web interface or any other settings mechanism. If the user wishes to add other
IP aliases for other functionality, refer to the ACSELERATOR RTAC® SEL-5033 Instruction
Manual for information about the IEC 61131 functions that manage IP aliases.

How long does the IP alias last?


The IP alias in this configuration is managed by the library. If it is detected that both RTAC
units have the alias active, one unit will deactivate its alias. IP aliases do not last through
power cycles, so when the RTAC first starts up it will negotiate with the second RTAC about
which unit should activate the IP alias (provided it is able to communicate with the other
RTAC). The IP alias will remain through project send. If maintenance mode is activated,
the IP alias will be deactivated on the RTAC unit.

Is the interface on which the alias is being managed turned on and


off?
No, the interface with a managed IP alias will always maintain a link connection. The
Ethernet port will have more than one IP address active when the alias is active. The IP
address that is configured via the RTAC webpage will always be active.

Can the managed IP alias interface be the same interface used to


communicate with the other RTAC unit?
Yes, the same interface can be used to both manage an IP alias and communicate with the
redundant RTAC. However, SEL recommends using a separate interface to communicate
with the redundant RTAC to increase the robustness of the redundancy scheme.

Can the IP alias logic work with different RTAC hardware variants
such as the SEL-3530 and SEL-3555?
Yes, the interface control logic will work between any two RTACs of any hardware combi-
nations. This includes any combination of RTAC hardware variants including the SEL-2240
Axion.

Why does RtacEthernetCommsGood not assert?


If you have trouble establishing the Ethernet link between the two RTACs, check the fol-
lowing:
ä Confirm both RTACs are configured in the same subnet.
ä Confirm both RTACs are connected to the network.

Programming Reference Instruction Manual Date Code 20190830


IPAliasRedundancy 13.3
Introduction

ä Confirm IP addresses configured on the interface Control blocks.


ä Confirm that the setting “LocalAPPort” matches the port number in the Ethernet
Listening access point that was added to the RTAC configuration.

Why does RtacSerialCommsGood not assert?


If you have trouble establishing serial communications between two RTACs, check the
following:
ä Confirm that the LocalSerialPort setting does not conflict with any other configured
serial ports in the RTAC configuration. If there is a conflict, error messages are not
generated as they are for other serial port conflicts.
ä Confirm that the cable connections are secure.
ä Confirm that the cable is wired correctly. Reference each RTAC hardware instruction
manual to ensure the pinout is correct. The connection is designed to use RS-232.
The user is not responsible for configuring any additional parameters other than the
physical serial port connections.

Why is my project unstable when I am trying to use a serial


connection?
If the LocalSerialPort setting is configured to a port number that does not exist on the
hardware being used, the RTAC will not run correctly.

Why does IPAliasActive not activate or deactivate exactly at the


time specified by the input CommStatusTimeout?
The library will detect failover conditions based on the CommStatusTimeout input. Once
the specified time-out has occurred, the library will take the actions to activate or deac-
tivate the IP alias. This involves reading system diagnostics and changing IP addresses
with the operating system. These actions do not occur as quickly as contact I/O or other
protocol operations. I/O and protocol actions usually occur in hundreds of milliseconds or
less. Making changes to IP addresses on the RTAC will fluctuate between approximately
one and five seconds. System updates for IP address link status occur on a five-second in-
terval. For CommStatusTimeout inputs that are less than five seconds, there will be some
variation (as much as 5 seconds) in the time that the IP alias actions occur. For CommSta-
tusTimeout inputs that are greater than five seconds, the variation should be less than one
second in most cases. Task cycle time, system burden, and processing power will all affect
the end failover time in small amounts. To obtain a failover time as close as possible to the
specified CommStatusTimeout value, make sure the CPU burden percentage is less than
80 percent. The failover functionality for IP address redundancy is intended for SCADA
and HMI redundancy-type applications. This library is not intended for applications that
require high-accuracy IP alias failover in less than two seconds.

Date Code 20190830 Instruction Manual Programming Reference


13.4 IPAliasRedundancy
Supported Firmware Versions

How will other devices reach the IP alias if it is in a different


subnetwork from the primary IP alias on the controlled interface?
If the IP alias is not in the same subnetwork as the primary IP address, you can add a static
route in the RTAC web interface on the Static Routes page to allow traffic to reach your
IP alias. Refer to the ACSELERATOR RTAC Instruction Manual for more information.

Special Considerations
ä Copying function blocks from this library causes unwanted behavior. This means
the following:
1. The assignment operator “:=” must not be used on any function block from
this library; consider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler


error such as:
// "C0328: Assignment not allowed for type
class_IpAliasRedundancyObject"
myIpAliasRedundancyObject := otherIpAliasRedundancyObject;

// This is fine
someVariable := myIpAliasRedundancyObject.value;
// As is this
pt_myIpAliasRedundancyObject :=
ADR(myIpAliasRedundancyObject);

2. Function blocks from this library must never be VAR_INPUT or VAR_OUT-


PUT members in function blocks, functions, or methods. Place them in the
VAR_IN_OUT section or use pointers instead.
ä Function blocks 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).
ä The two RTACs managing the IP alias can communicate with each other through use
of either an Ethernet or a serial connection. These connections are not designed to
be used simultaneously. Doing so may cause undesired behavior.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R140 or higher.
Versions 3.5.0.3 and older can be used on RTAC firmware version R140 and higher.

Programming Reference Instruction Manual Date Code 20190830


IPAliasRedundancy 13.5
Function Blocks

Function Blocks
This library provides two function blocks. Both function blocks provide the same redun-
dancy functionality. The InterfaceControlWithSerialCheck function block allows for the
same redundancy configuration to be applied to two RTACs, and the logic will identify
which IP address and behavior should be associated with which RTAC based upon the
supplied RTAC serial numbers.

fb_InterfaceControl (Function Block)


This function block is designed to control the IP alias on a given interface on the RTAC
unit. It will communicate with another function block on a separate RTAC unit to determine
which RTAC unit should have the active IP alias. Each function block must have unique
parameters to ensure communications on each project configuration.
This function block works together with an access point. When using this function block,
add an Ethernet incoming (listens for connections) access point. The network connection
type will be Raw TCP and the local port number setting needs to match the LocalAPPort
setting on the function block.

Inputs
Name IEC 61131 Type Description
ControlledInterface enum_interface_ID Interface that will be managed with Con-
trolledIPAlias
ControlledIPAlias STRING(18) IP address and CIDR value that will be man-
aged on the ControlledInterface pin
Backup BOOL If TRUE, the unit will operate in backup mode.
If FALSE, the unit will operate in primary
mode.
RemoteRtacIP STRING(15) IP address of remote RTAC
RemoteRtacPort UINT Port number of the other RTAC. This setting
needs to match the LocalAPPort setting on the
remote RTAC
LocalAPPort UINT Port number for RTAC-to-RTAC communica-
tions on the unit. This setting needs to match
the listening access point that is configured.
LocalClientConnectPort UINT Port number for the RTAC to use to create a
TCP connection to the remote RTAC (29459
by default)
LocalSerialPort UINT The communications port that will be used to
communicate with the other RTAC
CommStatusTimeout TIME The amount of time for which the RTAC will
activate the IP alias when RTAC-to-RTAC
communications is lost. This setting has a
range of 500 ms to 1 hour.
EnterMaintenanceMode BOOL This pin on a rising edge will activate main-
tenance mode. When the unit is in mainte-
nance mode, it will not participate in redun-
dancy logic.

Date Code 20190830 Instruction Manual Programming Reference


13.6 IPAliasRedundancy
Function Blocks

ExitMaintenanceMode BOOL This pin on a rising edge will remove the unit
from maintenance mode and allow the unit to
participate in managing the IP alias
InterfaceLinkStatus SPS Connect to the system tags Ethernet link sta-
tus, which shows the current value of the man-
aged interface

Outputs
Name IEC 61131 Type Description
IPAliasActive BOOL This pin shows if the IP address that is as-
signed on “ControlledIPAlias” is active on
the RTAC unit
MaintenanceMode BOOL This pin shows if the unit is currently in
maintenance mode. If the unit is in mainte-
nance mode, the RTAC will not participate
in redundancy logic. Maintenance mode
persists through power cycle and settings
changes on the unit. Once the unit is set to
exit maintenance mode it will participate in
the redundancy scheme of the “Controlled-
InterfaceIP”.
RtacEthernetCommsGood BOOL If both RTAC connections are communicat-
ing via the Ethernet connection, this pin will
be set to TRUE
RtacSerialCommsGood BOOL If both RTAC connections are communicat-
ing via the serial connection, this pin will be
set to TRUE
InvalidInputPin STRING Lists an incorrectly configured input pin

fb_InterfaceControlWithSerialCheck (Function Block)


This function block is designed to control the IP alias on a given interface on the RTAC
unit. It will communicate with another function block on a separate RTAC unit to determine
which RTAC unit should have the active IP alias. Each function block will have the exact
same configuration and the logic will associate functionality for each RTAC unit based on
the serial numbers of each RTAC unit as inputs to the logic.
This function block works together with an access point. When using this function block,
add an Ethernet incoming (listens for connections) access point. The network connection
type will be Raw TCP and the local port number setting must match the LocalAPPort
setting on the function block.

Programming Reference Instruction Manual Date Code 20190830


IPAliasRedundancy 13.7
Function Blocks

Inputs
Name IEC 61131 Type Description
ControlledInterface enum_interface_ID The interface that will be managed with the
ControlledIPAlias
ControlledIPAlias String(18) The IP address and CIDR value that will be
managed by the Controlled_Interface pin
SerialNumber String(80) The serial number of the unit on which redun-
dancy logic will operate
Backup BOOL If this is true, the unit will operate in backup
mode. If false, the unit will operate in primary
mode.
RemoteRtacIP STRING(15) IP address of the remote RTAC
RemoteRtacPort UINT Port number of the remote RTAC. This setting
must match the LocalAPPort setting on the re-
mote RTAC.
LocalAPPort UINT Port number for RTAC-to-RTAC communica-
tion on the unit. This setting must match the
listening access point
LocalClientConnectPort UINT Port number for the RTAC to use to create a
TCP connection to the remote RTAC (23459
by default)
LocalSerialPort UINT Communications port that will be used to
communicate with the other RTAC
CommStatusTimeout TIME Time without remote RTAC communications
or link status before activating IP alias. Range
of 500 ms to 1 hour. Default is 5 seconds.
EnterMaintenanceMode BOOL A rising edge will activate maintenance mode
ExitMaintenanceMode BOOL A rising edge will remove the unit from main-
tenance mode
InterfaceLinkStatus SPS Connect to the system tags Ethernet link sta-
tus, which shows the current value of the man-
aged interface

Outputs
Name IEC 61131 Type Description
IPAliasActive BOOL This pin shows if the IP address that is as-
signed on “ControlledIPAlias” is active on
the RTAC unit
MaintenanceMode BOOL This pin shows if the unit is currently in
maintenance mode. If the unit is in mainte-
nance mode, the RTAC will not participate
in redundancy logic. Maintenance mode
persists through power cycle and settings
change on the unit. Once the unit is set to
exit maintenance mode, it will participate in
the redundancy scheme of the “Controlled-
InterfaceIP”.
RtacEthernetCommsGood BOOL If both RTAC connections are communicat-
ing via the Ethernet connection, this pin will
be set to TRUE

Date Code 20190830 Instruction Manual Programming Reference


13.8 IPAliasRedundancy
Examples

RtacSerialCommsGood BOOL If both RTAC connections are communicat-


ing via the serial connection, this pin will be
set to TRUE
SerialNumberMismatch BOOL If the assigned and actual serial numbers do
not match, this pin will be TRUE. Redun-
dancy logic will only function if this value
is FALSE .
ProjectIDMismatch BOOL If the project IDs between the two RTAC
units do not match, this output will be
TRUE. The value of this pin is retained
through power cycles and will only compare
if Ethernet or serial communication is active
between the two RTAC units
InvalidInputPin STRING Lists an incorrectly configured input pin

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.

Using Interface Control to Manage an IP Alias


Objective
A user would like to use a single IP address between two RTACs for a client to seamlessly
communicate with redundant data concentrators. This example will demonstrate how to
configure two RTACs to share one IP address.

Assumptions
This example assumes the following:
ä The IP alias and its associated subnet do not overlap with any other configured sub-
nets on any Ethernet interface or other IP aliases.
ä The client will communicate with the RTAC on Ethernet Port 2.
ä Both RTACs will communicate with each other on Ethernet Port 1.
ä Both RTACs have IP addresses in the same subnet on Ethernet Port 1.
ä Ethernet Port 1 on each RTAC will be connected directly to the other RTAC or
through a switch.
ä Each RTAC configuration includes an Ethernet Listening, Raw TCP access point that
matches the LocalAPPort setting on the interface control function block.

Programming Reference Instruction Manual Date Code 20190830


IPAliasRedundancy 13.9
Examples

ä Each RTAC collects data from the other RTAC through serial ports or an Ethernet
port.
ä Any supported server protocol can be used to send data to the client via the IP alias.
ä If a serial connection is used, an RS-232 compatible cable that matches the wiring
diagram according to each connected serial port (as listed in the specific RTAC hard-
ware instruction manual) is used.

Solution
RTAC Project 1
The user creates an Ethernet listening access point as shown in Figure 13.1.

Figure 13.1 Ethernet Listening Access Point

The user creates a program as shown in Code Snippet 13.1:

Code Snippet 13.1 prg_InterfaceControlRTAC1


PROGRAM prg_InterfaceControlRTAC1
VAR
Port1Control : fb_InterfaceControl;
END_VAR

Port1Control(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
Backup := FALSE,
RemoteRtacIP := '192.168.25.8',
RemoteRTACPort := 3000,
LocalAPPort := 7500,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);

Figure 13.2 presents the same logic as Code Snippet 13.1 shown in CFC rather than an ST
program.

Date Code 20190830 Instruction Manual Programming Reference


13.10 IPAliasRedundancy
Examples

Figure 13.2 Interface Control in CFC

RTAC Project 2
The user creates an Ethernet listening access point as shown in Figure 13.3.

Figure 13.3 Ethernet Listening Access Point

The user creates a program as shown in Code Snippet 13.2:

Code Snippet 13.2 prg_InterfaceControlRTAC2


PROGRAM prg_InterfaceControlRTAC2
VAR
Port1Control : fb_InterfaceControl;
END_VAR

Port1Control(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
Backup := FALSE,
RemoteRtacIP := '192.168.25.7',
RemoteRTACPort := 7500,
LocalAPPort := 3000,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);

Programming Reference Instruction Manual Date Code 20190830


IPAliasRedundancy 13.11
Examples

Figure 13.4 presents the same logic as Code Snippet 13.2 shown in CFC rather than an ST
program.

Figure 13.4 Interface Control in CFC

Using Interface Control With the Same Configuration on


Two RTACs
Objective
A user would like to use the exact same RTAC configuration on two RTAC units to provide
redundancy. This examples shows how to use InterfaceControlWithSerialCheck, which
includes additional functionality to verify the serial number of the RTAC that the logic
executes on and to verify that the ProjectID matches between the two RTACs. Even though
two function blocks are defined in the RTAC project, only one function block will manage
the IP alias (provided that the configured serial number matches the serial number of the
RTAC unit).
This example also provides the same functionality as the previous example for managing
an IP alias.

Assumptions
This example assumes the following:
ä The IP alias and its associated subnet mask do not overlap with any other configured
subnets on any Ethernet interface or other IP aliases.
ä The client will communicate with the RTAC on Ethernet Port 2.
ä Both RTACs will communicate with each other on Ethernet Port 1.
ä Both RTACs have IP addresses in the same subnet on Ethernet Port 1.

Date Code 20190830 Instruction Manual Programming Reference


13.12 IPAliasRedundancy
Examples

ä Ethernet port 1 on each RTAC will be connected directly to the other RTAC or
through a switch.
ä Each RTAC configuration includes an Ethernet Listening of Raw TCP access point
that matches the LocalAPPort setting on the interface control function block.
ä Each RTAC collects data from the other RTAC through serial ports or an Ethernet
port.
ä Any supported server protocol can be used to send data to the client via the IP alias.
ä If a serial connection is used, then an RS-232 compatible cable that matches the
wiring diagram according to each connected serial port (as listed in the specific
RTAC hardware instruction manual) is used.

Solution
In each RTAC configuration, create one access point of type Ethernet incoming listening
that matches the settings of the LocalAPPort setting on each function block.

Figure 13.5 Ethernet Listening Access Point for PortControlRTAC1

Figure 13.6 Ethernet Listening Access Point for PortControlRTAC2

The user creates a program as shown in Code Snippet 13.3:

Code Snippet 13.3 prgInterfaceControlWithSerialCheck


PROGRAM prg_InterfaceControlWithSerialCheck
VAR
PortControlRTAC1 : fb_InterfaceControlWithSerialCheck;
PortControlRTAC2 : fb_InterfaceControlWithSerialCheck;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


IPAliasRedundancy 13.13
Examples

Code Snippet 13.3 prgInterfaceControlWithSerialCheck (Continued)


PortControlRTAC1(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
SerialNumber := '1122440328',
Backup := FALSE,
RemoteRtacIP := '192.168.25.8',
RemoteRTACPort := 3000,
LocalAPPort := 7500,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);

PortControlRTAC2(
ControlledInterface := Eth_02,
ControlledIPAlias := '10.55.55.55/24',
SerialNumber := '1122680283',
Backup := FALSE,
RemoteRtacIP := '192.168.25.7',
RemoteRTACPort := 7500,
LocalAPPort := 3000,
LocalClientConnectPort := 8788,
LocalSerialPort := 1,
CommStatusTimeout := T#5S,
InterfaceLinkStatus := SystemTags.Eth_02_Link
);

Figure 13.7 presents the same logic as Code Snippet 13.3 shown in CFC rather than an ST
program.

Date Code 20190830 Instruction Manual Programming Reference


13.14 IPAliasRedundancy
Examples

Figure 13.7 InterfaceControlWithSerialCheck in CFC

Programming Reference Instruction Manual Date Code 20190830


SECTION 14

MathComplex
Introduction
The MathComplex library allows the storage of complex numbers as well as basic manip-
ulations that can be performed on them.
All numbers in polar notation are expected to be in units of degrees and not radians.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.2 and older can be used on RTAC firmware version R132 and higher.

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.

struct_ComplexRect
This structure represents a complex number in rectangular coordinates.

Name IEC 61131 Type Description


Re LREAL The real component of this complex number.
Im LREAL The imaginary component of this complex number.

Functions
fun_ComplexAbs (Function)
This function returns the absolute value, or magnitude, of the provided complex number.

Date Code 20190830 Instruction Manual Programming Reference


14.2 MathComplex
Functions

Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number from which the absolute value is calculated.

Return Value
IEC 61131 Type Description
LREAL The absolute value of num.

Processing
p
This function returns a value equal to (num.Re)2 + (num.Im)2 .

fun_ComplexAdd (Function)
This function returns the sum of two complex numbers.

Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The first addend.
num2 struct_ComplexRect The second addend.

Return Value
IEC 61131 Type Description
struct_ComplexRect The result of num1 + num2.

fun_ComplexCmp (Function)
This function compares two complex values based on magnitude.

Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The first value to compare.
num2 struct_ComplexRect The second value to compare.

Programming Reference Instruction Manual Date Code 20190830


MathComplex 14.3
Functions

Return Value
IEC 61131 Type Description
INT Returns –1 if the magnitude of num2 is larger than num1, 0 if the magni-
tudes are equal, and 1 if the magnitude of num1 is larger than num2.

Processing
This function calculates the absolute value of both provided inputs and then provides its
return based on which one is larger.

fun_ComplexConjugate (Function)
This function returns the conjugate of the provided complex number.

Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number from which the conjugate is derived.

Return Value
IEC 61131 Type Description
struct_ComplexRect The complex conjugate of num.

Processing
This function returns a struct_ComplexRect with a negated imaginary component.

fun_ComplexDivide (Function)
This function returns the quotient of num1 / num2.

Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The dividend.
num2 struct_ComplexRect The divisor.

Date Code 20190830 Instruction Manual Programming Reference


14.4 MathComplex
Functions

Return Value
IEC 61131 Type Description
struct_ComplexRect The quotient of num1 / num2.

Processing
num1 × num2∗
This function performs the equivalent of providing a result formatted as
num2 × num2∗
a single complex number.

fun_ComplexExp (Function)
Compute enum .

Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number e will be raised to.

Return Value
IEC 61131 Type Description
struct_ComplexRect The result of enum .

Processing
Performs the calculation ea+bi = ea (cos b + i sin b).

fun_ComplexLn (Function)
Compute the natural logarithm of num.

Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number from which the natural log is calculated.

Programming Reference Instruction Manual Date Code 20190830


MathComplex 14.5
Functions

Return Value
IEC 61131 Type Description
struct_ComplexRect The natural log of num.

Processing
This function returns an Re component of the natural log of the magnitude of num and an
Im component of the angle defined by the arctangent of num.Im and num.Re.

fun_ComplexMultiply (Function)
This function returns the product of multiplying two complex numbers.

Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The first factor.
num2 struct_ComplexRect The second factor.

Return Value
IEC 61131 Type Description
struct_ComplexRect The product of num1 and num2.

fun_ComplexScale (Function)
This function multiplies a complex number by a scalar.

Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The number to scale.
scalar LREAL The scalar.

Date Code 20190830 Instruction Manual Programming Reference


14.6 MathComplex
Functions

Return Value
IEC 61131 Type Description
struct_ComplexRect The product of num and scalar.

fun_ComplexSubtract (Function)
This function returns the difference of two complex numbers.

Inputs
Name IEC 61131 Type Description
num1 struct_ComplexRect The minuend.
num2 struct_ComplexRect The subtrahend.

Return Value
IEC 61131 Type Description
struct_ComplexRect The difference of num1 – num2.

fun_ComplexZero (Function)
This function zeros the provided struct_ComplexRect.

Inputs/Outputs
Name IEC 61131 Type Description
num struct_ComplexRect The struct to be zeroed.

struct_ComplexRect_TO_vector_t (Function)
This function converts a complex number stored as rectangular coordinates to a complex
number stored as polar coordinates. The angle returned by this function will be between
–180 and 180 degrees.

Programming Reference Instruction Manual Date Code 20190830


MathComplex 14.7
Benchmarks

Inputs
Name IEC 61131 Type Description
num struct_ComplexRect The rectangular coordinates to be converted.

Return Value
IEC 61131 Type Description
vector_t num represented as polar coordinates.

vector_t_TO_struct_ComplexRect (Function)
This function converts a complex number stored as polar coordinates to a complex number
stored as rectangular coordinates.

Inputs
Name IEC 61131 Type Description
num vector_t The polar coordinates to be converted.

Return Value
IEC 61131 Type Description
struct_ComplexRect num represented as rectangular coordinates.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R135-V0 firmware
ä SEL-3530
â R135-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM

Date Code 20190830 Instruction Manual Programming Reference


14.8 MathComplex
Benchmarks

â R135-V0 firmware

Benchmark Test Descriptions


BasicOps Performance
The times fun_ComplexAbs, fun_ComplexZero, and fun_ComplexConjugate require to
run, averaged over 1000 calls.

AlgebraicOps Performance
The times fun_ComplexAdd, fun_ComplexSubtract, fun_ComplexDivide, fun_ComplexS-
cale, and fun_ComplexMultiply require to run, averaged over 1000 calls.

Exponential Performance
The times fun_ComplexExp and fun_ComplexLn require to run, averaged over 1000 calls.

Conversion Performance
The times struct_ComplexRect_TO_vector_t and vector_t_TO_struct_ComplexRect require
to run, averaged over 1000 calls.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_ComplexAbs 10 7 1
fun_ComplexConjugate 5 4 1
fun_ComplexZero 1 1 1
fun_ComplexAdd 2 2 1
fun_ComplexSubtract 2 2 1
fun_ComplexMultiply 2 2 1
fun_ComplexDivision 3 2 1
fun_ComplexScale 1 1 1
fun_ComplexExp 36 15 1
fun_ComplexLn 50 13 1
vector_t_TO_struct_ComplexRect 19 6 1
struct_ComplexRect_TO_vector_t 23 12 1

Programming Reference Instruction Manual Date Code 20190830


MathComplex 14.9
Examples

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.

Performing a Mathematical Operation on Two Complex


Numbers
Objective
A user has a need to sum two complex numbers.

Solution
The usage shown in Code Snippet 14.1 would be the same for any other operation as well.

Code Snippet 14.1 prg_ComplexAdd


PROGRAM prg_ComplexAdd
VAR
ComplexNumOne : struct_ComplexRect := (Re := 4.0, Im := 3.0);
ComplexNumTwo : struct_ComplexRect := (Re := 2.0, Im := 7.0);
ComplexResult : struct_ComplexRect;
END_VAR

ComplexResult := fun_ComplexAdd(ComplexNumOne, ComplexNumTwo);

Manipulating vector_t Structures


Objective
A user has data points received through an Axion module containing complex numbers
represented in polar notation as vector_t objects.
The user would like to perform some set of mathematical operations on them and then
prepare them to send to another device.

Date Code 20190830 Instruction Manual Programming Reference


14.10 MathComplex
Examples

Solution

Code Snippet 14.2 prg_ComplexConvert


PROGRAM prg_ComplexConvert
VAR
DatumOne : vector_t := (ang := 36.87, mag := 35_614);
DatumTwo : vector_t := (ang := 53.13, mag := 17_735);
ComplexNumOne : struct_ComplexRect;
ComplexNumTwo : struct_ComplexRect;
ComplexResult : struct_ComplexRect;
DatumResult : vector_t;
END_VAR

ComplexNumOne := vector_t_TO_struct_ComplexRect(DatumOne);
ComplexNumTwo := vector_t_TO_struct_ComplexRect(DatumTwo);
ComplexResult := fun_ComplexAdd(ComplexNumOne, ComplexNumTwo);
//Scale from Kilovolts to Volts.
ComplexResult := fun_ComplexScale(ComplexResult, 1000);
DatumResult := struct_ComplexRect_TO_vector_t(ComplexResult);

Programming Reference Instruction Manual Date Code 20190830


SECTION 15

MathMatrix
Introduction
The MathMatrix library allows for the creation of matrices of complex numbers. There are
multiple desired workflows that exist when working with matrices and the library provides
several options for working with them.
The library is designed to facilitate two basic types of matrix operations: operations that
modify an existing matrix and operations that take one or more matrices as arguments
and place the result in a different matrix. Operations that affect only the active matrix are
completed using the methods on class_Matrix objects. Operations that affect two or more
matrices are performed by external functions or special matrix manipulation classes.
The library also allows for operations of varying levels of required immediacy. For work
on large or highly variant sized matrices that can be completed over multiple task cycles, NOTE: Because of the cost of
checking the system time, the time is
it provides matrix manipulation classes that are loaded with operator and result matrices, not validated at each step in the
stimulated to run to completion, and given a fixed number of steps or a fixed time slice. algorithm but rather after multiple
steps have been completed.
For operations that must complete immediately, ideally on fixed sized matrices so the com-
putation time can be evaluated to validate timing requirements, functions provided by the
library accomplish the same work while guaranteeing the completion of the algorithm be-
fore returning.
This library is dependent on the capabilities defined in the MathComplex library for all
operations (see the MathComplex library documentation for more information on the op-
eration of this library).

Special Considerations
ä Copying classes from this library causes unwanted behavior. This means the follow-
ing:
1. The assignment operator “:=” must not be used on any class from this library;
consider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type
class_MathMatrixObject"
myMathMatrixObject := otherMathMatrixObject;

// This is fine
someVariable := myMathMatrixObject.value;
// As is this
pt_myMathMatrixObject := ADR(myMathMatrixObject);

Date Code 20190830 Instruction Manual Programming Reference


15.2 MathMatrix
Functions

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.
ä 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).
ä Though this library provides the capability to dynamically resize, create, and destroy
matrices, memory operations can be long running and care should be taken to avoid
unnecessary use of this type of operation on a time-critical task.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.1 and older can be used on RTAC firmware version R132 and higher.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_MatrixState
Enumeration Description
NOT_INITIALIZED This matrix has no memory assigned to it, call SetSize() to
initialize.
NO_OPERATION The matrix is not locked to any operation.
MATRIX_SCALE The matrix is being scaled by one value.
EXTERNAL_OPERATION The matrix is being operated on by an external class.
MATRIX_ROW_STEP_MULT The matrix is multiplying a row by a scalar.
MATRIX_ROW_STEP_DIV The matrix is dividing a row by a scalar.
MATRIX_ROW_STEP_ADD The matrix is adding two rows together.
MATRIX_ROW_STEP_SUB The matrix is subtracting one row from another.

Functions
fun_DeleteMatrix (Function)
The user should call this after completing work on a matrix received through fun_NewMatrix()
before the matrix goes out of scope. It releases all system resources.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.3
Functions

Inputs/Outputs
Name IEC 61131 Type Description
pt_matrix POINTER TO class_Matrix The matrix to be deleted. This pointer must be re-
ceived through fun_NewMatrix.

Return Value
IEC 61131 Type Description
BOOL TRUE if the memory is successfully deallocated.

Processing
This function frees all system resources owned by this matrix. After completion of the
function, pt_matrix is NULL(0).

fun_MatrixAdd (Function)
This function adds two matrices and places the result in a third. The entire operation will
complete before the function returns.

Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The first addend.
matrix2 class_Matrix The second addend.
result class_Matrix The sum of the two matrices.

Return Value
IEC 61131 Type Description
BOOL The matrix addition completed successfully.

Date Code 20190830 Instruction Manual Programming Reference


15.4 MathMatrix
Functions

Processing
This function sets the return value to TRUE if all conditions for performing the addition
are met as follows:
ä matrix1 and matrix2 are initialized.
ä All three matrices are not busy performing a stepwise operation.
ä result is a separate matrix from both matrix1 and matrix2.
ä matrix1 and matrix2 have the same dimensions.
ä If necessary, result is successfully resized.
It then performs the addition.

fun_MatrixCopyColumn (Function)
This function copies one column from one matrix to a column in a second matrix. The
entire operation will complete before the function returns.

Inputs
Name IEC 61131 Type Description
fromColumn UINT The column index of the column being copied from.
toColumn UINT The column index of the column being copied to.

Inputs/Outputs
Name IEC 61131 Type Description
fromMatrix class_Matrix The matrix being copied from.
toMatrix class_Matrix The matrix being copied to.

Return Value
IEC 61131 Type Description
BOOL The column copy completed successfully.

Processing
This function sets the return value to TRUE if all conditions for performing the copy are
met as follows:
ä Both matrices are initialized.
ä Both matrices are not busy performing a stepwise operation.
ä Both matrices have the same number of rows.
ä The column indices provided are within the size of the matrices referenced.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.5
Functions

It then performs the copy.

fun_MatrixDeterminant (Function)
This function calculates the determinant of a square matrix. The entire operation will
complete before the function returns.
If the purpose behind calculating the determinant is a check before inverting a matrix or
as part of the process of solving a system of equations this class is not the most optimal to
use. In these cases it is better to use the fun_MatrixInvert or the fun_MatrixGaussianElim
object instead as the overhead for all three is similar.

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to calculate the determinant of. This matrix is
left unchanged.
workspace class_Matrix Memory to do the calculation in. If this is the same size
as original, no memory allocation will occur in finding the
determinant.

Outputs
Name IEC 61131 Type Description
determinant struct_ComplexRect The determinant of the matrix. Zero if the matrix is not
invertible.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation was attempted.

Processing
1. This function sets the return value to TRUE if all conditions for performing the
calculation are met as follows:
ä original is initialized.
ä original is a square matrix.
ä workspace is a separate matrix from original.
ä Neither matrix is busy performing some other operation.
ä If necessary, workspace is successfully resized.
2. Copies the contents of original into workspace.
3. Reduces workspace to an identity matrix using elementary row operations.

Date Code 20190830 Instruction Manual Programming Reference


15.6 MathMatrix
Functions

4. Calculates the determinant from the row operations performed.


5. If at any time the row operations cannot reduce workspace further and it is still not
an identity matrix, the operation is terminated and determinant is set to zero.

fun_MatrixGaussianElim (Function)
This function simplifies a matrix to a diagonal ones matrix with trailing columns using
Gaussian elimination. The contents of coefficients are destroyed and the contents of solu-
tions are modified by this function. The entire operation will complete before the function
returns.

Inputs/Outputs
Name IEC 61131 Type Description
coefficients class_Matrix The coefficients of the variables being solved for.
solutions class_Matrix The right hand side of the system of equations.

Outputs
Name IEC 61131 Type Description
error BOOL This algorithm cannot solve this system of equations.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination was attempted and the matrices
could have been modified.

Processing
ä This function sets the return value to TRUE if all conditions for performing the cal-
culation are met as follows:
â Both matrices are initialized.
â Both matrices are not busy performing a stepwise operation.
â coefficients is a separate matrix from solutions.
â coefficients has at least as many columns as rows.
â solutions has the same number of rows as coefficients.
ä Reduces the first Rows • Rows of coefficients to an identity matrix using elementary
row operations.
ä Performs the same row operations on solutions.
ä If at any time the row operations cannot reduce coefficients further and there is still
not an identity matrix on the left the operation is terminated and error is set.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.7
Functions

ä The contents of coefficients are destroyed and the contents of solutions are modified
by this method.

Output Combination Meanings


Error Return Description
FALSE FALSE This should never occur.
FALSE TRUE The Gaussian elimination completed successfully.
TRUE FALSE The matrix state prevented the Gaussian elimination request.
TRUE TRUE The matrix is not invertible and cannot be reduced by this Gaussian elimi-
nation algorithm.

fun_MatrixInvert (Function)
This function creates the inverse of a square matrix. original is destroyed in the process
so if the data are still desired, they must be copied before the function is called. The entire
operation will complete before the function returns.
One common use case for inverting a matrix is to solve a system of equations. In this library
that use case is discouraged unless solving the same system for many solutions as Gaussian
elimination performs the same functionality with less overhead.

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to invert.
result class_Matrix The inverted matrix.

Outputs
Name IEC 61131 Type Description
error BOOL The inversion could not be attempted or original cannot be in-
verted.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if inversion was attempted and the matrices could have been
modified.

Processing
1. This function sets the return value to TRUE if all conditions for performing the
calculation are met as follows:
ä original is initialized.

Date Code 20190830 Instruction Manual Programming Reference


15.8 MathMatrix
Functions

ä Both matrices are not busy performing a stepwise operation.


ä result is a separate matrix from original.
ä original is a square matrix.
ä If necessary, result is successfully resized.
2. Sets result to an identity matrix.
3. Reduces original to an identity matrix using elementary row operations.
4. Performs the same row operations on result to create the inverse.
5. If at any time the row operations cannot reduce original further and it is still not an
identity matrix, the operation is terminated and error is set.

Output Combination Meanings


Error Return Description
FALSE FALSE This should never occur.
FALSE TRUE The inversion completed successfully.
TRUE FALSE The matrix state prevented the inversion request.
TRUE TRUE The matrix is not invertible.

fun_MatrixMultiply (Function)
This function multiplies two matrices and places the result in a third. The entire operation
will complete before the function returns.

Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The multiplier.
matrix2 class_Matrix The multiplicand.
result class_Matrix The product of the two matrices.

Return Value
IEC 61131 Type Description
BOOL The matrix multiplication completed successfully.

Processing
This function sets the return value to TRUE if all conditions for performing the calculation
are met as follows:
ä matrix1 and matrix2 are initialized.
ä All three matrices are not busy performing a stepwise operation.
ä result is a separate matrix from both matrix1 and matrix2.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.9
Functions

ä The column count of matrix1 equals the row count of matrix2.


If necessary, it sets the size of result. It then performs the multiplication.

fun_MatrixSubtract (Function)
This function subtracts one matrix from another and places the result in a third. The entire
operation will complete before the function returns.

Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The minuend.
matrix2 class_Matrix The subtrahend.
result class_Matrix The difference of the two matrices.

Return Value
IEC 61131 Type Description
BOOL The matrix subtraction completed successfully.

Processing
This function verifies that the subtraction can be performed:
1. matrix1 and matrix2 are initialized.
2. All three matrices are not busy performing a stepwise operation.
3. result is a separate matrix from both matrix1 and matrix2.
4. matrix1 and matrix2 have the same dimensions.
If necessary, the function resizes result. It then performs the subtraction.

fun_MatrixTranspose (Function)
This function places the transpose of a matrix into a result. The entire operation will com-
plete before the function returns.

Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be the Hermitian Transpose.
Before each element is placed in result, it will be conjugated.

Date Code 20190830 Instruction Manual Programming Reference


15.10 MathMatrix
Functions

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix whose transpose is calculated.
result class_Matrix The transpose of the original matrix.

Return Value
IEC 61131 Type Description
BOOL The matrix transpose completed successfully.

Processing
This function verifies that the transpose can be performed:
1. original is initialized.
2. Both matrices are not busy performing a stepwise operation.
3. result is a separate matrix from original.
If necessary the function resizes result. It then performs the transpose. If conjugate is
TRUE, conjugate each element in result.

fun_Matrix_ATA (Function)
This function performs an optimization of the operation (AT A) transposing an input matrix
and multiplying it by itself. The entire operation will complete before the function returns.

Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be calculated using the Her-
mitian Transpose. Before the transpose step is complete, each
element will be conjugated.

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix A.
result class_Matrix The matrix for the result.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.11
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed successfully.

Processing
This function verifies that the operation can be performed:
1. original is initialized.
2. Both matrices are not busy performing a stepwise operation.
3. result is a separate matrix from original.
If necessary, the function resizes result. It then performs the operation AT A. If conjugate
is TRUE, conjugate each element in the transpose before using it in the multiply.

fun_NewMatrix (Function)
Request a new matrix from the system with all required resources. Matrices received
through this function must be freed through the fun_DeleteMatrix() function before
they leave scope.

Inputs
Name IEC 61131 Type Description
rows UINT The number of rows in the new matrix.
cols UINT The number of columns in the new matrix.

Return Value
IEC 61131 Type Description
POINTER TO class_Matrix The address of the new class_Matrix.

Processing
This function allocates system resources for a rows by cols matrix of struct_ComplexRect
objects.

Classes
This library provides the following classes as extensions of the IEC 61131 function block.

Date Code 20190830 Instruction Manual Programming Reference


15.12 MathMatrix
Classes

class_Matrix (Class)
This is the fundamental class for this library. It allows for the storage of struct_Com-
plexRect objects ordered by row and column. It manages all required system resources
internally.

Initialization Inputs
Name IEC 61131 Type Description
rowCount UINT The number of rows this matrix begins with.
colCount UINT The number of columns this matrix begins with.

Outputs
Name IEC 61131 Type Description
pt_Data POINTER TO POINTER TO Pointer to an array of pointers (one for each
struct_ComplexRect row). Allows accessing the matrix with [row][col]
syntax. Indexing starts at zero. This pointer should
be re-read before access after any resize operation.
Rows UINT The number of rows in the matrix.
Cols UINT The number of columns in the matrix.
State enum_MatrixState The active matrix operation.

Clear (Method)
This method returns all system resources internal to this matrix and sets its size to zero
rows by zero columns. In addition it clears all locks on the matrix and resets all internal
state machines.
This should typically be used only to free the system resources held by this matrix before
it goes out of scope.

MatrixRowAdd (Method)
This method adds one row to another inside this matrix, replacing the content of the second
row (Matrix[toRow] = Matrix[toRow] + Matrix[fromRow] • scalar). The entire operation
will complete before the method returns.

Inputs
Name IEC 61131 Type Description
fromRow UINT The first addend.
toRow UINT The second addend and the location of the result.
scalar struct_ComplexRect A constant that is multiplied against the value of each entry
in fromRow before adding it to the entry in toRow.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.13
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the addition.

Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates that the provided row indices exist.
3. If the checks pass, multiplies fromRow by scalar and adds the result to toRow.
4. fromRow remains unchanged.

MatrixRowDivide (Method)
This method divides each element in rowIndex by scalar and stores the results back in
rowIndex (Matrix[rowIndex] = Matrix[rowIndex] / scalar). The entire operation will com-
plete before the method returns.

Inputs
Name IEC 61131 Type Description
rowIndex UINT The row to be modified.
scalar struct_ComplexRect A constant used as the divisor against the value of each entry
in rowIndex.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the division.

Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates the row index provided exists.
3. If the checks pass, divides each entry in rowIndex by scalar.

MatrixRowMultiply (Method)
This method multiplies each element in rowIndex by scalar and stores the results back
in rowIndex (Matrix[rowIndex] = Matrix[rowIndex] • scalar). The entire operation will
complete before the method returns.

Date Code 20190830 Instruction Manual Programming Reference


15.14 MathMatrix
Classes

Inputs
Name IEC 61131 Type Description
rowIndex UINT The row to be modified.
scalar struct_ComplexRect A constant used as the multiplier against the value of each
entry in rowIndex.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the multiplication.

Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates the row index provided exists.
3. If the checks pass, multiplies each entry in rowIndex by scalar.

MatrixRowSubtract (Method)
This method subtracts one row from another inside this matrix, replacing the content of
the second row (Matrix[toRow] = Matrix[toRow] – Matrix[fromRow] • scalar). The entire
operation will complete before the method returns.

Inputs
Name IEC 61131 Type Description
fromRow UINT The subtrahend.
toRow UINT The minuend and the location of the result.
scalar struct_ComplexRect A constant that is multiplied against the value of each entry
in fromRow before subtracting it from the entry in toRow.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the subtraction.

Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. Validates the row indices provided exist.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.15
Classes

3. If the checks pass, multiplies fromRow by scalar and subtracts the result from
toRow.
4. fromRow remains unchanged.

MatrixScale (Method)
Multiplies each element in this matrix by a scalar. The entire operation will complete before
the method returns.

Inputs
Name IEC 61131 Type Description
scalar struct_ComplexRect A constant that is multiplied against the value of each entry this
matrix.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method scaled the matrix.

Processing
1. Validates that the matrix is initialized and not in the middle of a stepwise operation.
2. If the checks pass, multiplies each element in the matrix by scalar, placing the result
in the same location.

MatrixStepRowAdd (Method)
This method adds one row to another inside this matrix, replacing the content of the second
row (Matrix[toRow] = Matrix[toRow] + Matrix[fromRow] • scalar).
The operation will perform the next steps operations of the complete addition. This de-
sign allows for the completion of the algorithm over the course of multiple task cycles for
matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.

Date Code 20190830 Instruction Manual Programming Reference


15.16 MathMatrix
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the addition.

Processing
1. Validates that the matrix is initialized and has begun a stepwise addition.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and add the result to toRow.
3. fromRow remains unchanged.
4. Performs, at most, the next steps operations toward completing the addition algo-
rithm.
5. Decrements steps by the number of operations consumed.
6. Returns TRUE and unlocks the matrix if the addition completed.
7. Returns FALSE if the addition was not attempted or steps was exhausted before the
algorithm completed.

MatrixStepRowDivide (Method)
This method divides each element in toRow by scalar and stores the results back in toRow
(Matrix[toRow] = Matrix[toRow] / scalar).
The operation will perform the next steps operations of the complete division. This de-
sign allows for the completion of the algorithm over the course of multiple task cycles for
matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the division.

Processing
1. Validates that the matrix is initialized and has begun a stepwise division.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to divide each element in toRow by scalar.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.17
Classes

3. Performs, at most, the next steps operations toward completing the division algo-
rithm.
4. Decrements steps by the number of operations consumed.
5. Returns TRUE and unlocks the matrix if the division completed.
6. Returns FALSE if the division was not attempted or steps was exhausted before the
algorithm completed.

MatrixStepRowMultiply (Method)
This method multiplies each element in toRow by scalar and stores the results back in
toRow (Matrix[toRow] = Matrix[toRow] • scalar).
The operation will perform the next steps operations of the complete multiplication. This
design allows for the completion of the algorithm over the course of multiple task cycles
for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the multiplication.

Processing
1. Validates that the matrix is initialized and has begun a stepwise multiplication.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each entry in toRow by scalar.
3. Performs, at most, the next steps operations toward completing the multiplication
algorithm.
4. Decrements steps by the number of operations consumed.
5. Returns TRUE and unlocks the matrix if the multiplication completed.
6. Returns FALSE if the multiplication was not attempted or steps was exhausted be-
fore the algorithm completed.

MatrixStepRowSubtract (Method)
This method subtracts one row from another inside this matrix, replacing the content of the
second row (Matrix[toRow] = Matrix[toRow] – Matrix[fromRow] • scalar).

Date Code 20190830 Instruction Manual Programming Reference


15.18 MathMatrix
Classes

The operation will perform the next steps operations of the complete subtraction. This
design allows for the completion of the algorithm over the course of multiple task cycles
for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the subtraction.

Processing
1. Validates that the matrix is initialized and has begun a stepwise subtraction.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and subtract the result from toRow.
3. fromRow remains unchanged.
4. Performs, at most, the next steps operations toward completing the subtraction al-
gorithm.
5. Decrements steps by the number of operations consumed.
6. Returns TRUE and unlocks the matrix if the subtraction completed.
7. Returns FALSE if the subtraction was not attempted or steps was exhausted before
the algorithm completed.

MatrixStepScale (Method)
Multiplies each element in this matrix by a scalar.
The operation will perform the next steps operations of the complete scaling operation.
This design allows for the completion of the algorithm over the course of multiple task
cycles for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of operations to attempt this task cycle.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.19
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the scaling operation.

Processing
1. Validates that the matrix is initialized and has begun a stepwise scaling operation.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each element in the matrix by scalar.
3. Performs, at most, the next steps operations toward completing the scaling algo-
rithm.
4. Decrements steps by the number of operations consumed.
5. Returns TRUE and unlocks the matrix if the scaling operation completed.
6. Returns FALSE if the scaling operation was not attempted or steps was exhausted
before the algorithm completed.

MatrixTimedRowAdd (Method)
This method adds one row to another inside this matrix, replacing the content of the second
row (Matrix[toRow] = Matrix[toRow] + Matrix[fromRow] • scalar).
The operation will perform work for the next duration microseconds toward completion
of the addition. This design allows for the completion of the algorithm over the course of
multiple task cycles for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the addition.

Processing
1. Validates that the matrix is initialized and has begun a stepwise addition.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and add the result to toRow.
3. fromRow remains unchanged.

Date Code 20190830 Instruction Manual Programming Reference


15.20 MathMatrix
Classes

4. Performs work toward completing the addition algorithm, in groups of steps, until
duration microseconds is exceeded.
5. Decrements duration by the microseconds consumed.
6. Returns TRUE and unlocks the matrix if the addition completed.
7. Returns FALSE if the addition was not attempted or duration was exhausted before
the algorithm completed.

MatrixTimedRowDivide (Method)
This method divides each element in toRow by scalar and stores the results back in toRow
(Matrix[toRow] = Matrix[toRow] / scalar).
The operation will perform work for the next duration microseconds toward the complete
division. This design allows for the completion of the algorithm over the course of multiple
task cycles for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the division.

Processing
1. Validates that the matrix is initialized and has begun a stepwise division.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to divide each element in toRow by scalar.
3. Performs work toward completing the division algorithm, in groups of steps, until
duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE and unlocks the matrix if the division completed.
6. Returns FALSE if the division was not attempted or duration was exhausted before
the algorithm completed.

MatrixTimedRowMultiply (Method)
This method multiplies each element in toRow by scalar and stores the results back in
toRow (Matrix[toRow] = Matrix[toRow] • scalar).

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.21
Classes

The operation will perform work for the next duration microseconds toward the complete
multiplication. This design allows for the completion of the algorithm over the course of
multiple task cycles for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the multiplication.

Processing
1. Validates that the matrix is initialized and has begun a stepwise multiplication.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each entry in toRow by scalar.
3. Performs work toward completing the multiplication algorithm, in groups of steps,
until duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE and unlocks the matrix if the multiplication completed.
6. Returns FALSE if the multiplication was not attempted or duration was exhausted
before the algorithm completed.

MatrixTimedRowSubtract (Method)
This method subtracts one row from another inside this matrix, replacing the content of the
second row (Matrix[toRow] = Matrix[toRow] – Matrix[fromRow] • scalar).
The operation will perform work for the next duration microseconds toward the complete
subtraction. This design allows for the completion of the algorithm over the course of
multiple task cycles for matrices large enough for completion time to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Date Code 20190830 Instruction Manual Programming Reference


15.22 MathMatrix
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the subtraction.

Processing
1. Validates that the matrix is initialized and has begun a stepwise subtraction.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply fromRow by scalar and subtract the result from toRow.
3. fromRow remains unchanged.
4. Performs work toward completing the subtraction algorithm, in groups of steps,
until duration microseconds is exceeded.
5. Decrements duration by the microseconds consumed.
6. Returns TRUE and unlocks the matrix if the subtraction completed.
7. Returns FALSE if the subtraction was not attempted or duration was exhausted
before the algorithm completed.

MatrixTimedScale (Method)
Multiplies each element in this matrix by a scalar.
The operation will perform work for the next duration microseconds toward the complete
scaling operation. This design allows for the completion of the algorithm over the course
of multiple task cycles for matrices large enough for completion duration to be a concern.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method completed the scaling operation.

Processing
1. Validates that the matrix is initialized and has begun a stepwise scaling operation.
2. If the checks pass, this method uses the values provided in StartMatrixOperation()
to multiply each element in the matrix by scalar.
3. Performs work toward completing the scaling algorithm, in groups of steps, until
duration microseconds is exceeded.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.23
Classes

4. Decrements duration by the microseconds consumed.


5. Returns TRUE and unlocks the matrix if the scaling operation completed.
6. Returns FALSE if the scaling operation was not attempted or duration was ex-
hausted before the algorithm completed.

RowSwap (Method)
This method exchanges the position of two rows in a given matrix.

Inputs
Name IEC 61131 Type Description
row1 UINT The first row to swap.
row2 UINT The second row to swap.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method performed the row swap.

Processing
1. Validates that the matrix is initialized and not performing any stepwise operation.
2. If the checks pass, swaps the positions of row1 and row2.
3. Returns TRUE if the swap succeeded.
4. Returns FALSE if the swap failed.

SetSize (Method)
This method changes the storage capacity of the matrix modifying Rows and Cols.

Inputs
Name IEC 61131 Type Description
rowCount UINT The new number of rows.
colCount UINT The new number of columns.

Date Code 20190830 Instruction Manual Programming Reference


15.24 MathMatrix
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method resized the matrix.

Processing
1. Validates that the matrix is not performing any stepwise operation.
2. If either rowCount or colCount is zero, sets Rows and Cols to zero and frees all
system resources.
3. If both rowCount equals Rows and colCount equals Cols, leaves the matrix un-
changed.
4. If rowCount is greater than Rows, adds zeroed rows to the bottom of the matrix.
5. If rowCount is less than Rows, removes rows from the bottom of the matrix.
6. If colCount is greater than Cols, adds zeros to the end of each row.
7. If colCount is less than Cols, truncates each row to the new count.
8. Returns TRUE if the matrix is the newly requested size.
9. Returns FALSE if the matrix is not the newly requested size.
10. If the resize fails, the matrix retains all old values.

StartMatrixOperation (Method)
This method must be called to configure any stepwise or timed operation on only this ma-
trix. It accepts and stores the values used during the operation.

Inputs
Name IEC 61131 Type Description
operation enum_MatrixState The stepwise operation to begin.
fromRow UINT The row to use in the modification. Used only in addition
and subtraction.
toRow UINT The row to be modified.
scalar struct_ComplexRect The constant value to be used during the operation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the method locked the matrix to the requested operation.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.25
Classes

Processing
1. Validates that the matrix is initialized and not performing any stepwise operation.
2. Validates row indices required for the operation requested. For addition and sub-
traction, both indices must be within the matrix. For multiplication and division,
only toRow is validated. For scaling operations, no row index is validated
3. Stores scalar for use during the operation.
4. Locks the matrix to prevent other operations from occurring.
5. Returns TRUE if the operation is primed.
6. Returns FALSE if anything prevents the operation from being primed.

class_MatrixAdd (Class)
This class handles the locking handshakes and the state required to add two class_Matrix
objects over the course of multiple scans.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to perform a new addition (result = matrix1 + matrix2). It
must be called before each addition of two matrices to be performed.

Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The first addend.
matrix2 class_Matrix The second addend.
result class_Matrix The sum of matrix1 and matrix2.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the addition operation is now ready.

Processing
1. Returns FALSE if either matrix1 or matrix2 is not initialized.

Date Code 20190830 Instruction Manual Programming Reference


15.26 MathMatrix
Classes

2. Returns FALSE if result is not a separate matrix from both matrix1 and matrix2.
3. Returns FALSE if any of the three matrices is busy doing any stepwise operation.
4. Returns FALSE if the dimensions of matrix1 do not match those of matrix2.
5. Returns FALSE if result cannot be made to be the same dimensions as the other
two matrices.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of result are destroyed by this method.

ProcessSteps (Method)
This method performs the addition algorithm on three already locked-in matrices.
The operation will perform the next steps sub-operations of the complete addition algo-
rithm.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the addition completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Adds each element in matrix1 to its corresponding element in matrix2 and stores
the sum in result.
3. Decrements steps by the number of operations performed.
4. Returns TRUE if the addition algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.

ProcessTimed (Method)
This method performs the addition algorithm on three already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
addition algorithm.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.27
Classes

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the addition completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Adds each element in matrix1 to its corresponding element in matrix2 and stores
the sum in result.
3. Performs work toward completing the addition algorithm, in groups of steps, until
duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the addition algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixCopyColumn (Class)
This class handles the locking handshakes and the state required to copy a column from
one class_Matrix object to another over the course of multiple scans.

Date Code 20190830 Instruction Manual Programming Reference


15.28 MathMatrix
Classes

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to perform a new column copy. It must be called before each
column copy to be performed.

Inputs
Name IEC 61131 Type Description
fromColumn UINT The index of the column to copy from.
toColumn UINT The index of the column to copy to.

Inputs/Outputs
Name IEC 61131 Type Description
fromMatrix class_Matrix The matrix to be copied from.
toMatrix class_Matrix The matrix to be copied to.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the copy operation is now ready.

Processing
1. Returns FALSE if either fromMatrix or toMatrix is not initialized.
2. Returns FALSE if either of the matrices is busy doing any stepwise operation.
3. Returns FALSE if Rows of matrix1 does not match Rows of matrix2.
4. Returns FALSE if either index provided is outside of the corresponding matrix.
5. Returns FALSE if it cannot lock all matrices involved in the operation.
6. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.

ProcessSteps (Method)
This method performs the copy algorithm on two already locked-in matrices.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.29
Classes

The operation will perform the next steps sub-operations of the complete copy.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the copy completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Copies each element in column fromColumn of fromMatrix to its corresponding
element in column toColumn of toMatrix.
3. Decrements steps by the number of sub-operations performed.
4. Returns TRUE if the copy algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.

ProcessTimed (Method)
This method performs the copy algorithm on two already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
copy.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the copy completed.

Processing
1. Validates that LockMatrices() has been successfully called.

Date Code 20190830 Instruction Manual Programming Reference


15.30 MathMatrix
Classes

2. Copies each element in column fromColumn of fromMatrix to its corresponding


element in column toColumn of toMatrix.
3. Performs work toward completing the copy algorithm, in groups of steps, until du-
ration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the copy algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixDeterminant (Class)
This class handles the locking handshakes and the state required to calculate the determi-
nant of a matrix over the course of multiple scans.
If the purpose behind calculating the determinant is a check before inverting a matrix or as
part of the process of solving a system of equations this class is not the most optimal to use.
In these cases it is better to use the class_MatrixInvert or the class_MatrixGaussianElim
object instead as the overhead for all three is similar.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to calculate the determinant of a new matrix. It must be called
before each operation to be performed.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.31
Classes

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to calculate the determinant of. This matrix is
left unchanged.
workspace class_Matrix Memory to do the calculation in. If this is the same size
as original, no memory allocation will occur in finding the
determinant.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation is now ready.

Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if workspace is not a separate matrix from original.
3. Returns FALSE if either of the matrices is busy doing any stepwise operation.
4. Returns FALSE if original is not a square matrix.
5. Returns FALSE if workspace cannot be resized to the correct dimensions.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of workspace are destroyed by this method.

ProcessSteps (Method)
This method computes the determinant of an already locked-in matrix.
The operation will perform the next steps sub-operations of the complete task.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Date Code 20190830 Instruction Manual Programming Reference


15.32 MathMatrix
Classes

Outputs
Name IEC 61131 Type Description
determinant struct_ComplexRect The determinant of the matrix. Zero if the calculation is
incomplete or the matrix is not invertible.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Decrements steps by the number of sub-operations performed.
3. Returns TRUE and outputs the calculated determinant if the algorithm completed
before steps was exhausted.
4. Returns FALSE and outputs a determinant of zero if LockMatrices() has not
been called or steps was exhausted before completing the algorithm.
5. In the case that the matrix is not invertible, outputs a determinant of zero.

ProcessTimed (Method)
This method computes the determinant of an already locked-in matrix.
The operation will perform work for the next duration microseconds toward the complete
matrix operation.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Outputs
Name IEC 61131 Type Description
determinant struct_ComplexRect The determinant of the matrix. Zero if the calculation is
incomplete or the matrix is not invertible.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.33
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
3. Decrements duration by the microseconds consumed.
4. Returns TRUE and outputs the calculated determinant if the operation completed
before duration was exhausted.
5. Returns FALSE and outputs a determinant of zero if LockMatrices() has not
been called or duration was exhausted before completing the algorithm.
6. In the case that the matrix is not invertible, outputs a determinant of zero.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixGaussianElim (Class)
This class handles the locking handshakes and the state required to simplify the matrix to
a diagonal ones matrix with trailing columns using Gaussian elimination over the course
of multiple scans. The contents of coefficients are destroyed and the contents of solutions
are modified by this class.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

Date Code 20190830 Instruction Manual Programming Reference


15.34 MathMatrix
Classes

LockMatrices (Method)
This method primes the class to perform the Gaussian elimination. It must be called before
each calculation to be performed.

Inputs/Outputs
Name IEC 61131 Type Description
coefficients class_Matrix The coefficients of the variables being solved for.
solutions class_Matrix The right hand side of the system of equations.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination is now ready.

Processing
1. Returns FALSE if either matrix is not initialized.
2. Returns FALSE if coefficients is not a separate matrix from solutions.
3. Returns FALSE if either matrix is busy doing any stepwise operation.
4. Returns FALSE if coefficients has fewer columns than rows.
5. Returns FALSE if solutions is not one column with the same number of rows as
coefficients.
6. Returns FALSE if it cannot lock both matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.

ProcessSteps (Method)
This method performs Gaussian elimination on two already locked-in matrices.
The operation will perform the next steps sub-operations of the complete calculation.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.35
Classes

Outputs
Name IEC 61131 Type Description
error BOOL This algorithm cannot solve this system of equations.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Reduces the first Rows • Rows of coefficients to an identity matrix using elementary
row operations.
3. Performs the same row operations on solutions.
4. If at any time the row operations cannot reduce coefficients further and there is still
not an identity matrix on the left, the operation is terminated and error is set.
5. Decrements steps by the number of operations performed.
6. Returns TRUE if the Gaussian elimination completed before steps was exhausted.
7. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
8. The contents of coefficients are destroyed and the contents of solutions are modified
by this method.

Output Combination Meanings


Error Return Description
FALSE FALSE This should never occur.
FALSE TRUE The Gaussian elimination completed successfully.
TRUE FALSE The matrix state prevented the Gaussian elimination request.
TRUE TRUE The matrix is not invertible and cannot be reduced by this Gaussian elimi-
nation algorithm.

ProcessTimed (Method)
This method performs Gaussian elimination on two already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
inversion algorithm.

Date Code 20190830 Instruction Manual Programming Reference


15.36 MathMatrix
Classes

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Outputs
Name IEC 61131 Type Description
error BOOL This algorithm cannot solve this system of equations.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the Gaussian elimination completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Reduces the first Rows • Rows of coefficients to an identity matrix using elementary
row operations.
3. Performs the same row operations on solutions.
4. If at any time the row operations cannot reduce coefficients further and there is still
not an identity matrix on the left, the operation is terminated and error is set.
5. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
6. Decrements duration by the microseconds consumed.
7. Returns TRUE if the Gaussian elimination completed before duration was exhausted.
8. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
9. The contents of coefficients are destroyed and the contents of solutions are modified
by this method.
The table, listed for the previous method, is provided as reference for interpreting output
combinations.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.37
Classes

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixInvert (Class)
This class handles the locking handshakes and the state required to create the inverse of a
square matrix over the course of multiple scans. The contents of original are destroyed in
the process so if the data are still desired, they must be copied before this class is used. The
entire operation will complete before the function returns.
One common use case for inverting a matrix is to solve a system of equations. In this library
that use case is discouraged unless solving the same system for many solutions as Gaussian
elimination performs the same functionality with less overhead.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to invert a matrix. (result = original-1 ). It must be called
before each inversion to be performed.

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to invert.
result class_Matrix The inverted matrix.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the inversion operation is now ready.

Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if result is not a separate matrix from original.
3. Returns FALSE if any of the matrices is busy doing any stepwise operation.
4. Returns FALSE if original is not a square matrix.

Date Code 20190830 Instruction Manual Programming Reference


15.38 MathMatrix
Classes

5. Returns FALSE if result cannot be sized correctly to store the product.


6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of result are destroyed by this method.

ProcessSteps (Method)
This method performs the inversion algorithm on two already locked-in matrices.
The operation will perform the next steps sub-operations of the complete inversion algo-
rithm.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Outputs
Name IEC 61131 Type Description
error BOOL The matrix is not invertible.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the inversion completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Sets result to an identity matrix.
3. Reduces original to an identity matrix using elementary row operations.
4. Performs the same row operations on result to create the inverse.
5. If at any time the row operations cannot reduce original further and it is still not an
identity matrix, the operation is terminated and error is set.
6. Decrements steps by the number of operations performed.
7. Returns TRUE if the inversion algorithm completed before steps was exhausted.
8. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.
9. The contents of original are destroyed by this method.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.39
Classes

ProcessTimed (Method)
This method performs the inversion algorithm on two already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
inversion algorithm.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Outputs
Name IEC 61131 Type Description
error BOOL The matrix is not invertible.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the inversion completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Sets result to an identity matrix.
3. Reduces original to an identity matrix using elementary row operations.
4. Performs the same row operations on result to create the inverse.
5. If at any time the row operations cannot reduce original further and it is still not an
identity matrix, the operation is terminated and error is set.
6. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
7. Decrements duration by the microseconds consumed.
8. Returns TRUE if the inversion algorithm completed before duration was exhausted.
9. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.
10. The contents of original are destroyed by this method.

Date Code 20190830 Instruction Manual Programming Reference


15.40 MathMatrix
Classes

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixMultiply (Class)
This class handles the locking handshakes and the state required to multiply two class_-
Matrix objects over the course of multiple scans.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to perform a new multiply (result = matrix1 • matrix2). It
must be called before each multiply to be performed.

Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The multiplicand.
matrix2 class_Matrix The multiplier.
result class_Matrix The matrix to store the product.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the multiply operation is now ready.

Processing
1. Returns FALSE if either matrix1 or matrix2 is not initialized.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.41
Classes

2. Returns FALSE if result is not a separate matrix from both matrix1 and matrix2.
3. Returns FALSE if any of the matrices are busy doing any stepwise operation.
4. Returns FALSE if Cols of matrix1 does not match Rows of matrix2.
5. Returns FALSE if result cannot be sized correctly to store the product.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of result are destroyed by this method.

ProcessSteps (Method)
This method performs the multiplication algorithm on three already locked-in matrices.
The operation will perform the next steps sub-operations of the complete multiplication
algorithm.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the multiplication completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Multiplies matrix1 by matrix2.
3. Decrements steps by the number of operations performed.
4. Returns TRUE if the multiply algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.

ProcessTimed (Method)
This method performs the multiplication algorithm on three already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
multiplication algorithm.

Date Code 20190830 Instruction Manual Programming Reference


15.42 MathMatrix
Classes

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the multiplication completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Multiplies matrix1 by matrix2.
3. Performs work toward completing the multiplication algorithm, in groups of steps,
until duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the multiply algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixSubtract (Class)
This class handles the locking handshakes and the state required to subtract one class_-
Matrix object from another over the course of multiple scans.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.43
Classes

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to perform a new subtraction (result = matrix1 – matrix2). It
must be called before each subtraction to be performed.

Inputs/Outputs
Name IEC 61131 Type Description
matrix1 class_Matrix The minuend.
matrix2 class_Matrix The subtrahend.
result class_Matrix The difference of matrix1 – matrix2.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the subtraction operation is now ready.

Processing
1. Returns FALSE if either matrix1 or matrix2 is not initialized.
2. Returns FALSE if result is not a separate matrix from both matrix1 and matrix2.
3. Returns FALSE any of the matrices are busy doing any stepwise operation.
4. Returns FALSE if the dimensions of matrix1 do not match those of matrix2.
5. Returns FALSE if result cannot be resized to match the dimensions of the other two
matrices.
6. Returns FALSE if it cannot lock all matrices involved in the operation.
7. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
8. The contents of result are destroyed by this method.

ProcessSteps (Method)
This method performs the subtraction algorithm on three already locked-in matrices.
The operation will perform the next steps sub-operations of the complete subtraction algo-
rithm.

Date Code 20190830 Instruction Manual Programming Reference


15.44 MathMatrix
Classes

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the subtraction completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Subtracts each element in matrix2 from its corresponding element in matrix1 and
the difference in result.
3. Decrements steps by the number of sub-operations performed.
4. Returns TRUE if the subtraction algorithm completed before steps was exhausted.
5. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.

ProcessTimed (Method)
This method performs the subtraction algorithm on three already locked-in matrices.
The operation will perform work for the next duration microseconds toward the complete
subtraction algorithm.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the subtraction completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Subtracts each element in matrix2 from its corresponding element in matrix1 and
stores the difference in result.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.45
Classes

3. Performs work toward completing the subtraction algorithm, in groups of steps,


until duration microseconds is exceeded.
4. Decrements duration by the microseconds consumed.
5. Returns TRUE if the subtraction algorithm completed before duration was exhausted.
6. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_MatrixTranspose (Class)
This class handles the locking handshakes and the state required to transpose a class_Matrix
object over the course of multiple scans.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to perform a new matrix transpose. It must be called before
each transpose to be performed.

Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be the Hermitian Transpose.
Before each element is placed in result, it will be conjugated.

Date Code 20190830 Instruction Manual Programming Reference


15.46 MathMatrix
Classes

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix to copy from.
result class_Matrix The matrix to copy to.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the transpose operation is now ready.

Processing
1. Returns FALSE if original is not initialized.
2. Returns FALSE if result is not a separate matrix from original.
3. Returns FALSE if either of the matrices is busy doing any stepwise operation.
4. Returns FALSE if result cannot be resized to the correct dimensions.
5. Returns FALSE if it cannot lock all matrices involved in the operation.
6. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
7. The contents of result are destroyed by this method.

ProcessSteps (Method)
This method transposes an already locked-in matrix.
The operation will perform the next steps sub-operations of the complete matrix transpose.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the transpose completed.

Processing
1. Validates that LockMatrices() has been successfully called.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.47
Classes

2. Copies each element (i, j) from original to element (j, i) of result.


3. If conjugate was TRUE, conjugate each element in result.
4. Decrements steps by the number of sub-operations performed.
5. Returns TRUE if the transpose algorithm completed before steps was exhausted.
6. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.

ProcessTimed (Method)
This method transposes an already locked-in matrix.
The operation will perform work for the next duration microseconds toward the complete
matrix transpose.

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the transpose completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Copies each element (i, j) from original to element (j, i) of result.
3. If conjugate was TRUE, conjugate each element in result.
4. Performs work toward completing the transpose, in groups of steps, until duration
microseconds is exceeded.
5. Decrements duration by the microseconds consumed.
6. Returns TRUE if the transpose algorithm completed before duration was exhausted.
7. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Date Code 20190830 Instruction Manual Programming Reference


15.48 MathMatrix
Classes

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

class_Matrix_ATA (Class)
This class handles the locking handshakes and the state required for an optimization of the
operation (AT A) transposing the input matrix and multiplying it by the original matrix over
the course of multiple scans.

Outputs
Name IEC 61131 Type Description
Busy BOOL This class has locked class_Matrix instances and is in the middle
of a calculation.

LockMatrices (Method)
This method primes the class to perform a new matrix operation AT A. It must be called
before each operation to be performed.

Inputs
Name IEC 61131 Type Description
conjugate BOOL The result of this operation will be calculated using the Her-
mitian Transpose. Before the transpose step is complete, each
element will be conjugated.

Inputs/Outputs
Name IEC 61131 Type Description
original class_Matrix The matrix A.
result class_Matrix The matrix for the result.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation is now ready.

Processing
1. Returns FALSE if original is not initialized.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.49
Classes

2. Returns FALSE if result is not a separate matrix from original.


3. Returns FALSE if either of the matrices is busy doing any stepwise operation.
4. Returns FALSE if result cannot be resized to the correct dimensions.
5. Returns FALSE if it cannot lock all matrices involved in the operation.
6. If all other checks succeeded, then stores required references, sets Busy to TRUE,
and returns TRUE.
7. The contents of result are destroyed by this method.

ProcessSteps (Method)
This method computes AT A of an already locked-in matrix.
The operation will perform the next steps sub-operations of the complete task.

Inputs/Outputs
Name IEC 61131 Type Description
steps UDINT The number of sub-operations to attempt this task cycle.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Decrements steps by the number of sub-operations performed.
3. Returns TRUE if the algorithm completed before steps was exhausted.
4. Returns FALSE if LockMatrices() has not been called or steps was exhausted
before completing the algorithm.

ProcessTimed (Method)
This method computes AT A of an already locked-in matrix.
The operation will perform work for the next duration microseconds toward the complete
matrix operation.

Date Code 20190830 Instruction Manual Programming Reference


15.50 MathMatrix
Benchmarks

Inputs/Outputs
Name IEC 61131 Type Description
duration UDINT The number of microseconds to spend on this calculation.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the operation completed.

Processing
1. Validates that LockMatrices() has been successfully called.
2. Performs work toward completing the algorithm, in groups of steps, until duration
microseconds is exceeded.
3. Decrements duration by the microseconds consumed.
4. Returns TRUE if the operation completed before duration was exhausted.
5. Returns FALSE if LockMatrices() has not been called or duration was exhausted
before completing the algorithm.

UnlockMatrices (Method)
This method unlocks any matrices locked by LockMatrices(). It only needs to be called
by the user if the matrix operation has been terminated early by calling Clear() on any of
the dependent matrices. In all other cases, the matrices will be unlocked on completion of
the algorithm.

Processing
1. Requests that all locked matrices free themselves for other operations.
2. Sets Busy to FALSE.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134 firmware
ä SEL-3530
â R134 firmware

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.51
Benchmarks

ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware

Benchmark Test Descriptions


Each benchmark is run on three different matrices: a 2 by 2, an 8 by 8, and a 64 by 64. All
matrices used in the benchmarks are sized such that no memory allocations occur during
the benchmark run.

fun_DeleteMatrix
The posted time is the average execution time of 100 consecutive calls when deleting a
matrix.

fun_MatrixAdd
The posted time is the average execution time of 100 consecutive calls when adding two
matrices.

fun_MatrixCopyColumn
The posted time is the average execution time of 100 consecutive calls when copying a
column from one matrix to another.

fun_MatrixDeterminant
The posted time is the average execution time of 100 consecutive calls when operating on
a valid invertable matrix.

fun_MatrixGaussianElim
The posted time is the average execution time of 100 consecutive calls when operating on
a valid matrix that allows the algorithm to run to completion.

fun_MatrixInvert
The posted time is the average execution time of 100 consecutive calls when inverting a
matrix.

Date Code 20190830 Instruction Manual Programming Reference


15.52 MathMatrix
Benchmarks

fun_MatrixMultiply
The posted time is the average execution time of 100 consecutive calls when multiplying
two matrices.

fun_MatrixSubtract
The posted time is the average execution time of 100 consecutive calls when subtracting
two matrices.

fun_MatrixTranspose
The posted time is the average execution time of 100 consecutive calls when transposing a
matrix.

fun_MatrixTranspose (Hermitian)
The posted time is the average execution time of 100 consecutive calls when calculating
the Hermitian transpose of a matrix.

fun_Matrix_ATA
The posted time is the average execution time of 100 consecutive calls when calculating
AT A.

fun_Matrix_ATA (Hermitian)
The posted time is the average execution time of 100 consecutive calls when calculating
AT A when using the Hermitian transpose.

fun_NewMatrix
The posted time is the average execution time of 100 consecutive calls when allocating a
new matrix.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_DeleteMatrix - 2x2 118 54 6
fun_DeleteMatrix - 8x8 105 49 4
fun_DeleteMatrix - 64x64 119 57 4
fun_MatrixAdd - 2x2 17 7 1
fun_MatrixAdd - 8x8 66 46 4

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.53
Examples

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_MatrixAdd - 64x64 5 408 3 299 244
fun_MatrixCopyColumn - 2x2 7 2 1
fun_MatrixCopyColumn - 8x8 10 3 1
fun_MatrixCopyColumn - 64x64 61 36 1
fun_MatrixDeterminant - 2x2 69 41 3
fun_MatrixDeterminant - 8x8 1 118 665 53
fun_MatrixDeterminant - 64x64 515 458 292 846 26 267
fun_MatrixGaussianElim - 2x2 76 39 2
fun_MatrixGaussianElim - 8x8 1 392 731 61
fun_MatrixGaussianElim - 64x64 516 370 296 721 26 789
fun_MatrixInvert - 2x2 74 48 3
fun_MatrixInvert - 8x8 2 092 1 243 105
fun_MatrixInvert - 64x64 1 034 455 581 496 52 648
fun_MatrixMultiply - 2x2 26 15 2
fun_MatrixMultiply - 8x8 1 002 626 51
fun_MatrixMultiply - 64x64 554 947 325 479 26 534
fun_MatrixSubtract - 2x2 13 6 1
fun_MatrixSubtract - 8x8 90 41 4
fun_MatrixSubtract - 64x64 5 341 3 066 242
fun_MatrixTranspose - 2x2 8 4 1
fun_MatrixTranspose - 8x8 29 12 1
fun_MatrixTranspose - 64x64 2 447 1 731 71
fun_MatrixTranspose (Hermitian) - 2x2 14 7 1
fun_MatrixTranspose (Hermitian) - 8x8 97 48 3
fun_MatrixTranspose (Hermitian) - 64x64 6 071 3 699 192
fun_Matrix_ATA - 2x2 26 15 1
fun_Matrix_ATA - 8x8 563 318 29
fun_Matrix_ATA - 64x64 308 482 179 945 13 186
fun_Matrix_ATA (Hermitian) - 2x2 34 19 1
fun_Matrix_ATA (Hermitian) - 8x8 877 455 39
fun_Matrix_ATA (Hermitian) - 64x64 431 940 239 407 17 341
fun_NewMatrix - 2x2 340 98 10
fun_NewMatrix - 8x8 87 39 5
fun_NewMatrix - 64x64 744 327 13

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.

Date Code 20190830 Instruction Manual Programming Reference


15.54 MathMatrix
Examples

Solving a System of Equations


Objective
The user desires to repeatably solve a system of equations for some set of outputs. This
example solves three equations for three unknowns.
For example, on a given scan the system of equations could be:

x + 2y + 3z = 2

2x + 3y + z = 2

3x + 2y + z = 10

This becomes a 3x4 matrix which, after Gaussian elimination, appears as follows:
   
1 2 3 2 1 0 0 5
 2 3 1 2  =>  0 1 0 −3 
   

3 2 1 10 0 0 1 1

By inspection the solution becomes:



x = 5

y = −3

z=1

Assumptions
Each scan the user has placed the values to use into a pair of arrays of struct_ComplexRect
objects, Values and Answers, before this program is called.

Solution
The user can call this program each scan to receive a solution for the provided inputs, as
shown in Code Snippet 15.1.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.55
Examples

Code Snippet 15.1 prg_MatrixSolver


PROGRAM prg_MatrixSolver
VAR
(* Here are sample values to generate a matrix with a known solution
[[ 1 2 3 | 2 ]
[ 2 3 1 | 2 ]
[ 3 2 1 | 10 ]] *)
Values : ARRAY [0 .. 8] OF struct_ComplexRect :=
[(Re := 1), (Re := 2), (Re := 3),
(Re := 2), (Re := 3), (Re := 1),
(Re := 3), (Re := 2), (Re := 1)];
AnswerCol : ARRAY [0 .. 2] OF struct_ComplexRect :=
[(Re := 2), (Re := 2), (Re := 10)];
// The result should be [5, -3, 1]
Solution : ARRAY [0 .. 2] OF struct_ComplexRect;

CoefficientsMatrix : class_Matrix(3, 3);


SolutionsMatrix : class_Matrix(3, 1);
pt_Data : POINTER TO POINTER TO struct_ComplexRect;
Unsolved : BOOL;

Row : UINT;
Col : UINT;
END_VAR

//Load each row of the matrix


FOR Row := 0 to CoefficientsMatrix.Rows - 1 DO
pt_Data := CoefficientsMatrix.pt_Data;
//Load all but the answer column of the matrix
FOR Col := 0 TO CoefficientsMatrix.Cols - 1 DO
pt_Data[Row][Col] := Values[Row*(CoefficientsMatrix.Cols) + Col];
END_FOR
//Load the answer column after the final increment above
pt_Data := SolutionsMatrix.pt_Data;
pt_Data[Row][0] := AnswerCol[Row];
END_FOR

fun_MatrixGaussianElim(CoefficientsMatrix, SolutionsMatrix, error =>


Unsolved);
FOR Row := 0 to SolutionsMatrix.Rows - 1 DO
//If a solution was successfully found update the solution array.
IF NOT Unsolved THEN
pt_Data := SolutionsMatrix.pt_Data;
Solution[Row] := pt_Data[Row][0];
END_IF
END_FOR

Manipulating a Matrix Across Multiple Scans


Objective
The user needs to manipulate a set of data in matrix form, but has some set of timing
constraints that cause concern regarding the completion of the operations.

Date Code 20190830 Instruction Manual Programming Reference


15.56 MathMatrix
Examples

Assumptions
The user has created an enumeration to assist in managing the data flow to the desired
outcome.

Code Snippet 15.2 enum_States


TYPE enum_States :
(
IDLE,
BUILD_MATRICES,
SUM_MATRICES,
SCALE_RESULT,
STORE_RESULT,
ERROR
);
END_TYPE

Solution
The user can call this program each scan, as shown in Code Snippet 15.3, to receive a
solution for the provided inputs. When Begin is set to true, the calculation will commence.
When the program has copied the answer into Solution, the program sets the Complete flag
to true.

Code Snippet 15.3 prg_MatrixManipulation


PROGRAM prg_MatrixManipulation
VAR CONSTANT
c_StepsPerScan : UDINT := 5;
END_VAR
VAR
State : enum_States := IDLE;

Values1 : ARRAY [0 .. 11] OF struct_ComplexRect;


Values2 : ARRAY [0 .. 11] OF struct_ComplexRect;
Solution : ARRAY [0 .. 11] OF struct_ComplexRect;

Matrix1 : class_Matrix(4, 3);


Matrix2 : class_Matrix(4, 3);
MatrixEnd : class_Matrix(4, 3);
Adder : class_MatrixAdd;
Scalar : struct_ComplexRect := (Re := 2, Im := 0);
pt_Data1 : POINTER TO POINTER TO struct_ComplexRect;
pt_Data2 : POINTER TO POINTER TO struct_ComplexRect;

Row : UINT;
Col : UINT;
Steps : UDINT;
Scans : UDINT;
Begin : BOOL;
Complete : BOOL;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.57
Examples

Code Snippet 15.3 prg_MatrixManipulation (Continued)


Steps := c_StepsPerScan;
Scans := Scans + 1;
WHILE Steps > 0 DO
CASE State OF
IDLE:
IF Begin THEN
State := BUILD_MATRICES;
Row := 0;
Col := 0;
Scans := 1;
pt_Data1 := Matrix1.pt_Data;
pt_Data2 := Matrix2.pt_Data;
Begin := FALSE;
Complete := FALSE;
Steps := Steps - 1;
ELSE
Scans := Scans - 1;
Steps := 0;
END_IF
BUILD_MATRICES:
//This is a state machine to load the matrix a few values at a time
Steps := Steps - 1;
pt_Data1[Row][Col] := Values1[Row*(Matrix1.Cols) + Col];
pt_Data2[Row][Col] := Values2[Row*(Matrix1.Cols) + Col];
Col := Col + 1;
IF Col = Matrix1.Cols THEN
Col := 0;
Row := Row + 1;
IF Row = Matrix1.Rows THEN
IF Adder.LockMatrices(Matrix1, Matrix2, MatrixEnd) THEN
State := SUM_MATRICES;
ELSE
State := ERROR;
END_IF
END_IF
END_IF
SUM_MATRICES:
IF Adder.ProcessSteps(steps) THEN
IF MatrixEnd.StartMatrixOperation(MATRIX_SCALE, 0, 0, Scalar)
THEN
State := SCALE_RESULT;
ELSE
State := ERROR;
END_IF
END_IF
SCALE_RESULT:
IF MatrixEnd.MatrixStepScale(steps) THEN
State := STORE_RESULT;
Row := 0;
Col := 0;
END_IF

Date Code 20190830 Instruction Manual Programming Reference


15.58 MathMatrix
Examples

Code Snippet 15.3 prg_MatrixManipulation (Continued)


STORE_RESULT:
Steps := Steps - 1;
Solution[Row*(MatrixEnd.Cols) + Col] :=
MatrixEnd.pt_Data[Row][Col];
Col := Col + 1;
IF Col = MatrixEnd.Cols THEN
Col := 0;
Row := Row + 1;
IF Row = MatrixEnd.Rows THEN
State := IDLE;
Complete := TRUE;
Steps := 0;
END_IF
END_IF
ERROR:
Steps := 0;
END_CASE
END_WHILE

Troubleshooting a Matrix
Objective
The user has designed a solution with matrices to perform some set of calculations and
something is not going as desired. The user would like to have additional insight into the
matrix element values for online troubleshooting.

Assumptions
This solution assumes a static matrix size. This is not required but if the Rows and Cols
variables of the matrix do not match the sizes provided for the troubleshooting variable,
the user must realize that only data up to the size of the matrix are valid.

Solution
The user can add an additional pointer variable to provide additional insight during runtime.
The syntax for this pointer is shown in Code Snippet 15.4.

Programming Reference Instruction Manual Date Code 20190830


MathMatrix 15.59
Examples

Code Snippet 15.4 prg_MatrixTroubleshoot


PROGRAM prg_MatrixTroubleshoot
VAR CONSTANT
c_Rows : UINT := 2;
c_Cols : UINT := 6;
END_VAR
VAR
Values1 : ARRAY [0 .. 11] OF struct_ComplexRect;

Matrix1 : class_Matrix(c_Rows, c_Cols);

(*This is the troubleshooting variable that has been added.


To be valid it must be reassigned each time the memory allocated to
the matrix could change, so the safest usage is to assign it
immediately
before using it.*)
pt_Raw : POINTER TO ARRAY [0 .. c_Rows-1] OF
POINTER TO ARRAY [0 .. c_Cols-1] OF struct_ComplexRect;
END_VAR

//Load the matrix


(*The SysMemCpy command allows the movement of large quantities of
contiguous
data with a single instruction. This can greatly increase the
performance
of large data copies. If the destination and the source could overlap
then the SysMemMove call facilitates this with a little more overhead.*)
SysMemCpy(Matrix1.pt_Data[0], ADR(Values1),
c_Cols*SIZEOF(struct_ComplexRect));
SysMemCpy(Matrix1.pt_Data[1], ADR(Values1[6]),
c_Cols*SIZEOF(struct_ComplexRect));

(*Here is where we find some meaningful work up to the point of interest


for troubleshooting.*)

//Assign the troubleshooting variable. Now the data can be seen in


//online mode.
//This line is where a breakpoint would be added.
pt_Raw := Matrix1.pt_Data;

(*There is probably additional work to be accomplished after the point of


interest as well*)

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 16

PacketEncodings
Introduction
The PacketEncoding library provides functions and classes to decode from and encode to
common data representations.
Various functions translate bytes of data to and from classes that facilitate storing informa-
tion in an easy-to-use manner. NOTE: See the ACSELERATOR RTAC
Library Extensions Instruction Manual
(LibraryExtensionsIM) for explanation
of the concepts used by the
object-oriented extensions to the
Special Considerations IEC 61131-3 standard.

Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_VectorObject"
myVectorObject := otherVectorObject;

// This is fine
someVariable := myVectorObject.value;
// As is this
pt_myVectorObject := ADR(myVectorObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT members


in function blocks, functions, or methods. Place them in the VAR_IN_OUT section
or use pointers instead.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.4 and older can be used on RTAC firmware version R132 and higher.

Date Code 20190830 Instruction Manual Programming Reference


16.2 PacketEncodings
Enumerations

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_Asn1ClassType
Enumeration Value Description
UNIVERSAL 0 The type is native to ASN.1.
APPLICATION 1 The type is only valid for one specific application.
CONTEXT_SPECIFIC 2 The meaning of this type depends on the context.
SPECIAL_PRIVATE 3 This type is defined in private specifications.

enum_Asn1UniversalClassTags
Enumeration Value
EOC 00
BOOLEAN 01
INTEGER 02
BIT_STRING 03
OCTET_STRING 04
NULL 05
OBJECT_IDENTIFIER 06
OBJECT_DESCRIPTOR 07
EXTERNAL 08
REAL_FLOAT 09
ENUMERATED 10
EMBEDDED_PDV 11
UTF8_STRING 12
RELATIVE_OID 13
RESERVED_1 14
RESERVED_2 15
SEQUENCE 16
SET 17
NUMERIC_STRING 18
PRINTABLE_STRING 19
T61_STRING 20
VIDEOTEX_STRING 21
IA5_STRING 22
UTC_TIME 23
GENERALIZED_TIME 24
GRAPHIC_STRING 25
VISIBLE_STRING 26
GENERAL_STRING 27

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.3
Functions

Enumeration Value
UNIVERSAL_STRING 28
CHARACTER_STRING 29
BMP_STRING 30
LONG_FORM 31

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.

struct_Asn1Index
Name IEC 61131 Type Description
Class enum_Asn1ClassType The class as defined by the first two Identifier
bits.
Constructed BOOL True for constructed entries, False for prim-
itive entries.
TagNumber enum_Asn1UniversalClassTags The type of the entry.
BytesInValue UDINT The number of content bytes.
Index UDINT The starting location of the content bytes as a
byte offset from the beginning of the parsed
byte array.

Functions
This library provides the following functions.

fun_IndexAsn1Packet
Walk the provided byte array and populate a class_Asn1IndexVector with the size, starting
index, and type of each first level entry in an ASN.1 packet as defined by the “Basic Encod-
ing Rules” (BER), the superset of encoding algorithms explained in the ASN.1 standard.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The packet to parse.
numBytes UDINT The number of bytes in the provided packet.

Date Code 20190830 Instruction Manual Programming Reference


16.4 PacketEncodings
Functions

Inputs/Outputs
Name IEC 61131 Type Description
parsedData class_Asn1IndexVector The vector for storing the list of data types and indices.

Return Value
IEC 61131 Type Description
BOOL TRUE if all data objects were indexed successfully.

Processing
The fun_IndexAsn1Packet() function does the following:
ä Validates pt_data for readability.
ä Clears all data from parsedData.
ä Locates the beginning of each first-level data entry in the packet.
ä Stores the class, tag number, and length in bytes of each entry found as well as
whether the entry is primitive or constructed.
ä Stores the index zero for any objects of length zero.
ä Stores the index of the first content byte of the entry as a byte offset from pt_data for
all other data types.
This is accomplished by traversing the entire byte array from the beginning to the end.
Any failure in parsing data results in an error and the function stops attempting to parse
the provided data. The algorithm in use takes the first byte and interprets it to find the
type of data being encoded. If the function finds a tag type of 0b11111 the next bytes are
interpreted as the type of the data. If more than 32 bits of data are used to encode the type,
then this method will return an error. The function interprets the next bytes as the length
of the data.
Three length definitions are allowed:
1. A value less than 0x80 is a direct reference to the length. The function tags the next
byte as the index and skips to the end of the object as defined by its length.
2. A value of 0x80 indicates that the length is not predefined. This value is only al-
lowed for constructed types. The function tags the next byte as the index and im-
mediately terminates the object. The function parses subsequent objects for length
and ignores the content until it finds one End-of-Content object for each previously
recorded length 0x80. The length becomes the accumulation of all the sizes of the
child objects, including their headers.
3. A value between 0x81 and 0x84 indicates that one to four subsequent bytes define
the length of the object as an unsigned integer. The function stores those bytes as
the length and places the index directly after them. It then skips to the end of the
object as defined by its length and the next object begins.
Though values larger than 0x84 are legal, they define numbers of bytes larger than this
library can index and result in an error.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.5
Functions

This process repeats for each object found until the end of the provided data. If the final
length sends the function beyond the end of the array or unclosed length 0x80 objects
remain, the function returns an error.

0101FF02038765430904A73546FF048180<128 Octets>
Becomes
0101FF BOOLEAN length 1 index 2
0203876543 INTEGER length 3 index 5
0904A73546FF REAL_FLOAT length 4 index 10
048180<128 Octets> OCTET_STRING length 128 index 17

fun_DecodeAsn1_Boolean
Decode a Boolean encoded in ASN.1 following the Basic Encoding Rules.

Inputs
Name IEC 61131 Type Description
data BYTE The byte to parse. This should be the byte at the index returned
by fun_IndexAsn1Packet().

Inputs/Outputs
Name IEC 61131 Type Description
value BOOL The result of parsing the data.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the Boolean.

Processing
The fun_DecodeAsn1_Boolean() function does the following:
1. Parses the provided byte into a Boolean.
2. Returns TRUE if the function encountered no errors during parsing.
This function recognizes any non-zero value as TRUE and only the value of zero as FALSE.

0b11001100 = TRUE
0b00000001 = TRUE
0b00000000 = FALSE

Date Code 20190830 Instruction Manual Programming Reference


16.6 PacketEncodings
Functions

fun_DecodeAsn1_Integer
Decode an integer encoded in ASN.1 following the “Basic Encoding Rules.”

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of the
Index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This
should be the BytesInValue returned by fun_-
IndexAsn1Packet().

Inputs/Outputs
Name IEC 61131 Type Description
value DINT The result of parsing the data.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the integer.

Processing
The fun_DecodeAsn1_Integer() function does the following:
1. Validates pt_data for readability.
2. Parses the bytes provided into an integer.
3. Returns FALSE if rollover prevents the function from returning the exact value.
4. Returns TRUE if the function encounters no errors during parsing.
This function expects the provided bytes to be an integer represented in two’s complement
notation using the least number of bytes possible. It only parses numbers represented by
four or fewer bytes.

0x80 = -128
0xFF80 results in an error because it uses more bytes than necessary.
0x7F7F = 32639
0x007F7F results in an error because it uses more bytes than necessary.

fun_DecodeAsn1_Enumerated
Decode an enumeration encoded in ASN.1 following the “Basic Encoding Rules.”

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.7
Functions

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of then
Index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This
should be the BytesInValue returned by fun_-
IndexAsn1Packet().

Inputs/Outputs
Name IEC 61131 Type Description
value DINT The result of parsing the data.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the enumeration.

Processing
The fun_DecodeAsn1_Enumerated() function does the following:
1. Validates pt_data for readability.
2. Parses the bytes provided into an integer.
3. Returns FALSE if rollover prevents returning the exact value.
4. Returns TRUE if the function encountered no errors during parsing.
This function expects the provided bytes to be an integer represented in two’s complement
notation using the least number of bytes possible. It only parses numbers represented by
four or fewer bytes.

0x80 = -128
0xFF80 results in an error because it uses more bytes than necessary.
0x7F7F = 32639
0x007F7F results in an error because it uses more bytes than necessary.

fun_DecodeAsn1_Object_Identifier
Decode an Object Identifier (OID) encoded in ASN.1 following the “Basic Encoding Rules”
to a list of UDINTs.

Date Code 20190830 Instruction Manual Programming Reference


16.8 PacketEncodings
Functions

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of the
index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This
should be the BytesInValue returned by fun_-
IndexAsn1Packet().

Inputs/Outputs
Name IEC 61131 Type Description
value class_DwordVector The vector for storing the list of OID entries.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the OID.

Processing
The fun_DecodeAsn1_Object_Identifier() function does the following:
1. Validates pt_data for readability.
2. Clears all data from value.
3. Parses the bytes provided into an OID.
4. Returns FALSE if rollover prevents the function from returning exact values.
5. Returns TRUE if the function encountered no errors during parsing.
This function expects the provided bytes to appear as a sequence of unsigned integers rep-
resented in the fewest bytes possible. Any byte with the value 1 as its most significant bit
indicates that the next byte is part of the same integer value. A value of one in the most sig-
nificant bit of the final byte of the referenced data indicates the OID would extend beyond
numBytes and the function returns FALSE. If any unsigned integer begins with 0x80, the
number is represented by more bytes than required and the function returns FALSE. The
function also returns FALSE if any unsigned integer requires more than 32 bits to contain
its value.
After finding the first unsigned integer, the function parses it into two distinct values. For
this example, consider val to be the first unsigned integer found. If val is between 0 and
39, the OID begins with 0.val. If val is between 40 and 79, the OID begins with 1.(val-40).
Finally, if val is greater than 79 the OID begins with 2.(val-80).

0x2B0601040181F84F01952A0D040100
Broken into parts
0x2B 0x06 0x01 0x04 0x01 0x81F84F 0x01 0x952A 0x0D 0x04
0x01 0x00
Extra formatting stripped

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.9
Functions

0x2B => 40 & 3 => 1.3


0x81F84F => 0b1_111_1000_100_1111 => 31823
0x952A => 0b1_0101_010_1010 => 2730
1.3.6.1.4.1.31823.1.2730.13.4.1.0

fun_DecodeAsn1_Real
Decode a floating point number encoded as ASN.1 in base 2, 8, or 16 according to the
“Basic Encoding Rules.”

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The byte array to parse. This should be the address of the
index returned by fun_IndexAsn1Packet().
numBytes UDINT The number of bytes in the provided data. This should be
the BytesInValue returned by fun_IndexAsn1Packet().

Inputs/Outputs
Name IEC 61131 Type Description
value REAL The decoded floating point number.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful parsing of the number.

Processing
The fun_DecodeAsn1_Real() function does the following:
1. Validates pt_data for readability.
2. Validates the format and base found in pt_data.
3. Parses the bytes provided into a real.
4. Returns TRUE if the function encounters no errors during parsing.
The ASN.1 standard allows reals to be encoded through the use of both binary values and
character-based encodings. This function only decodes reals that are encoded as binary
values in base 2, 8, or 16.
The decoding of a real happens in eight steps:
1. This function checks for any special values (see Special Bit Patterns for Reals for
details).

Date Code 20190830 Instruction Manual Programming Reference


16.10 PacketEncodings
Functions

2. If numBytes is two, this function returns FALSE because there are no valid real
encodings of length two.
3. This function checks the first byte to ensure it can be parsed. Bit 8 must be one. Bit
7 stores the sign of the value. Bits 6–5 represent the base of the number (B): 0b00 is
base 2, 0b01 is base 8, 0b10 is base 16, and 0b11 is invalid. Bits 4–3 are interpreted
as an unsigned number defining a power of two by which to shift the result (F). Bits
2–1 help delineate the length of the exponent in bytes. A value of 0b00 means one
byte of exponent, 0b01 two bytes, 0b10 three bytes, and 0b11 means the next byte
defines the length as a value from 0–255.
4. Because ASN.1 states the exponent must be represented in the fewest bytes pos-
sible, this function rounds any value with an exponent of three or more bytes to
positive/negative zero or infinity because it cannot represent numbers that large or
small.
5. The exponent is parsed as a two’s complement number (E) and saved.
6. The function interprets as many as the first four of the remaining bytes as an un-
signed integer.
7. Each byte greater than four results in the addition of eight to F, truncating the man-
tissa (M) to a size this function can handle.
8. Finally, the function calculates the result as (M • 2F • BE ), then adds the appropriate
sign.

0xD40C4567 M = 17767 E = 12 B = 8 F = 1
0x8DFF7F01030307 M = 16974599 E = -129 B = 2 F = 3
0x8DFF7F01030307AD M = 16974599 E = -129 B = 2 F = 11

Special Bit Patterns for Reals


Length Bit Pattern Value
0 N/A +0.0
1 0b01000011 –0.0
1 0b01000000 +Infinity
1 0b01000001 –Infinity
1 0b01000010 NaN

fun_SerializeAsn1_Boolean
Place the provided Boolean value as the next entry in an ASN.1 BER message.

Inputs
Name IEC 61131 Type Description
value BOOL The value to use as the payload of this Boolean.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.11
Functions

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the Boolean.

Processing
The fun_SerializeAsn1_Boolean() function does the following:
1. Serializes value and appends it as the next entry in message.
2. Returns TRUE if value was added to message.
This function appends 0x010100 for false and 0x010101 for true.

fun_SerializeAsn1_Integer
Place the integer value provided as the next entry in an ASN.1 BER message.

Inputs
Name IEC 61131 Type Description
value DINT The value to use as the payload of this integer.

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the integer.

Processing
The fun_SerializeAsn1_Integer() function does the following:
1. Serializes value and appends it as the next entry in message.

Date Code 20190830 Instruction Manual Programming Reference


16.12 PacketEncodings
Functions

2. Returns TRUE if value was added to message.


This function determines the fewest number of bytes necessary to encode the provided
integer by checking the most significant byte and the next bit for all ones or all zeros and
dropping the byte from the number. This process can be repeated as many as three times.
After this process completes, it appends the following to the message: 0x02, the number
of significant bytes, and the bytes themselves.

-1 0x0201FF
1 0x020101
134217728 0x02040F000000
-134217728 0x0204F8000000

fun_SerializeAsn1_Enumerated
Place the integer value provided as the next entry in an ASN.1 BER message.

Inputs
Name IEC 61131 Type Description
value DINT The value to use as the payload of this enumeration.

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the enumeration.

Processing
The fun_SerializeAsn1_Enumerated() function does the following:
1. Serializes value and appends it as the next entry in message.
2. Returns TRUE if value was added to message.
This function determines the fewest number of bytes necessary to encode the provided
integer by checking the most significant byte and the next bit for all ones or all zeros and
dropping the byte from the number. This process can be repeated as many as three times.
After this process completes, it appends the following to the message: 0x02, the number
of significant bytes, and the bytes themselves.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.13
Functions

-1 0x0201FF
1 0x020101
134217728 0x02040F000000
-134217728 0x0204F8000000

fun_SerializeAsn1_Real
Place the real provided as the next entry in an ASN.1 BER message.

Inputs
Name IEC 61131 Type Description
value REAL The value to use as the payload of this real.

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which value is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the real.

Processing
The fun_SerializeAsn1_Real() function does the following:
1. Serializes value as a base 2 floating point number and appends it as the next entry
in message.
2. Returns true if value was added to message.
This function serializes every real as a base 2 binary encoded real. First, it checks for any
special value encodings as listed in Special Bit Patterns for Reals. If this real is not a special
case, this method breaks the real into its constituent parts. This process consists of four
steps:
1. The sign is pulled from Bit 32, the exponent from Bits 31 to 24, and the mantissa
from Bits 23 to 1.
2. If the exponent is zero, the mantissa is saved as is. Otherwise the function prepends
a one to the mantissa as the 24th bit.
3. If the exponent is zero, a value of one is added to it. Then the function subtracts 127
subtracted from the exponent to turn it into a two’s complement, signed number; the
function also subtracts 23 from it to remove the decimal point from the mantissa.

Date Code 20190830 Instruction Manual Programming Reference


16.14 PacketEncodings
Functions

4. The function generates a descriptive byte where Bit 8 is one, Bit 7 is one for negative
and zero for positive, Bits 6–2 are zero, and Bit 1 is one for an exponent requiring
a two byte representation and zero for an exponent requiring one byte.
This function then appends 0x09; a length of 0x00, 0x01, 0x05 or 0x06; the descriptive
byte; the exponent; and the mantissa to message.

2.25 0x090580EA900000
-2.25 0x0905C0EA900000
1.25E-38 0x090681FF6B881CEA
1.25E-41 0x090681FF6B0022D8

fun_SerializeAsn1_Object_Identifier
Place the OID provided as the next entry in an ASN.1 BER message.

Inputs/Outputs
Name IEC 61131 Type Description
value class_DwordVector The OID to append to message.
message class_ByteVector The message to which value is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the OID.

Processing
The fun_SerializeAsn1_Object_Identifier() function does the following:
1. Serializes all dwords in value to construct the next entry in message.
2. Returns FALSE if value cannot be serialized.
3. Returns TRUE if value was added to message.
This function starts by adding the first two OID sub entries together ((40 • OID1) + OID2).
Using that result as the first sub entry, it builds a list where each OID sub entry is reduced
to the minimum number of seven-bit segments needed to represent it as an unsigned value.
The function prepends a one to each seven-bit segment except the least significant seven-bit
segment of every sub entry, which the function prepends with a zero. Once all sub entries
have been encoded, the function appends the following to message: 0x06, the number of
bytes representing the sub entries encoded in the same manner as the sub entries themselves,
and the sub entry list.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.15
Functions

1.3.6.1.4.1.31823.1.2730.13.4.4.213268340
Insert Extra formatting
OID Enumeration => 0x06
1.3 => 40 & 3 => 0x2B
.6.1.4.1 => 0x06010401
.31823 => 0x7C4F => 0x81F84F
.1 => 0x01
.2730 => 0x0AAA => 0x952A
.13.4.4 => 0x0D0404
.213268340 => 0xCB63774 => 0xE5D8EE74
length => 18 => 0x12
Construct as Enumeration, Length, SubEntry list
0x06122B0601040181F84F01952A0D0404E5D8EE74

fun_SerializeAsn1_Bit_String
Place the bit string provided as the next entry in an ASN.1 BER message.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The bit string to insert.
numBytes UDINT The number of bytes in the string.
ignoreBits USINT The number of bits of invalid data terminating the string.
(Range: 0–7)

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which the bit string is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the bit string.

Processing
The fun_SerializeAsn1_Bit_String() function does the following:
1. Validates pt_data for read access.
2. Limits ignoreBits to a maximum of seven.
3. Appends an entry containing all bytes prescribed to message, masking the last ig-
noreBits bits of the last byte by replacing then with zero.
4. Returns true if the entire bit string was added to message.

Date Code 20190830 Instruction Manual Programming Reference


16.16 PacketEncodings
Functions

This function appends 0x03, numBytes plus one for the ignoreBits information as the length,
ignoreBits, and the data found at pt_data to message, zeroing the final ignoreBits bits.

fun_BeginAsn1Constructed_Bit_String
Place the codes necessary to begin a constructed bit string in an ASN.1 BER message.
For each call to this method the user must call fun_AppendAsn1_Eoc() before the mes-
sage can be considered complete. Only bit strings should be appended to message until the
call to fun_AppendAsn1_Eoc().

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which the entry is appended.

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the entry.

Processing
The fun_BeginAsn1Constructed_Bit_String() function:
1. Appends the beginning of a constructed bit string to message, (0x2380).
2. Returns TRUE if the entry was added to message.

fun_AppendAsn1_Eoc
Place the codes necessary to end a variable length entry in an ASN.1 BER message.
To ensure proper packet construction, the user must call this function once for each variable
length entry begun.

Inputs/Outputs
Name IEC 61131 Type Description
message class_ByteVector The message to which the entry is appended.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.17
Functions

Return Value
IEC 61131 Type Description
BOOL TRUE for successful appending of the EOC.

Processing
The fun_AppendAsn1_Eoc() function does the following:
1. Appends the End-of-Content entry to message, 0x0000).
2. Returns TRUE if the EOC was added to message.

fun_EncodeBase64_MIME
Encodes a byte vector into base64-MIME format. See base64 and MIME descriptions in
RFC 2045 for complete definition of these encodings and their usage. A common example
is encoding the bytes of a file to be sent as email attachments.

Inputs/Outputs
Name IEC 61131 Type Description
source class_ByteVector The raw byte data to encode.
encoded class_ByteVector The encoded output of source.

Return Value
IEC 61131 Type Description
BOOL TRUE if data was successfully encoded; returns FALSE only if source was
empty.

Processing
The fun_EncodeBase64_MIME() function does the following:
1. Encodes the raw-bytes of source, writing the base64-MIME encoded output to en-
coded. Note that source will not be modified as a result of calling this function.
2. Returns TRUE if input was encoded successfully; returns FALSE only if source
was empty.
This function encodes a raw byte vector in base64-MIME. The output encoded will be
approximately 133% the size of source.

source := Drink plenty of Ovaltine


encoded := RHJpbmsgcGxlbnR5IG9mIE92YWx0aW5l

Date Code 20190830 Instruction Manual Programming Reference


16.18 PacketEncodings
Classes

fun_DecodeBase64_MIME
Decodes a byte vector encoded in base64-MIME format. See base64 and MIME descrip-
tions in RFC 2045 for complete definition of these encodings and their usage.

Inputs/Outputs
Name IEC 61131 Type Description
source class_ByteVector The base64-MIME encoded data to decode.
decoded class_ByteVector The decoded output of source.

Return Value
IEC 61131 Type Description
BOOL TRUE if data was successfully decoded without any corruption detected.
Returns FALSE if source contains only invalid characters or if the number
of valid characters in source is not a multiple of four.

Processing
The fun_DecodeBase64_MIME() function does the following:
1. Decodes the base64-MIME encoded input of source, placing output in decoded.
Invalid, non-base64 characters in source are ignored. Note that source will not be
modified as a result of calling this function.
2. Processes valid base64 characters in groups of four. It fails only if terminal charac-
ters are incorrectly placed or if the number of valid characters is not a multiple of
four.
3. Stops processing after the first group of four characters containing a terminal char-
acter.
4. If source is empty, then the function will return TRUE.
This function decodes a base64-MIME encoded string. The size of decoded will be ap-
proximately 75% of source.

source := RHJpbmsgcGxlbnR5IG9mIE92YWx0aW5l
decoded := Drink plenty of Ovaltine

Classes
Classes are a particular implementation of a Function Block(FB). They provide Methods
and Properties, which a normal FB does not provide.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.19
Classes

class_Asn1IndexVector (Class)
This class provides a DynamicVector structured specifically to store indexing information
about a byte array encoded in ASN.1.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Vector

GetAt (Method)
Provides a copy of the element at the specified index.

Inputs
Name IEC 61131 Type Description
index UDINT The index of the desired element in the vector.

Outputs
Name IEC 61131 Type Description
element struct_Asn1Index The element at the specified index. If the return value is
FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if index is valid and the element is copied. FALSE if index is invalid
or an error occurs.

SetAt (Method)
This method provides write access to any element within the vector.

Date Code 20190830 Instruction Manual Programming Reference


16.20 PacketEncodings
Classes

Inputs
Name IEC 61131 Type Description
index UDINT The index at which to set the value of an element.
value struct_Asn1Index The new element value.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully modified. If index is invalid, the vector
is not modified and the method returns FALSE.

Pop (Method)
This method provides a copy of the last item in the vector and removes that element from
the vector.

Outputs
Name IEC 61131 Type Description
element struct_Asn1Index A copy of the former last element in the vector. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if element is successfully copied and removed from the vector.
FALSE if the size is zero or an error occurs.

Push (Method)
This method appends a copy of the provided element to the end of the vector.

Inputs
Name IEC 61131 Type Description
element struct_Asn1Index The element to copy to the end of the vector.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.21
Benchmarks

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the vector. FALSE if an error
occurs.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware

Benchmark Test Descriptions


fun_IndexAsn1Packet
The posted time is the average execution time of 100 consecutive calls. The byte string
parsed is loaded with two Boolean values and three integer values.

fun_DecodeAsn1_Boolean
The posted time is the average execution time of 100 consecutive calls.

fun_DecodeAsn1_Integer
The posted time is the average execution time of 100 consecutive calls.

fun_DecodeAsn1_Enumerated
The posted time is the average execution time of 100 consecutive calls.

Date Code 20190830 Instruction Manual Programming Reference


16.22 PacketEncodings
Benchmarks

fun_DecodeAsn1_Object_Identifier
The posted time is the average execution time of 100 consecutive calls. The encoded object
identifier that is decoded has a value of (1, 17, 19).

fun_DecodeAsn1_Real
The posted time is the average execution time of 100 consecutive calls.

fun_SerializeAsn1_Boolean
The posted time is the average execution time of 100 consecutive calls.

fun_SerializeAsn1_Integer
The posted time is the average execution time of 100 consecutive calls.

fun_SerializeAsn1_Enumerated
The posted time is the average execution time of 100 consecutive calls.

fun_SerializeAsn1_Real
The posted time is the average execution time of 100 consecutive calls.

fun_SerializeAsn1_Object_Identifier
The posted time is the average execution time of 100 consecutive calls. The object identifier
encoded has a value of (1, 17, 19).

fun_SerializeAsn1_Bit_String
The posted time is the average execution time of 100 consecutive calls. The bit string
encoded has a ASCII value of “Hello World”.

fun_BeginAsn1Constructed_Bit_String
The posted time is the average execution time of 100 consecutive calls.

fun_AppendAsn1_Eoc
The posted time is the average execution time of 100 consecutive calls.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.23
Benchmarks

fun_EncodeBase64_MIME - No Memory Allocation


The posted time is the average execution time of 100 consecutive calls when encoding a
sequence of 100 random bytes. For this benchmark, the encoded vector is sized such that
no memory allocation is required during the benchmark run.

fun_EncodeBase64_MIME - Internal Memory Allocation


The posted time is the average execution time of 100 consecutive calls when encoding a
sequence of 100 random bytes. For this benchmark, the encoded vector is empty with no
memory allocated, thus requiring memory allocations during the benchmark run.

fun_DecodeBase64_MIME - No Memory Allocation


The posted time is the average execution time of 100 consecutive calls when decoding a
sequence of 100 randomly encoded bytes. Note that because the output is 100 bytes, the
input vector is more than 100 bytes. For this benchmark, the decoded vector is sized such
that no memory allocation is required during the benchmark run.

fun_DecodeBase64_MIME - Internal Memory Allocation.


The posted time is the average execution time of 100 consecutive calls when decoding a
sequence of 100 randomly encoded bytes. Note that because the output is 100 bytes, the
input vector is more than 100 bytes. For this benchmark, the encoded vector is empty with
no memory allocated, thus requiring memory allocations during the benchmark run.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_IndexAsn1Packet 30 15 1
fun_DecodeAsn1_Boolean 1 1 1
fun_DecodeAsn1_Integer 3 2 1
fun_DecodeAsn1_Enumerated 2 2 1
fun_DecodeAsn1_Object_Identifier 19 8 1
fun_DecodeAsn1_Real 10 5 1
fun_SerializeAsn1_Boolean 4 2 1
fun_SerializeAsn1_Integer 8 4 1
fun_SerializeAsn1_Enumerated 8 5 1
fun_SerializeAsn1_Real 6 3 1
fun_SerializeAsn1_Object_Identifier 159 42 4
fun_SerializeAsn1_Bit_String 18 9 1
fun_BeginAsn1Constructed_Bit_String 8 3 1
fun_AppendAsn1_Eoc 6 3 1
fun_EncodeBase64_MIME - No Allocation 432 234 25
fun_EncodeBase64_MIME - Allocation 637 291 28

Date Code 20190830 Instruction Manual Programming Reference


16.24 PacketEncodings
Examples

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
fun_DecodeBase64_MIME - No Allocation 430 240 21
fun_DecodeBase64_MIME - Allocation 699 307 25

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.

Decoding an ASN.1 Packet for All Integer Values


Objective
A user has a system that sends packets of data containing a mixture of integer values and
octet string descriptions. She needs to use the integers to make decisions but has no need
of the strings on this RTAC. This solution parses the packet and collects the four integer
values it contains.

Assumptions
This example shows the parsing of a static byte array. To truly use this functionality, the
user would need to populate that array after collecting the data from the network.

Solution
The user can create the program found in Code Snippet 16.1 to parse the byte array.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.25
Examples

Code Snippet 16.1 prg_ParseBytesForIntegers


PROGRAM prg_ParseBytesForIntegers
VAR
PacketBytes : ARRAY [0 .. 99] OF BYTE :=
[
(*The string Value1*)
16#04, 16#06, 16#56, 16#61, 16#6C, 16#75, 16#65, 16#31,
(*The integer 10_000*)
16#02, 16#02, 16#27, 16#10,
(*The string Value2*)
16#04, 16#06, 16#56, 16#61, 16#6C, 16#75, 16#65, 16#32,
(*The integer -50_000*)
16#02, 16#03, 16#FF, 16#3C, 16#B0,
(*The string Value3*)
16#04, 16#06, 16#56, 16#61, 16#6C, 16#75, 16#65, 16#33,
(*The integer 15*)
16#02, 16#01, 16#0F,
(*The string Value4*)
16#04, 16#06, 16#56, 16#61, 16#6C, 16#75, 16#65, 16#34,
(*The integer 1_500_000_000*)
16#02, 16#04, 16#59, 16#68, 16#2F, 16#00,
(*This is the end of the meaningful data. The array here is
bigger than
required as a reminder that this may need to be populated with
different values that take more or less space.*)
50(0)];
// The number of bytes of valid data. This will come from the network
socket.
ValidByteCount : UDINT := 50;

// Containers for parsed data.


IndexList : class_Asn1IndexVector;
IndexObject : struct_Asn1Index;

// Iterator counts.
ListPosition : UDINT;
ObjectCount : UDINT;

//The result array.


IntArray : ARRAY [0 .. 3] OF DINT;

// Flags for any errors that might be encountered.


Parsed : BOOL;
CorrectCount : BOOL;
ValidInts : ARRAY [0 .. 3] OF BOOL;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


16.26 PacketEncodings
Examples

Code Snippet 16.1 prg_ParseBytesForIntegers (Continued)


// Reset the ValidInts array in case there are less Integers this pass.
FOR ObjectCount := 0 TO 3 DO
ValidInts[ObjectCount] := FALSE;
END_FOR
// First parse the current packet for its indexes.
Parsed := fun_IndexAsn1Packet(ADR(PacketBytes), ValidByteCount, IndexList);
IF Parsed THEN
// If that worked walk the indices and parse each integer found.
ObjectCount := 0;
ListPosition := 0;
WHILE ListPosition < IndexList.Size DO
IndexList.GetAt(ListPosition, element => IndexObject);
IF IndexObject.Class = UNIVERSAL AND IndexObject.Asn1Class =
INTEGER THEN
// Make sure we are inside the bounds of our array.
IF ObjectCount > 3 THEN
// Set an error flag to indicate too many integers found.
CorrectCount := FALSE;
EXIT;
END_IF
ValidInts[ObjectCount] := fun_DecodeAsn1_Integer(
// Begin at the Index found.
ADR(PacketBytes[IndexObject.Index]),
// Walk the number of bytes specified.
IndexObject.BytesInValue,
// Place the result in the storage array.
IntArray[ObjectCount]);
ObjectCount := ObjectCount + 1;
END_IF
ListPosition := ListPosition + 1;
END_WHILE
IF ObjectCount <> 4 THEN
// Set an error flag if too few integers found.
CorrectCount := FALSE;
END_IF
END_IF

Decoding an OID Found Three Layers Deep in an ASN.1


Packet
Objective
A user receives a package with an OID nested three layers deep inside. He needs to decode
that OID before making a work decision.

Assumptions
This example shows the parsing of a static byte array. To truly use this functionality the
user would need to populate that array after collecting the data from the network.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.27
Examples

Solution
The user can create the program found in Code Snippet 16.2 to parse the byte array.

Code Snippet 16.2 prg_ParseThreeTiers


PROGRAM prg_ParseThreeTiers
VAR
PacketBytes : ARRAY [0 .. 99] OF BYTE :=
[
(*Constructed sequence*)
16#30, 16#13,
(*Constructed sequence*)
16#30, 16#11,
(*OID 1.3.6.1.4.1.31823.1.2730.13.4.1.0*)
16#06, 16#0F, 16#2B, 16#06, 16#01, 16#04, 16#01, 16#81, 16#F8,
16#4F, 16#01, 16#95, 16#2A, 16#0D, 16#04, 16#01, 16#00,
(*This is the end of the meaningful data
The array here is bigger than required as a reminder that
This may need to be populated with different values that take
more or less space. *)
79(0)];
// The number of bytes of valid data. This will come from the network
socket.
ValidByteCount : UDINT := 21;

// Containers for each tier.


Tier1Objects : class_Asn1IndexVector;
Tier2Objects : class_Asn1IndexVector;
Tier3Objects : class_Asn1IndexVector;
IndexObjectT1 : struct_Asn1Index;
IndexObjectT2 : struct_Asn1Index;
IndexObjectT3 : struct_Asn1Index;

// Flags to allow for separation of logic


ParsedL1 : BOOL;
ParsedL2 : BOOL;
ParsedL3 : BOOL;
ValidOid : BOOL;

// Container for the OID


Oid : PacketEncodings.class_DwordVector;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


16.28 PacketEncodings
Examples

Code Snippet 16.2 prg_ParseThreeTiers (Continued)


// Reset from last scan
ParsedL2 := FALSE;
ParsedL3 := FALSE;
ValidOid := FALSE;

// Parse the first tier.


ParsedL1 := fun_IndexAsn1Packet(ADR(PacketBytes), ValidByteCount,
Tier1Objects);
IF ParsedL1 THEN
IF Tier1Objects.GetAt(0, element => IndexObjectT1) THEN
IF IndexObjectT1.Constructed THEN
ParsedL2 := fun_IndexAsn1Packet(
// The new starting index is the original offset plus
the
// index identified in the previous level.
ADR(PacketBytes[IndexObjectT1.Index]),
// Only parse the bytes prescribed by the previous
object.
IndexObjectT1.BytesInValue, Tier2Objects);
END_IF
END_IF
END_IF
IF parsedL2 THEN
IF Tier2Objects.GetAt(0, element => IndexObjectT2) THEN
IF IndexObjectT2.Constructed THEN
ParsedL3 := fun_IndexAsn1Packet(
// The new starting index is the original offset plus
the
// offset of the first tier object plus
// index identified in the previous level.
ADR(PacketBytes[IndexObjectT1.Index +
IndexObjectT2.Index]),
// Only parse the bytes prescribed by the previous
object.
IndexObjectT2.BytesInValue, Tier3Objects);
END_IF
END_IF
END_IF
IF ParsedL3 THEN
IF Tier3Objects.GetAt(0, element => IndexObjectT3) THEN
IF IndexObjectT3.Class = UNIVERSAL AND
IndexObjectT3.Asn1Class = OBJECT_IDENTIFIER THEN
ValidOid := fun_DecodeAsn1_Object_Identifier(
// Here the starting index is based on all three tiers.
ADR(PacketBytes[ IndexObjectT1.Index
+ IndexObjectT2.Index
+ IndexObjectT3.Index]),
IndexObjectT3.BytesInValue,
Oid);
END_IF
END_IF
END_IF
IF ValidOid THEN
; // Do any necessary work based on the OID here.
END_IF

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.29
Examples

Encoding Data as an ASN.1 Packet


Objective
A user needs to package some integer and real data points. She also needs to intersperse
the data with Boolean flags based on the validity of the data.
Once the data are packaged the user needs to send the information to Port 1000 of a listening
server.

Assumptions
The RTAC also has access to the SELEthernetControllers library. The listening server must
know the format of the incoming data.

Solution
The user can create the program found in Code Snippet 16.3 to build the data package.

Code Snippet 16.3 prg_EncodeOutboundData


PROGRAM prg_EncodeOutboundData
VAR
// The storage for the outbound packet.
Packet : PacketEncodings.class_ByteVector;

// The integers to encode.


MyInts : ARRAY [1 .. 3] OF DINT := [-70, 45, 9000];
MyIntsValid : ARRAY [1 .. 3] OF BOOL := [FALSE, TRUE, TRUE];

// The reals to encode.


MyReals : ARRAY [1 .. 3] OF REAL := [1045.99, 45.2, 7];
MyRealsValid : ARRAY [1 .. 3] OF BOOL := [TRUE, FALSE, TRUE];

// Infrastructure required to place the packet on the wire.


MySocket : class_TcpClient;
LocalIP : SELEthernetController.INADDR := (ulAddr := 0);
DestinationIP : SELEthernetController.INADDR;
SocketInitialized : BOOL;

// Counting variable.
i : UDINT;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


16.30 PacketEncodings
Examples

Code Snippet 16.3 prg_EncodeOutboundData (Continued)


// Make sure the socket is configured correctly.
IF NOT SocketInitialized THEN
MySocket.bootstrap_SetLocalIP(1000, localIP);
fun_StringToInaddr('10.10.10.10', ipAddr => DestinationIP);
MySocket.SetIP(destinationIP, 1000);
MySocket.Open();
SocketInitialized := TRUE;
END_IF

// Build the packet.


Packet.Recycle();
FOR i := 1 TO 3 DO
fun_SerializeAsn1_Integer(myInts[i], Packet);
fun_SerializeAsn1_Boolean(myIntsValid[i], Packet);
END_FOR
FOR i := 1 TO 3 DO
fun_SerializeAsn1_Real(myReals[i], Packet);
fun_SerializeAsn1_Boolean(myRealsValid[i], Packet);
END_FOR

// Send the data.


MySocket.SendData(Packet.pt_Data, UDINT_TO_DINT(Packet.Size));

Encoding Raw Binary Data in Base64-MIME


Objective
A user needs to encode and store some binary data from the file system in base64-MIME
encoding. For illustrative purposes, the user saves their data to a file.

Assumptions
The RTAC has access to the DynamicVectors and FileIo libraries.

Solution
The user can create the program found in Code Snippet 16.4 to encode their data in base64-MIME
and store the encoded data to the local file system.

Programming Reference Instruction Manual Date Code 20190830


PacketEncodings 16.31
Examples

Code Snippet 16.4 prg_Base64_Example


PROGRAM prg_Base64_Example
VAR_INPUT
alarm : BOOL;
END_VAR
VAR
//State flags for file io operations
complete : BOOL := FALSE;
firstRead : BOOL := TRUE;
writeFile : BOOL := FALSE;
error : BOOL;
errorString : STRING(255);

//Location of the binary data the user wishes to encode


dataFile : STRING(255) := 'binaryData.data';
//Temporary location for the raw binary data
rawData : class_ByteVector;
//Temporary location for the encoded data
encodedData : class_ByteVector;
//File io objects
fileReader : class_FileReader();
fileWriter : class_Filewriter('encodedData.txt');
END_VAR

IF alarm THEN
IF NOT complete THEN
IF firstRead THEN
fileReader.ReadFile(dataFile);
firstRead := FALSE;
ELSIF fileReader.BytesInBuffer > 0 THEN
rawData.Recycle();
fileReader.AppendToVector(0,rawData);
//encode the raw data in base64-MIME
PacketEncodings.fun_EncodeBase64_MIME(source := rawData,
encoded := encodedData);
writeFile := TRUE;
END_IF

IF writeFile THEN
fileWriter.AppendVector(encodedData);
writeFile := FALSE;
complete := TRUE;
END_IF

//log any errors


IF fileReader.Error THEN
error := TRUE;
errorString := fileReader.ErrorDesc;
END_IF
IF fileWriter.Error THEN
error := TRUE;
errorString := fileWriter.ErrorDesc;
END_IF
END_IF
END_IF

//called each scan to complete the read/write ops


fileReader.Run();
fileWriter.Run();

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 17

PowerMetering
Introduction
This library provides objects for performing common power metering functions. These
functions provide event times for minimum and maximum thresholds, accumulated energy
over time, demand over a configurable length of time, and KYZ/KY accumulators. Exam-
ple applications include use of these function blocks with Axion analog input, digital input,
and/or CT/PT (current transformer/potential transformer) modules.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.1.0 and older can be used on RTAC firmware version R132 and higher.

Function Blocks
fb_Maximum
Compare input value to stored maximum value, update output if greater, and record the
date/time of occurrence.

Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided initial
values; a value of TRUE results in setting Maximum to
zero and the time stamp to the present time.
initialValue REAL Maximum value to use for initialization if set-
tingsChange is FALSE.
initialTime timestamp_t Time stamp value to use for initialization if set-
tingsChange is FALSE.

Date Code 20190830 Instruction Manual Programming Reference


17.2 PowerMetering
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable maximum comparison.
AnalogQuantity REAL Value to check against Maximum.
Reset BOOL Flag to reset Maximum and time stamp.

Outputs
Name IEC 61131 Type Description
Maximum REAL Maximum value.
EventTime timestamp_t The moment at which Maximum was last updated.

Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, Maximum is set to zero and
will take on the next AnalogQuantity received.
ä Compare the input AnalogQuantity to the stored Maximum value.
ä If the input is greater than the stored value for two or more samples, update Maximum
and record the date and time of occurrence.

fb_Minimum
Compare input real value to stored minimum value, update output if greater, and record the
date/time of occurrence.

Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided
initial values; a value of TRUE results in setting
Minimum to zero and the time stamp to the present
time.
initialValue REAL Minimum value to use for initialization, if set-
tingsChange is FALSE.
initialTime timestamp_t Time stamp value to use for initialization, if set-
tingsChange is FALSE.
minimumThreshold REAL Lowest value this function block will record.

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.3
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable minimum comparison.
AnalogQuantity REAL Value to check against Minimum.
Reset BOOL Flag to reset Minimum and time stamp.

Outputs
Name IEC 61131 Type Description
Minimum REAL Minimum value.
EventTime timestamp_t The moment at which Minimum was last updated.

Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, Minimum is set to zero and
will take on the next AnalogQuantity received.
ä Compare the input AnalogQuantity to the stored Minimum value.
ä If the input is less than the stored value and greater than minimumThreshold for two
or more samples, update Minimum and record the date and time of occurrence.
ä This function block will work with any values but is designed for use alongside fb_-
Maximum with positive numbers.

fb_Energy
Collect energy input over time, accumulating positive and negative values in separate reg-
isters.

Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided ini-
tial values; a value of TRUE results in setting Ener-
gyIn and EnergyOut to zero.
initialValueIn REAL EnergyIn value to use for initialization, if set-
tingsChange is FALSE.
initialValueOut REAL EnergyOut value to use for initialization, if set-
tingsChange is FALSE.
rolloverThreshold REAL Rollover value for this function block.

Date Code 20190830 Instruction Manual Programming Reference


17.4 PowerMetering
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable energy accumulation.
AnalogQuantity REAL Value to use for accumulating energy.
Reset BOOL Flag to reset EnergyIn and EnergyOut.

Outputs
Name IEC 61131 Type Description
EnergyIn REAL Accumulated energy in.
EnergyOut REAL Accumulated energy out.

Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, EnergyIn and EnergyOut are
set to zero.
ä Maintain the accumulated IN/OUT energy. A negative power value is considered IN
energy while a positive power value is considered OUT energy. Receiving a positive
power value (OUT) will not affect the accumulated IN value and vice versa.
ä Update no more frequently than once a second regardless of the RTE cycle time.
ä Restart either output to zero when it exceeds rolloverThreshold.

fb_Demand
Calculates demand.

Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided
initial values; a value of TRUE results in setting De-
mand to zero.
initialValue REAL Demand value to use for initialization, if set-
tingsChange is FALSE.
demandType Demand_Enum The calculation method this function block will use;
either ROLLING or THERMAL.
timeConstant Time_Constant_Enum The time constant this function block will use dur-
ing demand calculations, MIN5, MIN10, MIN15,
MIN20, MIN30, MIN60.

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.5
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable demand calculation.
AnalogQuantity REAL Value to use for calculating demand.
Reset BOOL Flag to reset Demand.

Outputs
Name IEC 61131 Type Description
Demand REAL Demand value.

Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, Demand is set to zero.
ä Update no more frequently than once a second regardless of the RTE cycle time.
ä Thermal demand output updates with each call to the function block.
ä Thermal demand is a logarithmic average of the power used, with more-recent load
weighted more heavily than less-recent load. For a steady state transition, this block
outputs Demand of 90% of the change after timeConstant has passed.
ä Rolling demand output only updates once every 5 minutes.
ä Rolling demand averages input over periods of 5 minutes and outputs Demand as an
average of enough 5 minute averages to equal timeConstant.

fb_KYZ
Accumulate a count of transitions from only a Y of true to only a Z of true or back again.

Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided initial
values; a value of TRUE results in setting CV and ROV
to zero.
initialCV BCR Initial accumulator state, if settingsChange is FALSE.
initialROV UDINT Initial roll over value, if settingsChange is FALSE.
maxValue UDINT The value of the accumulator at which roll over occurs

Date Code 20190830 Instruction Manual Programming Reference


17.6 PowerMetering
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable the KYZ accumulator.
Y SPS Terminal Y.
Z SPS Terminal Z.
Reset BOOL Flag to reset the state of the KYZ block.

Outputs
Name IEC 61131 Type Description
CV BCR The number of transitions from Y to Z or Z to Y.
ROV UDINT The number of times CV has reset to zero.

Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, CV is set to the default state
and ROV is set to zero.
ä Monitor Y and Z when EN is TRUE and Reset is FALSE.
ä Define a countable state as Y and Z being in opposite states with qualities of good.
ä Define a countable transition as the present inputs being in a countable state and the
present state of the inputs is opposite to the previous counted state of the inputs.
ä Count only at times when both Y and Z report good quality (i.e., q.validity = good).
ä Set the CV quality attribute based on the input with the least quality. (I.e., If input
Y.q.validity is invalid and Z.q.validity is good, then CV.q.validity is invalid.)
ä Override the quality of CV to invalid if the block is disabled or being reset.
ä Increment ROV and the accumulator to zero when the accumulator equals maxValue.
The practical implication is that maxValue declared at initialization is never reported,
but instead the accumulator rolls over to zero allowing the total count to be calculated
as CV + ROV • maxValue.

fb_KY
Accumulate a count of transitions of a single variable Y.

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.7
Function Blocks

Initialization Inputs
Name IEC 61131 Type Description
settingsChange BOOL Flag to prevent setting outputs based on provided initial
values; a value of TRUE results in setting CV and ROV
to zero.
initialCV BCR Initial accumulator state, if settingsChange is FALSE.
initialROV UDINT Initial roll over value, if settingsChange is FALSE.
maxValue UDINT The value of the accumulator at which roll over occurs

Inputs
Name IEC 61131 Type Description
EN BOOL Flag to enable or disable the KY accumulator.
Y SPS Terminal Y.
Reset BOOL Flag to reset the state of the KY block.

Outputs
Name IEC 61131 Type Description
CV BCR The number of transitions of Y.
ROV UDINT The number of times CV has reset to zero.

Processing
ä If settingsChange is FALSE, the function block initializes to the values passed in.
ä If settingsChange is TRUE or after reset is deasserted, CV is set to the default state
and ROV is set to zero.
ä Monitor Y when EN is TRUE and Reset is FALSE.
ä Define a countable transition as the present input being opposite its previous value.
ä Count only at times when Y reports good quality (i.e., q.validity = good).
ä Set the CV quality attribute as the quality of the input.
ä Override the quality of CV to invalid if the block is disabled or being reset.
ä Increment ROV and the accumulator to zero when the accumulator equals maxValue.
The practical implication is that maxValue declared at initialization is never reported,
but instead the accumulator rolls over to zero allowing the total count to be calculated
as CV + ROV • maxValue.

Date Code 20190830 Instruction Manual Programming Reference


17.8 PowerMetering
Benchmarks

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R135-V1 firmware
ä SEL-3530
â R135-V2 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V0 firmware

Benchmark Test Descriptions


fb_Maximum
The posted time is the average execution time of 100 calls in which a new maximum value
was observed. This constitutes the longest running time for this call.

fb_Minimum
The posted time is the average execution time of 100 calls in which a new minimum value
was observed. This constitutes the longest running time for this call.

fb_Energy
The posted time is the average execution time of 100 calls at the top of the second. This
constitutes the longest running time for this call.

fb_Demand (Thermal)
The posted time is the average execution time of 100 calls at the top of the second. This
constitutes the longest running time for this call.

fb_Demand (Rolling)
The posted time is the average execution time of 100 calls at a 5-minute boundary. This
constitutes the longest running time for this call.

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.9
Examples

fb_KYZ
The posted time is the average execution time of 100 calls where the block incremented.
This constitutes the longest running time for this call.

fb_KY
The posted time is the average execution time of 100 calls where the block incremented.
This constitutes the longest running time for this call.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fb_Maximum 5 3 2
fb_Minimum 4 3 1
fb_Energy 4 3 1
fb_Demand(Thermal) 5 3 1
fb_Demand(Rolling) 5 3 1
fb_KYZ 1 1 1
fb_KY 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.

Maximum
Objective
A user has an analog variable and wants to determine the greatest observed value of the
analog.

Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for non-volatile variables while the second program assumes
there is a requirement that variables are retained through power loss.

Date Code 20190830 Instruction Manual Programming Reference


17.10 PowerMetering
Examples

Solution
The user can create a program as shown in Code Snippet 17.1. Note that this example does
not use retain variables.

Code Snippet 17.1 prg_Maximum_Example


PROGRAM prg_Maximum_Example
VAR
En : BOOL;
Value : REAL;
InitValue : REAL;
Reset : BOOL;
Maximum : REAL;
Max_Event : timestamp_t;

Max1 : fb_Maximum( settingsChange := TRUE,


initialValue := InitValue,
initialTime := Max_Event);
END_VAR

//Call the Maximum function with the desired value


Max1(EN:=En, AnalogQuantity:=Value, Reset:=Reset);

// Assign the outputs


Maximum := Max1.Maximum;
Max_Event := Max1.EventTime;

Solution With Retain Variables


Retain variables allow variable values to remain consistent through removal and restora-
tion of power and program downloads. The user can create a program as shown in Code
Snippet 17.2. RETAIN_UID must be initialized on the first run. See Retain Variables on
page 17.21 for more details on retain variables.

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.11
Examples

Code Snippet 17.2 prg_Maximum_Retain_Example


VAR_GLOBAL RETAIN
// If Event Time is not desired to be retained a REAL value can be used
Max1Retain : MV;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD:=1;
END_VAR

PROGRAM prg_Maximum_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;

Max1 : fb_Maximum( settingsChange := RETAIN_VERSION <> VERSION,


initialValue := Max1Retain.instMag,
initialTime := Max1Retain.t);
(*If VERSION has been modified, Maximum value will be reset to zero,
*otherwise the retain values will be used. settingsChange should be
evaluated
*from constants or retain variables only. *)
END_VAR

Code Snippet 17.2 prg_Maximum_Retain_Example (Continued)


//Update the retain variable first thing
RETAIN_VERSION := VERSION;

//Call the Maximum function with the desired value


Max1(EN:=En, AnalogQuantity:=Value, Reset:=Reset);

// Assign the outputs to the retain variables


Max1Retain.instMag := Max1.Maximum;
Max1Retain.t := Max1.EventTime;

Minimum
Objective
A user has an analog variable and wants to determine the smallest observed value of the
analog.

Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables, and the second program assumes
there is a requirement that variables are retained through power loss.

Date Code 20190830 Instruction Manual Programming Reference


17.12 PowerMetering
Examples

Solution
The user can create a program as shown in Code Snippet 17.3. Note that this example does
not use retain variables.

Code Snippet 17.3 prg_Minimum_Example


PROGRAM prg_Minimum_Example
VAR
En : BOOL;
InitValue : REAL;
Value : REAL;
Reset : BOOL;
Minimum : REAL;
MinThreshold : REAL := 50000;
Min_Event : timestamp_t;

Min1 : fb_Minimum( settingsChange := TRUE,


initialValue := InitValue,
initialTime := Min_Event,
minimumThreshold := MinThreshold);
END_VAR

Code Snippet 17.3 prg_Minimum_Example (Continued)


//Call the Minimum function with the desired value
Min1(EN := En, AnalogQuantity := Value, Reset := Reset);

// Assign the outputs


Minimum := Min1.Minimum;
Min_Event := Min1.EventTime;

Solution With Retain Variables


Retain variables allow variable values to remain consistent through removal and restora-
tion of power and program downloads. The user can create a program as shown in Code
Snippet 17.4. RETAIN_UID must be initialized on the first run. See Retain Variables on
page 17.21 for more details on retain variables.

Code Snippet 17.4 prg_Minimum_Retain_Example


VAR_GLOBAL RETAIN
// If Event Time is not desired to be retained a REAL value can be used
Min1Retain : MV;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD := 1;
END_VAR

PROGRAM prg_Minimum_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.13
Examples

MinThreshold : REAL := 50000;

Min1 : fb_Minimum( settingsChange := RETAIN_VERSION <>


VERSION,
initialValue := Min1Retain.instMag,
initialTime := Min1Retain.t,
minimumThreshold := MinThreshold);
(*If VERSION has been modified, Minimum value will be reset to zero,
*otherwise the retain values will be used. settingsChange should be
evaluated
*from constants or retain variables only. *)
END_VAR

//Update the retain variable first thing


RETAIN_VERSION := VERSION;

//Call the Minimum function with the desired value


Min1(EN:=En, AnalogQuantity:=Value, Reset:=Reset);

// Assign the outputs to the retain variables


Min1Retain.instMag := Min1.Minimum;
Min1Retain.t := Min1.EventTime;

Energy
Objective
A user has a power quantity and wants to keep track of energy flow. Positive power value
is considered to be “out” and negative power is considered to be “in.”

Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.

Solution
The user can create a program as shown in Code Snippet 17.5. Note that this example does
not use retain variables.

Code Snippet 17.5 prg_Energy_Example


PROGRAM prg_Energy_Example
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;
InitIn : REAL;
InitOut : REAL;
Threshold : REAL;
EnergyIn : REAL;

Date Code 20190830 Instruction Manual Programming Reference


17.14 PowerMetering
Examples

EnergyOut : REAL;

Energy1 : fb_Energy( settingsChange := TRUE,


initialValueIn := InitIn,
initialValueOut := InitOut,
rollOverThreshold := Threshold);
END_VAR

//Call the Energy function with the desired value


Energy1(EN := En, AnalogQuantity := Value, Reset := Reset);

// Assign the outputs


EnergyIn := Energy1.EnergyIn;
EnergyOut := Energy1.EnergyOut;

Solution With Retain Variables


Retain variables allow variable values to remain consistent through removal and restora-
tion of power and program downloads. The user can create a program as shown in Code
Snippet 17.6. RETAIN_UID must be initialized on the first run. See Retain Variables on
page 17.21 for more details on retain variables.

Code Snippet 17.6 prg_Energy_Retain_Example


VAR_GLOBAL RETAIN
EnergyIn : REAL;
EnergyOut : REAL;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD := 1;
END_VAR

PROGRAM prg_Energy_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;
Threshold : REAL;

Energy1 : fb_Energy( settingsChange := (RETAIN_VERSION <>


VERSION),
initialValueIn := EnergyIn,
initialValueOut := EnergyOut,
rollOverThreshold := Threshold);
(*If VERSION has been modified, the energy values will be reset to zero,
*otherwise the retain values will be used. settingsChange should be
evaluated
*from constants or retain variables only. *)
END_VAR

//Update the retain variable first thing


RETAIN_VERSION := VERSION;

//Call the Energy function with the desired value

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.15
Examples

Energy1(EN := En, AnalogQuantity := Value, Reset := Reset);

// Assign the outputs to the retain variables


EnergyIn := Energy1.EnergyIn;
EnergyOut := Energy1.EnergyOut;

Demand
Objective
A user wants to calculate demand on an analog quantity.

Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.

Solution
The user can create a program as shown in Code Snippet 17.7. Note that this example does
not use retain variables.

Code Snippet 17.7 prg_Demand_Example


PROGRAM prg_Demand_Example
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;
InitValue : REAL;
DemandTherm : REAL;
DemandRolling : REAL;

Demand1 : fb_Demand( settingsChange := TRUE,


initialValue := InitValue,
DemandType := THERMAL,
timeConstant := MIN10);

Demand2 : fb_Demand( settingsChange := TRUE,


initialValue := InitValue,
DemandType := ROLLING,
timeConstant := MIN20);
END_VAR

//Call the Demand function with the desired values


Demand1(EN := En, AnalogQuantity := Value, Reset := Reset);
Demand2(EN := En, AnalogQuantity := Value, Reset := Reset);

// Assign the outputs


DemandTherm := Demand1.Demand;
DemandRolling := Demand2.Demand;

Date Code 20190830 Instruction Manual Programming Reference


17.16 PowerMetering
Examples

Solution With Retain Variables


Retain variables allow variable values to remain consistent through removal and restora-
tion of power and program downloads. The user can create a program as shown in Code
Snippet 17.8. RETAIN_UID must be initialized on the first run. See Retain Variables on
page 17.21 for more details on retain variables.

Code Snippet 17.8 prg_Demand_Retain_Example


VAR_GLOBAL RETAIN
DemandTherm : REAL;
DemandRolling : REAL;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD := 1;
END_VAR

Code Snippet 17.8 prg_Demand_Retain_Example (Continued)


PROGRAM prg_Demand_Example_Retain
VAR
En : BOOL;
Value : REAL;
Reset : BOOL;

Demand1 : fb_Demand( settingsChange := (RETAIN_VERSION <> VERSION),


initialValue := DemandTherm,
DemandType := THERMAL,
timeConstant := MIN10);

Demand2 : fb_Demand(settingsChange := (RETAIN_VERSION <> VERSION),


initialValue := DemandRolling,
DemandType := ROLLING,
timeConstant := MIN20);
(*If VERSION has been modified, the demand values will be reset to zero,
*otherwise the retain values will be used. settingsChange should be
evaluated
*from constants or retain variables only. *)
END_VAR

//Update the retain variable first thing


RETAIN_VERSION := VERSION;

//Call the Demand function with the desired value


Demand1(EN := En, AnalogQuantity := Value, Reset := Reset);
Demand2(EN := En, AnalogQuantity := Value, Reset := Reset);

// Assign the outputs to the retain variables


DemandTherm := Demand1.Demand;
DemandRolling := Demand2.Demand;

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.17
Examples

KYZ
Objective
A user has two inputs connected to the Y and Z terminal of a meter and wants to count the
number of transitions.

Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.

Solution
The user can create a program as shown in Code Snippet 17.9. Note that this example does
not use retain variables.

Code Snippet 17.9 prg_KYZ_Example


PROGRAM prg_KYZ_Example
VAR
//Terminal for Y and Z pulses
DI_Y_Terminal : SPS;
DI_Z_Terminal : SPS;
//Enabling and Rest Conditions
Enable : BOOL;
Reset : BOOL;

//Placeholder for DNP Tag


DNP_Counter1 : BCR;
DNP_Counter2 : BCR;
//Additional Outputs
RollOver1 : UDINT;
RollOver2 : UDINT;

//The KYZ blocks ignore their initial values because settingsChange is


true.
KYZ_12bit : fb_KYZ( settingsChange := TRUE, initialCV :=
DNP_Counter1,
initialROV := 0, maxValue := 4095);

KYZ_32bit : fb_KYZ( settingsChange := TRUE, initialCV :=


DNP_Counter2,
initialROV := 0, maxValue := 4294967295);
END_VAR

//Call the function block every cycle and assign outputs


KYZ_12bit( EN := Enable, Y := DI_Y_Terminal, Z := DI_Z_Terminal, Reset
:= Reset,
CV => DNP_Counter1, ROV => RollOver1);

KYZ_32bit( EN := Enable, Y := DI_Y_Terminal, Z := DI_Z_Terminal, Reset


:= Reset,
CV => DNP_Counter2, ROV => RollOver2);

Date Code 20190830 Instruction Manual Programming Reference


17.18 PowerMetering
Examples

Solution With Retain Variables


Retain variables allow variable values to remain consistent through removal and restora-
tion of power and program downloads. The user can create a program as shown in Code
Snippet 17.10. RETAIN_UID must be initialized on the first run. See Retain Variables on
page 17.21 for more details on retain variables.

Code Snippet 17.10 prg_KYZ_Retain_Example


VAR_GLOBAL RETAIN
//Persistent storage for counter values
Counter : BCR;
RollOver : UDINT;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD := 1;
END_VAR

Code Snippet 17.10 prg_KYZ_Retain_Example (Continued)


PROGRAM prg_KYZ_Retain_Example
VAR
//Block inputs
DI_Y_Terminal : SPS;
DI_Z_Terminal : SPS;
Enable : BOOL;
Reset : BOOL;

//Placeholder for DNP output tags


DNP_Counter : BCR;

KYZ_12bit : fb_KYZ( settingsChange := (RETAIN_VERSION <>


VERSION),
initialCV := Counter, initialROV :=
RollOver,
maxValue := 4095);
(*If VERSION has been modified, the counter values will be reset to zero,
*otherwise the retain values will be used. settingsChange should be
evaluated
*from constants or retain variables only. *)
END_VAR

//Update the retain variable first thing


RETAIN_VERSION := VERSION;

//Call the function block every cycle and assign outputs


KYZ_12bit( EN := Enable, Y := DI_Y_Terminal, Z := DI_Z_Terminal, Reset
:= Reset,
CV => Counter, ROV => RollOver);

//Copy output to outbound communication channels


DNP_Counter := Counter;

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.19
Examples

KY
Objective
A user has one input connected to the Y terminal of a meter and wants to count the number
of transitions.

Assumptions
The following example provides code for two different situations. The first program as-
sumes there is no requirement for nonvolatile variables while the second program assumes
there is a requirement that variables are retained through power loss.

Solution
The user can create a program as shown in Code Snippet 17.11. Note that this example
does not use retain variables.

Code Snippet 17.11 prg_KY_Example


PROGRAM prg_KY_Example
VAR
//Terminal for Y pulses
DI_Y_Terminal : SPS;
Enable : BOOL;
Reset : BOOL;

//Placeholder for DNP Tag


DNP_Counter1 : BCR;
DNP_Counter2 : BCR;
//Additional Outputs
RollOver1 : UDINT;
RollOver2 : UDINT;

//The KY blocks ignore their initial values because settingsChange is


true.
KY_12bit : fb_KY( settingsChange := TRUE, initialCV :=
DNP_Counter1,
initialROV := 0, maxValue := 4095);

KY_32bit : fb_KY( settingsChange := TRUE, initialCV :=


DNP_Counter2,
initialROV := 0, maxValue := 4294967295);
END_VAR

//Call the function block every cycle and assign outputs


KY_12bit( EN := Enable, Y := DI_Y_Terminal, Reset := Reset,
CV => DNP_Counter1, ROV => RollOver1);

KY_32bit( EN := Enable, Y := DI_Y_Terminal, Reset := Reset,


CV => DNP_Counter2, ROV => RollOver2);

Date Code 20190830 Instruction Manual Programming Reference


17.20 PowerMetering
Examples

Solution With Retain Variables


Retain variables allow variable values to remain consistent through removal and restora-
tion of power and program downloads. The user can create a program as shown in Code
Snippet 17.12. RETAIN_UID must be initialized on the first run. See Retain Variables on
page 17.21 for more details on retain variables.

Code Snippet 17.12 prg_KY_Retain_Example


VAR_GLOBAL RETAIN
//Persistent storage for counter values
Counter : BCR;
RollOver : UDINT;
RETAIN_VERSION : DWORD;
END_VAR
VAR_GLOBAL
// Modify this when the retain value should not be used.
VERSION : DWORD := 1;
END_VAR

Code Snippet 17.12 prg_KY_Retain_Example (Continued)


PROGRAM prg_KY_Retain_Example
VAR
//Terminal for Y pulses
DI_Y_Terminal : SPS;
//Enabling and Rest Conditions
Enable : BOOL;
Reset : BOOL;

//Placeholder for DNP output tags


DNP_Counter : BCR;

KY_12bit : fb_KY( settingsChange := (RETAIN_VERSION <>


VERSION),
initialCV := Counter, initialROV :=
RollOver,
maxValue := 4095);
(*If VERSION has been modified, the counter values will be reset to zero,
*otherwise the retain values will be used. settingsChange should be
evaluated
*from constants or retain variables only. *)
END_VAR

//Update the retain variable first thing


RETAIN_VERSION := VERSION;

//Call the function block every cycle and assign outputs


KY_12bit( EN := Enable, Y := DI_Y_Terminal, Reset := Reset,
CV => Counter, ROV => RollOver);

//Copy output to outbound communication channels


DNP_Counter := Counter;

Programming Reference Instruction Manual Date Code 20190830


PowerMetering 17.21
Retain Variables

Retain Variables
Note on Usage
Retain variables allow values to persist through removal and restoration of power, a reboot,
and some program downloads. To accomplish this, retain variables point to a specific
location in nonvolatile memory. This results in a situation where changing the definition
of any retain variable (e.g., creating or deleting variables or changing variable order), can
result in the variables pointing to a different location in memory, meaning an incorrect
value would be used in logic. Therefore, you should initialize all retain variables when you
change or add any retain variable declarations. Furthermore, it is best practice to keep all
retain variables in the same global variable list to avoid the opportunity of the lists being
reordered.

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 18

PowerSystemModel
Introduction
The PowerSystemModel library provides the ability to instantiate, describe, and connect
different power system elements. With each scan of the logic engine task, it will collect
the available measured information and determine which nodes are connected. The model
provides a single voltage quantity for all devices connected without impedance (an elec-
trical node) and a current for each branch that can be directly calculated using Kirchhoff’s
current law.
The PowerSystemModel library works with the C37.118 synchrophasor stream to provide a
more detailed snapshot of the system than can be provided by the raw data alone. Internally
the model treats all data and parameters as three-phase data at base units (e.g., ohms and
amperes) and it uses those three-phase data to perform its calculations. Each monitored
input contains a quality_t structure. If validity inside this structure is set to anything other
than GOOD, that measured value is not used in the calculations during this scan. Once all
inputs have been validated, the model expands existing current and voltage data to as many
nodes and branches as possible, and where sufficient data is available, provides a sanity
check on the measured values and breaker states.
The PowerSystemModel library is primarily designed to support the following two use
cases: extending system observability given a sparsely metered system and validating mea-
surements and topology given a densely metered system. The breaker-and-a-half configu-
ration, shown in Figure 18.1, is used to illustrate the different use cases.

A A A A A

A A

A A A A A

(a) (b) (c)

Figure 18.1 Differing Levels of Observability

Observability Extension: Figure 18.1a shows current meters installed on all three breakers.
By combining these measurements and the topology information, the power system model
can calculate the current injected into both of the unmetered lines.
Error Detection: Figure 18.1b shows current meters installed on two of the three breakers
and both lines. By combining these measurements and the topology information, the power
system model can calculate the current flow through the unmetered breaker and detect if a
metering error has likely occurred.

Date Code 20190830 Instruction Manual Programming Reference


18.2 PowerSystemModel
Introduction

Error Detection and Identification: Figure 18.1c shows fully redundant current. By com-
bining these measurements and the topology information, the power system model can
validate each of the redundant measurements, detect any inconsistencies, and provide an
indicator that one of the meters within the collection is providing incorrect data.

Glossary
These terms are used throughout this document to describe the functionality provided by
this library.
Conducting Equipment Any piece of electrical equipment that is designed to carry cur-
rent or that is conductively connected to the network. This does not include containers
that hold this equipment. For example, a power transformer is not conducting equipment
even though it can hold multiple power transformer ends which are themselves conducting
equipment.
Connectivity Node A representation of the connecting point for two or more terminals.
The model will create these anywhere two or more terminals are connected via the bootstrap
methods. At no time should the user ever instantiate a connectivity node.
Model In this library, the model is a collection of conducting equipment that is connected
and the data that describes that equipment.
Power Transformer End A transformer winding. A given transformer may have two or
more windings.
Terminal The part of a piece of electrical equipment that is meant to connect it to other
equipment. Every piece of conducting equipment has at least one terminal and all terminals
should be attached to at least one other terminal at a connectivity node. These also serve
as anchoring points for various measurement devices.

Placing a System Into the Model


As an example, the user desires to represent a substation using this library. The high-
voltage side of the substation being modeled is represented by the one-line diagram shown
in Figure 18.2:

Figure 18.2 High-Voltage End of a Substation

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.3
Introduction

To begin with, the user must identify the individual pieces of conducting equipment rep-
resented by this diagram. This defines what objects must be created within the library to
model this system, as seen in Figure 18.3. Note that every piece of conducting equipment
in the model has one or more terminals that are implicitly created with the object—the bus
can be represented as only a single terminal.

Energy Source

Breaker Bus
Switch

Switch Switch
Transformer End
Breaker Breaker
Switch

Energy Source

Figure 18.3 High-Voltage Components Identified

To tie each of the pieces of equipment together, we introduce the idea of a connectivity
node. These nodes provide a location to tie together as many terminals as desired. In the
library the user does not need to create these nodes. They are created automatically when
two or more terminals are connected. Figure 18.4 shows how this might be conveyed. As
before, there is a connectivity node where the terminals of the three lines join the terminal
of the bus.

Figure 18.4 Model Tied Together With Connectivity Nodes

Figure 18.5 shows the user indicating where data are fed into (classes named as Measure-
ments) and read out of (classes named as Report) the model. Each of these I/O points is
tied to a terminal that it monitors. The direction of current flow is standardized as being
positive when flow is moving through the terminal from the conducting equipment into the
connectivity node. For example; if current was flowing from left-to-right through a breaker,
a measurement point on the left terminal would read as a negative value flowing into the
conducting equipment, away from the connectivity node; and a measurement point on the
right terminal would read as a positive value flowing away from the conducting equipment,
into the connectivity node.

Date Code 20190830 Instruction Manual Programming Reference


18.4 PowerSystemModel
Supported Firmware Versions

Though current and voltage values may be read in from measurements in whatever units
desired, they must be scaled to volts or amperes with the correct sign for use in the model.
Measurement classes provide a scalar that must be correctly populated to translate the units
and directionality being fed into the model from the synchrophasor stream into the required
magnitudes and directions.

A A

Figure 18.5 Tied Model With Measurement Points Identified

Finally, some objects need to be part of a container to define their interaction with other
objects. For example, all conducting equipment must be placed in a nominal voltage and
transformer ends must be placed in a transformer with other transformer ends, as shown in
Figure 18.6.

V
230,000 V
A High
to
Low
A A

Figure 18.6 All Objects Defined for One Side of the Substation

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Version 3.5.0.0 can be used on RTAC firmware version R132 and higher.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.5
Structures

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_ValueSource
Enumeration Description
UNAVAILABLE The value is not measured and cannot be calculated by the installed
system.
MEASURED The value is reported exactly as measured.
DIRECT_ASSOCIATION The value was achieved through comparing like values connected
without impedance.
CALCULATED The value was achieved through linear extrapolation based on pro-
vided parameters.
UNTRUSTED The value measured here conflicts with other measured values or
the provided parameters. This can be set if a measured value is too
different from a calculated value or switch that reports open has a
calculated current.

enum_WindingConnection
Enumeration Description
DELTA A Delta winding.
WYE A Wye winding.
ZIGZAG A ZigZag winding.
WYE_NEUTRAL A Wye winding with neutral brought out for grounding.
ZIGZAG_NEUTRAL A ZigZag winding with neutral brought out for grounding.
AUTO An Autotransformer common winding.
INDEPENDENT An independent winding for single-phase connections.

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
This library makes use of several ACSELERATOR RTAC Data Types for data input, out-
put, and storage. The layout of these structures can be found in the ACSELERATOR RTAC
SEL-5033 Software Instruction Manual.
CMV A communications structure for moving phasors.
MV A communications structure for moving analog values.
quality_t A communications structure for indicating data health.
SPS A communications structure for moving binary points.

Date Code 20190830 Instruction Manual Programming Reference


18.6 PowerSystemModel
Classes

vector_t A structure for storing phasors as an angle and a magnitude.

Classes
Classes are a particular implementation of a function block. They are generally initial-
ized using bootstrap methods and provide methods and properties, which normal function
blocks do not provide.

class_PowerSystemModel (Class)
This class contains the working algorithms for the model. It stores the connections of
objects to each other, controls the order of operations each scan, and provides a centralizing
point for all other features.
For the model to do its work, all elements must be tied to it before calling run. In general,
this means that all terminals must be tied first using bootstrap_ConnectTerminals().
Then individual objects should be configured using their assorted bootstrap_Set and boot-
strap_Configure methods. Finally, objects can be grouped in containers and transformers
and meters can be added using bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
Filename STRING The name of the log file for this model’s initialization.
ABCRotation BOOL The rotation of the phases in this model. True indicates
that after the A-phase current crosses a reference angle,
B-phase current will cross it next.

bootstrap_ConnectTerminals (Method)
Call this method to connect two terminals to each other. A terminal can be used as an
argument to this method more than once to connect more than two terminals to each other.
If Terminal A is connected to Terminal B and then Terminal A is connected to Terminal C,
Terminal B is implicitly connected to Terminal C and the two do not need to be connected
by an explicit call to this method.
This is the first bootstrap method to be called. It must be called after all objects are instan-
tiated and before any other bootstrap method and before Run().

Inputs
Name IEC 61131 Type Description
pt_terminal1 POINTER TO class_Terminal The first terminal to connect.
pt_terminal2 POINTER TO class_Terminal The second terminal to connect.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.7
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the terminals are connected together and added to the
model.

Processing
This method is intended to be called before processing to link objects together in the model.
It performs the following actions:
ä Stores a reference to the model in both objects.
ä Connects the two terminals together at a connectivity node.
ä Connects both terminals to any other terminals already attached to the connectivity
node.
ä Returns FALSE if the references are not stored, either because the objects are no
longer in the initialization phase or a terminal is already attached to another model.

bootstrap_FinalizeConnections (Method)
To ensure proper tying of all model objects, this method must be called after all terminals
have been connected by bootstrap_ConnectTerminals and before calling any other
bootstrap methods or Run(). It switches the model out of the terminal connection state in
preparation for all other work.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the model has been successfully tied together.

Processing
This method prompts the model to perform the following actions:
ä Disable the connection of additional terminals.
ä Enable the insertion of objects (e.g., class_Breakers, class_ACLineSegments, and
others) into containers (i.e. class_VoltageLevels and class_PowerTransformers).
ä Build internal linking structures required for additional processing.
ä Return FALSE if bootstrap_ConnectTerminals() has not been successfully called
or if the system state prevented the final connections.

bootstrap_ValidateModel (Method)
This verifies the state of all objects and that the model itself can operate without error. Until
this method is called, no work is done by the Run() method.

Date Code 20190830 Instruction Manual Programming Reference


18.8 PowerSystemModel
Classes

Upon completion of this method, the model is ready to write out a log file summarizing
the configuration of the model. This file will be completed during the first few iterations of
the calls to the Run() method. Its format can be seen in Log File Format on page 18.70.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the model is ready to monitor inputs and update outputs.

Processing
This method is intended to be called before ever calling Run() to finalize all model con-
figuration. It prompts the model to perform the following actions:
ä Disable the attachment of any additional containers.
ä Check that all model objects have every reference required for calculations.
ä Return FALSE if the model is unable to calculate model state due to a configuration
error. Any such error will be described in the file filename.

Run (Method)
This method drives all work done by the model. It should be called once per task scan after
all configuration information has been processed.

Processing
Each time Run() is called, it performs the following tasks:
ä Checks that the model has been validated and deemed healthy.
ä Updates the measurements from all inputs configured during bootstrap.
ä Determines the observability of the system. This decides which current values can
be calculated and which cannot based on the switch states and valid measurement
values available.
ä Calculates the current through all observable pieces of conducting equipment and the
voltage at all observable terminals. If measurements beyond the minimum required
for observability are available, the method uses all available information to generate
a minimum mean squared error estimate.
ä If measurements are deemed to be too far from calculated values, the resulting output
will be flagged as UNTRUSTED. Likewise, any switch reporting as open with more
than minimal current running through it will be reported as UNTRUSTED.
ä Once all measurements are calculated and outputs are flagged, the time-aligned val-
ues will be placed in the outputs of all user-provided measurement points and all
switches and breakers.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.9
Classes

class_ConductingEquipment
This class is never instantiated by the user. This is a category of object that is extended
to allow objects of multiple types to be treated as if they are the same for the purpose of
grouping and analysis. Classes that extend this class can be added to class_VoltageLevels.

class_Measurement
This class is never instantiated by the user. This is a category of object that is extended
to allow objects of multiple types to be treated as if they are the same for the purpose of
grouping and analysis. Classes that extend this class can be added to terminals for both
input and output of measurement values.

class_Terminal
The point on a piece of conducting equipment that connects to other conducting equipment.
Terminals are used to join all objects together and provide explicit points of contact for
measurement units.
This class is never instantiated by the user. All instantiated conducting equipment already
have terminals as member objects. The user must be aware that terminals exist to facilitate
calling bootstrap methods to ty the model together and to attach measurement points.

bootstrap_AddMeasurement (Method)
Call this method to tie a measurement point to a specific terminal.
This is the last type of bootstrap method to be called. It must be called after all terminals
are connected and all configure and set bootstrap methods have been completed.

Inputs/Outputs
Name IEC 61131 Type Description
measurement class_Measurement The measurement to be applied to this terminal.

Return Value
IEC 61131 Type Description
BOOL The measurement was successfully added to the terminal.

Processing
This method stores a reference to the provided measurement at this terminal unless the ob-
jects are no longer in the initialization phase or the terminal is attached to a bus or junction
and the measurement is a current measurement. After being attached, these measurement
inputs and outputs will be used with all operations acting on the model.

Date Code 20190830 Instruction Manual Programming Reference


18.10 PowerSystemModel
Classes

class_Switch
Instantiate one instance of this class for any non-load breaking switch in the model. The
instance tracks the open-close state of that device. Before this class can be used, one or
both of its bootstrap methods must be called.
If none of the variables being monitored are healthy on a given scan, the switch will be
analyzed per its TypicallyClosed value and the StO_Quality will be set to UNAVAILABLE.
If only one value is available, because only one bootstrap method is called or only one
monitored value is healthy, that value will be used as the open-close state. If both values
are bootstrapped and healthy and the two values conflict, the switch will be analyzed per
its TypicallyClosed value and the StO_Quality will be set to UNTRUSTED.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
TypicallyClosed BOOL This switch is closed under normal operating condi-
tions. This is the value that will be used if there is no
communication with the switch.

Inputs/Outputs
Name IEC 61131 Type Description
pt_TerminalA POINTER TO class_Terminal The first terminal of this switch, used to
attach it inside the model.
pt_TerminalB POINTER TO class_Terminal The second terminal of this switch, used
to attach it inside the model.
StIn_IsClosed BOOL The switch is reporting as closed.
StIn_IsClosedQOk BOOL The channel communicating switch state
is healthy.
StO_IsClosed BOOL The state the model calculates the switch
to be in. The model may override an
open condition if current is still detected
across the link.
StO_Quality enum_ValueSource The confidence level in the StO_Is-
Closed flag.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.11
Classes

bootstrap_ConfigureIsOpenInput (Method)
Call this method to provide a reference to the value the switch should monitor to detect an
open condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsOpen SPS The variable that will be monitored to determine the open
status of this switch.

Return Value
IEC 61131 Type Description
BOOL The switch was successfully configured.

Processing
This method is intended to be called before processing to associate a data location with the
switch. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the switch already had this
bootstrap method called.

bootstrap_ConfigureIsClosedInput (Method)
Call this method to provide a reference to the value the switch should monitor to detect a
closed condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsClosed SPS The variable that will be monitored to determine the
closed status of this switch.

Date Code 20190830 Instruction Manual Programming Reference


18.12 PowerSystemModel
Classes

Return Value
IEC 61131 Type Description
BOOL The switch was successfully configured.

Processing
This method is intended to be called before processing to associate a data location with the
switch. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the switch already had this
bootstrap method called.

class_Breaker
Instantiate one instance of this class for any load breaking device in the model. The instance
tracks open-close state of that device. Before this class can be used, one or both of its
bootstrap methods must be called.
If none of the variables being monitored are healthy on a given scan, the breaker will be
analyzed per its TypicallyClosed value and the StO_Quality will be set to UNAVAILABLE.
If only one value is available, because only one bootstrap method is called or only one
monitored value is healthy, that value will be used as the open-close state. If both values
are bootstrapped and healthy and the two values conflict, the breaker will be analyzed per
its TypicallyClosed value and the StO_Quality will be set to UNTRUSTED.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment
ä class_Switch

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
TypicallyClosed BOOL This breaker is closed under normal operating condi-
tions. This is the value that will be used if there is no
communication with the breaker.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.13
Classes

Outputs
Name IEC 61131 Type Description
pt_TerminalA POINTER TO class_Terminal The first terminal of this breaker, used to
attach it inside the model.
pt_TerminalB POINTER TO class_Terminal The second terminal of this breaker, used
to attach it inside the model.
StIn_IsClosed BOOL The breaker is reporting as closed.
StIn_IsClosedQOk BOOL The channel communicating breaker
state is healthy.
StO_IsClosed BOOL The state the model calculates the
breaker to be in. The model may over-
ride an open condition if current is still
detected across the link.
StO_Quality enum_ValueSource The confidence level in the StO_Is-
Closed flag.

bootstrap_ConfigureIsOpenInput (Method)
Call this method to provide a reference to the value the breaker should monitor to detect an
open condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsOpen SPS The variable that will be monitored to determine the open
status of this breaker.

Return Value
IEC 61131 Type Description
BOOL The breaker was successfully configured.

Processing
This method is intended to be called before processing to associate a data location with the
breaker. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the breaker already had this
bootstrap method called.

Date Code 20190830 Instruction Manual Programming Reference


18.14 PowerSystemModel
Classes

bootstrap_ConfigureIsClosedInput (Method)
Call this method to provide a reference to the value the breaker should monitor to detect a
closed condition.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
stIn_IsClosed SPS The variable that will be monitored to determine the
closed status of this breaker.

Return Value
IEC 61131 Type Description
BOOL The breaker was successfully configured.

Processing
This method is intended to be called before processing to associate a data location with the
breaker. It performs the following actions:
ä Stores a reference to the provided variable to be used later.
ä Returns FALSE if the reference is not stored because the breaker already had this
bootstrap method called.

class_EnergySource
This class is a terminating element. It represents an edge of the model being worked on.
Instantiate one instance of this class anywhere it is desired to model all elements beyond
this point as a metered source of electrical power.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.15
Classes

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.

Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this source, used to attach it in-
side the model.

class_EnergyConsumer
This class is a terminating element. It represents an edge of the model being worked on.
Instantiate one instance of this class anywhere it is desired to model all elements beyond
this point as a metered electrical load.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.

Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this load, used to attach it inside
the model.

Date Code 20190830 Instruction Manual Programming Reference


18.16 PowerSystemModel
Classes

class_ShuntCompensator
This class is a terminating element. It represents an edge of the model being worked on.
Instantiate one instance of this class anywhere it is desired to model a shunt capacitor,
inductor, or resistor. The provided values are used during all operations on the model.
Inputs to this class must be in units of siemens.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
conductanceAPhase LREAL The real part of the shunt admittance of the
A-phase.
susceptanceAPhase LREAL The reactive part of the shunt admittance of the
A-phase.
conductanceBPhase LREAL The real part of the shunt admittance of the
B-phase.
susceptanceBPhase LREAL The reactive part of the shunt admittance of the
B-phase.
conductanceCPhase LREAL The real part of the shunt admittance of the
C-phase.
susceptanceCPhase LREAL The reactive part of the shunt admittance of the
C-phase.
conductanceABPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
susceptanceABPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
conductanceACPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
susceptanceACPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
conductanceBCPhase LREAL The real part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
susceptanceBCPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.17
Classes

Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this compensator, used to attach
it inside the model.

class_ACLineSegment
Instantiate one instance of this class at each location where it is desired to model the con-
nection between two points as having impedance. Each instance defaults to zero impedance
and zero shunt admittance unless an appropriate bootstrapping method is called.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.

Outputs
Name IEC 61131 Type Description
pt_TerminalA POINTER TO class_Terminal The first terminal of this line, used to attach it
inside the model.
pt_TerminalB POINTER TO class_Terminal The second terminal of this line, used to at-
tach it inside the model.

bootstrap_SetNominalLineImpedance1Line (Method)
Call this method to set the line impedance using a 1-line model. Arguments of this method
must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Date Code 20190830 Instruction Manual Programming Reference


18.18 PowerSystemModel
Classes

Inputs
Name IEC 61131 Type Description
resistance LREAL The real part of the positive-sequence series impedance.
reactance LREAL The reactive part of the positive-sequence series impedance.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.

Processing
This method sets the impedance of the line based on the provided values and returns TRUE,
unless the impedance of the line was set previously or the model is no longer in the initial-
ization phase.

bootstrap_SetNominalLineImpedance3Phase (Method)
Call this method to set the line impedance using three-phase data. Arguments of this
method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
resistanceAPhase LREAL The real part of the series impedance of the
A-phase.
reactanceAPhase LREAL The reactive part of the series impedance of the
A-phase.
resistanceBPhase LREAL The real part of the series impedance of the
B-phase.
reactanceBPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceCPhase LREAL The real part of the series impedance of the
B-phase.
reactanceCPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceABPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the B-phase.
reactanceABPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the B-phase.
resistanceACPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the C-phase.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.19
Classes

reactanceACPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the C-phase.
resistanceBCPhase LREAL The real part of the series impedance due to mutual
coupling between the B-phase and the C-phase.
reactanceBCPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the B-phase and the C-phase.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.

Processing
This method sets the impedance of the line based on the provided values and returns TRUE,
unless the impedance of the line was set previously or the model is no longer in the initial-
ization phase.

bootstrap_SetNominalLineImpedanceWZeroSequence (Method)
Call this method to set the line impedance using a positive- and zero-sequence data model.
Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
resistancePosSequence LREAL The real part of the positive-sequence series
impedance.
reactancePosSequence LREAL The reactive part of the positive-sequence se-
ries impedance.
resistanceZeroSequence LREAL The real part of the zero-sequence series
impedance.
reactanceZeroSequence LREAL The reactive part of the zero-sequence series
impedance.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.

Date Code 20190830 Instruction Manual Programming Reference


18.20 PowerSystemModel
Classes

Processing
This method sets the impedance of the line based on the provided values and returns TRUE,
unless the impedance of the line was set previously or the model is no longer in the initial-
ization phase.

bootstrap_SetNominalShuntAdmittance1Line (Method)
Call this method to set the shunt admittance of the line using a one-line model. Arguments
of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
conductance LREAL The real part of the positive-sequence shunt admittance.
susceptance LREAL The reactive part of the positive-sequence shunt admit-
tance.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.

Processing
This method sets the admittance of the line based on the provided values and returns TRUE,
unless the admittance of the line was set previously or the model is no longer in the initial-
ization phase.

bootstrap_SetNominalShuntAdmittance3Phase (Method)
Call this method to set the line’s shunt admittance using three-phase data. Arguments of
this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
conductanceAPhase LREAL The real part of the shunt admittance of the
A-phase.
susceptanceAPhase LREAL The reactive part of the shunt admittance of the
A-phase.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.21
Classes

conductanceBPhase LREAL The real part of the shunt admittance of the


B-phase.
susceptanceBPhase LREAL The reactive part of the shunt admittance of the
B-phase.
conductanceCPhase LREAL The real part of the shunt admittance of the
C-phase.
susceptanceCPhase LREAL The reactive part of the shunt admittance of the
C-phase.
conductanceABPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
susceptanceABPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
conductanceACPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
susceptanceACPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
conductanceBCPhase LREAL The real part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
susceptanceBCPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.

Return Value
IEC 61131 Type Description
BOOL Returns true if the admittance was set based on the provided values.

Processing
This method sets the admittance of the line based on the provided values and returns TRUE,
unless the admittance of the line was set previously or the model is no longer in the initial-
ization phase.

bootstrap_SetNominalShuntAdmittanceWZeroSequence (Method)
Call this method to set the line’s shunt admittance using a positive- and zero-sequence data
model. Arguments of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Date Code 20190830 Instruction Manual Programming Reference


18.22 PowerSystemModel
Classes

Inputs
Name IEC 61131 Type Description
conductancePosSequence LREAL The real part of the positive-sequence shunt
admittance.
susceptancePosSequence LREAL The reactive part of the positive-sequence
shunt admittance.
conductanceZeroSeqeunce LREAL The real part of the zero-sequence shunt ad-
mittance.
susceptanceZeroSequence LREAL The reactive part of the zero-sequence shunt
admittance.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.

Processing
This method sets the admittance of the line based on the provided values and returns TRUE,
unless the admittance of the line was set previously or the model is no longer in the initial-
ization phase.

class_PowerTransformerEnd
Instantiate one instance of this class for each transformer winding desired in the model.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
NominalRatio REAL The modifier to use as the expected change be-
tween this winding and others in the system.
ConnectionType enum_WindingConnection The wiring configuration of the winding.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.23
Classes

Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this transformer winding, used
to attach it into the model.

bootstrap_AddTapChanger (Method)
Call this method to add a tap changer that will modify the NominalRatio of this transformer
end.
This is the last type of bootstrap method to be called. It must be called after all terminals
are connected and all configure and set bootstrap methods have been completed.

Inputs/Outputs
Name IEC 61131 Type Description
tapChanger class_TapChanger The tap changer that will modify this winding.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the tap changer is added to this winding.

Processing
This method links the provided tap changer to this winding and returns true, unless another
tap changer has already been set, the tap changer is already modifying another transformer
end, or the model is no longer in the initialization phase.

bootstrap_SetNominalEndImpedance1Line (Method)
Call this method to set the impedance of the transformer winding from a 1-line model.
Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
resistance LREAL The real part of the positive-sequence series impedance.
reactance LREAL The reactive part of the positive-sequence series impedance.

Date Code 20190830 Instruction Manual Programming Reference


18.24 PowerSystemModel
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.

Processing
This method sets the impedance of the transformer end based on the provided values and
returns TRUE, unless the impedance of the transformer end was set previously or the model
is no longer in the initialization phase.

bootstrap_SetNominalEndImpedance3Phase (Method)
Call this method to set the impedance of the transformer winding from three-phase data.
Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
resistanceAPhase LREAL The real part of the series impedance of the
A-phase.
reactanceAPhase LREAL The reactive part of the series impedance of the
A-phase.
resistanceBPhase LREAL The real part of the series impedance of the
B-phase.
reactanceBPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceCPhase LREAL The real part of the series impedance of the
B-phase.
reactanceCPhase LREAL The reactive part of the series impedance of the
B-phase.
resistanceABPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the B-phase.
reactanceABPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the B-phase.
resistanceACPhase LREAL The real part of the series impedance due to mutual
coupling between the A-phase and the C-phase.
reactanceACPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the A-phase and the C-phase.
resistanceBCPhase LREAL The real part of the series impedance due to mutual
coupling between the B-phase and the C-phase.
reactanceBCPhase LREAL The reactive part of the series impedance due to mu-
tual coupling between the B-phase and the C-phase.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.25
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.

Processing
This method sets the impedance of the transformer end based on the provided values and
returns TRUE, unless the impedance of the transformer end was set previously or the model
is no longer in the initialization phase.

bootstrap_SetNominalEndImpedanceWZeroSequence (Method)
Call this method to set the impedance of the transformer winding from a positive- and
zero-sequence data model. Arguments of this method must be in units of ohms.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
resistancePosSequence LREAL The real part of the positive-sequence series
impedance.
reactancePosSequence LREAL The reactive part of the positive-sequence se-
ries impedance.
resistanceZeroSequence LREAL The real part of the zero-sequence series
impedance.
reactanceZeroSequence LREAL The reactive part of the zero-sequence series
impedance.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the impedance was set based on the provided values.

Processing
This method sets the impedance of the transformer end based on the provided values and
returns TRUE, unless the impedance of the transformer end was set previously or the model
is no longer in the initialization phase.

Date Code 20190830 Instruction Manual Programming Reference


18.26 PowerSystemModel
Classes

bootstrap_SetNominalShuntAdmittance1Line (Method)
Call this method to set the shunt admittance of the transformer end from a 1-line model.
Arguments of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
conductance LREAL The real part of the positive-sequence shunt admittance.
susceptance LREAL The reactive part of the positive-sequence shunt admit-
tance.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.

Processing
This method sets the admittance of the transformer end based on the provided values and
returns TRUE, unless the admittance of the transformer end was set previously or the model
is no longer in the initialization phase.

bootstrap_SetNominalShuntAdmittance3Phase (Method)
Call this method to set the shunt admittance of the transformer winding from three-phase
data. Arguments of this method must be in units of siemens.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs
Name IEC 61131 Type Description
conductanceAPhase LREAL The real part of the shunt admittance of the
A-phase.
susceptanceAPhase LREAL The reactive part of the shunt admittance of the
A-phase.
conductanceBPhase LREAL The real part of the shunt admittance of the
B-phase.
susceptanceBPhase LREAL The reactive part of the shunt admittance of the
B-phase.
conductanceCPhase LREAL The real part of the shunt admittance of the
C-phase.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.27
Classes

susceptanceCPhase LREAL The reactive part of the shunt admittance of the


C-phase.
conductanceABPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
susceptanceABPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
B-phase.
conductanceACPhase LREAL The real part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
susceptanceACPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the A-phase and the
C-phase.
conductanceBCPhase LREAL The real part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.
susceptanceBCPhase LREAL The reactive part of the shunt admittance due to
mutual coupling between the B-phase and the
C-phase.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.

Processing
This method sets the admittance of the transformer end based on the provided values and
returns TRUE, unless the admittance of the transformer end was set previously or the model
is no longer in the initialization phase.

bootstrap_SetNominalShuntAdmittanceWZeroSequence (Method)
Call this method to set the shunt admittance of the transformer end from a positive- and
zero-sequence data model. Arguments of this method must be in units of siemens.

Inputs
Name IEC 61131 Type Description
conductancePosSequence LREAL The real part of the positive-sequence shunt
admittance.
susceptancePosSequence LREAL The reactive part of the positive-sequence
shunt admittance.
conductanceZeroSeqeunce LREAL The real part of the zero-sequence shunt ad-
mittance.
susceptanceZeroSequence LREAL The reactive part of the zero-sequence shunt
admittance.

Date Code 20190830 Instruction Manual Programming Reference


18.28 PowerSystemModel
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the admittance was set based on the provided values.

Processing
This method sets the admittance of the transformer end based on the provided values and
returns TRUE, unless the admittance of the transformer end was set previously or the model
is no longer in the initialization phase.

class_BusbarSection
Instantiate one instance of this class for each location of a bus desired to be modeled.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.

Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this bus, used to attach it into
the model.

class_Junction
Instantiate one instance of this class for each location of a non-bus intersection of three or
more terminals that requires a name.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.29
Classes

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_ConductingEquipment

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.

Outputs
Name IEC 61131 Type Description
pt_Terminal POINTER TO class_Terminal The terminal of this junction, used to attach it
into the model.

class_TapChanger
Instantiate one instance of this class for each class_PowerTransformerEnd requiring a dy-
namic transformer ratio.

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
DefaultStep INT The step value this tap changer will use if communica-
tion with the device is unhealthy. A value of zero leaves
the PowerTransformer winding at its default Nominal-
Ratio.
StepSize REAL The size of each step in percentage.
StepHighLimit INT The maximum multiplier this tap changer allows.
StepLowLimit INT The minimum multiplier this tap changer allows.

Date Code 20190830 Instruction Manual Programming Reference


18.30 PowerSystemModel
Classes

Outputs
Name IEC 61131 Type Description
StIn_RatioModifier REAL The measured value of the tap changer as a
percentage.
StIn_RatioModifierQOk BOOL The health of the communications channel
providing the ratio modifier. This will be
FALSE if the value is out of bounds or the
communication is flagged as invalid.

bootstrap_ConfigureInputs (Method)
Call this method to provide a reference to all required variables the tap changer should
monitor for its state.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
ratioModifier INS The variable that will report the step position of the tap
changer.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the variables are successfully tied to the tap changer.

Processing
This method stores references to the provided variables and returns true, unless it has al-
ready been called for this tap changer.

class_PowerTransformer
Instantiate one instance of this class for each set of correlated windings to be modeled.
This class acts as a container for class_PowerTransformerEnd objects and relates them to
each other.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.31
Classes

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
PowerFactorRating REAL The information required to derive the maximum
angle from real power this transformer allows be-
fore its behavior becomes non-linear.
RealPowerRating REAL The maximum real power this transformer can han-
dle.

bootstrap_AddWinding (Method)
Call this method to attach a class_PowerTransformerEnd to this transformer as one of mul-
tiple windings.
This is the last type of bootstrap method to be called. It must be called after all terminals
are connected and all configure and set bootstrap methods have been completed.

Inputs/Outputs
Name IEC 61131 Type Description
winding class_PowerTransformerEnd The winding to add to this transformer.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the winding was added successfully.

Processing
This method attaches the transformer end to this transformer and returns true, unless the
transformer end is already attached to a transformer, the transformer has ends attached to
a different model, or the model is no longer in the initialization stage.

class_VoltageLevel
Instantiate one voltage level for each nominal voltage desired in the model. The model uses
values provided here in per-unit calculations.

Date Code 20190830 Instruction Manual Programming Reference


18.32 PowerSystemModel
Classes

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
NominalVoltage REAL The voltage value to be used in per-unit calculations
for all equipment added to this voltage level.

bootstrap_AddEquipment (Method)
Call this method for each piece of equipment that should be associated with this container.

Inputs/Outputs
Name IEC 61131 Type Description
equipment class_ConductingEquipment The equipment to add to the container.

Return Value
IEC 61131 Type Description
BOOL The equipment was successfully added to the container.

Processing
This method is intended to be called before processing to associate equipment with this
container. It performs the following actions:
ä Stores a reference to the object so that it can be accessed as part of the container later.
ä If the equipment can be stored in only one of this container type, prompts the equip-
ment to store a reference to the container as well.
ä Returns FALSE if the object cannot be added to the container because either the
objects are no longer in the initialization phase or the equipment was already added
to a conflicting container.

class_CurrentMeasurement
Current measurement objects can be added to any class_Terminal except one correlating
to a bus or junction. Measurements are complex phasors that must be scaled to present the
current injection from the equipment out, in amperes. Instantiate one instance of this class
for each set of current meter data that the model needs to account for.
class_CurrentMeasurement objects also reports three-phase current values after data ma-
nipulation.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.33
Classes

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
ScaleFactor REAL A multiplier applied as values enter the model.
MaxError REAL The maximum error percentage allowed on this meter
before it is flagged as UNTRUSTED. Default is 1%.
MinimumValue REAL The minimum value in amperes that will be used as the
denominator in calculating percentage error. Default is
1 ampere.

Outputs
Name IEC 61131 Type Description
StIn_IsEnabled BOOL The values read by this measurement are allowed
by the operator to be used in model calculations.
StIn_QOk BOOL The values provided to this measurement object
are healthy.
StIn_PhaseA vector_t A-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseB vector_t B-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseC vector_t C-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PosSequence vector_t PosSequence is calculated for three-phase inputs,
or as a measured PosSequence input.
StIn_ZeroSequence vector_t ZeroSequence is calculated for three-phase inputs,
or as a measured ZeroSequence input.
StIn_NegSequence vector_t NegSequence is calculated for three-phase inputs,
or as a measured NegSequence input.
StO_PhaseAQuality enum_ValueSource The confidence level in the reported A-phase
value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported B-phase
value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported C-phase
value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.

Date Code 20190830 Instruction Manual Programming Reference


18.34 PowerSystemModel
Classes

bootstrap_ConfigureInputsPosSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from a
single value, positive-sequence. It ensures that values read will be converted from positive-
sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.

Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.

bootstrap_ConfigureInputsSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three values: positive-, negative-, and zero-sequence. It ensures that values read will be
converted from sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.35
Classes

Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.
zeroSequence CMV The variable that will be monitored to determine the
zero-sequence value of this measurement.
negSequence CMV The variable that will be monitored to determine the
negative-sequence value of this measurement.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.

Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.

bootstrap_ConfigureInputsThreePhase (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three-phase values. It ensures that values read will be used directly in later calculations by
the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual override of
this measurement.
phaseA CMV The variable that will be monitored to determine the A-phase
value of this measurement.
phaseB CMV The variable that will be monitored to determine the B-phase
value of this measurement.
phaseC CMV The variable that will be monitored to determine the C-phase
value of this measurement.

Date Code 20190830 Instruction Manual Programming Reference


18.36 PowerSystemModel
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.

Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.

class_VoltageMeasurement
Voltage measurement objects can be added to any class_Terminal. Measurements are com-
plex phasors that must be scaled to present the voltage in volts. Instantiate one instance of
this class for each set of voltage meter data that the model needs to account for.
class_VoltageMeasurement objects also reports three-phase voltage values after data ma-
nipulation.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
ScaleFactor REAL A multiplier applied as values enter the model.
MaxError REAL The maximum error percentage allowed on this meter
before it is flagged as UNTRUSTED. Default is 1%.
MinimumValue REAL The minimum value in volts that will be used as the
denominator in calculating percentage error. Default is
1 volt.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.37
Classes

Outputs
Name IEC 61131 Type Description
StIn_IsEnabled BOOL The values read by this measurement are allowed
by the operator to be used in model calculations.
StIn_QOk BOOL The values provided to this measurement object
are healthy.
StIn_PhaseA vector_t A-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseB vector_t B-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PhaseC vector_t C-phase values as measured for three-phase in-
puts, or a decomposition to vectors for PosSe-
quence or Sequence input.
StIn_PosSequence vector_t PosSequence is calculated for three-phase inputs,
or as a measured PosSequence input.
StIn_ZeroSequence vector_t ZeroSequence is calculated for three-phase inputs,
or as a measured ZeroSequence input.
StIn_NegSequence vector_t NegSequence is calculated for three-phase inputs,
or as a measured NegSequence input.
StO_PhaseAQuality enum_ValueSource The confidence level in the reported A-phase
value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported B-phase
value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported C-phase
value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.

bootstrap_ConfigureInputsPosSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from a
single value, positive-sequence. It ensures that values read will be converted from positive-
sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.

Date Code 20190830 Instruction Manual Programming Reference


18.38 PowerSystemModel
Classes

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.

Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.

bootstrap_ConfigureInputsSequence (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three values: positive-, negative-, and zero-sequence. It ensures that values read will be
converted from sequence to three-phase for later calculations by the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual over-
ride of this measurement.
posSequence CMV The variable that will be monitored to determine the
positive-sequence value of this measurement.
zeroSequence CMV The variable that will be monitored to determine the
zero-sequence value of this measurement.
negSequence CMV The variable that will be monitored to determine the
negative-sequence value of this measurement.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.

Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.39
Classes

bootstrap_ConfigureInputsThreePhase (Method)
Call this method to provide a reference to all required variables the measurement should
monitor for its state. This method configures this measurement’s inputs to be read from
three-phase values. It ensures that values read will be used directly in later calculations by
the model.
This type of bootstrap method must be called after tying terminals and before calling any
bootstrap_Add methods.

Inputs/Outputs
Name IEC 61131 Type Description
enable BOOL The variable that will report the state of the manual override of
this measurement.
phaseA CMV The variable that will be monitored to determine the A-phase
value of this measurement.
phaseB CMV The variable that will be monitored to determine the B-phase
value of this measurement.
phaseC CMV The variable that will be monitored to determine the C-phase
value of this measurement.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if references to the variables are stored for future use.

Processing
This method stores references to the data locations provided as well as the type of data
expected and returns true, unless the measurement has already been given other inputs.

class_ReportedCurrent3Phase
Reported current objects can be added to any class_Terminal except one correlating to a
bus or junction. Reports are complex phasors that present the current injection from the
equipment out, in amperes. Instantiate one instance of this class for each unmonitored
location where knowledge of the current is desired.

Date Code 20190830 Instruction Manual Programming Reference


18.40 PowerSystemModel
Classes

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
PerPhaseMaxThreshold REAL The value that, if exceeded by the results of any
phase, will flag a possible error condition. This
value is compared directly against the final un-
scaled output.

Outputs
Name IEC 61131 Type Description
StO_PhaseAQuality enum_ValueSource The confidence level in the reported
A-phase value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported
B-phase value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported
C-phase value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.
PhaseAThresholdExceeded BOOL The magnitude of the A-phase value re-
ported exceeds the provided threshold.
PhaseBThresholdExceeded BOOL The magnitude of the B-phase value re-
ported exceeds the provided threshold.
PhaseCThresholdExceeded BOOL The magnitude of the C-phase value re-
ported exceeds the provided threshold.

class_ReportedCurrentSequence
Reported current objects can be added to any class_Terminal except one correlating to a
bus or junction. Reports are complex phasors that present the current injection from the
equipment out, in amperes. Instantiate one instance of this class for each unmonitored
location where knowledge of the current is desired.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.41
Classes

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power sys-
tem.
Description STRING A human-readable description of this ob-
ject.
positiveSeqMaxThreshold REAL The value that, if exceeded by the
positive-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.
zeroSeqMaxThreshold REAL The value that, if exceeded by the
zero-sequence results, will flag a possible
error condition. This value is compared
directly against the final unscaled output.
negativeSeqMaxThreshold REAL The value that, if exceeded by the
negative-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.

Outputs
Name IEC 61131 Type Description
StO_Quality enum_ValueSource The confidence level in the reported
sequence values.
StO_PosSequence vector_t The calculated positive-sequence
value.
StO_ZeroSequence vector_t The calculated negative-sequence
value.
StO_NegSequence vector_t The calculated zero-sequence value.
positiveSeqThresholdExceeded BOOL The magnitude of the
positive-sequence value reported
exceeds the provided threshold.
zeroSeqThresholdExceeded BOOL The magnitude of the zero-sequence
value reported exceeds the provided
threshold.
negativeSeqThresholdExceeded BOOL The magnitude of the
negative-sequence value reported
exceeds the provided threshold.

Date Code 20190830 Instruction Manual Programming Reference


18.42 PowerSystemModel
Classes

class_ReportedVoltage3Phase
Voltage report objects can be added to any class_Terminal. Reports are complex phasors
that present voltage in volts. Instantiate one instance of this class for each unmonitored
location where knowledge of the voltage is desired.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power system.
Description STRING A human-readable description of this object.
PerPhaseMaxThreshold REAL The value that, if exceeded by the results of any
phase, will flag a possible error condition. This
value is compared directly against the final un-
scaled output.

Outputs
Name IEC 61131 Type Description
StO_PhaseAQuality enum_ValueSource The confidence level in the reported
A-phase value.
StO_PhaseBQuality enum_ValueSource The confidence level in the reported
B-phase value.
StO_PhaseCQuality enum_ValueSource The confidence level in the reported
C-phase value.
StO_PhaseA vector_t The A-phase value after adjustments.
StO_PhaseB vector_t The B-phase value after adjustments.
StO_PhaseC vector_t The C-phase value after adjustments.
PhaseAThresholdExceeded BOOL The magnitude of the A-phase value re-
ported exceeds the provided threshold.
PhaseBThresholdExceeded BOOL The magnitude of the B-phase value re-
ported exceeds the provided threshold.
PhaseCThresholdExceeded BOOL The magnitude of the C-phase value re-
ported exceeds the provided threshold.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.43
Classes

class_ReportedVoltageSequence
Voltage report objects can be added to any class_Terminal. Reports are complex phasors
that present voltage in volts. Instantiate one instance of this class for each unmonitored
location where knowledge of the voltage is desired. All values presented are in the base
units used by the library.

Extended Classes
Extending a class provides full inheritance of all that classes features (methods, variables,
properties). A class may only extend one other class directly, but class extension can be
tiered indefinitely.
ä class_Measurement

Inputs
Name IEC 61131 Type Description
Name STRING The name of this object on the power sys-
tem.
Description STRING A human-readable description of this ob-
ject.
positiveSeqMaxThreshold REAL The value that, if exceeded by the
positive-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.
zeroSeqMaxThreshold REAL The value that, if exceeded by the
zero-sequence results, will flag a possible
error condition. This value is compared
directly against the final unscaled output.
negativeSeqMaxThreshold REAL The value that, if exceeded by the
negative-sequence results, will flag a
possible error condition. This value is com-
pared directly against the final unscaled
output.

Outputs
Name IEC 61131 Type Description
StO_Quality enum_ValueSource The confidence level in the reported
sequence values.
StO_PosSequence vector_t The calculated positive-sequence
value.
StO_ZeroSequence vector_t The calculated negative-sequence
value.
StO_NegSequence vector_t The calculated zero-sequence value.
positiveSeqThresholdExceeded BOOL The magnitude of the
positive-sequence value reported
exceeds the provided threshold.

Date Code 20190830 Instruction Manual Programming Reference


18.44 PowerSystemModel
Benchmarks

zeroSeqThresholdExceeded BOOL The magnitude of the zero-sequence


value reported exceeds the provided
threshold.
negativeSeqThresholdExceeded BOOL The magnitude of the
negative-sequence value reported
exceeds the provided threshold.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R135-V0 firmware
ä SEL-3530
â R135-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R135-V0 firmware

Benchmark Test Descriptions


Substation Example
The posted time is the average execution time of 100 consecutive calls to the Run() method
after initializing the system shown in Modeling a Substation on page 18.45.

Distribution Network Example


The posted time is the average execution time of 100 consecutive calls to the Run() method
after initializing the system shown in Modeling a Distribution Network on page 18.54.

Ring Network Example


The posted time is the average execution time of 100 consecutive calls to the Run() method
after initializing the system shown in Modeling a Ring Network on page 18.63.

Benchmark Results

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.45
Examples

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
Substation Example Run() Time 327,803 198,856 12,858
Distribution Example Run() Time 266,256 161,899 9,550
Ring Network Example Run() Time 164,639 97,313 6,689

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Modeling a Substation
Objective
A user has a substation that needs to be monitored. The substation is laid out as seen in
Figure 18.7.

V V
230,000 V 115,000 V A
A High
to A
A A Low A A
A
A
A

Figure 18.7 Example Substation Model

Assumptions
Typically all inputs to a model would be assigned directly from a communications channel,
however for ease in compilation for this example all inputs are pulled from a GVL shown
below in Code Snippet 18.1:

Code Snippet 18.1 gvl_TagHarness


VAR_GLOBAL
OpenStateValues : ARRAY [1..g_c_NumSwitches+g_c_NumBreakers] OF SPS
:= [ (stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),

Date Code 20190830 Instruction Manual Programming Reference


18.46 PowerSystemModel
Examples

(stVal := FALSE, q := (validity := good)),


(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good))
];

TapChangerValue : INS := (stVal := 1, q := (validity := good));

EnableBits : ARRAY [1..g_c_NumVoltageMeters+g_c_NumCurrentMeters] OF


BOOL :=
[g_c_NumVoltageMeters(TRUE), g_c_NumCurrentMeters(TRUE)];

PhaseAValues : ARRAY [1..g_c_NumVoltageMeters+g_c_NumCurrentMeters] OF


CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 2000)),
(q := (validity := good), instCVal := (ang := 0, mag := 1000))
];

PhaseBValues : ARRAY [1..g_c_NumVoltageMeters+g_c_NumCurrentMeters] OF


CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 2000)),
(q := (validity := good), instCVal := (ang := 0, mag := 1000))
];

PhaseCValues : ARRAY [1..g_c_NumVoltageMeters+g_c_NumCurrentMeters] OF


CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.47
Examples

(q := (validity := good), instCVal := (ang := 0, mag := 2)),


(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 2000)),
(q := (validity := good), instCVal := (ang := 0, mag := 1000))
];
END_VAR

Solution
Once the user has identified all the elements of the model and decided the source for all
required data there are only two other elements the user must create for the model to do its
work. First, all configuration and bootstrap methods must be called before calling Run().
In this example this is shown as completed in a GVL, Code Snippet 18.3, which allows
the configuration to complete before any task cycles begin. Second, the user must create a
program that calls the model instance’s Run() method, as shown in Code Snippet 18.2.

Code Snippet 18.2 prg_RunModel


PROGRAM prg_RunModel

g_Model1.Run();

Code Snippet 18.3 gvl_Bootstrap


{attribute 'linkalways'}
VAR_GLOBAL CONSTANT
g_c_NumSwitches : UDINT := 10;
g_c_NumBreakers : UDINT := 8;
g_c_ConnectionCount : UDINT := 28;
g_c_NumVoltageMeters : UDINT := 2;
g_c_NumCurrentMeters : UDINT := 10;
g_c_AreaCount : UDINT := 45;
g_c_ConfigurationCount : UDINT := 39;
END_VAR

VAR_GLOBAL
// Instantiate any desired models here:
g_Model1 : class_PowerSystemModel :=
(Filename := 'GlobalModel1.log', ABCRotation := TRUE);

// Instantiate all other components:


g_Source1 : class_EnergySource :=
(Name := 'Source1', Description := 'Line from elsewhere');
g_Source2 : class_EnergySource :=
(Name := 'Source2', Description := 'Another line');
g_Load1 : class_EnergyConsumer := (Name := 'Load1');
g_Load2 : class_EnergyConsumer := (Name := 'Load2');
g_Load3 : class_EnergyConsumer := (Name := 'Load3');
g_Load4 : class_EnergyConsumer := (Name := 'Load4');

g_Bus1 : class_BusbarSection := (Name := 'Bus1');

Date Code 20190830 Instruction Manual Programming Reference


18.48 PowerSystemModel
Examples

g_Bus2 : class_BusbarSection := (Name := 'Bus2');

g_Switches : ARRAY [1..g_c_NumSwitches] OF class_Switch


:= [ (Name := 'Sw_Source1', TypicallyClosed := TRUE),
(Name := 'Sw_Source2', TypicallyClosed := TRUE),
(Name := 'Sw_Bus1Bkr', TypicallyClosed := TRUE),
(Name := 'Sw_Bus1Transformer', TypicallyClosed := TRUE),
(Name := 'Sw_Bus2Transformer', TypicallyClosed := TRUE),
(Name := 'Sw_Bus2Bkr', TypicallyClosed := TRUE),
(Name := 'Sw_Load1', TypicallyClosed := TRUE),
(Name := 'Sw_Load2', TypicallyClosed := TRUE),
(Name := 'Sw_Load3', TypicallyClosed := FALSE),
(Name := 'Sw_Load4', TypicallyClosed := TRUE)
];
g_Breakers : ARRAY [1..g_c_NumBreakers] OF class_Breaker
:= [ (Name := 'Bkr_Source1', TypicallyClosed := TRUE),
(Name := 'Bkr_Source2', TypicallyClosed := TRUE),
(Name := 'Bkr_TransformerHigh', TypicallyClosed := TRUE),
(Name := 'Bkr_TransformerLow', TypicallyClosed := TRUE),
(Name := 'Bkr_Load1', TypicallyClosed := TRUE),
(Name := 'Bkr_Load2', TypicallyClosed := TRUE),
(Name := 'Bkr_Load3', TypicallyClosed := FALSE),
(Name := 'Bkr_Load4', TypicallyClosed := TRUE)
];

g_VoltageMeters : ARRAY [1..g_c_NumVoltageMeters] OF


class_VoltageMeasurement
:= [ (Name := 'Bus1Voltage', ScaleFactor := 1000),
(Name := 'Bus2Voltage', ScaleFactor := 1000)
];

g_CurrentMeters : ARRAY [1..g_c_NumCurrentMeters] OF


class_CurrentMeasurement
:= [ (Name := 'Source1', ScaleFactor := 1),
(Name := 'Source2', ScaleFactor := 1),
(Name := 'Bus1CurrentOut', ScaleFactor := -1),
(Name := 'TransformerCurrentHigh', ScaleFactor := -1),
(Name := 'TransformerCurrentLow', ScaleFactor := 1),
(Name := 'Bus2CurrentIn', ScaleFactor := 1),
(Name := 'Load1', ScaleFactor := -1),
(Name := 'Load2', ScaleFactor := -1),
(Name := 'Load3', ScaleFactor := -1),
(Name := 'Load4', ScaleFactor := -1)
];

g_Source1Line : class_ACLineSegment := (Name := 'Line1');


g_Source2Line : class_ACLineSegment := (Name := 'Line2');

g_TransformerA : class_PowerTransformer := (Name :=


'InboundTransformer');

g_TransformerAHighVoltage : class_PowerTransformerEnd :=
(Name := 'TransEndHigh', ConnectionType := WYE, NominalRatio
:= 1.0);
g_TransformerALowVoltage : class_PowerTransformerEnd :=
(Name := 'TransEndLow', ConnectionType := WYE, NominalRatio :=
0.5);
g_TransformerATapChanger : class_TapChanger := (DefaultStep := 0,
StepSize := 0.05, StepHighLimit := 16, StepLowLimit := -16);

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.49
Examples

g_HighVoltage : class_VoltageLevel;
g_LowVoltage : class_VoltageLevel;

(* Tie object terminals together.


** This should be done immediately after instantiating objects.
** This must be done before adding objects to containers. *)
g_ObjectsTied : ARRAY [1 .. g_c_ConnectionCount] OF BOOL
:= [ g_Model1.bootstrap_ConnectTerminals
(g_Source1.pt_Terminal, g_Source1Line.pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Source1Line.pt_TerminalB,
g_Switches[1].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Source2.pt_Terminal, g_Source2Line.pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Source2Line.pt_TerminalB,
g_Switches[2].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[1].pt_TerminalB,
g_Breakers[1].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[2].pt_TerminalB,
g_Breakers[2].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Bus1.pt_Terminal, g_Breakers[1].pt_TerminalB),
g_Model1.bootstrap_ConnectTerminals
(g_Bus1.pt_Terminal, g_Breakers[2].pt_TerminalB),
g_Model1.bootstrap_ConnectTerminals
(g_Bus1.pt_Terminal, g_Switches[3].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[3].pt_TerminalB,
g_Breakers[3].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Breakers[3].pt_TerminalB,
g_Switches[4].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[4].pt_TerminalB,
g_TransformerAHighVoltage.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals
(g_TransformerALowVoltage.pt_Terminal,
g_Switches[5].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[5].pt_TerminalB,
g_Breakers[4].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Breakers[4].pt_TerminalB,
g_Switches[6].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Bus2.pt_Terminal, g_Switches[6].pt_TerminalB),
g_Model1.bootstrap_ConnectTerminals
(g_Bus2.pt_Terminal, g_Breakers[5].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Bus2.pt_Terminal, g_Breakers[6].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Bus2.pt_Terminal, g_Breakers[7].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Bus2.pt_Terminal, g_Breakers[8].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals

Date Code 20190830 Instruction Manual Programming Reference


18.50 PowerSystemModel
Examples

(g_Breakers[5].pt_TerminalB,
g_Switches[7].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Breakers[6].pt_TerminalB,
g_Switches[8].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Breakers[7].pt_TerminalB,
g_Switches[9].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Breakers[8].pt_TerminalB,
g_Switches[10].pt_TerminalA),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[7].pt_TerminalB, g_Load1.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[8].pt_TerminalB, g_Load2.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[9].pt_TerminalB, g_Load3.pt_Terminal),
g_Model1.bootstrap_ConnectTerminals
(g_Switches[10].pt_TerminalB, g_Load4.pt_Terminal)
];
// Finish connecting terminals and enable population of containers.
g_TerminalsComplete : BOOL := g_Model1.bootstrap_FinalizeConnections();

// Set object configuration:


g_ConfigsSet : ARRAY [1 .. g_c_ConfigurationCount] OF BOOL := [
g_Switches[1].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[1]),
g_Switches[2].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[2]),
g_Switches[3].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[3]),
g_Switches[4].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[4]),
g_Switches[5].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[5]),
g_Switches[6].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[6]),
g_Switches[7].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[7]),
g_Switches[8].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[8]),
g_Switches[9].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[9]),
g_Switches[10].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[10]),
g_Breakers[1].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[11]),
g_Breakers[2].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[12]),
g_Breakers[3].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[13]),
g_Breakers[4].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[14]),
g_Breakers[5].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[15]),
g_Breakers[6].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[16]),
g_Breakers[7].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[17]),

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.51
Examples

g_Breakers[8].bootstrap_ConfigureIsOpenInput
(stIn_IsOpen := OpenStateValues[18]),

g_CurrentMeters[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[1], phaseA := PhaseAValues[1],
phaseB := PhaseBValues[1], phaseC := PhaseCValues[1]),
g_CurrentMeters[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[2], phaseA := PhaseAValues[2],
phaseB := PhaseBValues[2], phaseC := PhaseCValues[2]),
g_CurrentMeters[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[3], phaseA := PhaseAValues[3],
phaseB := PhaseBValues[3], phaseC := PhaseCValues[3]),
g_CurrentMeters[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[4], phaseA := PhaseAValues[4],
phaseB := PhaseBValues[4], phaseC := PhaseCValues[4]),
g_CurrentMeters[5].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[5], phaseA := PhaseAValues[5],
phaseB := PhaseBValues[5], phaseC := PhaseCValues[5]),
g_CurrentMeters[6].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[6], phaseA := PhaseAValues[6],
phaseB := PhaseBValues[6], phaseC := PhaseCValues[6]),
g_CurrentMeters[7].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[7], phaseA := PhaseAValues[7],
phaseB := PhaseBValues[7], phaseC := PhaseCValues[7]),
g_CurrentMeters[8].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[8], phaseA := PhaseAValues[8],
phaseB := PhaseBValues[8], phaseC := PhaseCValues[8]),
g_CurrentMeters[9].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[9], phaseA := PhaseAValues[9],
phaseB := PhaseBValues[9], phaseC := PhaseCValues[9]),
g_CurrentMeters[10].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[10], phaseA := PhaseAValues[10],
phaseB := PhaseBValues[10], phaseC := PhaseCValues[10]),
g_VoltageMeters[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[11], phaseA := PhaseAValues[11],
phaseB := PhaseBValues[11], phaseC := PhaseCValues[11]),
g_VoltageMeters[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits[12], phaseA := PhaseAValues[12],
phaseB := PhaseBValues[12], phaseC := PhaseCValues[12]),

g_Source1Line.bootstrap_SetNominalLineImpedance1Line
(resistance := 1.2, reactance := 12),
g_Source1Line.bootstrap_SetNominalShuntAdmittance1Line
(conductance := 12, susceptance := 1.2),
g_Source2Line.bootstrap_SetNominalLineImpedance1Line
(resistance := 1.2, reactance := 12),
g_Source2Line.bootstrap_SetNominalShuntAdmittance1Line
(conductance := 12, susceptance := 1.2),
g_TransformerAHighVoltage.bootstrap_SetNominalEndImpedance3Phase(
reactanceAPhase := 10, resistanceAPhase := 1,
reactanceBPhase := 10, resistanceBPhase := 1,
reactanceCPhase := 10, resistanceCPhase := 1,
reactanceABPhase := 1, resistanceABPhase := 0.1,
reactanceACPhase := 1, resistanceACPhase := 0.1,
reactanceBCPhase := 1, resistanceBCPhase := 0.1),

g_TransformerAHighVoltage.bootstrap_SetNominalShuntAdmittance3Phase(
conductanceAPhase := 10, susceptanceAPhase := 1,
conductanceBPhase := 10, susceptanceBPhase := 1,

Date Code 20190830 Instruction Manual Programming Reference


18.52 PowerSystemModel
Examples

conductanceCPhase := 10, susceptanceCPhase := 1,


conductanceABPhase := 1, susceptanceABPhase := 0.1,
conductanceACPhase := 1, susceptanceACPhase := 0.1,
conductanceBCPhase := 1, susceptanceBCPhase := 0.1),
g_TransformerALowVoltage.bootstrap_SetNominalEndImpedance3Phase(
reactanceAPhase := 10, resistanceAPhase := 1,
reactanceBPhase := 10, resistanceBPhase := 1,
reactanceCPhase := 10, resistanceCPhase := 1,
reactanceABPhase := 1, resistanceABPhase := 0.1,
reactanceACPhase := 1, resistanceACPhase := 0.1,
reactanceBCPhase := 1, resistanceBCPhase := 0.1),
g_TransformerALowVoltage.bootstrap_SetNominalShuntAdmittance3Phase(
conductanceAPhase := 10, susceptanceAPhase := 1,
conductanceBPhase := 10, susceptanceBPhase := 1,
conductanceCPhase := 10, susceptanceCPhase := 1,
conductanceABPhase := 1, susceptanceABPhase := 0.1,
conductanceACPhase := 1, susceptanceACPhase := 0.1,
conductanceBCPhase := 1, susceptanceBCPhase := 0.1),

g_TransformerATapChanger.bootstrap_ConfigureInputs
(ratioModifier := TapChangerValue)
];

(* Add objects to containers as desired.


** This should be the last configuration done. *)
g_AreaLoaded : ARRAY [1 .. g_c_AreaCount] OF BOOL
:= [ g_TransformerA.bootstrap_AddWinding(winding :=
g_TransformerAHighVoltage),
g_TransformerA.bootstrap_AddWinding(winding :=
g_TransformerALowVoltage),
g_TransformerALowVoltage.bootstrap_AddTapChanger
(tapChanger := g_TransformerATapChanger),

g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_TransformerAHighVoltage),
g_HighVoltage.bootstrap_AddEquipment(equipment := g_Source1),
g_HighVoltage.bootstrap_AddEquipment(equipment := g_Source2),
g_HighVoltage.bootstrap_AddEquipment(equipment := g_Bus1),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[1]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[2]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[3]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[4]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[1]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[2]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[3]),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Source1Line),
g_HighVoltage.bootstrap_AddEquipment(equipment :=
g_Source2Line),

g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_TransformerALowVoltage),

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.53
Examples

g_LowVoltage.bootstrap_AddEquipment(equipment := g_Bus2),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[5]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[6]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[7]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[8]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[9]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Switches[10]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[4]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[5]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[6]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[7]),
g_LowVoltage.bootstrap_AddEquipment(equipment :=
g_Breakers[8]),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load1),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load2),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load3),
g_LowVoltage.bootstrap_AddEquipment(equipment := g_Load4),

g_Breakers[1].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[1]),
g_Breakers[2].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[2]),
g_Breakers[3].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[3]),
g_TransformerAHighVoltage.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[4]),
g_TransformerALowVoltage.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[5]),
g_Breakers[4].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[6]),
g_Breakers[5].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[7]),
g_Breakers[6].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[8]),
g_Breakers[7].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[9]),
g_Breakers[8].pt_TerminalA^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters[10]),

g_Bus1.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters[1]),
g_Bus2.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters[2])
];

// Finalize all model configuration.


g_ModelValidated : BOOL := g_Model1.bootstrap_ValidateModel();
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


18.54 PowerSystemModel
Examples

Modeling a Distribution Network


Objective
A user would like to monitor the power used on some distribution lines. The layout of the
lines is as seen in Figure 18.8.

AB
V
23 kV
115 kV 5 kV
BC
A
CA

A AG
A V
A BG
V
A CG
V

Figure 18.8 Distribution Network of Interest

Assumptions
Typically all inputs to a model would be assigned directly from a communication channel,
however for ease in compilation for this example all inputs are pulled from a GVL shown
in Code Snippet 18.4. Because the user needs to add single-phase monitoring, they must
create dummy inputs for the non-existent phases as the input sources for both voltage and
current.

Code Snippet 18.4 gvl_TagHarness


VAR_GLOBAL
g_DummyVoltage : CMV
:= (q := (validity := invalid), instCVal := (ang := 0, mag :=
0));
g_DummyCurrent : CMV
:= (q := (validity := good), instCVal := (ang := 0, mag := 0));

OpenStateValues2 : ARRAY [1..g_c_NumSwitches2+g_c_NumBreakers2] OF SPS


:= [ (stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good))
];

TapChangerValueN : INS := (stVal := 0, q := (validity := good));


TapChangerValueS : INS := (stVal := 0, q := (validity := good));

EnableBits2 : ARRAY [1..g_c_NumVoltageMeters2+g_c_NumCurrentMeters2]


OF BOOL :=
[g_c_NumVoltageMeters2(TRUE), g_c_NumCurrentMeters2(TRUE)];

PhaseAValues2 : ARRAY [1..g_c_NumVoltageMeters2+g_c_NumCurrentMeters2]


OF CMV

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.55
Examples

:= [ (q := (validity := good), instCVal := (ang := 0, mag := 1)),


(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.5)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.25)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.25)),
(q := (validity := good), instCVal := (ang := 0, mag := 25)),
(q := (validity := good), instCVal := (ang := 0, mag := 5)),
(q := (validity := invalid), instCVal := (ang := 0, mag := 0)),
(q := (validity := invalid), instCVal := (ang := 0, mag := 0))
];

PhaseBValues2 : ARRAY [1..g_c_NumVoltageMeters2+g_c_NumCurrentMeters2]


OF CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.5)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.25)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.25)),
(q := (validity := good), instCVal := (ang := 0, mag := 25)),
(q := (validity := invalid), instCVal := (ang := 0, mag := 0)),
(q := (validity := good), instCVal := (ang := 0, mag := 5)),
(q := (validity := invalid), instCVal := (ang := 0, mag := 0))
];

PhaseCValues2 : ARRAY [1..g_c_NumVoltageMeters2+g_c_NumCurrentMeters2]


OF CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.5)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.25)),
(q := (validity := good), instCVal := (ang := 0, mag := 0.25)),
(q := (validity := good), instCVal := (ang := 0, mag := 25)),
(q := (validity := invalid), instCVal := (ang := 0, mag := 0)),
(q := (validity := invalid), instCVal := (ang := 0, mag := 0)),
(q := (validity := good), instCVal := (ang := 0, mag := 5))
];
END_VAR

Solution
Once the user has identified all the elements of the model and decided the source for all
required data there are only two other elements the user must create for the model to do its
work. First, all configuration and bootstrap methods must be called before calling Run().
In this example this is shown as completed in a GVL, Code Snippet 18.6, which allows
the configuration to complete before any task cycles begin. Second, the user must create a
program that calls the model instance’s Run() method, Code Snippet 18.5:

Code Snippet 18.5 prg_RunModel


PROGRAM prg_RunModel

g_Model2.Run();

Code Snippet 18.6 gvl_Bootstrap


{attribute 'linkalways'}

Date Code 20190830 Instruction Manual Programming Reference


18.56 PowerSystemModel
Examples

VAR_GLOBAL CONSTANT
g_c_NumSwitches2 : UDINT := 4;
g_c_NumBreakers2 : UDINT := 2;
g_c_ConnectionCount2 : UDINT := 28;
g_c_NumVoltageMeters2 : UDINT := 4;
g_c_NumCurrentMeters2 : UDINT := 5;
g_c_AreaCount2 : UDINT := 49;
g_c_ConfigurationCount2 : UDINT := 37;

g_c_SeriesRealImpedancePerMile : LREAL := 0.186;


g_c_SeriesReactiveImpedancePerMile : LREAL := 0.415;
g_c_ShuntRealAdmittancePerMile : LREAL := 0;
g_c_ShuntReactiveAdmittancePerMile : LREAL := 1.044E-5;
END_VAR

VAR_GLOBAL
// Instantiate any desired models here:
g_Model2 : class_PowerSystemModel :=
(Filename := 'GlobalModel2.log', ABCRotation := TRUE);

// Instantiate all other components:


g_SourceN : class_EnergySource :=
(Name := 'Source1', Description := 'North Line');
g_SourceS : class_EnergySource :=
(Name := 'Source2', Description := 'South Line');
g_LoadAB : class_EnergyConsumer := (Name := 'LoadAB');
g_LoadBC : class_EnergyConsumer := (Name := 'LoadBC');
g_LoadCA : class_EnergyConsumer := (Name := 'LoadCA');
g_LoadA : class_EnergyConsumer := (Name := 'LoadA');
g_LoadB : class_EnergyConsumer := (Name := 'LoadB');
g_LoadC : class_EnergyConsumer := (Name := 'LoadC');

g_Bus : class_BusbarSection := (Name := 'Bus');


g_Junction1 : class_Junction := (Name := 'Source Line Junction');
g_Junction2 : class_Junction := (Name := 'Junction N Shunt');
g_Junction3 : class_Junction := (Name := 'Junction S Shunt');
g_Junction4 : class_Junction := (Name := 'Junction two phase split');
g_Junction5 : class_Junction := (Name := 'Junction one phase split');

g_Switches2 : ARRAY [1..g_c_NumSwitches2] OF class_Switch


:= [ (Name := 'Sw_SourceS', TypicallyClosed := TRUE),
(Name := 'Sw_SourceTrans', TypicallyClosed := TRUE),
(Name := 'Sw_LineN', TypicallyClosed := TRUE),
(Name := 'Sw_LineS', TypicallyClosed := TRUE)
];
g_Breakers2 : ARRAY [1..g_c_NumBreakers2] OF class_Breaker
:= [ (Name := 'Bkr_LineN', TypicallyClosed := TRUE),
(Name := 'Bkr_LineS', TypicallyClosed := TRUE)
];

g_VoltageMeters2 : ARRAY [1..g_c_NumVoltageMeters2] OF


class_VoltageMeasurement
:= [ (Name := 'TransformerOutVolts', ScaleFactor := 1000),
(Name := 'ALineVoltage', ScaleFactor := 1000),
(Name := 'BLineVoltage', ScaleFactor := 1000),
(Name := 'CLineVoltage', ScaleFactor := 1000)
];

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.57
Examples

g_CurrentMeters2 : ARRAY [1..g_c_NumCurrentMeters2] OF


class_CurrentMeasurement
:= [ (Name := 'CurrentN', ScaleFactor := 1),
(Name := 'CurrentS', ScaleFactor := 1),
(Name := 'CurrentA', ScaleFactor := -1),
(Name := 'CurrentB', ScaleFactor := -1),
(Name := 'CurrentC', ScaleFactor := -1)
];

g_LineN1 : class_ACLineSegment := (Name := 'LineN1');


g_LineN2 : class_ACLineSegment := (Name := 'LineN2');
g_LineS1 : class_ACLineSegment := (Name := 'LineS1');
g_LineS2 : class_ACLineSegment := (Name := 'LineS2');

g_TransformerIn : class_PowerTransformer := (Name :=


'InboundTransformer');
g_TransformerN : class_PowerTransformer := (Name :=
'LineNTransformer');
g_TransformerS : class_PowerTransformer := (Name :=
'LineSTransformer');

g_TransformerInHigh : class_PowerTransformerEnd :=
(Name := 'InHighVolts', ConnectionType := WYE, NominalRatio :=
1.0);
g_TransformerInLow : class_PowerTransformerEnd :=
(Name := 'InLowVolts', ConnectionType := WYE, NominalRatio :=
0.2);
g_TransformerNHigh : class_PowerTransformerEnd :=
(Name := 'LineNHighVolts', ConnectionType := WYE, NominalRatio
:= 1.0);
g_TransformerNLow : class_PowerTransformerEnd :=
(Name := 'LineNLowVolts', ConnectionType := WYE, NominalRatio
:= 0.21739);
g_TransformerNTap : class_TapChanger := (DefaultStep := 0,
StepSize := 0.05, StepHighLimit := 16, StepLowLimit := -16);
g_TransformerSHigh : class_PowerTransformerEnd :=
(Name := 'LineSHighVolts', ConnectionType := WYE, NominalRatio
:= 1.0);
g_TransformerSLow : class_PowerTransformerEnd :=
(Name := 'LineSLowVolts', ConnectionType := WYE, NominalRatio
:= 0.21739);
g_TransformerSTap : class_TapChanger := (DefaultStep := 0,
StepSize := 0.05, StepHighLimit := 16, StepLowLimit := -16);

g_HighVoltage2 : class_VoltageLevel;
g_MidVoltage2 : class_VoltageLevel;
g_LowVoltage2 : class_VoltageLevel;

g_NorthShunt : class_ShuntCompensator
:= ( Name := 'North Line Shunt Cap',
conductanceAPhase := 0,
susceptanceAPhase := 25,
conductanceBPhase := 0,
susceptanceBPhase := 25,
conductanceCPhase := 0,
susceptanceCPhase := 25
);
g_SouthShunt : class_ShuntCompensator
:= ( Name := 'South Line Shunt Cap',

Date Code 20190830 Instruction Manual Programming Reference


18.58 PowerSystemModel
Examples

conductanceAPhase := 0,
susceptanceAPhase := 25,
conductanceBPhase := 0,
susceptanceBPhase := 25,
conductanceCPhase := 0,
susceptanceCPhase := 25
);

(* Tie object terminals together.


** This should be done immediately after instantiating objects.
** This must be done before adding objects to containers. *)
g_ObjectsTied2 : ARRAY [1 .. g_c_ConnectionCount2] OF BOOL
:= [ g_Model2.bootstrap_ConnectTerminals
(g_Junction1.pt_Terminal, g_SourceN.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction1.pt_Terminal, g_Switches2[1].pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals
(g_SourceS.pt_Terminal, g_Switches2[1].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Junction1.pt_Terminal, g_Switches2[2].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Switches2[2].pt_TerminalB,
g_TransformerInHigh.pt_Terminal),
//The equipment between the transformers
g_Model2.bootstrap_ConnectTerminals
(g_Bus.pt_Terminal, g_TransformerInLow.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Bus.pt_Terminal, g_Switches2[3].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Switches2[3].pt_TerminalB,
g_Breakers2[1].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Breakers2[1].pt_TerminalB,
g_TransformerNHigh.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Bus.pt_Terminal, g_Switches2[4].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Switches2[4].pt_TerminalB,
g_Breakers2[2].pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Breakers2[2].pt_TerminalB,
g_TransformerSHigh.pt_Terminal),
//The equipment on the north line after the transformer
g_Model2.bootstrap_ConnectTerminals
(g_TransformerNLow.pt_Terminal, g_LineN1.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Junction2.pt_Terminal, g_LineN1.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals
(g_Junction2.pt_Terminal, g_NorthShunt.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction2.pt_Terminal, g_LineN2.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Junction4.pt_Terminal, g_LineN2.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals
(g_Junction4.pt_Terminal, g_LoadAB.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction4.pt_Terminal, g_LoadBC.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction4.pt_Terminal, g_LoadCA.pt_Terminal),

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.59
Examples

// The equipment on the south line after the transformer


g_Model2.bootstrap_ConnectTerminals
(g_TransformerSLow.pt_Terminal, g_LineS1.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Junction3.pt_Terminal, g_LineS1.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals
(g_Junction3.pt_Terminal, g_SouthShunt.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction3.pt_Terminal, g_LineS2.pt_TerminalA),
g_Model2.bootstrap_ConnectTerminals
(g_Junction5.pt_Terminal, g_LineS2.pt_TerminalB),
g_Model2.bootstrap_ConnectTerminals
(g_Junction5.pt_Terminal, g_LoadA.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction5.pt_Terminal, g_LoadB.pt_Terminal),
g_Model2.bootstrap_ConnectTerminals
(g_Junction5.pt_Terminal, g_LoadC.pt_Terminal)

];
// Finish connecting terminals and enable population of conatiners.
g_TerminalsComplete2 : BOOL :=
g_Model2.bootstrap_FinalizeConnections();

// Set object configuration:


g_ConfigsSet2 : ARRAY [1 .. g_c_ConfigurationCount2] OF BOOL
:= [ g_Switches2[1].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues2[1]),
g_Switches2[2].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues2[2]),
g_Switches2[3].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues2[3]),
g_Switches2[4].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues2[4]),
g_Breakers2[1].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues2[5]),
g_Breakers2[2].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues2[6]),

g_CurrentMeters2[1].bootstrap_ConfigureInputsThreePhase(
enable := EnableBits2[1], phaseA := PhaseAValues2[1],
phaseB := PhaseBValues2[1], phaseC :=
PhaseCValues2[1]),
g_CurrentMeters2[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[2], phaseA := PhaseAValues2[2],
phaseB := PhaseBValues2[2], phaseC :=
PhaseCValues2[2]),
g_CurrentMeters2[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[3], phaseA := PhaseAValues2[3],
phaseB := g_DummyCurrent, phaseC := g_DummyCurrent),
g_CurrentMeters2[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[4], phaseA := g_DummyCurrent,
phaseB := PhaseBValues2[4], phaseC := g_DummyCurrent),
g_CurrentMeters2[5].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[5], phaseA := g_DummyCurrent,
phaseB := g_DummyCurrent, phaseC := PhaseCValues2[5]),
g_VoltageMeters2[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[6], phaseA := PhaseAValues2[6],
phaseB := PhaseBValues2[6], phaseC :=
PhaseCValues2[6]),

Date Code 20190830 Instruction Manual Programming Reference


18.60 PowerSystemModel
Examples

g_VoltageMeters2[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[7], phaseA := PhaseAValues2[7],
phaseB := g_DummyVoltage, phaseC := g_DummyVoltage),
g_VoltageMeters2[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[8], phaseA := g_DummyVoltage,
phaseB := PhaseBValues2[8], phaseC := g_DummyVoltage),
g_VoltageMeters2[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits2[9], phaseA := g_DummyVoltage,
phaseB := g_DummyVoltage, phaseC := PhaseCValues2[9]),

g_LineN1.bootstrap_SetNominalLineImpedance1Line
(resistance := g_c_SeriesRealImpedancePerMile * 45,
reactance := g_c_SeriesReactiveImpedancePerMile *
45),
g_LineN1.bootstrap_SetNominalShuntAdmittance1Line
(conductance := g_c_ShuntRealAdmittancePerMile * 45,
susceptance := g_c_ShuntReactiveAdmittancePerMile *
45),
g_LineN2.bootstrap_SetNominalLineImpedance1Line
(resistance := g_c_SeriesRealImpedancePerMile * 2,
reactance := g_c_SeriesReactiveImpedancePerMile * 2),
g_LineN2.bootstrap_SetNominalShuntAdmittance1Line
(conductance := g_c_ShuntRealAdmittancePerMile * 2,
susceptance := g_c_ShuntReactiveAdmittancePerMile *
2),
g_LineS1.bootstrap_SetNominalLineImpedance1Line
(resistance := g_c_SeriesRealImpedancePerMile * 37,
reactance := g_c_SeriesReactiveImpedancePerMile *
37),
g_LineS1.bootstrap_SetNominalShuntAdmittance1Line
(conductance := g_c_ShuntRealAdmittancePerMile * 37,
susceptance := g_c_ShuntReactiveAdmittancePerMile *
37),
g_LineS2.bootstrap_SetNominalLineImpedance1Line
(resistance := g_c_SeriesRealImpedancePerMile * 2,
reactance := g_c_SeriesReactiveImpedancePerMile * 2),
g_LineS2.bootstrap_SetNominalShuntAdmittance1Line
(conductance := g_c_ShuntRealAdmittancePerMile * 2,
susceptance := g_c_ShuntReactiveAdmittancePerMile *
2),
g_TransformerInHigh.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_TransformerInHigh.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_TransformerInLow.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_TransformerInLow.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),

g_TransformerNHigh.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_TransformerNHigh.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_TransformerNLow.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_TransformerNLow.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),

g_TransformerSHigh.bootstrap_SetNominalEndImpedance1Line(

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.61
Examples

reactance := 10, resistance := 1),


g_TransformerSHigh.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_TransformerSLow.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_TransformerSLow.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),

g_TransformerNTap.bootstrap_ConfigureInputs
(ratioModifier := TapChangerValueN),
g_TransformerSTap.bootstrap_ConfigureInputs
(ratioModifier := TapChangerValueS)
];

(* Add objects to containers as desired.


** This should be the last configuration done. *)
g_AreaLoaded2 : ARRAY [1 .. g_c_AreaCount2] OF BOOL
:= [ g_TransformerIn.bootstrap_AddWinding(winding :=
g_TransformerInHigh),
g_TransformerIn.bootstrap_AddWinding(winding :=
g_TransformerInLow),
g_TransformerN.bootstrap_AddWinding(winding :=
g_TransformerNHigh),
g_TransformerN.bootstrap_AddWinding(winding :=
g_TransformerNLow),
g_TransformerNLow.bootstrap_AddTapChanger
(tapChanger := g_TransformerNTap),
g_TransformerS.bootstrap_AddWinding(winding :=
g_TransformerSHigh),
g_TransformerS.bootstrap_AddWinding(winding :=
g_TransformerSLow),
g_TransformerSLow.bootstrap_AddTapChanger
(tapChanger := g_TransformerSTap),

g_HighVoltage2.bootstrap_AddEquipment(equipment :=
g_TransformerInHigh),
g_HighVoltage2.bootstrap_AddEquipment(equipment := g_SourceN),
g_HighVoltage2.bootstrap_AddEquipment(equipment := g_SourceS),
g_HighVoltage2.bootstrap_AddEquipment(equipment :=
g_Junction1),
g_HighVoltage2.bootstrap_AddEquipment(equipment :=
g_Switches2[1]),
g_HighVoltage2.bootstrap_AddEquipment(equipment :=
g_Switches2[2]),

g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_TransformerInLow),
g_MidVoltage2.bootstrap_AddEquipment(equipment := g_Bus),
g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_Switches2[3]),
g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_Switches2[4]),
g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_Breakers2[1]),
g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_Breakers2[2]),
g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_TransformerNHigh),

Date Code 20190830 Instruction Manual Programming Reference


18.62 PowerSystemModel
Examples

g_MidVoltage2.bootstrap_AddEquipment(equipment :=
g_TransformerSHigh),

g_LowVoltage2.bootstrap_AddEquipment(equipment :=
g_TransformerNLow),
g_LowVoltage2.bootstrap_AddEquipment(equipment :=
g_TransformerSLow),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineN1),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineN2),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineS1),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LineS2),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction2),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction3),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction4),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_Junction5),
g_LowVoltage2.bootstrap_AddEquipment(equipment :=
g_NorthShunt),
g_LowVoltage2.bootstrap_AddEquipment(equipment :=
g_SouthShunt),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadAB),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadBC),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadCA),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadA),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadB),
g_LowVoltage2.bootstrap_AddEquipment(equipment := g_LoadC),

g_Breakers2[1].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[1]),
g_Breakers2[2].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[2]),
g_LoadA.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[3]),
g_LoadB.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[4]),
g_LoadC.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters2[5]),

g_Bus.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[1]),
g_LoadA.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[2]),
g_LoadB.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[3]),
g_LoadC.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters2[4])
];

// Finalize all model configuration.


g_ModelValidated2 : BOOL := g_Model2.bootstrap_ValidateModel();
END_VAR

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.63
Examples

Modeling a Ring Network


Objective
A user would like to monitor the power supplied on a ring network as seen in Figure 18.9.

120 V

A 600 V
A

12 kV
A A
V V

A
A A

240 V

Figure 18.9 ring of Network of Interest

Assumptions
Typically all inputs to a model would be assigned directly from a communication channel,
however for ease in compilation for this example all inputs are pulled from a GVL shown
in Code Snippet 18.7.

Code Snippet 18.7 gvl_TagHarness


VAR_GLOBAL
OpenStateValues3 : ARRAY [1..1+g_c_NumBreakers3] OF SPS
:= [ (stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good)),
(stVal := FALSE, q := (validity := good))
];

EnableBits3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]


OF BOOL :=
[g_c_NumVoltageMeters3(TRUE), g_c_NumCurrentMeters3(TRUE)];

PhaseAValues3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]


OF CMV

Date Code 20190830 Instruction Manual Programming Reference


18.64 PowerSystemModel
Examples

:= [ (q := (validity := good), instCVal := (ang := 0, mag := 600)),


(q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 10)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 2))
];

PhaseBValues3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]


OF CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 10)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 2))
];

PhaseCValues3 : ARRAY [1..g_c_NumVoltageMeters3+g_c_NumCurrentMeters3]


OF CMV
:= [ (q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 600)),
(q := (validity := good), instCVal := (ang := 0, mag := 10)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 2)),
(q := (validity := good), instCVal := (ang := 0, mag := 1)),
(q := (validity := good), instCVal := (ang := 0, mag := 4)),
(q := (validity := good), instCVal := (ang := 0, mag := 2))
];
END_VAR

Solution
Once the user has identified all the elements of the model and decided the source for all
required data there are only two other elements the user must create for the model to do
its work. First, the user must call all configuration and bootstrap methods before calling
Run(). In this example, this is shown as completed in a GVL, Code Snippet 18.9, which
allows the configuration to complete before any task cycles begin. Second, the user must
create a program that calls the model instance’s Run() method, Code Snippet 18.8:

Code Snippet 18.8 prg_RunModel


PROGRAM prg_RunModel

g_Model2.Run();

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.65
Examples

Code Snippet 18.9 gvl_Bootstrap


{attribute 'linkalways'}
VAR_GLOBAL CONSTANT
g_c_NumBreakers3 : UDINT := 8;
g_c_ConnectionCount3 : UDINT := 21;
g_c_NumVoltageMeters3 : UDINT := 3;
g_c_NumCurrentMeters3 : UDINT := 7;
g_c_AreaCount3 : UDINT := 40;
g_c_ConfigurationCount3 : UDINT := 31;
END_VAR

VAR_GLOBAL
// Instantiate any desired models here:
g_Model3 : class_PowerSystemModel :=
(Filename := 'GlobalModel3.log', ABCRotation := TRUE);

// Instantiate all other components:


g_Source12K : class_EnergySource :=
(Name := 'Utility');
g_Source600 : class_EnergySource :=
(Name := 'Generation');
g_Load120 : class_EnergyConsumer := (Name := 'Load120');
g_Load600_1 : class_EnergyConsumer := (Name := 'LargeLoad1');
g_Load600_2 : class_EnergyConsumer := (Name := 'LargeLoad2');
g_Load240 : class_EnergyConsumer := (Name := 'Load240');

g_JunctionW : class_Junction := (Name := 'W Junction');


g_JunctionE : class_Junction := (Name := 'E Junction');
g_JunctionS : class_Junction := (Name := 'S Junction');

g_Switch : class_Switch := (Name := 'Sw_Generation');

g_Breakers3 : ARRAY [1..g_c_NumBreakers3] OF class_Breaker


:= [ (Name := 'Bkr_W', TypicallyClosed := TRUE),
(Name := 'Bkr_WNW', TypicallyClosed := TRUE),
(Name := 'Bkr_NW', TypicallyClosed := TRUE),
(Name := 'Bkr_NE', TypicallyClosed := TRUE),
(Name := 'Bkr_ESE', TypicallyClosed := TRUE),
(Name := 'Bkr_SE', TypicallyClosed := TRUE),
(Name := 'Bkr_SW', TypicallyClosed := TRUE),
(Name := 'Bkr_WSW', TypicallyClosed := TRUE)
];

g_VoltageMeters3 : ARRAY [1..g_c_NumVoltageMeters3] OF


class_VoltageMeasurement
:= [ (Name := 'Volts_W', ScaleFactor := 1),
(Name := 'Volts_E', ScaleFactor := 1),
(Name := 'Volts_S', ScaleFactor := 1)
];

g_CurrentMeters3 : ARRAY [1..g_c_NumCurrentMeters3] OF


class_CurrentMeasurement
:= [ (Name := 'CurrentW' , ScaleFactor := 1),
(Name := 'CurrentNW', ScaleFactor := -1),
(Name := 'CurrentE' , ScaleFactor := -1),
(Name := 'CurrentSE', ScaleFactor := -1),
(Name := 'CurrentS' , ScaleFactor := 1),
(Name := 'CurrentSW', ScaleFactor := -1),
(Name := 'CurrentRing' , ScaleFactor := 1)

Date Code 20190830 Instruction Manual Programming Reference


18.66 PowerSystemModel
Examples

];

g_Transformer12Kto600 : class_PowerTransformer := (Name :=


'Transformer12K');
g_Transformer600to120 : class_PowerTransformer := (Name :=
'Transformer120');
g_Transformer600to240 : class_PowerTransformer := (Name :=
'Transformer240');

g_12Kin600 : class_PowerTransformerEnd :=
(Name := '12K Winding', ConnectionType := WYE, NominalRatio :=
1.0);
g_12Kout600 : class_PowerTransformerEnd :=
(Name := '600 Winding', ConnectionType := WYE, NominalRatio :=
0.05);
g_600in120 : class_PowerTransformerEnd :=
(Name := '600 Winding 120', ConnectionType := WYE,
NominalRatio := 1.0);
g_600out120 : class_PowerTransformerEnd :=
(Name := '120 Winding', ConnectionType := WYE, NominalRatio :=
0.2);
g_600in240 : class_PowerTransformerEnd :=
(Name := '600 Winding 240', ConnectionType := WYE,
NominalRatio := 1.0);
g_600out240 : class_PowerTransformerEnd :=
(Name := '240 Winding', ConnectionType := WYE, NominalRatio :=
0.4);

g_12KVolts : class_VoltageLevel;
g_600Volts : class_VoltageLevel;
g_240Volts : class_VoltageLevel;
g_120Volts : class_VoltageLevel;

(* Tie object terminals together.


** This should be done immediately after instantiating objects.
** This must be done before adding objects to containers. *)
g_ObjectsTied3 : ARRAY [1 .. g_c_ConnectionCount3] OF BOOL
:= [ g_Model3.bootstrap_ConnectTerminals
(g_Source12K.pt_Terminal, g_Breakers3[1].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[1].pt_TerminalB, g_12Kin600.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionW.pt_Terminal, g_12Kout600.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionW.pt_Terminal, g_Breakers3[2].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[2].pt_TerminalB, g_600in120.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[2].pt_TerminalB,
g_Breakers3[3].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[3].pt_TerminalB,
g_Breakers3[4].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionE.pt_Terminal, g_Breakers3[4].pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionE.pt_Terminal, g_Load600_1.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionE.pt_Terminal, g_Breakers3[5].pt_TerminalA),

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.67
Examples

g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[5].pt_TerminalB, g_600in240.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[5].pt_TerminalB,
g_Breakers3[6].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionS.pt_Terminal, g_Breakers3[6].pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionS.pt_Terminal, g_Switch.pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals
(g_Switch.pt_TerminalA, g_Source600.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionS.pt_Terminal, g_Breakers3[7].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[7].pt_TerminalB, g_Load600_2.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_Breakers3[7].pt_TerminalB,
g_Breakers3[8].pt_TerminalA),
g_Model3.bootstrap_ConnectTerminals
(g_JunctionW.pt_Terminal, g_Breakers3[8].pt_TerminalB),
g_Model3.bootstrap_ConnectTerminals
(g_600out120.pt_Terminal, g_Load120.pt_Terminal),
g_Model3.bootstrap_ConnectTerminals
(g_600out240.pt_Terminal, g_Load240.pt_Terminal)
];

// Finish connecting terminals and enable population of conatiners.


g_TerminalsComplete3 : BOOL :=
g_Model3.bootstrap_FinalizeConnections();

// Set object configuration:


g_ConfigsSet3 : ARRAY [1 .. g_c_ConfigurationCount3] OF BOOL
:= [ g_Switch.bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[1]),
g_Breakers3[1].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[2]),
g_Breakers3[2].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[3]),
g_Breakers3[3].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[4]),
g_Breakers3[4].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[5]),
g_Breakers3[5].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[6]),
g_Breakers3[6].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[7]),
g_Breakers3[7].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[8]),
g_Breakers3[8].bootstrap_ConfigureIsOpenInput(stIn_IsOpen :=
OpenStateValues3[9]),

g_CurrentMeters3[1].bootstrap_ConfigureInputsThreePhase(
enable := EnableBits3[1], phaseA := PhaseAValues3[1],
phaseB := PhaseBValues3[1], phaseC :=
PhaseCValues3[1]),
g_CurrentMeters3[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[2], phaseA := PhaseAValues3[2],
phaseB := PhaseBValues3[2], phaseC :=
PhaseCValues3[2]),

Date Code 20190830 Instruction Manual Programming Reference


18.68 PowerSystemModel
Examples

g_CurrentMeters3[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[3], phaseA := PhaseAValues3[3],
phaseB := PhaseBValues3[3], phaseC :=
PhaseCValues3[3]),
g_CurrentMeters3[4].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[4], phaseA := PhaseAValues3[4],
phaseB := PhaseBValues3[4], phaseC :=
PhaseCValues3[4]),
g_CurrentMeters3[5].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[5], phaseA := PhaseAValues3[5],
phaseB := PhaseBValues3[5], phaseC :=
PhaseCValues3[5]),
g_CurrentMeters3[6].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[6], phaseA := PhaseAValues3[6],
phaseB := PhaseBValues3[6], phaseC :=
PhaseCValues3[6]),
g_CurrentMeters3[7].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[7], phaseA := PhaseAValues3[7],
phaseB := PhaseBValues3[7], phaseC :=
PhaseCValues3[7]),
g_VoltageMeters3[1].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[8], phaseA := PhaseAValues3[8],
phaseB := PhaseBValues3[8], phaseC :=
PhaseCValues3[8]),
g_VoltageMeters3[2].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[9], phaseA := PhaseAValues3[9],
phaseB := PhaseBValues3[9], phaseC :=
PhaseCValues3[9]),
g_VoltageMeters3[3].bootstrap_ConfigureInputsThreePhase
(enable := EnableBits3[10], phaseA :=
PhaseAValues3[10],
phaseB := PhaseBValues3[10], phaseC :=
PhaseCValues3[10]),

g_12Kin600.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_12Kin600.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_12Kout600.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_12Kout600.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),

g_600in240.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_600in240.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_600out240.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_600out240.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),

g_600in120.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_600in120.bootstrap_SetNominalShuntAdmittance1Line(
conductance := 10, susceptance := 1),
g_600out120.bootstrap_SetNominalEndImpedance1Line(
reactance := 10, resistance := 1),
g_600out120.bootstrap_SetNominalShuntAdmittance1Line(

Programming Reference Instruction Manual Date Code 20190830


PowerSystemModel 18.69
Examples

conductance := 10, susceptance := 1)


];

(* Add objects to containers as desired.


** This should be the last configuration done. *)
g_AreaLoaded3 : ARRAY [1 .. g_c_AreaCount3] OF BOOL
:= [ g_Transformer12Kto600.bootstrap_AddWinding(winding :=
g_12Kin600),
g_Transformer12Kto600.bootstrap_AddWinding(winding :=
g_12Kout600),
g_Transformer600to240.bootstrap_AddWinding(winding :=
g_600in240),
g_Transformer600to240.bootstrap_AddWinding(winding :=
g_600out240),
g_Transformer600to120.bootstrap_AddWinding(winding :=
g_600in120),
g_Transformer600to120.bootstrap_AddWinding(winding :=
g_600out120),

g_12KVolts.bootstrap_AddEquipment(equipment := g_12Kin600),
g_12KVolts.bootstrap_AddEquipment(equipment := g_Breakers3[1]),
g_12KVolts.bootstrap_AddEquipment(equipment := g_Source12K),

g_600Volts.bootstrap_AddEquipment(equipment := g_12Kout600),
g_600Volts.bootstrap_AddEquipment(equipment := g_600in240),
g_600Volts.bootstrap_AddEquipment(equipment := g_600in120),
g_600Volts.bootstrap_AddEquipment(equipment := g_JunctionW),
g_600Volts.bootstrap_AddEquipment(equipment := g_JunctionE),
g_600Volts.bootstrap_AddEquipment(equipment := g_JunctionS),
g_600Volts.bootstrap_AddEquipment(equipment := g_Source600),
g_600Volts.bootstrap_AddEquipment(equipment := g_Load600_1),
g_600Volts.bootstrap_AddEquipment(equipment := g_Load600_2),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[2]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[3]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[4]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[5]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[6]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[7]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Breakers3[8]),
g_600Volts.bootstrap_AddEquipment(equipment := g_Switch),

g_240Volts.bootstrap_AddEquipment(equipment := g_600out240),
g_240Volts.bootstrap_AddEquipment(equipment := g_Load240),

g_120Volts.bootstrap_AddEquipment(equipment := g_600out120),
g_120Volts.bootstrap_AddEquipment(equipment := g_Load120),

g_JunctionW.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters3[1]),
g_JunctionE.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters3[1]),
g_JunctionS.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_VoltageMeters3[1]),

g_12Kout600.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[1]),
g_600in120.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[2]),
g_Load600_1.pt_Terminal^.bootstrap_AddMeasurement

Date Code 20190830 Instruction Manual Programming Reference


18.70 PowerSystemModel
Log File Format

(measurement := g_CurrentMeters3[3]),
g_600in240.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[4]),
g_Switch.pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[5]),
g_Load600_2.pt_Terminal^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[6]),
g_Breakers3[4].pt_TerminalB^.bootstrap_AddMeasurement
(measurement := g_CurrentMeters3[7])
];

// Finalize all model configuration.


g_ModelValidated3 : BOOL := g_Model3.bootstrap_ValidateModel();
END_VAR

Log File Format


A log file is written to a file defined by the class_PowerSystemModel object’s Filename
variable. This file is written in four parts.
First is a summary of connections. This should show a count of terminals, equipment,
and nodes (locations where terminals are tied). Next is a list of quantities for each type
of equipment. These two sets of numbers can be compared to the system desired to be
modeled to validate that all pieces of the model are tied together. Third, any errors that
might have been encountered during validation are printed. This prints any errors detected
in a particular device, followed by the name of the device in which the errors were encoun-
tered. Finally, a summary of windings per transformer is provided. A sample log file for
Modeling a Substation on page 18.45 with an added voltage tying error is presented below:

This model is constructed from 50 terminals connected to 30 pieces of


equipment by 22 nodes.

This model is comprised of the following equipment:


Energy Sources: 2
Energy Consumers: 4
Switches: 10
Breakers: 8
Lines: 2
Buses and Junctions: 2
Shunt Compensators: 0
Transformers: 1

Conducting equipment TransEndLow not in Voltage Level.


Errors in transformer winding TransEndLow.
Transformer InboundTransformer tied to model with 2 windings.

Programming Reference Instruction Manual Date Code 20190830


SECTION 19

PowerSystemProtection
Introduction
The power system protection library provides function blocks that implement various pro-
tection elements for power systems. This library is intended to be used in conjunction with
the SEL-2245-42 AC Protection Module.

Special Considerations
ä This library is not supported on the SEL-3505 class of RTACs. This is because the
SEL-3505 does not support the Axion AC Protection Module. However, this library
is not prevented from running on a SEL-3505, but is not tested and has no guarantee
on expected behavior.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Library version 3.5.0.0 is meant to be used with the AC Protection Module, which is not
supported until RTAC firmware R137. However, there are no explicit checks to enforce
this, and the library version 3.5.0.0 can be imported and used in logic in RTAC projects
targeting firmware version R132 or later.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_LineBusStates
Given the voltage levels on the bus side and line side of a breaker, the line side and bus
side can each be either live or dead. This enumeration represents the four permutations
that result from the two monitored locations, each in one of two states. There are also per-
mutations provided for when one of the states can be confirmed, but not the other.

Date Code 20190830 Instruction Manual Programming Reference


19.2 PowerSystemProtection
Function Blocks

Enumeration Description
DLDB Dead-Line, Dead-Bus
DLLB Dead-Line, Live-Bus
DLUB Dead-Line, Undefined-Bus (bus voltage is above dead threshold, but not above
live threshold)
LLDB Live-Line, Dead-Bus
LLLB Live-Line, Live-Bus
LLUB Live-Line, Undefined-Bus (bus voltage is above dead threshold, but not above
live threshold)
ULDB Undefined-Line, Dead-Bus (line voltage is above dead threshold, but not above
live threshold)
ULLB Undefined-Line, Live-Bus (bus voltage is above dead threshold, but not above
live threshold)
ULUB Undefined-Line, Undefined-Bus (bus voltage and Line Voltage are both above
dead threshold and below live threshold, or the computation is being blocked
because of an error)

Function Blocks
fb_DefiniteTime (Function Block)
This function block implements instantaneous and definite-time overcurrent protection
functionality.
The settings inputs (starting with Set) are read on the first call to the function block after
EN becomes TRUE or on the first call to the function block. All changes to the settings
inputs during runtime are ignored until the next rising edge of EN is detected.

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetPickupSetting REAL Pickup current of the protection element. This is the
minimum current required to initiate the operation
of the protection element.
SetDelayTime TIME Time delay for definite-time overcurrent protection
element. This should be set to a multiple of the
RTAC processing scan time on which this object is
instantiated and represents the amount of time Op-
eratingQuantity must exceed PickupSetting prior to
asserting the protection element output.
OperatingQuantity REAL The fundamental magnitude of the current. This
quantity may be phase (A, B, or C), ground, or
negative-sequence current measurement.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.3
Function Blocks

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
PickupSetting REAL Pickup current value used in the protection element,
read from SetPickupSetting.
DelayTime TIME Definite-time overcurrent time delay value used in the
protection element, read from SetDelayTime.
ElementPickup BOOL Instantaneous overcurrent protection element has op-
erated. Set to TRUE when OperatingQuantity >= Pick-
upSetting.
PickupTimeOut BOOL Definite-time overcurrent protection element has op-
erated. Set to TRUE when OperatingQuantity > Pick-
upSetting for a time longer than DelayTime.

Processing
ä If OperatingQuantity >= PickupSetting, then set ElementPickup to TRUE.
ä If ElementPickup has been TRUE for longer than DelayTime, then set PickupTimeOut
TRUE.
ä When OperatingQuantity < PickupSetting, reset the elapsed time in the timer to 0
and set the ElementPickup to FALSE.

fb_InverseTimeCurveUser (Function Block)


This function block defines a custom characteristic curve of an inverse-time overcurrent
protection element. It implements the analytic equations for the operating time and reset
time specified in section 4.2 of IEEE C37.112-1996, IEEE Standard Inverse-Time Char-
acteristic Equations for Overcurrent Relays. This function block allows the user to apply
constants to Equation 19.1 and Equation 19.2 to define an inverse-time overcurrent char-
acteristic curve.
The actual operating time or reset time of the function block is guaranteed to be within
±1% of the calculated value or ±(2 × P rocessingIntervalRT AC ).
The settings inputs (starting with Set) are read on the first call to the function block after
EN becomes TRUE. All changes to the settings inputs during runtime are ignored until the
next rising edge of EN is detected.

Equations
B
OperatingT ime = T imeDial ∗ (A + ) (Equation 19.1)
MC − 1

R
ResetT ime = T imeDial ∗ ( ) (Equation 19.2)
1 − M2

where:

Date Code 20190830 Instruction Manual Programming Reference


19.4 PowerSystemProtection
Function Blocks

ä M is the applied multiple of pickup current


â for operating time, M > 1
â for reset time, M < 1

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetPickupSetting REAL Pickup current magnitude of the protection element.
If OperatingQuantity goes above this quantity, the
protection element initiates its operation. This input
is read once on first call to the function block. All
changes to this input during runtime are ignored.
SetTimeDial REAL Time-dial setting. This input adjusts the protection
element to a predetermined trip time at a specified
current, as described in IEEE C37.112-1996, IEEE
Standard Inverse-Time Characteristic Equations for
Overcurrent Relays. This input is read once on first
call to the function block. All changes to this input
during runtime are ignored.
OperatingQuantity REAL The fundamental magnitude of the current. This
quantity may be phase (A, B, or C), ground, or
negative-sequence current measurement.
SetA REAL Sets user-defined A parameter for inverse curve cal-
culation (see Equation 19.1 ).
SetB REAL Sets user-defined B parameter for inverse curve cal-
culation (see Equation 19.1 ).
SetC REAL Sets user-defined C parameter for inverse curve cal-
culation (see Equation 19.1 ).
SetR REAL Sets user-defined R parameter for inverse curve cal-
culation (see Equation 19.2 ).

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
PickupSetting REAL Pickup current value used in the protection element.
This value is read from SetPickupSetting on first run of
the function block.
TimeDial REAL Time-dial setting value used in the protection element.
This value is read from SetTimeDial on first run of the
function block.
ElementPickup BOOL The protection element has initiated operation. Set to
TRUE if OperatingQuantity > PickupSetting.
PickupTimeOut BOOL The protection element has operated. Set to TRUE
when the operating time expires.
ElementReset BOOL The protection element has reset (refer to section 3.2
of IEEE C37.112-1996, IEEE Standard Inverse-Time
Characteristic Equations for Overcurrent Relays).
Aval REAL Value being used that was set from SetA.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.5
Function Blocks

Bval REAL Value being used that was set from SetB.
Cval REAL Value being used that was set from SetC.
Rval REAL Value being used that was set from SetR.

Processing
START

OperatingQuantity
M= P ickupV alue

n n Inc = −ResetT ime


M = 1 M > 1
ElementPickup = FALSE
y y

Inc = OperationT ime


ElementPickup = TRUE

∆T
Acck = Acck−1 + Inc

n n
Acc <= 0 Acc > 1

y y

Acc = 0 Acc = 1
PickupTimeOut= False PickupTimeOut= TRUE
ElementReset= TRUE ElementReset= FALSE

END

Predefined Inverse-Time Overcurrent Function Blocks


The function blocks listed below implement the U.S. and IEC inverse-time overcurrent
curves, in accordance with IEEE C37.112-1996, IEEE Standard Inverse-Time Character-
istic Equations for Overcurrent Relays.
The curve type, operating type, and reset time equations associated with each function
block are listed in Table 19.1 and Table 19.2.

Date Code 20190830 Instruction Manual Programming Reference


19.6 PowerSystemProtection
Function Blocks

The settings inputs (starting with Set) are read on the first call to the function block after
EN becomes TRUE. All changes to the settings inputs during runtime are ignored until the
next rising edge of EN is detected.

Table 19.1 IEC Equations Associated With Predefined Inverse-Time Overcurrent


Function Blocks
Curve Function Block Name Operating Time (sec) Reset Time (sec)
0.14 13.5
C1–Standard Inverse fb_InverseTimeCurveC1 TD ∗ ( M 0.02 −1
) T D ∗ ( 1−M 2)
13.5 47.3
C2–Very Inverse fb_InverseTimeCurveC2 TD ∗ ( M −1 ) T D ∗ ( 1−M 2)

C3–Extremely Inverse fb_InverseTimeCurveC3 TD ∗ ( M80


2 −1 )
80
T D ∗ ( 1−M 2)

C4–Long-Time Inverse fb_InverseTimeCurveC4 TD ∗ ( M120


−1
) 120
T D ∗ ( 1−M )
0.05 4.85
C5–Short-Time Inverse fb_InverseTimeCurveC5 TD ∗ ( M 0.04 −1
) T D ∗ ( 1−M 2)

Table 19.2 U.S. Equations Associated With Predefined Inverse-Time Overcurrent


Function Blocks
Curve Function Block Name Operating Time (sec) Reset Time (sec)
U1–Moderately Inverse fb_InverseTimeCurveU1 T D ∗ (0.0226 + M0.0104
0.02 −1 )
1.08
T D ∗ ( 1−M 2)

U2–Inverse fb_InverseTimeCurveU2 T D ∗ (0.180 + M5.95


2 −1 )
5.95
T D ∗ ( 1−M 2)

U3–Very Inverse fb_InverseTimeCurveU3 T D ∗ (0.0963 + M3.88


2 −1 )
3.88
T D ∗ ( 1−M 2)

U4–Extremely Inverse fb_InverseTimeCurveU4 T D ∗ (0.0352 + M5.67


2 −1 )
5.67
T D ∗ ( 1−M 2)

U5–Short-Time Inverse fb_InverseTimeCurveU5 T D∗(0.00262+ M0.00342


0.02 −1 )
0.323
T D ∗ ( 1−M 2)

where:
ä TD = time-dial setting
ä M = applied multiple of pickup current
â for operating time, M > 1;
â for reset time, M < 1

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetPickupSetting REAL Pickup current magnitude of the protection element.
If OperatingQuantity goes above this quantity, the
protection element initiates its operation. This input
is read once on first call to the function block. All
changes to this input during runtime are ignored.
SetTimeDial REAL Time-dial setting. This input adjusts the protection
element to a predetermined trip time at a specified
current, as described in IEEE C37.112-1996, IEEE
Standard Inverse-Time Characteristic Equations for
Overcurrent Relays. This input is read once on first
call to the function block. All changes to this input
during runtime are ignored.
OperatingQuantity REAL The fundamental magnitude of the current. This
quantity may be phase (A, B, or C), ground, or
negative-sequence current measurement.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.7
Function Blocks

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
PickupSetting REAL Pickup current value used in the protection element.
This value is read from SetPickupSetting on first run of
the function block.
TimeDial REAL Time-dial setting value used in the protection element.
This value is read from SetTimeDial on first run of the
function block.
ElementPickup BOOL The protection element has initiated operation. Set to
TRUE if OperatingQuantity > PickupSetting.
PickupTimeOut BOOL The protection element has operated. Set to TRUE
when the operating time expires.
ElementReset BOOL The protection element has reset (refer to section 3.2
of IEEE C37.112-1996, IEEE Standard Inverse-Time
Characteristic Equations for Overcurrent Relays).

Processing
The calculations for these predefined curves happens exactly the same as for the fb_In-
verseTimeCurveUser (Function Block) on page 19.3, except that the coefficients used are
hard-coded instead of user-settable.

fb_LossOfPotential (Function Block)


Fuses often protect the secondary windings of the power system potential transformers.
The loss-of-potential logic is used to detect blown potential transformer fuses. The output
of this function block should be used to disable protection elements that rely on voltage
inputs so that voltage-based protection is performed securely and does not cause tripping
to occur when the transformer fuse is blown.
The function block declares a loss-of-potential condition if V1 drops in magnitude by at
least ten percent and there is no corresponding change in the magnitude or angle of I1 or
I0. A loss-of-potential condition persisting for 15 power cycles causes the loss-of-potential
output to latch. The output resets when V1 returns to a level greater than 85 percent nominal
voltage and V0 is less than 10 percent of the positive-sequence voltage (V1).
This function block is intended to be used with the SEL-2245-42 AC Protection Module.
When using the LossOfPotential function block, make sure that the RTAC task cycle time
is set to 4 ms.
The settings inputs (starting with Set) are read on the first call to the function block after
EN becomes TRUE. All changes to the settings inputs during runtime are ignored until the
next rising edge of EN is detected.

Date Code 20190830 Instruction Manual Programming Reference


19.8 PowerSystemProtection
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block.
SetNominalFrequency DINT(50..60) The nominal frequency (Hz) of the power
system (50 or 60). Recommend setting
this input equal to the RTAC system tag:
SystemTags.Nominal_Frequency.stVal
SetAmpsNominal REAL The maximum nominal amperage expected
(usually 1 A or 5 A secondary).
SetVoltsNominal REAL The nominal line-to-line voltage.
VoltsPosSeq vector_t The positive-sequence fundamental voltage vec-
tor.
VoltsZeroSeq vector_t The zero-sequence voltage fundamental vector.
AmpsZeroSeq vector_t The zero-sequence current fundamental vector.
AmpsPosSeq vector_t The positive-sequence current fundamental vec-
tor.
AmpsNegSeq vector_t The negative-sequence current fundamental
vector.
AmpsPhaseA vector_t The fundamental Phase A current.
AmpsPhaseB vector_t The fundamental Phase B current.
AmpsPhaseC vector_t The fundamental Phase C current.
FundQok BOOL The fundamental quantities above are report-
ing good quality. If values are being read
from the SEL-2245-42 module, then enable the
QUALITY_FUND tag on the module and assign
that tag to this input.
FundTimeStamp timestamp_t The time stamp of the fundamental quantity
measurements. Assign the TIMESTAMP_FUND.
tag on the SEL-2245-42 module to this input.

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled
ErrorDesc STRING(80) Displays an error description if one exists
NominalFrequency DINT[50,60] The nominal frequency of the power system (Hz).
AmpsNominal REAL The magnitude of the maximum nominal amperage
expected, read once from SetAmpsNominal.
VoltsNominal REAL The magnitude of the nominal line-to-line voltage.
This value is read once from SetVoltsNominal.
LossOfPotential BOOL Loss-of-potential condition detected. If ENO is
FALSE, then this value returns to the default TRUE
state. Use this output to disable protection elements
that use voltage to trip.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.9
Function Blocks

Processing

Figure 19.1 Loss-of-Potential Logic

Date Code 20190830 Instruction Manual Programming Reference


19.10 PowerSystemProtection
Function Blocks

fb_OverVoltage (Function Block)


Asserts OverVoltage when the measured voltage is higher than the threshold setting and
the function block is enabled.

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block. This should be set to
FALSE if the quantity being measured is bad qual-
ity or a loss-of-potential condition is detected.
ThresholdVoltage REAL The voltage to compare the magnitude against.
MeasuredVoltage REAL The magnitude of the voltage to measure.

Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is enabled.
OverVoltage BOOL The MeasuredVoltage is exceeding the voltage threshold.

Processing
The OverVoltage and ENO outputs are computed based on the input states according to the
following logic diagram:

MeasuredVoltage +

ThresholdVoltage −

OverVoltage

EN ENO

Figure 19.2 Overvoltage Logic

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.11
Function Blocks

fb_UnderVoltage (Function Block)


Asserts UnderVoltage when the measured voltage is lower than the threshold setting and
the function block is enabled.

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block. This should be set to
FALSE if the quantity being measured is bad qual-
ity or a loss-of-potential condition is detected.
ThresholdVoltage REAL The voltage to compare the magnitude against.
MeasuredVoltage REAL The magnitude of the voltage to measure.

Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is enabled.
UnderVoltage BOOL The MeasuredVoltage is presently less than the threshold
voltage.

Processing
The UnderVoltage and ENO outputs are computed based on the input states according to
the following logic diagram:

MeasuredVoltage −

ThresholdVoltage +

UnderVoltage

EN ENO

Figure 19.3 Undervoltage Logic

Date Code 20190830 Instruction Manual Programming Reference


19.12 PowerSystemProtection
Function Blocks

fb_BusLineVoltageCheck (Function Block)


Checks the single-phase voltage levels on the bus side and line side of a breaker. The line
side and bus side can both be either “live” or “dead”, and this function block provides the
logic to decide which permutation the voltages on each side of the breaker are in (see the
Enumerations on page 31.2 section for the listed enumeration).

Inputs
Name IEC 61131 Type Description
EN BOOL Enable this function block. Set this to FALSE if the
quantity being measured is bad quality or a loss-of-
potential condition is detected.
LineDeadThreshold REAL The voltage at which to declare the line dead.
LineLiveThreshold REAL The voltage at which to declare the line live.
BusDeadThreshold REAL The voltage at which to declare the bus dead.
BusLiveThreshold REAL The voltage at which to declare the bus live.
LineVoltage REAL The measured voltage of the line.
BusVoltage REAL The measured voltage of the bus.

Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is enabled.
ErrorDesc STRING(80) Displays an error description, if one exists.
LineBusState enum_LineBusStates The decided permutation.

Processing
ä If LineDeadThreshold > LineLiveThreshold, then an error is displayed in ErrorDesc.
ä If BusDeadThreshold > BusLiveThreshold, then an error is displayed in ErrorDesc.
ä When the following conditions are met, ENO is set to TRUE:
â LineDeadThreshold ≤ LineLiveThreshold.
â BusDeadThreshold ≤ BusLiveThreshold.
â EN = TRUE.
ä If ENO = TRUE, then the bus and line states are computed independently using this
logic:
â If the voltage is below the associated dead threshold, declare it dead.
â If the voltage is above the associated live threshold, declare it live.
â If neither of the above conditions are TRUE, declare it dead.
ä If ENO = FALSE, then the LineBusState is set to ULUB (undefined bus, undefined
line).

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.13
Function Blocks

fb_ConductorThermalOverload (Function Block)


This function block estimates the temperature of a conductor by measuring the current flow-
ing through that conductor and the ambient temperature and declares an overload condition
when the approximated temperature exceeds the provided maximum temperature.
The settings inputs (starting with Set) are read on the first call to the function block after
EN becomes TRUE or on the or first call to the function block. All changes to the settings
inputs during runtime are ignored until the next rising edge of EN is detected.

Inputs
Name IEC 61131 Type Description
EN BOOL Enables the computations of this function
block.
SetInitialTemp REAL Given in ℃; the assumed initial tempera-
ture of the line. This initializes the output
CalculatedTemp on the first scan that EN is
set to TRUE.
SetTimeConstant TIME The time constant (T ) which represents the
heating/cooling constant of the conductor
associated with the thermal capacity of the
line.
SetRatedCurrent REAL The amount of current which the conductor
is rated to carry continuously. Units must
match with the MeasuredCurrent.
SetReferenceAmbientTemp REAL The ambient temperature in ℃ at which
MaxConductorTemp was measured.
SetMaxConductorTemp REAL Given in ℃; the steady state temperature if
rated current flows continuously.
MeasuredCurrent REAL The rms current presently measured flow-
ing in the conductor. Units must match the
RatedCurrent value provided.
AmbientTemp REAL The ambient dry-bulb temperature in ℃.
The highest measured air temperature ex-
perienced by the conductor over its span.

Date Code 20190830 Instruction Manual Programming Reference


19.14 PowerSystemProtection
Function Blocks

Outputs
Name IEC 61131 Type Description
ENO BOOL This function block is active.
TimeConstant TIME The value (T ) read from SetTimeConstant.
RatedCurrent REAL The value read from SetRatedCurrent.
ReferenceAmbientTemp REAL The value read from SetReferenceAmbient-
Temp.
MaxConductorTemp REAL The value read from SetMaxConductorTemp.
CalculatedTemp REAL Based on the parameters provided, this is the
calculated temperature of the conductor, given
in ℃. Initialized by SetInitialTemp.
TimeToOverload TIME Assuming the inputs MeasuredCurrent and
AmbientTemp remain at their present value,
this is the amount of time remaining until an
overload condition is declared.
Overloaded BOOL MaxConductorTemperature has been reached.

Processing
This section describes the formulas used by this function block to calculate the outputs.

Input Validation Before Enabling


Inputs are read once and the ENO output is set to TRUE at the rising edge of the following
combination of input conditions: EN = T RU E AND SetRatedCurrent > 0.
Once set, the values used by the function block are displayed on the outputs and will not
be read again until the rising edge described above is again detected.

Temperature Calculation
An internal model is employed which assumes that the thermal dissipation capacity of
the conductor varies only with environmental temperature, which can either be entered
manually, or a temperature sensor can be used to measure the actual environmental air
temperature.
In the following, the uppercase Latin character T is used for temperature (℃) and the
uppercase Greek T for time constant. Lowercase t is used to represent time.
Most of the internal temperatures used in the equations are relative to ambient temperature.
These relative temperatures are represented by T∆ .
The temperature rise beyond ambient that is experienced by the conductor at steady-state
when carrying the maximum rated current is given by Equation 19.3 .

T∆n = M axConductorT emp − Ref erenceAmbientT emp (Equation 19.3)

Where the MaxConductorTemp and ReferenceAmbientTemp are provided by the manufac-


turer. MaxConductorTemp is the temperature experienced by the conductor at steady-state
when carrying rated current when the surrounding air is at the ReferenceAmbientTemp.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.15
Function Blocks

The assumed maximum line temperature for this scan is shown as TCalculatedT empk , and
the correlating calculated temperature is given in Equation 19.4 .

T∆k = CalculatedT emp − AmbientT emp (Equation 19.4)

Equation 19.5 shows the thermal differential equation, where h is the heat transfer coeffi-
cient of the conductor surface and A is the area of the surface of the conductor.

I 2R
 
dT 1
= −T (Equation 19.5)
dt T hA

Equation 19.6 and Equation 19.7 show the solution of Equation 19.5 in time-domain and
discrete domain, respectively.

I 2R  t
 t
T∆ = 1 − e− T + T∆Initial e− T (Equation 19.6)
hA

∆t R

T T hA I 2 + T∆k−1
T∆k = ∆t
(Equation 19.7)
1+ T

We can use a particular solution to find the relation between the coefficients R, h, and A: if
rated current In flows for a long amount of time (infinite), the steady state temperature of
the conductor is T∆n . Substituting these values in Equation 19.6 , the following equation
can be obtained:

R T∆n
= 2 (Equation 19.8)
hA In

Substituting Equation 19.8 in Equation 19.7 :

 2
∆t I
T In T∆n + T∆k−1
T∆k = ∆t
(Equation 19.9)
1+ T

Equation 19.3 and Equation 19.4 may be expressed as follows:

T∆k = TCalculatedk − TAmbient (Equation 19.10)

T∆k−1 = Tk−1 − TAmbient (Equation 19.11)

T∆n = TM axConductor − TRef erence (Equation 19.12)

Substituting Equation 19.10 , Equation 19.11 , and Equation 19.12 in Equation 19.9 ,
we get the equation that is used by this function block to calculate the temperature of the
conductor:
 2
I T
In (TM axConductor − TRef erence ) + ∆t Tk−1 + TAmbient
TCalculatedk = T
1 + ∆t
(Equation 19.13)

Date Code 20190830 Instruction Manual Programming Reference


19.16 PowerSystemProtection
Benchmarks

where:
TCalculatedk ≡ CalculatedT emp
TM axConductor ≡ M axConductorT emp
TRef erence ≡ Ref erenceAmbientT emp
TAmbient ≡ AmbientT emp
I ≡ M easuredCurrent
In ≡ RatedCurrent

Time to Overload Calculation


When the generation of heat exceeds the estimated thermal dissipation capacity, the esti-
mated temperature of the conductor is raised at a rate provided by the user (TimeConstant),
which models the thermal capacity of the line.
On each execution of the function block, a new estimated line temperature - T∆k is calcu-
lated using Equation 19.13 .
The CalculatedTemp is then compared to the MaxConductorTemp setting for this function
block. If the new estimated temperature is above the value: TempThreshold, then Over-
loaded is set to True and TimeToOverload is set to 0.
Internally, the predicted steady-state temperature which will result if the inputs remain
unchanged from their present state (Tss ) is calculated using Equation 19.14 .

I 2 T∆n
Tss = + TAmbient (Equation 19.14)
In2
While the steady-state temperature Tss > TM axConductor and TCalculatedk < TM axConductor
then there is an imminent overload condition. The time to the overload is calculated using
Equation 19.15 :

Tss − TCalculatedk
T imeT oOverload = T × ln (Equation 19.15)
Tss − TM axConductor

If the internal steady-state temperature is lower than TempThreshold, the TimeToOverload


output is set to the maximum value stored by type TIME.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530 / SEL-2241
â R136 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R136 firmware

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.17
Benchmarks

Benchmark Test Descriptions


Execution Time of Overcurrent Function Blocks
The posted time is the average execution time of 1000 consecutive calls to the function
blocks where the operating quantity alternates between a value that is barely above the
pickup threshold, to a value of 0.
This test is performed on the following function blocks:
ä fb_DefiniteTime
ä fb_InverseTimeCurveUser (The performance results for this function block are also
valid for any of the other inverse time curve blocks for the specific curves.)

Execution Time of Voltage Element Function Blocks


The posted time is the average execution time of 1000 consecutive calls to the function
blocks.
This test is performed on the following function blocks:
ä fb_BusLineVoltageCheck
ä fb_OverVoltage
ä fb_UnderVoltage

Execution Time of LossOfPotential Function Block


The posted time is the average execution time of 1000 consecutive calls to the fb_LossOf-
Potential function block.

Execution Time of Thermal Overload Function Blocks


The posted time is the average execution time of 1000 consecutive calls to the function
blocks.
This test is performed on the fb_ConductorThermalOverload function block.

Benchmark Results
Platform (time in µs)
Operation Tested SEL-3530 SEL-3555
SEL-2241
fb_DefiniteTime 3.1 0.5
fb_InverseTimeCurveUser 12.6 0.9
fb_LossOfPotential 10.8 0.4
fb_BusLineVoltageCheck 5.2 0.3
fb_OverVoltage 0.9 0.1
fb_UnderVoltage 1.1 0.1

Date Code 20190830 Instruction Manual Programming Reference


19.18 PowerSystemProtection
Examples

Platform (time in µs)


Operation Tested SEL-3530 SEL-3555
SEL-2241
fb_ConductorThermalOverload 15.0 0.8

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Create a Three-Phase Definite-Time Overcurrent Element


Objective
The user would like to create a program that implements a Three-Phase Definite-Time
Overcurrent element that asserts when any phase is detected overcurrent. The diagram is
shown below.

IA_F U N D.mag A Protection


OperatingQuantity ElementP ickup

SET 50P SetP ickupSetting P ickupT imeOut


SetDelayT ime DelayT ime
T #10S
P ickupSetting

IB_F U N D.mag B Protection


OperatingQuantity ElementP ickup

SET 50P SetP ickupSetting P ickupT imeOut O50P T


SetDelayT ime DelayT ime
T #10S
P ickupSetting

IC_F U N D.mag C Protection


OperatingQuantity ElementP ickup

SET 50P SetP ickupSetting P ickupT imeOut


SetDelayT ime DelayT ime
T #10S
P ickupSetting

Assumptions
This example assumes the user has an AC Protection Module setup to get current input
measurements.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.19
Examples

Solution
The user can create a program shown in Code Snippet 19.1:

Code Snippet 19.1 prg_50Element


PROGRAM prg_50Element
VAR
//50 protection elements
AProtection : PowerSystemProtection.fb_DefiniteTime;
BProtection : PowerSystemProtection.fb_DefiniteTime;
CProtection : PowerSystemProtection.fb_DefiniteTime;

//User defined inputs to 50 element


SET50P : REAL := 100;
SET50PTD : TIME := T#1S;

//Program Outputs
O50PT : BOOL;
END_VAR

AProtection(OperatingQuantity := SEL_prCTPT_1_ECAT.IA_FUND.mag,
SetPickupSetting := SET50P,
SetDelayTime := SET50PTD);
BProtection(OperatingQuantity := SEL_prCTPT_1_ECAT.IB_FUND.mag,
SetPickupSetting := SET50P,
SetDelayTime := SET50PTD);
CProtection(OperatingQuantity := SEL_prCTPT_1_ECAT.IC_FUND.mag,
SetPickupSetting := SET50P,
SetDelayTime := SET50PTD);

O50PT := AProtection.PickupTimeout
OR BProtection.PickupTimeout
OR CProtection.PickupTimeout;

Create a Three-Phase Inverse-Time Overcurrent Element


Objective
The user would like to create a program with behavior of 51 Three-Phase Inverse-Time
Overcurrent ORMODE outputs.

Assumptions
This example assumes the user has a SEL-2245-42 AC Protection Module configured in
the RTAC project to obtain fundamental measurements. NOTE: The module is assumed to
have the name:
"SEL_prCTPT_1_ECAT".

Date Code 20190830 Instruction Manual Programming Reference


19.20 PowerSystemProtection
Examples

Solution
The user can create a program shown in Code Snippet 19.2:

Code Snippet 19.2 prg_51Element


PROGRAM prg_51Element
VAR
//Inverse Time Curve Function Blocks
Aphase : PowerSystemProtection.fb_InverseTimeCurveC2;
Bphase : PowerSystemProtection.fb_InverseTimeCurveC2;
Cphase : PowerSystemProtection.fb_InverseTimeCurveC2;
Nphase : PowerSystemProtection.fb_InverseTimeCurveC2;
//Phase Overcurrent Settings
Set51PPU : REAL := 0;
Set51PTD : REAL := 1.0;
//Neutral Overcurrent Settings
Set51NPU : REAL := 0;
Set51NTD : TIME := T#1S;
//OR Mode Outputs
O51PT : BOOL;
O51PR : BOOL;
O51P : BOOL;
END_VAR

Aphase( OperatingQuantity :=SEL_prCTPT_1_ECAT.IA_FUND.mag,


SetPickupSetting := Set51PPU,
SetTimeDial := Set51PTD );

Bphase( OperatingQuantity :=SEL_prCTPT_1_ECAT.IB_FUND.mag,


SetPickupSetting := Set51PPU,
SetTimeDial := Set51PTD );

Cphase( OperatingQuantity :=SEL_prCTPT_1_ECAT.IC_FUND.mag,


SetPickupSetting := Set51PPU,
SetTimeDial := Set51PTD );

O51P := Aphase.ElementPickup
AND Bphase.ElementPickup
AND Cphase.ElementPickup;

O51PT := Aphase.PickupTimeOut
AND Bphase.PickupTimeOut
AND Cphase.PickupTimeOut;

O51PR := Aphase.ElementReset
AND Bphase.ElementReset
AND Cphase.ElementReset;

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.21
Examples

Detect a Loss-of-Potential Condition


Objective
The user would like to detect an overvoltage condition of Phase A voltage and, when one
or more of the PT fuses or breakers is blown, prevent Phase A overvoltage detection from
enabling LED 1 on an RTAC/Axion.

Assumptions
This example assumes the user has a SEL-2245-42 AC Protection Module configured in
the RTAC project to obtain fundamental measurements.
For voltage Phase A overvoltage detection, the current and voltage phasors are assumed to
be: NOTE: The module is assumed to
have the name:
"SEL_prCTPT_1_ECAT".
Current Phase A: 4 A ∠ 0
Current Phase B: 4 A ∠ -120
Current Phase C: 4 A ∠ 120
Voltage Phase A: 70 V ∠ 0
Voltage Phase B: 67 V ∠ -120
Voltage Phase C: 67 V ∠ 120
A loss-of-potential condition can be triggered by using the following values and the LED
1 will turn off:
Current Phase A: 4 A ∠ 0
Current Phase B: 4 A ∠ -120
Current Phase C: 4 A ∠ 120
Voltage Phase A: 70 V ∠ 0
Voltage Phase B: 0 V ∠ -120
Voltage Phase C: 67 V ∠ 120

Solution
The user can create a program shown in Code Snippet 19.3:

Code Snippet 19.3 prg_LopDetection


PROGRAM prg_LopDetection
VAR
LossOfPotential : PowerSystemProtection.fb_LossOfPotential;
PhaseAOverVoltage : PowerSystemProtection.fb_OverVoltage;

Initalized : BOOL;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


19.22 PowerSystemProtection
Examples

Code Snippet 19.3 prg_LopDetection (Continued)


IF NOT Initalized THEN
// Assign all Set inputs and run once to initailize.
LossOfPotential.SetAmpsNominal := 5;
LossOfPotential.SetNominalFrequency :=
SystemTags.Nominal_Frequency.stVal;
LossOfPotential.SetVoltsNominal := 66.4;
LossOfPotential.EN := TRUE;
LossOfPotential();

PhaseAOverVoltage.ThresholdVoltage := 69;
END_IF

LossOfPotential.FundQok := SEL_prCTPT_1_ECAT.QUALITY_FUND;
LossOfPotential.FundTimeStamp := SEL_prCTPT_1_ECAT.TIMESTAMP_FUND;

LossOfPotential.AmpsNegSeq := SEL_prCTPT_1_ECAT.I2_FUND;
LossOfPotential.AmpsPosSeq := SEL_prCTPT_1_ECAT.I1_FUND;
LossOfPotential.AmpsZeroSeq := SEL_prCTPT_1_ECAT.I0_FUND;

LossOfPotential.AmpsPhaseA := SEL_prCTPT_1_ECAT.IA_FUND;
LossOfPotential.AmpsPhaseB := SEL_prCTPT_1_ECAT.IB_FUND;
LossOfPotential.AmpsPhaseC := SEL_prCTPT_1_ECAT.IC_FUND;

LossOfPotential.VoltsPosSeq := SEL_prCTPT_1_ECAT.V1_FUND;
LossOfPotential.VoltsZeroSeq := SEL_prCTPT_1_ECAT.V0_FUND;

LossOfPotential();

// When loss of potential is detected, the overvoltage element will be


disabled.
PhaseAOverVoltage.EN := NOT LossOfPotential.LossOfPotential;
PhaseAOverVoltage.MeasuredVoltage := SEL_prCTPT_1_ECAT.VA_FUND.mag;
PhaseAOverVoltage();

IF PhaseAOverVoltage.OverVoltage THEN
SystemTags.Aux_LED_01.operSet.ctlVal := TRUE;
SystemTags.Aux_LED_01.operClear.ctlVal := FALSE;
ELSE
SystemTags.Aux_LED_01.operSet.ctlVal := FALSE;
SystemTags.Aux_LED_01.operClear.ctlVal := TRUE;
END_IF

Detect a Thermal Overload for a Single Phase


Objective
The user would like to detect when Phase A has exceeded a maximum conductor temper-
ature and turn on LED 1.

Programming Reference Instruction Manual Date Code 20190830


PowerSystemProtection 19.23
Examples

Assumptions
This example assumes the user has a SEL-2245-42 AC Protection Module configured in
the RTAC project to obtain rms measurements.
The AmbientTemperature pin values can be forced by the user to observe functionality. Val-
ues greater than 20.3℃ will cause a thermal overload condition when the MeasuredCurrent NOTE: The module is assumed to
have the name:
is set to 100 A. "SEL_prCTPT_1_ECAT".

Solution
The user can create a program shown in Code Snippet 19.4:

Code Snippet 19.4 prg_ThermalElementExample


PROGRAM prg_ThermalElementExample
VAR
ThermalOverload :
PowerSystemProtection.fb_ConductorThermalOverload :=
(SetInitialTemp := 20,
// This is an unrealistic time constant for a real system,
// but will demonstrate the behavior of the function block
on
// the order of seconds for this example.
SetTimeConstant := T#1S,
SetRatedCurrent := 105,
SetReferenceAmbientTemp := 20,
SetMaxConductorTemp := 24);

// This value can be force changed to view behavior of


function block.
AmbientTemp : REAL := 21;
END_VAR

ThermalOverload.AmbientTemperature := AmbientTemp;
ThermalOverload.MeasuredCurrent := SEL_prCTPT_1_ECAT.IA_RMS;
ThermalOverload();

IF ThermalOverload.Overloaded THEN
SystemTags.Aux_LED_01.operSet.ctlVal := TRUE;
SystemTags.Aux_LED_01.operClear.ctlVal := FALSE;
ELSE
SystemTags.Aux_LED_01.operSet.ctlVal := FALSE;
SystemTags.Aux_LED_01.operClear.ctlVal := TRUE;
END_IF

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 20

Queue
Introduction
See the ACSELERATOR RTAC Library Extensions Instruction Manual (LibraryExtension-
sIM) for an explanation of the concepts used by the object-oriented extensions to the IEC 61131-3
standard.

Queues
A queue is a fundamental data structure in computer science, and is implemented within
this library as an object.
The term “queue” is often used interchangeably with the term “First-In-First-Out” (FIFO),
which is a more descriptive name. The queue is often used as a buffer, allowing information
to be queued up to be processed in the same order that it was received in, but at a different
rate. This library defines the front of a queue as the oldest element pushed into the queue
and the back of the queue is the newest element pushed into the queue.
This is easily visualized and remembered by using the common image of customers stand-
ing in a line, also known as a queue. The customer that has been in line the longest is at
the front of the queue, and people awaiting service are added to the back of the queue.
All queues in this library assume that all elements within the queue are the same size.

Double-Ended Queues (Deques)


This library provides a a double-ended queue implementation (a deque). A deque can do
anything that a standard queue can do, but can have items added or removed from either
the front or the back.
With a deque, the library assembly can move priority information to the front of a queue,
or balance several parallel queues by removing items from the back of one queue and reas-
signing them to the back of other queues. These are operations that cannot be performed
on a pure queue.
The deque implementation used in this library also ensures that all the data within the queue
are kept in contiguous memory, which is not guaranteed in all queue implementations.

Date Code 20190830 Instruction Manual Programming Reference


20.2 Queue
Interfaces

Special Considerations
Classes in this library have memory allocated inside them. As such, they should only be
created in environments of permanent scope (e.g., Programs, Global Variable Lists, or
VAR_STAT sections).
Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_QueueObject"
myQueueObject := otherQueueObject;

// This is fine
someVariable := myQueueObject.value;
// As is this
pt_myQueueObject := ADR(myQueueObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT members


in function blocks, functions, or methods. Place them in the VAR_IN_OUT section
or use pointers instead.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.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.

Name IEC 61131 Type Value Description


g_p_DefaultQueueSize UDINT 32 The default number of elements that
a queue can hold.

Interfaces
This library provides the following interface.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.3
Interfaces

I_Queue (Interface)
This interface is implemented by any class that provides a queue data type.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


ElementSize UDINT R The number of bytes required for each element
in the queue.
MaxSize UDINT R The number of elements this queue can hold
before a reallocation for additional memory is
required.
Size UDINT R The number of elements in the queue.

Clear (Method)
Deallocates all memory associated with the queue. Call this method only if the queue is
instantiated with limited scope (i.e., if it is instantiated as a local variable of a function or
method).

Return Value
IEC 61131 Type Description
BOOL TRUE if the queue successfully deallocates its internal memory. FALSE
if an error occurs.

EraseFront (Method)
This method deletes the specified number of elements from the front of the queue.

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the front of the
queue.

Date Code 20190830 Instruction Manual Programming Reference


20.4 Queue
Interfaces

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the queue.

Processing
ä Removes as many as numToErase elements from the front of the queue.
ä If the Size of the queue is less than numToErase, only Size elements are removed
from the queue.

Front (Method)
This method copies the specified number of elements from the front of the queue to the
provided pointer location. The queue is not modified.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the front of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the front of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

PopFront (Method)
This method copies the specified number of elements from the front of the queue to the
provided pointer location and deletes them from the queue.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.5
Interfaces

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the front of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the queue.
Zero if the queue was not modified.

Processing
ä Copies as many as numToPop elements from the front of the queue to pt_destination.
ä If the Size of the queue is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the queue.
ä If pt_destination is invalid or the elements cannot be copied, the queue is not modi-
fied and zero is returned.

PushBack (Method)
This method copies elements from the specified pointer location and pushes them onto the
back of the queue.

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the queue. Zero if an
error occurred and the queue was not modified.

Date Code 20190830 Instruction Manual Programming Reference


20.6 Queue
Classes

Processing
ä If the queue is not large enough to contain the new elements, additional memory is
allocated to enlarge the queue.
ä Copies the elements from pt_source and pushes them onto the back of the queue.
ä If pt_source is invalid or numToPush is zero, the queue is not modified and zero is
returned.

Recycle (Method)
This method removes all elements from the queue without modifying the memory allocated
to the queue.

Return Value
IEC 61131 Type Description
BOOL TRUE if the queue successfully removes all elements. FALSE if an error
occurs.

Processing
All elements are removed from the queue.
ä After recycling, the Size of the queue is zero.
ä The MaxSize is unchanged after a call to Recycle().
ä This method neither allocates nor frees any memory.

Classes
class_Deque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque can handle objects of arbitrary size, so long as the number of bytes
required for each element is the same.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.7
Classes

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Initialization Inputs
Name IEC 61131 Type Description
elementSize UDINT The number of bytes required for each element that this
deque can hold. If zero, defaults to one.
numElements UDINT The number of elements to allocate initially. If zero, g_-
p_DefaultQueueSize is used.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Date Code 20190830 Instruction Manual Programming Reference


20.8 Queue
Classes

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.9
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Date Code 20190830 Instruction Manual Programming Reference


20.10 Queue
Classes

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_ByteDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type BYTE.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.11
Classes

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Date Code 20190830 Instruction Manual Programming Reference


20.12 Queue
Classes

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackByte (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.13
Classes

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontByte (Method)
This method provides the element at the front of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Date Code 20190830 Instruction Manual Programming Reference


20.14 Queue
Classes

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

PopBackByte (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PopFrontByte (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.15
Classes

Outputs
Name IEC 61131 Type Description
element BYTE A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackByte (Method)
This method appends a copy of the provided element to the back of the deque.

Inputs
Name IEC 61131 Type Description
element BYTE The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.16 Queue
Classes

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

PushFrontByte (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element BYTE The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.17
Classes

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_DwordDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type DWORD.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Date Code 20190830 Instruction Manual Programming Reference


20.18 Queue
Classes

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.19
Classes

ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackDword (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontDword (Method)
This method provides the element at the front of the deque without modifying the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.20 Queue
Classes

Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.21
Classes

PopBackDword (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PopFrontDword (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element DWORD A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackDword (Method)
This method appends a copy of the provided element to the back of the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.22 Queue
Classes

Inputs
Name IEC 61131 Type Description
element DWORD The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.23
Classes

PushFrontDword (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element DWORD The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.

Date Code 20190830 Instruction Manual Programming Reference


20.24 Queue
Classes

ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_LwordDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type DWORD.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.25
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackLword (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.26 Queue
Classes

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontLword (Method)
This method provides the element at the front of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.27
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

PopBackLword (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

Date Code 20190830 Instruction Manual Programming Reference


20.28 Queue
Classes

PopFrontLword (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element LWORD A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackLword (Method)
This method appends a copy of the provided element to the back of the deque.

Inputs
Name IEC 61131 Type Description
element LWORD The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.29
Classes

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

PushFrontLword (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element LWORD The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Date Code 20190830 Instruction Manual Programming Reference


20.30 Queue
Classes

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_LrealDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type LREAL.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Programming Reference Instruction Manual Date Code 20190830


Queue 20.31
Classes

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.

Date Code 20190830 Instruction Manual Programming Reference


20.32 Queue
Classes

ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackLreal (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontLreal (Method)
This method provides the element at the front of the deque without modifying the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.33
Classes

Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

Date Code 20190830 Instruction Manual Programming Reference


20.34 Queue
Classes

PopBackLreal (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PopFrontLreal (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element LREAL A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackLreal (Method)
This method appends a copy of the provided element to the back of the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.35
Classes

Inputs
Name IEC 61131 Type Description
element LREAL The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

Date Code 20190830 Instruction Manual Programming Reference


20.36 Queue
Classes

PushFrontLreal (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element LREAL The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.37
Classes

ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_PointerDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type POINTER TO ANY.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Date Code 20190830 Instruction Manual Programming Reference


20.38 Queue
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackPointer (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.39
Classes

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontPointer (Method)
This method provides the element at the front of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.40 Queue
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

PopBackPointer (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.41
Classes

PopFrontPointer (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element POINTER TO BYTE A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackPointer (Method)
This method appends a copy of the provided element to the back of the deque.

Inputs
Name IEC 61131 Type Description
element POINTER TO BYTE The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.42 Queue
Classes

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

PushFrontPointer (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element POINTER TO BYTE The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.43
Classes

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_RealDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type REAL.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Date Code 20190830 Instruction Manual Programming Reference


20.44 Queue
Classes

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.45
Classes

ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackReal (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontReal (Method)
This method provides the element at the front of the deque without modifying the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.46 Queue
Classes

Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.47
Classes

PopBackReal (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PopFrontReal (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element REAL A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackReal (Method)
This method appends a copy of the provided element to the back of the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.48 Queue
Classes

Inputs
Name IEC 61131 Type Description
element REAL The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.49
Classes

PushFrontReal (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element REAL The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.

Date Code 20190830 Instruction Manual Programming Reference


20.50 Queue
Classes

ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

class_WordDeque
This class implements a double-ended queue that internally handles dynamic allocation of
memory. This deque operates only on elements of type WORD.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_Queue

Initialization Inputs
Name IEC 61131 Type Description
size UDINT The number of elements to allocate initially. If zero, use g_p_-
DefaultQueueSize.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Data UDINT R A pointer to the first element in the deque. This im-
plementation of deque ensures that all elements are
in contiguous memory. The pointer value returned
by this method is only valid until the next operation
is performed on the deque, since any modification
to the contents of this object can cause the storage
location to move.

Back (Method)
This method copies the specified number of elements from the back of the queue to the
provided pointer location. The queue is not modified.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.51
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToCopy UDINT The number of elements to copy from the back of the
queue.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied.

Processing
ä Copies as many as numToCopy elements from the back of the queue to pt_destina-
tion.
ä If the Size of the queue is less than numToCopy, only Size elements are copied to
pt_destination.
ä If pt_destination is invalid or the elements cannot be copied, zero is returned.

BackWord (Method)
This method provides the element at the back of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

EraseBack (Method)
This method deletes the specified number of elements from the back of the deque.

Date Code 20190830 Instruction Manual Programming Reference


20.52 Queue
Classes

Inputs
Name IEC 61131 Type Description
numToErase UDINT The number of elements to erase from the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully removed from the back of the deque.

Processing
ä Removes as many as numToErase elements from the back of the deque.
ä If the Size of the deque is less than numToErase, then only Size elements are removed
from the deque.

FrontWord (Method)
This method provides the element at the front of the deque without modifying the deque.

Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the front of the deque. If the return
value is false, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied. FALSE if the size is zero or
an error occurs.

PopBack (Method)
This method copies the specified number of elements from the back of the deque to the
provided pointer location and deletes them from the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.53
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE A pointer to the destination to which the elements are
copied.
numToPop UDINT The number of elements to pop off the back of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully copied and removed from the deque.
Zero if the deque was not modified.

Processing
ä Copies as many as numToPop elements from the back of the deque to pt_destination.
ä If the Size of the deque is less than numToPop, only Size elements are copied to
pt_destination.
ä Removes the copied elements from the deque.
ä If pt_destination is invalid or the elements cannot be copied, the deque is not modi-
fied and zero is returned.

PopBackWord (Method)
This method provides a copy of the element at the back of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the back of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

Date Code 20190830 Instruction Manual Programming Reference


20.54 Queue
Classes

PopFrontWord (Method)
This method provides a copy of the element at the front of the deque and removes that
element from the deque.

Outputs
Name IEC 61131 Type Description
element WORD A copy of the element at the front of the deque. If the return
value is FALSE, this value is undefined.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully copied and removed from the deque.
FALSE if the size is zero or an error occurs.

PushBackWord (Method)
This method appends a copy of the provided element to the back of the deque.

Inputs
Name IEC 61131 Type Description
element WORD The element to append to the back of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

PushFront (Method)
This method copies elements from the specified pointer location and pushes them onto the
front of the deque.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.55
Classes

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE A pointer to the source from which the elements are
copied.
numToPush UDINT The number of elements to push onto the front of the
deque.

Return Value
IEC 61131 Type Description
UDINT The number of elements successfully pushed onto the deque. Zero if an
error occurred and the deque was not modified.

Processing
ä If the deque is not large enough to contain the new elements, additional memory is
allocated to enlarge the deque.
ä Copies the elements from the specified pointer and pushes them onto the front of the
deque.
ä If pt_source is invalid or numToPush is zero, the deque is not modified and zero is
returned.

PushFrontWord (Method)
This method appends a copy of the provided element to the front of the deque.

Inputs
Name IEC 61131 Type Description
element WORD The element to append to the front of the deque.

Return Value
IEC 61131 Type Description
BOOL TRUE if the element is successfully added to the deque. FALSE if an error
occurs.

Processing
If pushing element to the deque requires more memory than is currently available in the
deque, the library allocates additional memory.

Date Code 20190830 Instruction Manual Programming Reference


20.56 Queue
Benchmarks

Resize (Method)
This method resizes the deque so that it can hold the specified number of elements. If
reducing the size of the deque to less than Size, elements are deleted from the back of the
deque.

Inputs
Name IEC 61131 Type Description
newMaxSize UDINT The new maximum number of elements the deque can
hold before a memory allocation is required.

Return Value
IEC 61131 Type Description
BOOL TRUE if the deque was resized. FALSE if an error occurred and the deque
was not modified.

Processing
ä If newMaxSize is zero, all elements in the deque are deleted. This is the same func-
tionality as the Clear() method.
ä If newMaxSize is equal to MaxSize, the deque is not modified.
ä If newMaxSize is smaller than Size, elements are removed from the back of the deque
in order to resize the deque.
ä If newMaxSize is greater than or equal to Size, the deque is resized and retains all
existing elements.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3505
â R134 firmware

Programming Reference Instruction Manual Date Code 20190830


Queue 20.57
Benchmarks

Benchmark Test Descriptions


Benchmarks are only performed on the Typed queues as the performance of the generic
queues will depend entirely on the size of an individual element of the created queue. Tests
postfixed with _TYPE_ will call the typed version of the method dealing with only a single
element.

Back_TYPE_
The posted time is the average execution time of 100 calls when the Back_TYPE_() method
copies one element from a deque containing 100 elements.

Back - 100 Elements


The posted time is the average execution time of 100 calls when the Back() method copies
100 elements from a deque containing 100 elements.

Clear
The posted time is the average execution time of 100 calls when clearing a deque containing
100 elements.

EraseBack - 1 Element
The posted time is the average execution time of 100 calls when the EraseBack method
removes one element from a deque containing 100 elements.

EraseBack - 100 Elements


The posted time is the average execution time of 100 calls when the EraseBack() method
removes 100 elements from a deque containing 100 elements.

EraseFront - 1 Element
The posted time is the average execution time of 100 calls when the EraseFront() method
removes one element from a deque containing 100 elements.

EraseFront - 100 Elements


The posted time is the average execution time of 100 calls when the EraseFront() method
removes 100 elements from a deque containing 100 elements.

Date Code 20190830 Instruction Manual Programming Reference


20.58 Queue
Benchmarks

Front_TYPE_
The posted time is the average execution time of 100 calls when the Front_TYPE_()
method copies one element from a deque containing 100 elements.

Front - 100 Elements


The posted time is the average execution time of 100 calls when the Front() method copies
100 elements from a deque containing 100 elements.

PopBack_TYPE_
The posted time is the average execution time of 100 calls when popping one element from
a deque containing 100 elements.

PopBack - 100 Elements


The posted time is the average execution time of 100 calls when popping 100 elements
from the deque in a single method call. The deque is constructed such that it has at least
one resize caused by pushing prior to starting the pop measurement.

PopFront_TYPE_
The posted time is the average execution time of 100 calls when popping one element from
a deque containing 100 elements.

PopFront - 100 Elements


The posted time is the average execution time of 100 calls when popping 100 elements
from the deque in a single method call. The deque is constructed such that it has at least
one resize caused by pushing prior to starting the pop measurement.

PushBack_TYPE_
The posted time is the average execution time of 100 calls when pushing an element onto
a deque without causing a resize.

PushBack - 100 Elements


The posted time is the average execution time of 100 calls when pushing 100 elements onto
a deque and causing a resize.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.59
Benchmarks

PushFront_TYPE_
The posted time is the average execution time of 100 calls when pushing an element onto
a deque without causing a resize.

PushFront - 100 Elements


The posted time is the average execution time of 100 calls when pushing 100 elements onto
a deque and causing a resize.

Recycle
The posted time is the average execution time of 100 calls when recycling a deque contain-
ing 100 elements.

Resize - Enlarging
The posted time is the average execution time of 100 calls when resizing a full deque from
32 elements to 64 elements.

Resize - Shrinking
The posted time is the average execution time of 100 calls when resizing a full deque from
64 elements to 32 elements.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3555 SEL-3530 SEL-3505
Back - Byte 1 7 53
Back - Dword 1 5 16
Back - LReal 1 6 17
Back - Lword 1 4 23
Back - Pointer 1 5 26
Back - Real 1 6 28
Back - Word 1 6 19
Back 100 - Byte 1 3 16
Back 100 - Dword 1 3 8
Back 100 - LReal 1 6 10
Back 100 - Lword 1 4 14
Back 100 - Pointer 1 3 13
Back 100 - Real 1 5 14
Back 100 - Word 1 3 9
Clear - Byte 3 24 57
Clear - Dword 2 15 69

Date Code 20190830 Instruction Manual Programming Reference


20.60 Queue
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3555 SEL-3530 SEL-3505
Clear - LReal 2 33 55
Clear - Lword 2 15 61
Clear - Pointer 2 16 61
Clear - Real 2 24 60
Clear - Word 2 17 58
EraseBack 1 - Byte 1 2 3
EraseBack 1 - Dword 1 2 3
EraseBack 1 - LReal 1 2 3
EraseBack 1 - Lword 1 2 2
EraseBack 1 - Pointer 1 2 3
EraseBack 1 - Real 1 2 2
EraseBack 1 - Word 1 1 2
EraseBack 100 - Byte 1 1 1
EraseBack 100 - Dword 1 1 1
EraseBack 100 - LReal 1 1 2
EraseBack 100 - Lword 1 1 2
EraseBack 100 - Pointer 1 1 1
EraseBack 100 - Real 1 1 1
EraseBack 100 - Word 1 1 1
EraseFront 1 - Byte 1 3 12
EraseFront 1 - Dword 1 2 10
EraseFront 1 - LReal 1 5 7
EraseFront 1 - Lword 1 4 10
EraseFront 1 - Pointer 1 3 10
EraseFront 1 - Real 1 4 13
EraseFront 1 - Word 1 3 8
EraseFront 100 - Byte 1 2 2
EraseFront 100 - Dword 1 1 6
EraseFront 100 - LReal 1 2 2
EraseFront 100 - Lword 1 2 3
EraseFront 100 - Pointer 1 2 4
EraseFront 100 - Real 1 2 4
EraseFront 100 - Word 1 1 5
Front - Byte 1 10 11
Front - Dword 1 4 12
Front - LReal 1 6 16
Front - Lword 1 4 14
Front - Pointer 1 4 13
Front - Real 1 6 13
Front - Word 1 4 12
Front 100 - Byte 1 4 4
Front 100 - Dword 1 3 6
Front 100 - LReal 1 5 11
Front 100 - Lword 1 4 9
Front 100 - Pointer 1 3 7

Programming Reference Instruction Manual Date Code 20190830


Queue 20.61
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3555 SEL-3530 SEL-3505
Front 100 - Real 1 3 6
Front 100 - Word 1 3 5
PopBack - Byte 1 4 6
PopBack - Dword 1 3 15
PopBack - LReal 1 7 7
PopBack - Lword 1 3 7
PopBack - Pointer 1 4 9
PopBack - Real 1 5 10
PopBack - Word 1 4 19
PopBack 100 - Byte 1 3 4
PopBack 100 - Dword 1 4 16
PopBack 100 - LReal 1 9 7
PopBack 100 - Lword 1 4 8
PopBack 100 - Pointer 1 4 7
PopBack 100 - Real 1 5 7
PopBack 100 - Word 1 3 13
PopFront - Byte 1 5 8
PopFront - Dword 1 5 10
PopFront - LReal 1 7 16
PopFront - Lword 1 6 13
PopFront - Pointer 1 5 11
PopFront - Real 1 6 11
PopFront - Word 1 5 8
PopFront 100 - Byte 1 3 5
PopFront 100 - Dword 1 4 6
PopFront 100 - LReal 1 5 10
PopFront 100 - Lword 1 4 8
PopFront 100 - Pointer 1 4 7
PopFront 100 - Real 1 4 7
PopFront 100 - Word 1 3 5
PushBack - Byte 1 4 6
PushBack - Dword 1 3 7
PushBack - LReal 1 4 7
PushBack - Lword 1 3 6
PushBack - Pointer 1 3 6
PushBack - Real 1 3 6
PushBack - Word 1 3 5
PushBack 100 - Byte 4 86 84
PushBack 100 - Dword 4 29 89
PushBack 100 - LReal 4 40 106
PushBack 100 - Lword 4 29 98
PushBack 100 - Pointer 4 29 89
PushBack 100 - Real 4 63 88
PushBack 100 - Word 4 29 85
PushFront - Byte 1 5 15
PushFront - Dword 1 5 19

Date Code 20190830 Instruction Manual Programming Reference


20.62 Queue
Examples

Platform (time in µs)


Operation Tested
SEL-3555 SEL-3530 SEL-3505
PushFront - LReal 1 8 11
PushFront - Lword 1 6 16
PushFront - Pointer 1 5 20
PushFront - Real 1 8 19
PushFront - Word 1 5 15
PushFront 100 - Byte 6 49 137
PushFront 100 - Dword 4 34 117
PushFront 100 - LReal 4 40 165
PushFront 100 - Lword 4 32 152
PushFront 100 - Pointer 4 40 123
PushFront 100 - Real 4 32 124
PushFront 100 - Word 4 61 104
Recycle - Byte 1 1 2
Recycle - Dword 1 1 2
Recycle - LReal 1 1 2
Recycle - Lword 1 1 2
Recycle - Pointer 1 1 2
Recycle - Real 1 1 2
Recycle - Word 1 1 1
Resize Down - Byte 3 30 103
Resize Down - Dword 3 22 124
Resize Down - LReal 3 44 80
Resize Down - Lword 3 23 78
Resize Down - Pointer 3 22 89
Resize Down - Real 3 31 92
Resize Down - Word 3 22 153
Resize Up - Byte 3 24 117
Resize Up - Dword 3 22 102
Resize Up - LReal 3 34 84
Resize Up - Lword 3 23 125
Resize Up - Pointer 3 22 133
Resize Up - Real 3 28 133
Resize Up - Word 3 22 79

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.

Programming Reference Instruction Manual Date Code 20190830


Queue 20.63
Examples

Simple Deque Operation


This example demonstrates basic operation of a deque.

Objective
This example comprises the following steps:
Step 1. Add a series of UINT values to a UINT deque; the first as a single value, and
the second from an array of values.
Step 2. Remove one value from the front.
Step 3. Remove a group of five values from the front.
Step 4. Remove one value from the back.
Step 5. Push four values onto the front.
Step 6. Remove six values from the back.
Step 7. Remove the remaining value individually from the front until the deque is
empty again.

Sequence of Operations
The operations that make up the solution are outlined here in detail. After each operation,
the expected state of the deque is shown. The notation used in this example assumes the
front of the deque is on the left and the back is on the right.
1. The deque begins empty
F ront [ ] Back

2. The first value pushed to the back of the deque is 0.


F ront [0] Back

3. An array of values, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], is pushed onto the back of the deque.
F ront [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Back

4. Five values are popped off of the front of the deque and into an array.
F ront [5, 6, 7, 8, 9, 10] Back
The resulting array contains [0, 1, 2, 3, 4].
5. The value at the back, 10, is then popped off.
F ront [5, 6, 7, 8, 9] Back

6. An array with four values, [11, 12, 13, 14], are then pushed onto the front.
F ront [11, 12, 13, 14, 5, 6, 7, 8, 9] Back

7. Six values are then popped off the back into an array.
F ront [11, 12, 13] Back
The resulting array that was popped off contains [14, 5, 6, 7, 8, 9].

Date Code 20190830 Instruction Manual Programming Reference


20.64 Queue
Examples

8. The values 11, 12, and 13 are then obtained by popping the remaining values off
the front of the deque one at a time, leaving it empty again.

F ront [ ] Back

Solution
The implementation of this example is shown in Code Snippet 20.1.

Code Snippet 20.1 prg_BasicDeque


PROGRAM prg_BasicDeque
VAR CONSTANT
c_NumPushStep3 : UDINT := 10;
c_NumPopStep4 : UDINT := 5;
c_NumPushStep6 : UDINT := 4;
c_NumPopStep7 : UDINT := 6;
END_VAR
VAR
Run : BOOL := TRUE; // Used to force the steps to only run once.
Ok : BOOL := FALSE; // Is true if the operation completed
MyDeque : class_WordDeque(numElements := 0); // Uses default internal
allocation

(* Arrays to push*)
Step3ArrayToPush : ARRAY[1..c_NumPushStep3] OF UINT :=
[1,2,3,4,5,6,7,8,9,10];
Step6ArrayToPush : ARRAY[1..c_NumPushStep6] OF UINT := [11,12,13,14];

(* Results *)
Step4ArrayPopped : ARRAY[1..c_NumPopStep4] OF UINT; // Expect :
[0,1,2,3,4]
Step5Popped : UINT; // Expect : 10
Step7ArrayPopped : ARRAY[1..c_NumPopStep7] OF UINT; // Expect :
[14,5,6,7,8,9]
Step8val1, Step8val2, Step8val3 : UINT; // Expect: 11, 12, 13
END_VAR

Programming Reference Instruction Manual Date Code 20190830


Queue 20.65
Examples

Code Snippet 20.1 prg_BasicDeque (Continued)


IF Run THEN
(*Step 1: The queue begins empty.*)
Ok := TRUE;
(*Step 2: Push 0 into back of deque. Ok if push returns TRUE.*)
Ok := Ok AND MyDeque.PushBackWord(0);
(*Step 3: Push array to back of deque. Ok if the number popped is as
requested.*)
Ok := Ok AND (c_NumPushStep3 =
MyDeque.PushBack(ADR(Step3ArrayToPush),c_NumPushStep3));
(*Step 4: Pop 5 values from front. Ok if number popped is as
requested.*)
Ok := Ok AND (c_NumPopStep4 =
MyDeque.PopFront(ADR(Step4ArrayPopped),c_NumPopStep4));
(*Step 5: Pop one number of the back of the queue.*)
Ok := Ok AND MyDeque.PopBackWord(element => Step5Popped);
(*Step 6: Add 4 new values to the front. Ok if push adds number
requested.*)
Ok := Ok AND (c_NumPushStep6 =
MyDeque.PushFront(ADR(Step6ArrayToPush),c_NumPushStep6));
(*Step 7: Pop 6 values from the back to an array. Ok if number popped
is as requested.*)
Ok := Ok AND (c_NumPopStep7 =
MyDeque.PopBack(ADR(Step7ArrayPopped),c_NumPopStep7));
(*Step 8 : Pop the last 3 values from the front. Each operation OK if
it returns TRUE.*)
Ok := Ok AND MyDeque.PopFrontWord(element => Step8val1);
Ok := Ok AND MyDeque.PopFrontWord(element => Step8val2);
Ok := Ok AND MyDeque.PopFrontWord(element => Step8val3);
Run := FALSE; // Only run 1 time.
END_IF

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 21

Quicksort
Introduction
This library implements the Quicksort algorithm for sorting arrays of objects. Due to the
strongly typed nature of IEC 61131, the sorting is provided with multiple functions, one
for each of the following datatypes:
ä USINT
ä SINT
ä UINT
ä INT
ä UDINT
ä DINT
ä ULINT
ä LINT
ä REAL
ä LREAL
This library also allows the sorting of arbitrary objects implementing the I_Comparable in-
terface. See the ACSELERATOR RTAC Library Extensions Instruction Manual (LibraryEx-
tensionsIM) for explanation of the concepts used by the object-oriented extensions to the
IEC 61131-3 standard. All functions sort in ascending order.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Version 3.5.0.0 can be used on RTAC firmware version R132 and higher.

Functions
The following functions are provided by this library.

Date Code 20190830 Instruction Manual Programming Reference


21.2 Quicksort
Functions

fun_SortUSINT (Function)
This function takes a pointer to an array of USINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO USINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortSINT (Function)
This function takes a pointer to an array of SINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO SINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Programming Reference Instruction Manual Date Code 20190830


Quicksort 21.3
Functions

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortUINT (Function)
This function takes a pointer to an array of UINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO UINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

Date Code 20190830 Instruction Manual Programming Reference


21.4 Quicksort
Functions

fun_SortINT (Function)
This function takes a pointer to an array of INTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO INT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortUDINT (Function)
This function takes a pointer to an array of UDINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO UDINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Programming Reference Instruction Manual Date Code 20190830


Quicksort 21.5
Functions

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortDINT (Function)
This function takes a pointer to an array of DINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO DINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

Date Code 20190830 Instruction Manual Programming Reference


21.6 Quicksort
Functions

fun_SortULINT (Function)
This function takes a pointer to an array of ULINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO ULINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortLINT (Function)
This function takes a pointer to an array of LINTs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO LINT Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Programming Reference Instruction Manual Date Code 20190830


Quicksort 21.7
Functions

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortREAL (Function)
This function takes a pointer to an array of REALs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO REAL Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

Date Code 20190830 Instruction Manual Programming Reference


21.8 Quicksort
Functions

fun_SortLREAL (Function)
This function takes a pointer to an array of LREALs and sorts the array in-place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO LREAL Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function uses the Quicksort algorithm to perform an in-place sorting of the array.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, sorting of the
array occurs through use of the Quicksort algorithm, and the function returns the
value TRUE.

fun_SortI_Comparable (Function)
This function takes a pointer to an array of I_Comparable objects and sorts the array in-
place by value.

Inputs
Name IEC 61131 Type Description
arrayPointer POINTER TO I_Comparable Pointer to the array to sort.
arraySize UDINT The number of elements in the array.

Programming Reference Instruction Manual Date Code 20190830


Quicksort 21.9
Interfaces

Return Value
IEC 61131 Type Description
BOOL TRUE if the sort completed successfully. FALSE if an error occured.

Processing
This function sorts the array in-place using the Quicksort algorithm.
ä The function returns false and does not attempt to sort the array if the arrayPointer
is invalid.
ä The function returns false and does not attempt to sort the array if any members of
the array pointed to by arrayPointer are invalid.
ä If arrayPointer is valid and arraySize is less than two, the function returns true with-
out sorting the array. Specifically, arrays of size zero or one are considered already
sorted.
ä If arrayPointer is valid and arraySize is greater than or equal to two, the array is
sorted using an in-place Quicksort algorithm and true is returned.

Interfaces
This library provides the following interfaces.

I_Comparable (Interface)
This interface is implemented by any class needing to be sortable. Any libraries needing
to sort arbitrary objects can create a class that implements this interface.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


pt_Self POINTER TO BYTE R Provides the THIS pointer for the class.

CompareTo (Method)
This method compares this object to another object of the same type. If the compare object
is not of the same class, exceptions will occur.

Date Code 20190830 Instruction Manual Programming Reference


21.10 Quicksort
Benchmarks

Inputs
Name IEC 61131 Type Description
compare I_Comparable The object to compare.

Return Value
IEC 61131 Type Description
INT Returns a signed integer representing the sorting order. A negative value
means this object goes before the compare object. Zero means this object
is equivalent to the compare object. A positive value means this object
goes after the compare object.

Processing
Compares this object to another object of the same type.
ä Returns a negative value if this object goes before the compare object.
ä Returns zero if this object is equivalent to the compare object.
ä Returns a positive value if this object goes after the compare object.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R134 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 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

Programming Reference Instruction Manual Date Code 20190830


Quicksort 21.11
Benchmarks

Benchmark Test Descriptions


All benchmark tests are based on an average of 100 calls in the described environment con-
taining 1000 elements for each DATATYPE having a Quicksort method where DATATYPE
is selected from the following types:
ä SINT
ä USINT
ä INT
ä UINT
ä DINT
ä UDINT
ä LINT
ä ULINT
ä REAL
ä LREAL
Sorting performance any I_Comparable object will depend on the implementation, so this
document does not attempt to characterize that behavior.

DATATYPE InOrderSort
The average time for completion of the sort method when all data are presorted.

DATATYPE ReverseOrderSort
The average time for completion of the sort method when all data are in reverse order.

DATATYPE RandomOrderSort
The average time for completion of the sort method when data are in random order.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3530 SEL-3354 SEL-3555
SINT InOrderSort 1483 258 86
SINT ReverseOrderSort 1519 269 95
SINT RandomOrderSort 1756 343 141
USINT InOrderSort 1472 257 87
USINT ReverseOrderSort 1499 268 96
USINT RandomOrderSort 1728 345 142
INT InOrderSort 1317 233 78
INT ReverseOrderSort 1471 275 97

Date Code 20190830 Instruction Manual Programming Reference


21.12 Quicksort
Examples

Platform (time in µs)


Operation Tested
SEL-3530 SEL-3354 SEL-3555
INT RandomOrderSort 1789 376 160
UINT InOrderSort 1327 233 76
UINT ReverseOrderSort 1476 271 94
UINT RandomOrderSort 1799 367 156
DINT InOrderSort 1317 229 76
DINT ReverseOrderSort 1469 272 94
DINT RandomOrderSort 1819 368 155
UDINT InOrderSort 1313 232 76
UDINT ReverseOrderSort 1461 271 92
UDINT RandomOrderSort 1800 368 157
LINT InOrderSort 1549 282 93
LINT ReverseOrderSort 1720 323 112
LINT RandomOrderSort 2159 444 181
ULINT InOrderSort 1552 275 91
ULINT ReverseOrderSort 1730 316 111
ULINT RandomOrderSort 2133 458 200
REAL InOrderSort 1460 242 78
REAL ReverseOrderSort 1634 283 97
REAL RandomOrderSort 2042 392 170
LREAL InOrderSort 1674 280 78
LREAL ReverseOrderSort 1863 314 97
LREAL RandomOrderSort 2323 444 168

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.

Sorting an Array of Integers


Objective
Code Snippet 21.1 demonstrates sorting a simple array of INTs.

Programming Reference Instruction Manual Date Code 20190830


Quicksort 21.13
Examples

Solution

Code Snippet 21.1 prg_SortInt


PROGRAM prg_SortInt
VAR
intArray : ARRAY [1..5] OF INT;
END_VAR

// Populate the array with unsorted values.


intArray[1] := 5;
intArray[2] := 2;
intArray[3] := 0;
intArray[4] := -1;
intArray[5] := -4;
// Sort the array.
fun_SortINT(ADR(intArray), 5);

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 22

RecordingTriggers
Introduction
This library provides various function blocks to detect specific conditions in analog and
digital signals to initiate the capture of data in oscillography recording devices, such as
RTAC Recording Groups or SEL-2245 analog input modules.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.3 and older can be used on RTAC firmware version R132 and higher.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_DigitalTriggerModes
This enumeration defines the operating mode of the fb_DigitalTrigger function block.

Enumeration Description
LEVEL Level mode
RISING_EDGE Rising-Edge mode
FALLING_EDGE Falling-Edge mode
RISING_FALLING_EDGE Rising/Falling-Edge mode

Date Code 20190830 Instruction Manual Programming Reference


22.2 RecordingTriggers
Function Blocks

Function Blocks
fb_HighThreshold (Function Block)
This function block monitors the value of an analog signal and compares it against a prede-
fined threshold value to detect if the signal is above the threshold. This function block has
two operating modes. The operating mode is selected by setting the initialization argument
risingEdgeMode to TRUE or FALSE when the function block is instantiated.
1. Level mode: The output of the function block asserts when the value of the analog
signal first becomes greater than or equal to the threshold value. The output of the
function block remains asserted until the value of the signal becomes less than or
equal to the threshold value minus the hysteresis value.
2. Rising-Edge mode: The output of the function block asserts for one RTAC process-
ing interval when the value of the analog signal first becomes greater than or equal
to the threshold value.

Initialization Inputs
Name IEC 61131 Type Description
risingEdgeMode BOOL Defines the operating mode of the function block.
When TRUE, the function block is in Rising-Edge
mode. When FALSE, the function block is in Level
mode.

Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal REAL Analog signal to observe.
Threshold REAL Minimum value of the analog signal required to assert the
trigger output of the function block.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


Hysteresis REAL R/W The value of the hysteresis. Write to this prop-
erty to set the value of the hysteresis when in
Level mode.

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.3
Function Blocks

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL High-threshold condition is detected.

Processing
ä Compare InSignal to Threshold.
ä If the function block was initialized in Rising-Edge mode(risingEdgeMode = TRUE):
â If InSignal becomes greater than or equal to Threshold, then assert TriggerOut
for one RTAC processing interval.
ä If the function block was initialized in Level mode risingEdgeMode = FALSE):
â If InSignal becomes greater than or equal to Threshold, then assert TriggerOut.
â If TriggerOut is asserted AND InSignal becomes less than or equal to (Thresh-
old-Hysteresis), then deassert TriggerOut.

fb_LowThreshold (Function Block)


This function block monitors the value of an analog signal and compares it against a prede-
fined threshold value to detect if the signal is below the threshold. This function block has
two operating modes. The operating mode is selected by setting the initialization argument
risingEdgeMode to TRUE or FALSE when the function block is instantiated.
1. Level mode: The output of the function block asserts when the value of the analog
signal first becomes less than or equal to the threshold value. The output of the
function block remains asserted until the value of the signal becomes greater than
or equal to the threshold value plus the hysteresis value.
2. Rising-Edge mode: The output of the function block asserts for one RTAC process-
ing interval when the value of the analog signal first becomes less than or equal to
the threshold value.

Initialization Inputs
Name IEC 61131 Type Description
risingEdgeMode BOOL Defines the operating mode of the function block.
When TRUE, the function block is in Rising-Edge
mode. When FALSE, the function block is in Level
mode.

Date Code 20190830 Instruction Manual Programming Reference


22.4 RecordingTriggers
Function Blocks

Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal REAL Analog signal to observe.
Threshold REAL Maximum value of the analog signal required to assert the
trigger output of the function block.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


Hysteresis REAL R/W The value of the hysteresis. Write to this prop-
erty to set the value of the hysteresis when in
Level mode.

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL Low threshold condition is detected.

Processing
ä Compare InSignal to Threshold.
ä If the function block was initialized in Rising-Edge mode(risingEdgeMode = TRUE):
â If InSignal becomes less than or equal to Threshold, then assert TriggerOut for
one RTAC processing interval.
ä If the function block was initialized in Level mode risingEdgeMode = FALSE):
â If InSignal becomes less than or equal to Threshold, then assert TriggerOut.
â If TriggerOut is asserted AND InSignal becomes greater than or equal to (Thresh-
old+Hysteresis), then deassert TriggerOut.

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.5
Function Blocks

fb_RateOfChange (Function Block)


This function block monitors the value of an analog signal to detect if the signal rate-of-
change exceeds a user-defined rate over a user-defined time period. The analog signal is
sampled at fixed intervals determined by SamplingPeriod and its magnitude is compared
to the previous sample. If the absolute value of the difference differs by RateOfChange
or more, the output of the function block asserts. This function block has two operating
modes. The operating mode is selected by setting the initialization argument risingEdge-
Mode to True or False when the function block is instantiated.
ä Level mode: The output of the function block asserts when the rate-of-change con-
dition is detected, and remains asserted until the rate-of-change condition clears.
ä Rising-Edge mode: The output of the function block asserts for one RTAC process-
ing interval when a rate-of-change condition is first detected. The output will not
assert again until the rate-of-change condition clears and a new rate-of-change is
detected.
Because the sampling is done at fixed intervals, if an analog signal transition exceeds the
RateOfChange value and returns below RateOfChange in between two consecutive sam-
ples, the trigger output will not assert for this condition.

Initialization Inputs
Name IEC 61131 Type Description
risingEdgeMode BOOL Defines the operating mode of the function block.
When TRUE, the function block is in Rising-Edge
mode. When FALSE, the function block is in Level
mode.

Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal REAL Analog signal to observe.
RateOfChange REAL Minimum change of the analog signal over a Sampling-
Period time required to set the trigger output of the
function block.
SamplingPeriod TIME Time period at which the analog signal is sampled to
detect a rate-of-change condition. This input should be
set to a multiple of the RTAC processing scan time on
which this object is instantiated.

Date Code 20190830 Instruction Manual Programming Reference


22.6 RecordingTriggers
Function Blocks

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL A rate-of-change condition is detected.
Sample_DN BOOL This output asserts for one RTAC processing cycle when
the analog signal is sampled and the rate-of-change calcu-
lation logic is executed.

Processing
The following logic is performed every SamplingPeriod time interval k):
ä Calculate the analog input change:

Deltak = |InSignalk − InSignalk−1 |

ä Assert Sample_DN for one RTAC processing interval.


ä If the function block was initialized in Rising-Edge mode RisingEdge = TRUE):
â If Deltak ≥ RateOf Change, then assert TriggerOut for one RTAC process-
ing interval.
ä If the function block was initialized in Level mode RisingEdge = FALSE):
â If Deltak ≥ RateOf Change, then assert TriggerOut.
â If TriggerOut is asserted AND Deltak < RateOfChange, then deassert Trig-
gerOut.

fb_DigitalTrigger (Function Block)


This function block monitors the status of a digital signal. The operation of the output of
the function block depends on the operating mode. This function block has four operating
modes. The operating mode is selected by setting the initialization argument OpMode to
the correspondent enumerated value (see Enumerations on page 22.1) when the function
block is instantiated. The supported operating modes are listed below.
ä Rising-Edge Mode: The output of the function block asserts for one RTAC process-
ing interval when the monitored digital signal changes from FALSE to TRUE.
ä Falling-Edge Mode: The output of the function block asserts for one RTAC process-
ing interval when the monitored digital signal changes from TRUE to FALSE.
ä Rising-/Falling-Edge Mode: The output of the function block asserts for one RTAC
processing interval when a change of state is detected in the monitored digital signal.
ä Level Mode: The output of the function block remains asserted as long as the input
signal is asserted.

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.7
Function Blocks

Initialization Inputs
Name IEC 61131 Type Description
OpMode enum_DigitalTriggerModes Defines the operating mode of the function block.

Inputs
Name IEC 61131 Type Description
EN BOOL Default=TRUE.
Enables the function block.
InSignal BOOL Digital signal to observe.

Outputs
Name IEC 61131 Type Description
ENO BOOL The function block is enabled.
TriggerOut BOOL Trigger condition is detected.

Processing
ä If the function block was initialized in Rising-Edge mode (OpMode = RISING_-
EDGE):
â If InSignal changes from FALSE to TRUE, then assert TriggerOut for one
RTAC processing interval.
ä If the function block was initialized in Falling-Edge mode OpMode = FALLING_-
EDGE):
â If InSignal changes from TRUE to FALSE, then assert TriggerOut for one
RTAC processing interval.
ä If the function block was initialized in Rising-/Falling-Edge mode OpMode = RIS-
ING_FALLING_EDGE):
â If a change of state is detected on InSignal, then assert TriggerOut for one
RTAC processing interval.
ä If the function block was initialized in Level mode (OpMode = LEVEL):
â If InSignal asserts, then TriggerOut is asserted.
â If InSignal deasserts, then TriggerOut is deasserted.

Date Code 20190830 Instruction Manual Programming Reference


22.8 RecordingTriggers
Benchmarks

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R139-V0 firmware
ä SEL-3530
â R139-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R139-V0 firmware

Benchmark Test Descriptions


The posted time is the average execution time of 1000 consecutive calls to the following
function blocks.
This testing is performed on the following function blocks:
ä fb_HighThreshold
ä fb_LowThreshold
ä fb_RateOfChange
ä fb_DigitalTriggers

Execution Time of High-Threshold Function Block


fb_HighThreshold. The time necessary to determine if a high-threshold condition oc-
curred.

Execution Time of Low-Threshold Function Block


fb_LowThreshold. The time necessary determine if a low-threshold condition occurred.

Execution Time of Rate of Change Function Block


fb_RateOfChange. The time necessary determine if a rate-of-change condition occurred.

Execution Time of Digital Triggers Function Block


The time necessary to determine if a digital trigger condition occurred.

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.9
Examples

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
fb_HighThreshold 1 1 1
fb_LowThreshold 2 1 1
fb_RateOfChange 2 1 1
fb_DigitalTriggers 1 1 1

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

fb_HighThreshold: Rising-Edge Mode


Objective
A user is using an Axion DC analog input module to read an analog signal. The user wants
to assert RTAC Output OUT201 when the value of the analog signal exceeds 75.

Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project.

Solution
To assert Output OUT201 when the analog signal is greater than or equal to 75, the user
can create a program as shown in Code Snippet 22.1.

Date Code 20190830 Instruction Manual Programming Reference


22.10 RecordingTriggers
Examples

Code Snippet 22.1 Rising-Edge Mode


PROGRAM Example_HighThreshold
VAR
HighTrigger_pulse: fb_HighThreshold(risingEdgeMode := TRUE)
:= (EN:= TRUE, Threshold := 75);
END_VAR

HighTrigger_pulse(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);

//Assert OUT201 if the function block output has triggered:


IF HighTrigger_pulse.TriggerOut THEN
SystemTags.OUT201.operSet.ctlVal := TRUE;
SystemTags.OUT201.operClear.ctlVal := FALSE;
END_IF

fb_HighThreshold: Level Mode


Objective
A user is using an Axion DC analog input module to read an analog signal. The user wants
to assert the Alarm variable when the value of the analog signal exceeds 100. The Alarm
variable deasserts when the analog signal drops to 95 or below.

Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project, and a global variable named Alarm exists in the project.

Solution
To assert the Alarm variable when the analog signal is greater than or equal to 100, and
deassert the variable when the analog signal drops to 95 or below, the user can create a
program as shown in Code Snippet 22.2.

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.11
Examples

Code Snippet 22.2 Level Mode


PROGRAM Example_HighThreshold
VAR
HighTrigger_level: fb_HighThreshold(risingEdgeMode := FALSE)
:= (EN:= TRUE, Threshold := 100, Hysteresis:=5);
END_VAR

HighTrigger_level(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);

//Assert Level if the function block output has triggered:


IF HighTrigger_level.TriggerOut THEN
Alarm := TRUE;
ELSE
Alarm := FALSE;
END_IF

fb_LowThreshold: Rising-Edge Mode


Objective
A user is using an Axion DC analog input module to read an analog signal. The user wants
to assert RTAC Output OUT201 when the value of the analog signal drops below 50.

Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project.

Solution
To assert Output OUT201 when the analog signal is less than or equal to 50, the user can
create a program as shown in Code Snippet 22.3.

Date Code 20190830 Instruction Manual Programming Reference


22.12 RecordingTriggers
Examples

Code Snippet 22.3 Rising-Edge Mode


PROGRAM Example_LowThreshold
VAR
LowTrigger_pulse: fb_LowThreshold(risingEdgeMode := TRUE)
:= (EN:= TRUE, Threshold := 50);
END_VAR

LowTrigger_pulse(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);

//Assert OUT201 if the function block output has triggered:


IF LowTrigger_pulse.TriggerOut THEN
SystemTags.OUT201.operSet.ctlVal := TRUE;
SystemTags.OUT201.operClear.ctlVal := FALSE;
END_IF

fb_LowThreshold: Level Mode


Objective
A user is using an Axion DC analog input module to read an analog signal. The user wants
to assert the Alarm variable when the value of the analog signal drops below 25. The Alarm
variable deasserts when the analog signal becomes equal to 28 or higher.

Assumptions
This example assumes that there is an Axion analog input module configured in the RTAC
project, and a global variable named Alarm exists in the project.

Solution
To assert the Alarm variable when the analog signal is less than or equal to 25, and deassert
the variable when the analog signal becomes greater than or equal to 28, the user can create
a program as shown in Code Snippet 22.4.

Code Snippet 22.4 Level Mode


PROGRAM Example_LowThreshold
VAR
LowTrigger_level: fb_LowThreshold(risingEdgeMode := FALSE)
:= (EN:= TRUE, Threshold := 25, Hysteresis:=3);
END_VAR

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.13
Examples

Code Snippet 22.4 Level Mode (Continued)


LowTrigger_level(InSignal := SEL_16AI_1_ECAT.INPUT_VALUE_001.instMag);

//Assert Level if the function block output has triggered:


IF LowTrigger_level.TriggerOut THEN
Alarm := TRUE;
ELSE
Alarm := FALSE;
END_IF

fb_RateOfChange
Objective
A user is using a Modbus client on the RTAC to read a temperature value from the field. The
user wants to assert the RTAC output OUT201 when the rate-of-change of the temperature
exceeds 10℃ per minute.

Assumptions
This example assumes that there is a Modbus client in the RTAC project, and it is configured
to read a temperature, in Celsius, from a measurement device installed on the field. The
name of the Modbus client in the project is myModbus_MODBUS and the temperature of
interest is mapped in the Modbus Holding Register Address 0.

Solution
To assert Output OUT201 when the rate-of-change of the temperature is greater than or
equal to 10℃ per minute, the user can create a program as shown in Code Snippet 22.5:

Date Code 20190830 Instruction Manual Programming Reference


22.14 RecordingTriggers
Examples

Code Snippet 22.5 Rate-of-Change Example


PROGRAM Example_RateOfChange
VAR
TemperatureRoC: fb_RateOfChange(risingEdgeMode := FALSE)
:= (EN:=TRUE, RateOfChange:=10, SamplingPeriod:=T#1M);
END_VAR

TemperatureRoC(InSignal := myModbus_MODBUS.HREG_00000.Status.stVal);
//Assert OUT201 if the function block output has triggered:
IF TemperatureRoC.TriggerOut THEN
SystemTags.OUT201.operSet.ctlVal := TRUE;
SystemTags.OUT201.operClear.ctlVal := FALSE;
ELSE
SystemTags.OUT201.operSet.ctlVal := FALSE;
SystemTags.OUT201.operClear.ctlVal := TRUE;
END_IF

fb_DigitalTrigger
Objective
A user is monitoring the status of a circuit breaker using a digital input channel in the
RTAC. The user wants to generate an oscillography event file when the circuit breaker
trips or closes (rising edge and falling edge).

Assumptions
This example assumes the following:
ä The circuit breaker is wired to the Digital Input IN201.
ä The oscillography is generated by using an RTAC recording group. The name of the
recording group in the RTAC project is recGroup.

Solution
To trigger the recording group when a change of state occurs on Input IN201 , the user can
create a program as shown in Code Snippet 22.6.

Programming Reference Instruction Manual Date Code 20190830


RecordingTriggers 22.15
Examples

Code Snippet 22.6 DigitalTrigger Example


PROGRAM Example_DigitalTrigger
VAR
BreakerStatusChange: fb_DigitalTrigger(OpMode := RISING_FALLING_EDGE)
:= (EN:= TRUE);
END_VAR

BreakerStatusChange(InSignal := SystemTags.IN201.stVal);

//Trigger Recording Group:


recGroup_POU.Event_Trigger := BreakerStatusChange.TriggerOut;

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 23

ReportGenerator
Introduction
The ReportGenerator library is intended for use by extensions that support the extension
text editor object but can be broadly applied as an advanced file writer/manager.

The term report, as used in this document, refers to the contents of a Queue.class_Byt-
eDeque instance at the time of calling the MakeReport() method plus ASCII 16#20(New-
line) characters and report management metadata as deemed necessary by the configured
ReportMethod input.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R145-V0 or higher.

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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type
class_ReportGeneratorObject"
myReportGeneratorObject := otherReportGeneratorObject;

// This is fine
someVariable := myReportGeneratorObject.value;
// As is this
pt_myReportGeneratorObject := ADR(myReportGeneratorObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.

Date Code 20190830 Instruction Manual Programming Reference


23.2 ReportGenerator
Enumerations

ä Classes in this library have memory allocated inside them. As such, they should
only be created in environments of permanent scope (e.g., Programs, Global Variable
Lists, or VAR_STAT sections).
ä All file read operations are done completely into RAM. This means that the reading
of large files that exceed the available RAM will not work as expected.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_ReportMethods
Enumeration Description
SINGLE_REPORT_FILES Each new report is placed in a dedicated file. The
file name contains the user settable fileName input
followed by a timestamp representing the RTAC
system time when the report was triggered.
MULTIPLE_REPORT_FILES New triggered reports are appended to the same
file. When the number of reports added to the file
equals the user-configured MaxReports setting, a
new file is created to contain the new report. File
names contain a timestamp that reflects the RTAC
system time when the oldest report in the file
was triggered. This timestamp has a resolution in
seconds.

Each report within the file is given a footer


consisting a single ASCII 16#20(Newline) char-
acter followed by 32 bytes of meta-data, (to be
used for report rotation management), followed
by a single ASCII 16#20(Newline) character.
MULTIPLE_REPORT_MANAGED_FILE New triggered reports are appended to a single
file. When the number of reports added to the file
equals the user-configured MaxReports setting,
the oldest report is deleted from the file, prior to
appending the new report.

Each report within the file is given a footer


consisting of a single ASCII 16#20(Newline)
character followed by 32 bytes of meta-data, (to
be used for report rotation management), followed
by a single ASCII 16#20(Newline) character.

Programming Reference Instruction Manual Date Code 20190830


ReportGenerator 23.3
Classes

enum_FileType
Enumeration Description
TXT File names are given a ".txt" extension.
HTML File names are given a ".html" extension.
CSV File names are given a ".csv" extension.

Classes
This library provides the following classes as extensions of the IEC-61131 function block.

class_ReportGenerator (Class)
This class facilitates the writing and management of user-defined reports within one or
more files.

Outputs
Name IEC 61131 Type Description
Initialized BOOL TRUE if the class instance is initialized and ready to ac-
cept new report requests via the MakeReport() method.
Busy BOOL TRUE if the class instance is performing file manage-
ment or file write activities.
Error BOOL TRUE if an internal processing error has occurred
ErrorMessage STRING(255) A text description of the last error encountered by this
class instance.

Date Code 20190830 Instruction Manual Programming Reference


23.4 ReportGenerator
Classes

Initialize (Method)
Call this method to assign the inputs and in/out variable for this class instance. This method
must be called whenever new project settings are sent to the RTAC or power to the RTAC
is cycled.

Inputs
Name IEC 61131 Type Description
Directory STRING(100) The directory in which to store and manage re-
port files. 100 characters max. / delimits the
folder path. It cannot contain any file path ma-
nipulation variables (\\, /./, /../).
FileName STRING(100) The name of the report, 100 characters max
FileType enum_FileType TXT, HTML, or CSV. Defines the file name ex-
tension. Does not affect formatting of report con-
tent.
ReportMethod enum_ReportMethods Method of report vs file creation.
MaxReports UINT For ReportMethod other than an SINGLE_-
REPORT_FILES MaxReports is the maximum
number of reports that can be contained within a
single file.
LogRuntimeErrors BOOL If TRUE, runtime errors are logged in the RTAC
SOE viewer.
InstanceName STRING(100) Context identification string for use with SOE
logging.

Note: FileName and Directory settings may contain all printable ASCII characters
between 16#20(Space) and 16#7E(tilde) except for ", ’, :, <, %, >, ?, \, and |.
The specified directory should already exist prior to calling Initialize(). If not, the
outputs may reflect an error condition until the first report is created.

Inputs/Outputs
Name IEC 61131 Type Description
Report Queue.class_ByteDeque A class_ByteDeque instance that will contain the full con-
tent of the report. It is the users’ responsibility to populate
the queue prior to calling the MakeReport() method.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if initialization completes without error.

Programming Reference Instruction Manual Date Code 20190830


ReportGenerator 23.5
Classes

Processing
ä If the Initialized class output is TRUE:
â Returns FALSE.
ä If the Initialized output is FALSE:
â Maps input variables to internal class variables.
â Assigns internal reference to manage the operation of the Report class_ByteD-
eque instance.
â Validates FileType, ReportMethod, and MaxReports inputs against specified
bounds.
â Returns TRUE if inputs are valid.
â Sets Initialized class output to the return value.

MakeReport (Method)
Call this method to generate a new report.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if no errors encountered.

Processing
ä If the Busy output is FALSE:
â The current RTAC system time is saved and may subsequently be appended to
a new file name depending upon the Report Method and state of the active file.
See description of enum_ReportMethods and the processing section of the Run
method for more information.
â Empties the contents of the Report class_ByteDeque instance into a local queue.
ä If the Busy output is TRUE:
â Returns FALSE.

Run (Method)
Call this method every task cycle to allow for the execution of asynchronous file operations.
The term active file is used here to describe a file in the RTAC file system that the next
triggered report is written to.

Processing - General
ä No work is done until the Initialized output is TRUE.
ä If Initialized is TRUE, work is done, regardless of the state of Error.

Date Code 20190830 Instruction Manual Programming Reference


23.6 ReportGenerator
Classes

Processing - SINGLE_REPORT_FILES Mode


ä FileName and Directory name settings are validated within the Run method, after
each call of MakeReport. Invalid settings assert the Error output and are described
via the ErrorDescription output.
ä If MakeReport() has been called and returns TRUE, creates a new file and assigns a
file name of {ReportName}_{RTAC system timestamp}.{FileType} and writes con-
tents of internal report queue to the file.

Processing - MULTIPLE_REPORT_FILES Mode


ä FileName and Directory name settings are validated within the Run method, after
each call of MakeReport. Invalid settings assert the Error output and are described
via the ErrorDescription output.
ä Reports are written to the active file from top to bottom of the file in order of newest
to oldest report.
ä If MakeReport() has been called and returns TRUE, and no active file exists or the
active file already contains a number of reports equal to MaxReports:
â Creates a new file with name of {ReportName}_{RTAC system timestamp}.{File-
Type}.
â Writes contents of Report queue to the top of the file, followed by the footer.
ä If MakeReport() has been called and returns TRUE, and the active file contains less
than MaxReports reports:
â Writes by contents of Report queue to the top of the file, followed by the footer.
ä If the RTAC is rebooted or settings changed, the reference to the active file is reset
to NULL and a new file is created on the next call to MakeReport().

Processing - MULTIPLE_REPORT_MANAGED_FILE Mode


ä FileName and Directory name settings are validated on the first call to Run after the
initial call to MakeReport. Invalid settings assert the Error output and are described
via the ErrorDescription output.
ä Reports are written to the active file from top to bottom of the file in order of newest
to oldest report.
ä If MakeReport() is called and returns TRUE:
â Writes contents of Report queue to the top of a file with file name of {Report-
Name}.{FileType}, followed by the footer.
â If the file already contains MaxReports reports, deletes the oldest report and
associated footer from the bottom of the file.

Programming Reference Instruction Manual Date Code 20190830


SECTION 24

SELEthernetController
Introduction
The SELEthernetController library provides the ability to stream data through TCP and
UDP ports. It provides client and server functionality for both TCP and UDP connections.
Various methods are used to initiate new read or write operations.
NOTE: See the ACSELERATOR RTAC
Library Extensions Instruction Manual
(LibraryExtensionsIM) for more

Special Considerations information about the concepts used


by the object-oriented extensions to
the IEC 61131-3 standard.

ä 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 bad and in most cases will provide a compiler error


such as:
// "C0328: Assignment not allowed for type class_SocketObject"
mySocketObject := otherSocketObject;

// This is fine
someVariable := mySocketObject.value;
// As is this
pt_mySocketObject := ADR(mySocketObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT


members in function blocks, functions, or methods. Place them in the VAR_-
IN_OUT section or use pointers instead.
ä 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).
ä Opening and closing large numbers of Ethernet connections can take significant time.
Take great care when using this library on a system with hard real-time requirements.
ä This library does not have the ability to open ports in the RTAC firewall to allow
inbound communication. This means that for the library to receive UDP packets or
act as a TCP server, those ports must be opened as Ethernet Incoming Access Points
in the AcRTAC project.

Date Code 20190830 Instruction Manual Programming Reference


24.2 SELEthernetController
Functions

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.6 and older can be used on RTAC firmware version R133 and higher.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_SocketState
Enumeration Description
LISTENING The server socket is ready to receive communication requests.
OPEN The socket is ready to send and receive UDP data.
CONNECTED The socket has an active client server TCP session.
CLOSED The socket will no longer allow communication.
ERROR The socket has encountered an error and needs reconfiguration.

Aliases
This section lists aliases that this library defines.

SESSION_HANDLE
Alias IEC 61131 Type
SESSION_HANDLE POINTER TO BYTE

Functions
This library provides the following functions.

fun_StringToInaddr
Convert basic strings to the INADDR type this library uses. Strings provided to this func-
tion must be in the format xxx.xxx.xxx.xxx, where xxx is a number between 0 and 255.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.3
Functions

Inputs
Name IEC 61131 Type Description
ipAddrString STRING(15) The string to convert to an INADDR.

Outputs
Name IEC 61131 Type Description
ipAddr INADDR The converted INADDR.

Return Value
IEC 61131 Type Description
BOOL TRUE if the string could be converted.

Processing
The fun_StringToInaddr() function does the following:
ä Parses the provided string into four bytes.
ä Outputs those bytes ordered in an INADDR.
ä Returns false and outputs an IP address of 0.0.0.0 if the string could not be converted.

fun_InaddrToString
Converts an INADDR to a string in the format xxx.xxx.xxx.xxx, where xxx is a number
between 0 and 255.

Inputs
Name IEC 61131 Type Description
ipAddr INADDR The INADDR to convert to a string.

Return Value
IEC 61131 Type Description
STRING(15) The resulting IP address as a string.

Processing
The fun_InaddrToString() function does the following:

Date Code 20190830 Instruction Manual Programming Reference


24.4 SELEthernetController
Classes

ä Parses the provided INADDR by its four bytes.


ä Returns a string in the format xxx.xxx.xxx.xxx, where xxx is a number between 0 and
255.

Classes
Classes are a particular implementation of a Function Block(FB). They provide methods
and properties, which a normal FB does not provide.

class_UdpSocket (Class)
This class provides a socket for sending and receiving using through use of the UDP pro-
tocol. Once enabled, the class creates, binds, sends, and receives to the configured ports.

Initialization Inputs
Name IEC 61131 Type Description
maxPacketSize DINT The maximum packet size, in bytes, to obtain through
use of this socket. A value of zero or less results in the
class imposing no limit on inbound packet size.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


State enum_SocketState R The state of this socket.
LocalPort UINT R The port number with which this socket
interfaces locally.
LocalIPAddr INADDR R The IP address with which this socket in-
terfaces locally.
pt_Error POINTER TO STRING R An error message describing any present
error condition.

bootstrap_SetLocalIP (Method)
Perform a one-time setting of the local IP address and port this socket will use.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.5
Classes

Inputs
Name IEC 61131 Type Description
localPort UINT The port number through which this socket receives and
sends data through.
localIPAddr INADDR The IP address on the local box this socket uses. Use
0.0.0.0 to allow all local IP addresses.

Return Value
IEC 61131 Type Description
BOOL TRUE if the IP address and port number are set.

Processing
The bootstrap_SetLocalIP() method does the following:
ä Immediately returns FALSE if the port and IP address are already set.
ä Sets the IP address and port on the local machine for use by this socket.

Open (Method)
Configure the class_UdpSocket to allow communication.

Return Value
IEC 61131 Type Description
BOOL TRUE if the port is ready to send data.

Processing
The Open() method does the following:
ä Opens the port for sending and receiving communication.
ä Returns FALSE if the socket was unable to bind.

Close (Method)
Unconfigure the class_UdpSocket to disable communication.

Processing
The Close() method does the following:
ä Discards any unread messages.

Date Code 20190830 Instruction Manual Programming Reference


24.6 SELEthernetController
Classes

ä Makes the socket unable to send or receive data.


ä Forces reopening of the socket before processing additional communication.

SendData (Method)
Send a block of data to the socket.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The data to send.
numBytes DINT The quantity of data in bytes.
destIPAddr INADDR The IP address to which data are sent.
destPort UINT The destination port to which data are sent.

Return Value
IEC 61131 Type Description
DINT The number of bytes sent.

Processing
The SendData() method does the following:
ä Sends data if Open() has been successfully called.
ä Validates access to the pointer provided.
ä Limits numBytes to a positive number.
ä Sends numBytes of data, starting at pt_data, to the socket.
ä Returns the number of bytes successfully sent.

SendQueuedData(Method)
Send a block of data to the socket from the front of a queue.

Inputs
Name IEC 61131 Type Description
destIPAddr INADDR The IP address to which data are sent.
destPort UINT The destination port to which data are sent.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.7
Classes

Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The queued data to send.

Return Value
IEC 61131 Type Description
DINT The number of bytes sent.

Processing
The SendQueuedData() method does the following:
ä Sends data if Open() has been successfully called.
ä Sends all data, starting at the front of queue, to the socket.
ä Returns the number of bytes successfully sent.
ä Removes bytes sent from the front of queue.

ReceiveFrom (Method)
Overwrites data with the first packet available to the socket.

Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector The container to which the data are written.

Outputs
Name IEC 61131 Type Description
fromIpAddr INADDR The IP address from which the data came.
fromPort UINT The port from which the data came.

Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.

Date Code 20190830 Instruction Manual Programming Reference


24.8 SELEthernetController
Classes

Processing
The ReceiveFrom() method does the following:
ä Does nothing if the socket is not open or a new packet is not available.
ä Deletes any data found in data.
ä Places the first packet—as many as maxPacketSize bytes—from this socket in data.
ä Returns the number of bytes loaded into data.

ReceiveToQueueFrom (Method)
Overwrites data with the first packet available to the socket.

Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteDeque The container to which the data are written.

Outputs
Name IEC 61131 Type Description
fromIpAddr INADDR The IP address from which the data came.
fromPort UINT The port from which the data came.

Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.

Processing
The ReceiveToQueueFrom() method does the following:
ä Does nothing if the socket is not open or a new packet is not available.
ä Deletes any data found in data.
ä Places the first packet—as many as maxPacketSize bytes—from this socket in data.
ä Returns the number of bytes loaded into data.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.9
Classes

class_TcpClient (Class)
This class provides a client socket for the TCP protocol. Once enabled, the class creates,
binds, and sends to the configured port. Because TCP is session-based communication, the
client should close the session upon completion of the communication to conserve server
resources.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


State enum_SocketState R The state of this socket.
LocalPort UINT R The port number provided by the user for
use locally. A value of zero means an OS-
chosen port value will be used.
LocalIPAddr INADDR R The IP address with which this socket in-
terfaces locally.
DestIPAddr INADDR R The IP address to which any triggered
message is sent.
DestPort UINT R The port number to which any triggered
message is sent.
pt_Error POINTER TO STRING R An error message describing any present
error condition.

bootstrap_SetLocalIP (Method)
Perform a one-time setting of the local IP address and port this socket will use.

Inputs
Name IEC 61131 Type Description
localPort UINT The port number through which this socket receives and
sends data. If this value is zero then the OS will choose a
random outgoing port.
localIPAddr INADDR The IP address on the local box this socket uses. Use
0.0.0.0 to allow all local IP addresses.

Return Value
IEC 61131 Type Description
BOOL TRUE if the IP address and port number are set.

Date Code 20190830 Instruction Manual Programming Reference


24.10 SELEthernetController
Classes

Processing
The bootstrap_SetLocalIP() method does the following:
ä Immediately returns FALSE if the port and IP address are already set.
ä Sets the IP address and port on the local machine for use by this socket.

SetIP (Method)
Set the IP address and port to be used on the next Open() request.

Inputs
Name IEC 61131 Type Description
destIPAddr INADDR The IP address to which data is sent.
destPort UINT The destination port to which data is sent.

Processing
The SetIP() method does the following:
ä Sets the IP address and port that will become the new destination the next time
Open() is called.

Open (Method)
Configure the class_TcpClient to allow communication.

Return Value
IEC 61131 Type Description
BOOL TRUE if the port is ready to send data.

Processing
The Open() method does the following:
ä Opens the port for sending and receiving communication, if SetIP() has been suc-
cessfully run.
ä Returns false if the socket was unable to connect.

Close (Method)
Unconfigure the class_TcpClient, to disable communication.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.11
Classes

Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.

Processing
The Close() method does the following:
ä Discards any unread data.
ä Allows server to retain session until all data are read, if forceClose is FALSE.
ä Makes the socket unable to send data or receive replies.
ä Forces reopening of the socket before processing additional communication.

SendData (Method)
Send a block of data to the socket.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The data to send.
numBytes DINT The quantity of data in bytes.

Return Value
IEC 61131 Type Description
DINT The number of bytes sent.

Processing
The SendData() method does the following:
ä Does nothing if the socket is not open.
ä Validates access to the pointer provided.
ä Limits numBytes to a positive number.
ä Sends all provided data to the socket.
ä Returns the number of bytes successfully sent.

SendQueuedData (Method)
Send a block of data to the socket from the front of a queue.

Date Code 20190830 Instruction Manual Programming Reference


24.12 SELEthernetController
Classes

Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The data to send.

Return Value
IEC 61131 Type Description
DINT The number of bytes sent.

Processing
The SendQueuedData() method does the following:
ä Does nothing if the socket is not open.
ä Sends all provided data, starting at the front of queue, to the socket.
ä Returns the number of bytes successfully sent.
ä Removes bytes sent from the front of queue.

ReceiveData (Method)
Appends a block of data from the socket to data.

Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.

Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector The container to which the data are written.

Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.

Processing
The ReceiveData() method does the following:

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.13
Classes

ä Does nothing if the socket is not open.


ä Requests data from the socket until there are either no more or it reaches numBytes,
whichever happens first.
ä Appends all data retrieved to data.
ä Returns the number of bytes appended.

ReceiveToQueue (Method)
Pushes a block of data from the socket to the back of queue.

Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.

Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The container to which the data are written.

Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.

Processing
The ReceiveToQueue() method does the following:
ä Does nothing if the socket is not open.
ä Requests data from the socket until there are either no more or it reaches numBytes,
whichever happens first.
ä Pushes all data retrieved to the back of queue.
ä Returns the number of bytes pushed.

class_TcpServer (Class)
This class provides a listening socket for the TCP protocol. Once enabled the class creates,
binds, and receives on the configured port.

Date Code 20190830 Instruction Manual Programming Reference


24.14 SELEthernetController
Classes

Initialization Inputs
Name IEC 61131 Type Description
maxSessions USINT The maximum number of concurrent sessions to allow on
this socket. This will be forced to at least one.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


State enum_SocketState R The state of this socket.
LocalPort UINT R The port number with which this socket
interfaces locally.
LocalIPAddr INADDR R The IP address with which this socket in-
terfaces locally.
NumSessions USINT R The number of client sessions connected
to this server block.
SessionState enum_SocketState R The state of the selected session.
CLOSED if nothing is connected or
CONNECTED if data can still be read
from the socket.
DestIPAddr INADDR R The IP address to which any triggered
message is sent.
DestPort UINT R The port to which any triggered message
is sent.
pt_Error POINTER TO STRING R An error message describing any present
error condition.

bootstrap_SetLocalIP (Method)
Perform a one-time setting of the local IP address and port this socket will use.

Inputs
Name IEC 61131 Type Description
localPort UINT The port number through which this socket receives and
sends data.
localIPAddr INADDR The IP address on the local box this socket uses. Use
0.0.0.0 to allow all local IP addresses.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.15
Classes

Return Value
IEC 61131 Type Description
BOOL TRUE if the IP address and port number are set.

Processing
The bootstrap_SetLocalIP() method does the following:
ä Immediately returns FALSE if the port and IP address are already set.
ä Sets the IP address and port on the local machine used by this socket.

Open (Method)
Configure the class_TcpServer to allow for communication.

Return Value
IEC 61131 Type Description
BOOL TRUE if the port is ready to receive connections.

Processing
The Open() method does the following:
ä Configures the server to receive client connections.
ä Returns FALSE if the socket was unable to bind.

Close (Method)
Unconfigure the class_TcpServer to disable communication.

Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.

Processing
The Close() method does the following:
ä Discards any unread data.
ä Closes all open client sessions: gracefully if forceClose is FALSE.
ä Makes the socket unable to send data or receive replies.

Date Code 20190830 Instruction Manual Programming Reference


24.16 SELEthernetController
Classes

ä Forces reconfiguration of the socket before attempting additional communication.

AcceptNextSession (Method)
Accept the next new inbound data session. This does not change the active session.

Return Value
IEC 61131 Type Description
SESSION_HANDLE The descriptor to allow further communication through this session.

Processing
The AcceptNextSession() method does the following:
ä Does nothing if the socket is not open for listening.
ä Accepts the next outstanding client session to as many as maxSessions.
ä Updates NumSessions based on the sessions accepted.
ä Returns the value SysSocket.RTS_INVALID_HANDLE if there are no outstanding
sessions.
ä Returns the handle to the accepted session.

SetSession (Method)
Select the session from which the class reads data from and replies to based on a previously
received identifier.

Inputs
Name IEC 61131 Type Description
sessionID SESSION_HANDLE The identifier of the desired session as returned by
AcceptNextSession().

Return Value
IEC 61131 Type Description
BOOL TRUE if the session exists.

Processing
The SetSession() method does the following:
ä Selects the read and write session tied to sessionID.
ä Sets DestIPAddr and DestPort to the values for the selected session.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.17
Classes

ä Returns false and sets DestIPAddr to 0.0.0.0, DestPort to 0, and SessionState


to closed if sessionID does not represent an active session.

GetSessionInfo (Method)
Get the IP address and port number related to a session handle.

Inputs
Name IEC 61131 Type Description
sessionID SESSION_HANDLE The identifier of a session as returned by
AcceptNextSession().

Outputs
Name IEC 61131 Type Description
sessionIPAddr INADDR The IP address attached to sessionID.
sessionPort UINT The port number attached to sessionID.

Processing
The GetSessionInfo() method does the following:
ä Outputs the IP address and port number tied to sessionID.
ä Sets sessionIPAddr to 0.0.0.0 and sessionPort to 0, if sessionID does not represent
an active session.

CloseSession (Method)
Close the selected session and clear any pending data.

Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.

Processing
The CloseSession() method does the following:
ä Closes the active session.
ä Sets DestIPAddr and DestPort to zero.
ä Discards any unread data.
ä Allows client to retain session until all data are read, if forceClose is FALSE.

Date Code 20190830 Instruction Manual Programming Reference


24.18 SELEthernetController
Classes

ä Decrements NumSessions.

SendData (Method)
Send a block of data to the socket.

Inputs
Name IEC 61131 Type Description
pt_data POINTER TO BYTE The data to send.
numBytes DINT The quantity of data in bytes.

Return Value
IEC 61131 Type Description
DINT The number of bytes sent.

Processing
The SendData() method does the following:
ä Does nothing if no valid session has been selected.
ä Validates access to the pointer provided.
ä Limits numBytes to a positive number.
ä Sends all provided data to the socket.
ä Returns the number of bytes successfully sent.

SendQueuedData (Method)
Send a block of data to the socket from the front of a queue.

Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The data to send.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.19
Classes

Return Value
IEC 61131 Type Description
DINT The number of bytes sent.

Processing
The SendQueuedData() method does the following:
ä Does nothing if the socket is not open.
ä Sends all provided data, starting at the front of the queue, to the socket.
ä Returns the number of bytes successfully sent.
ä Removes bytes sent from the front of queue.

ReceiveData (Method)
Receive a block of data from the active session.

Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.

Inputs/Outputs
Name IEC 61131 Type Description
data class_ByteVector The container to which the data are written.

Return Value
IEC 61131 Type Description
DINT The number of bytes loaded into data.

Processing
The ReceiveData() method does the following:
ä Does nothing if no valid session has been selected.
ä Checks for available data in the selected session.
ä Requests data from the socket until there are no more or it reaches numBytes, whichever
happens first.
ä Appends all data retrieved to data.

Date Code 20190830 Instruction Manual Programming Reference


24.20 SELEthernetController
Benchmarks

ä Returns the number of bytes appended.

ReceiveToQueue (Method)
Pushes a block of data from the socket to the back of queue.

Inputs
Name IEC 61131 Type Description
numBytes DINT The number of bytes requested.

Inputs/Outputs
Name IEC 61131 Type Description
queue class_ByteDeque The container to which the data are written.

Return Value
IEC 61131 Type Description
DINT The number of bytes loaded.

Processing
The ReceiveToQueue() method does the following:
ä Does nothing if the socket is not open.
ä Requests data from the socket until there are no more or it reaches numBytes, whichever
happens first.
ä Pushes all data retrieved to the back of queue.
ä Returns the number of bytes pushed.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.21
Benchmarks

ä SEL-3530
â R134-V0 firmware
ä SEL-3505
â R134-V0 firmware

Benchmark Test Descriptions


fun_StringToInaddr
The posted time is the average execution time of 100 consecutive calls for the string “192.168.100.100”.

fun_InaddrToString
The posted time is the average execution time of 100 consecutive calls for the IP address
192.168.100.100.

class_UdpSocket.Open
The posted time is the average execution time of 100 successful method calls to open a
socket.

class_UdpSocket.Close
The posted time is the average execution time of 100 successful method calls to close a
socket.

class_UdpSocket.SendData
The posted time is the average execution time of 100 consecutive calls when sending 504
bytes of data, resulting in a 512-byte total packet size.

class_UdpSocket.SendQueuedData
The posted time is the average execution time of 100 consecutive calls when sending 504
bytes of data, resulting in a 512-byte total packet size.

class_UdpSocket.ReceiveFrom
The posted time is the average execution time of 100 consecutive calls when receiving 504
bytes of data, resulting in a 512-byte total packet size.

Date Code 20190830 Instruction Manual Programming Reference


24.22 SELEthernetController
Benchmarks

class_UdpSocket.ReceiveToQueueFrom
The posted time is the average execution time of 100 consecutive calls when receiving 504
bytes of data, resulting in a 512-byte total packet size.

class_TcpClient.SetIP
The posted time is the average execution time of 100 consecutive calls.

class_TcpClient.Open
The posted time is the average execution time of 100 successful method calls to open a
socket.

class_TcpClient.Close
The posted time is the average execution time of 100 successful method calls to close a
socket.

class_TcpClient.SendData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.

class_TcpClient.SendQueuedData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.

class_TcpClient.ReceiveData
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.

class_TcpClient.ReceiveToQueue
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.

class_TcpServer.Open
The posted time is the average execution time of 100 successful method calls to open a
socket.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.23
Benchmarks

class_TcpServer.Close
The posted time is the average execution time of 100 successful method calls to close a
socket.

class_TcpServer.AcceptNextSession
The posted time is the average execution time of 100 successful method calls when there
is another session to accept.

class_TcpServer.SetSession
The posted time is the average execution time of 100 consecutive calls.

class_TcpServer.GetSessionInfo
The posted time is the average execution time of 100 consecutive calls.

class_TcpServer.CloseSession
The posted time is the average execution time of 100 successful method calls to close a
session.

class_TcpServer.SendData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.

class_TcpServer.SendQueuedData
The posted time is the average execution time of 100 consecutive calls when sending 1400
bytes of data.

class_TcpServer.ReceiveData
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.

class_TcpServer.ReceiveToQueue
The posted time is the average execution time of 100 consecutive calls when receiving 1400
bytes of data.

Date Code 20190830 Instruction Manual Programming Reference


24.24 SELEthernetController
Examples

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3555 SEL-3530 SEL-3505
fun_StringToInaddr 2 12 18
fun_InaddrToString 6 40 63
class_UdpSocket.Open 25 150 330
class_UdpSocket.Close 13 65 117
class_UdpSocket.SendData 26 150 380
class_UdpSocket.SendQueuedData 25 160 380
class_UdpSocket.ReceiveFrom 12 90 200
class_UdpSocket.ReceiveToQueueFrom 12 100 220
class_TcpClient.SetIP 1 1 1
class_TcpClient.Open 67 740 1200
class_TcpClient.Close 41 310 660
class_TcpClient.SendData 1 3 6
class_TcpClient.SendQueuedData 1 3 5
class_TcpClient.ReceiveData 8 80 110
class_TcpClient.ReceiveToQueue 7 80 110
class_TcpServer.Open 36 200 400
class_TcpServer.Close 20 100 140
class_TcpServer.AcceptNextSession 20 97 130
class_TcpServer.SetSession 2 4 6
class_TcpServer.GetSessionInfo 2 5 14
class_TcpServer.CloseSession 33 320 690
class_TcpServer.SendData 1 3 6
class_TcpServer.SendQueuedData 1 3 5
class_TcpServer.ReceiveData 9 80 110
class_TcpServer.ReceiveToQueue 8 75 110

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Sending Data Out a UDP Socket


Objective
A user has an array of bytes formatted to place on the network and needs to send it to a
specific IP address and port via UDP.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.25
Examples

Solution
The user can create the program shown in Code Snippet 24.1 to send the byte array out
each task cycle.

Code Snippet 24.1 prg_UdpOut


PROGRAM prg_UdpOut
VAR
// Configuration Information - Uses any available interface.
LocalIPAddress : STRING(15) := '0.0.0.0';
LocalPortNumber : UINT := 5000;
DestinationIPAddress : STRING(15) := '10.10.10.10';
DestinationPortNumber : UINT := 5000;

// Data to send each task cycle.


Data : ARRAY [1 .. 1000] OF BYTE;

// Socket to send data on.


UdpSocket : class_UdpSocket(maxPacketSize := 1024);

// Initialization variables.
SocketInitialized : BOOL := FALSE;
LocalIP : SELEthernetController.INADDR;
DestIP : SELEthernetController.INADDR;
END_VAR

IF NOT SocketInitialized THEN


fun_StringToInaddr(LocalIPAddress, ipAddr => LocalIP);
fun_StringToInaddr(DestinationIPAddress, ipAddr => DestIP);
UdpSocket.bootstrap_SetLocalIP(LocalPortNumber, LocalIP);
UdpSocket.Open();
SocketInitialized := TRUE;
ELSE
UdpSocket.SendData(ADR(Data[1]), SIZEOF(Data),
DestIP, DestinationPortNumber);
END_IF

Creating a UDP Server


Objective
A user would like the RTAC to be able to receive data from multiple clients over the UDP
protocol.
After some internal validation of a received packet, the server will reply with OK in ASCII
if the packet was correctly formatted.

Assumptions
This solution assumes that the AcRTAC project containing the provided code includes an
Access Point opening at the desired port and that the inbound packets are not larger than
1024 bytes.

Date Code 20190830 Instruction Manual Programming Reference


24.26 SELEthernetController
Examples

Solution
The user can create the program shown in Code Snippet 24.2 to receive one inbound data
packet each task cycle.

Code Snippet 24.2 prg_UdpServer


PROGRAM prg_UdpServer
VAR
// Configuration Information - Uses any available interface.
LocalIPAddress : STRING(15) := '0.0.0.0';
LocalPortNumber : UINT := 1515;

// Storage for inbound and outbound messages.


DataIn : SELEthernetController.class_ByteVector;
DataOut : STRING(2) := 'OK';

// The socket and its initialization data.


UdpSocket : class_UdpSocket(maxPacketSize := 1024);
SocketInitialized : BOOL := FALSE;
LocalIP : SELEthernetController.INADDR;

// Workbench variables for storing current client information.


DestIP : SELEthernetController.INADDR;
DestPort : UINT;
PacketValid : BOOL;
END_VAR

IF NOT SocketInitialized THEN


fun_StringToInaddr(LocalIPAddress, ipAddr => LocalIP);
UdpSocket.bootstrap_SetLocalIP(LocalPortNumber, LocalIP);
UdpSocket.Open();
SocketInitialized := TRUE;
ELSE
IF 0 <> UdpSocket.ReceiveFrom(DataIn, fromIpAddr => DestIP, fromPort
=> DestPort) THEN
; // Set PacketValid based on the contents of DataIn.
IF PacketValid THEN
UdpSocket.SendData(ADR(DataOut), 2, DestIP, DestPort);
END_IF
END_IF
END_IF

Creating a TCP Client


Objective
A user would like the RTAC to be able to send data to a TCP server for modification.

Assumptions
For this use case, we assume that the server doubles any data that are sent to it.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.27
Examples

Solution
The user can create the program defined in Code Snippet 24.3 to send packets to the remote
server and receive data in reply.

Code Snippet 24.3 prg_TcpClient


PROGRAM prg_TcpClient
VAR
// Configuration Information - Uses any available interface.
LocalIPAddress : STRING(15) := '0.0.0.0';
LocalPortNumber : UINT := 2442;
DestinationIPAddress : STRING(15) := '10.10.10.10';
DestinationPortNumber : UINT := 2442;

// Storage for data being sent and received.


DataOut : ARRAY [1 .. 200] OF BYTE;
DataIn : SELEthernetController.class_ByteVector;

// The socket and its initialization state.


TcpClient : class_TcpClient;
SocketInitialized : BOOL := FALSE;

// IP address variables.
LocalIP : SELEthernetController.INADDR;
DestIP : SELEthernetController.INADDR;

// Flags used in manipulating the state of the function.


IsSending : BOOL;
DataSent : DINT;
DataReceived : DINT;
END_VAR

IF NOT SocketInitialized THEN


fun_StringToInaddr(LocalIPAddress, ipAddr => LocalIP);
fun_StringToInaddr(DestinationIPAddress, ipAddr => DestIP);
TcpClient.bootstrap_SetLocalIP(LocalPortNumber, LocalIP);
TcpClient.SetIP(DestIP, DestinationPortNumber);
TcpClient.Open();
SocketInitialized := TRUE;
IsSending := TRUE;
ELSE
IF IsSending THEN
DataSent := TcpClient.SendData(ADR(DataOut[1]), 200);
DataIn.Recycle();
IsSending := FALSE;
DataReceived := 0;
ELSE
// Here we request the total data expected minus anything
// already received and add it to anything already received.
// This allows the reception of data to cross multiple cycles.
DataReceived := DataReceived +
TcpClient.ReceiveData((DataSent * 2)
- DataReceived, DataIn);
IF DataReceived = (2 * DataSent) THEN
; // Do some work based the server's reply.
IsSending := TRUE;
END_IF
END_IF
END_IF

Date Code 20190830 Instruction Manual Programming Reference


24.28 SELEthernetController
Examples

Parsing Network Traffic With a Deque


This example demonstrates using a deque for network communication.

Objective
Parse the data stream of information sent from a TCP server to the TCP client on the RTAC.
Increment a counter every time the characters “SEL” are seen in the stream.

Assumptions
This example assumes that there is a server to connect to and streams data through the
connection once the connection is established. It also assumes that the library Queue has
been inserted in the project.

Solution
The deque is used as storage for information received from a TCP socket. The received data
are then searched for the string ’SEL’ and a counter is incremented every time the string is
found. As it searches for the string, data are discarded from the front of the deque. This
implementation is shown in Code Snippet 24.4

Code Snippet 24.4 prg_SELSearch


PROGRAM prg_SELSearch
VAR
// Configuration Information - Uses any available interface.
LocalIPAddress : STRING(15) := '0.0.0.0';
LocalPortNumber : UINT := 2442;
DestinationIPAddress : STRING(15) := '10.10.10.10';
DestinationPortNumber : UINT := 2442;

// The socket and its initialization state.


TcpClient : class_TcpClient;
SocketInitialized : BOOL := FALSE;
// IP address variables.
LocalIP : SELEthernetController.INADDR;
DestIP : SELEthernetController.INADDR;
// Deque to hold received data.
DataIn : Queue.class_ByteDeque(0);
// The string to search for in the incoming data.
TargetString : STRING := 'SEL';
// A temporary string used to find the targetString.
Peek : STRING(3);
// A flag for breaking the search loop.
Searching : BOOL;
// Counter for the number of times the targetString is found.
Counter : UDINT := 0;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.29
Examples

IF NOT SocketInitialized THEN


fun_StringToInaddr(LocalIPAddress, ipAddr => LocalIP);
fun_StringToInaddr(DestinationIPAddress, ipAddr => DestIP);
TcpClient.bootstrap_SetLocalIP(LocalPortNumber, LocalIP);
TcpClient.SetIP(DestIP, DestinationPortNumber);
TcpClient.Open();
SocketInitialized := TRUE;
ELSE
// Read new data from the socket.
IF 0 <> TcpClient.ReceiveToQueue(10_000, DataIn) THEN
searching := TRUE;
WHILE searching DO
// See if the string 'SEL' appears in the front of the deque.
IF 3 = DataIn.Front(ADR(peek), 3) THEN
IF peek = TargetString THEN
(* The string 'SEL' was found, increment the counter
and erase the string from the deque. *)
Counter := Counter + 1;
DataIn.EraseFront(3);
ELSE
(* The string wasn't found, erase the first character
and continue looking. *)
DataIn.EraseFront(1);
END_IF
ELSE
Searching := FALSE;
END_IF
END_WHILE
END_IF
END_IF

Configuring a Simple TCP Server With Sessions


Objective
Parse all input data from several clients looking for the string “Hello.” When the string is
found, that client receives a reply “World$N$R”.
The server handles accepting and tracking all sessions and iterates across them to allow
each time to process.

Assumptions
This example assumes that Port 10024 is open through use of an Access Point configured
as Ethernet Incoming and set to receive Raw TCP. It also assumes that the client can access
that port through any intermediary firewalls. It also assumes that the library Queue has
been inserted in the project.
All error checking has been omitted to facilitate the brevity of this implementation.
There must be a structure defined to hold session related data. Code Snippet 24.5 shows an
example for this implementation.

Date Code 20190830 Instruction Manual Programming Reference


24.30 SELEthernetController
Examples

Code Snippet 24.5 Session Structure


TYPE struct_SessionInfo :
STRUCT
// There is a connected session stored here.
Active : BOOL := FALSE;
// The Handle for this session.
Handle : SESSION_HANDLE := SysSocket.RTS_INVALID_HANDLE;
// Deque containing incoming data ready for consumption.
ReceiveDeque : class_ByteDeque(0);
// Deque containing data ready to be sent to the telnet client.
SendDeque : class_ByteDeque(0);
END_STRUCT
END_TYPE

Solution
Instantiate a class_TcpServer and associated data control objects as seen in Code Snip-
pet 24.6. Allow this program to run every task scan.

Verification
To verify that this solution is functional, start running the server on the RTAC and then
attach with a raw TCP connection on port 10024. Any instance of the word “Hello” should
be followed immediately by the echo “World.”
Characters other than new-lines should eventually echo “Usage : Hello.”
The code as written should accept as many as five concurrent sessions with more allowed
after a given session disconnects.

Programming Reference Instruction Manual Date Code 20190830


SELEthernetController 24.31
Examples

Code Snippet 24.6 prg_SimpleServer


PROGRAM prg_SimpleServer
VAR CONSTANT
// The maximum number of sessions allowed for this server.
_c_NumSessions : USINT := 5;
// The maximum bytes to read per scan.
_c_NumBytes : DINT := 1024;
END_VAR
VAR
// Configuration Information
// Uses any available interface.
LocalIPAddress : STRING(15) := '0.0.0.0';
LocalPortNumber : UINT := 10024;
ListenIPAddr : INADDR;

SocketInitialized : BOOL := FALSE;


TcpServer : class_TcpServer(_c_NumSessions);

Sessions : ARRAY [1 .. _c_NumSessions] of struct_SessionInfo;

Peek : STRING(5);
Reply : STRING(7) := 'World$R$N';
Reply2 : STRING(15) := 'Usage : Hello$R$N';

tempSession : SESSION_HANDLE;
sendByteCount : DINT;
numSend : DINT;
i : UDINT;
END_VAR

IF NOT SocketInitialized THEN


IF SELEthernetController.fun_StringToInaddr(LocalIPAddress, ipAddr =>
ListenIPAddr) THEN
TcpServer.bootstrap_SetLocalIP(LocalPortNumber, ListenIPAddr);
IF TcpServer.Open() THEN
SocketInitialized := TRUE;
END_IF
END_IF
ELSE
// Clean up any session that is in error.
IF TcpServer.SessionState = ERROR THEN
TcpServer.CloseSession(TRUE);
END_IF

// Accept any new sessions if possible.


FOR i := 1 TO _c_NumSessions DO
IF NOT Sessions[i].Active THEN
// There is a session object available,
// see if there is a new session pending.
tempSession := TcpServer.AcceptNextSession();
IF tempSession <> SysSocket.RTS_INVALID_HANDLE THEN
Sessions[i].Handle := tempSession;
Sessions[i].Active := TRUE;
Sessions[i].SendDeque.Recycle();
Sessions[i].ReceiveDeque.Recycle();
ELSE
//There are no outstanding sessions. Stop asking.
EXIT;

Date Code 20190830 Instruction Manual Programming Reference


24.32 SELEthernetController
Examples

END_IF
END_IF
END_FOR

// Cycle through all current sessions and process their data.


FOR i := 1 TO _c_NumSessions DO
IF Sessions[i].Active THEN
IF TcpServer.SetSession(Sessions[i].Handle) THEN
// Read any data from the socket.
TcpServer.ReceiveToQueue(_c_NumBytes,
Sessions[i].ReceiveDeque);

// Here is where meaningful work would be added.


WHILE Sessions[i].ReceiveDeque.Size >= 5 DO
// See if the string 'SEL' appears in the front of the
deque.
IF 5 = Sessions[i].ReceiveDeque.Front(ADR(Peek), 5)
THEN
IF peek = 'Hello' THEN
Sessions[i].SendDeque.PushBack(ADR(Reply), 7);
Sessions[i].ReceiveDeque.EraseFront(5);
ELSIF peek[0] <> 10 and peek[0] <> 13 THEN
// The string wasn't found, erase the first
// character and continue looking.
Sessions[i].SendDeque.PushBack(ADR(Reply2),
15);
Sessions[i].ReceiveDeque.EraseFront(1);
ELSE
Sessions[i].ReceiveDeque.EraseFront(1);
END_IF
ELSE
EXIT;
END_IF
END_WHILE

TcpServer.SendQueuedData(Sessions[i].SendDeque);

// If the session closed while working with it, clean up.


IF TcpServer.SessionState = CLOSED THEN
Sessions[i].Handle := RTS_INVALID_HANDLE;
Sessions[i].Active := FALSE;
END_IF
ELSE
// If the session closed while doing other work, clean up.
Sessions[i].Handle := RTS_INVALID_HANDLE;
Sessions[i].Active := FALSE;
END_IF
END_IF
END_FOR
END_IF

Programming Reference Instruction Manual Date Code 20190830


SECTION 25

SELRand
Introduction
The SELRand library contains a set of functions that return pseudo-random numbers for
testing and other non-cryptographic purposes. A pseudo-random number generator is a
math function that takes advantage of its previous result and large number manipulations to
perform operations that are not immediately predictable. The beginning value for each use
of the sequence is called the seed. Generally, the seed is created from some measurement
expected to have a wide range of variance. Commonly, this can be noise on a wire, small
units of time, quantity and value of user input, or some other equally unpredictable quantity.
Pseudo-random number generators do tend to be cyclic in nature, but they can have very
large cycle times and excellent distribution.
These functions are not intended to be used for implementing any security feature.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.0 and older can be used on RTAC firmware version R132 and higher.

Functions
fun_Rand (Function)
This function randomly seeds itself and returns a pseudo-random number in the range of 0
inclusive to 232 exclusive.

Return Value
IEC 61131 Type Description
UDINT A random number between 0 inclusive to 232 exclusive.

Date Code 20190830 Instruction Manual Programming Reference


25.2 SELRand
Functions

Processing
At the first call of this function it randomly seeds itself. It will continually return pseudo-
random values with each use.

fun_RandRepeatable (Function)
This function always seeds itself with the same value and returns a pseudo-random number
in the range of 0 inclusive to 232 exclusive.

Return Value
IEC 61131 Type Description
UDINT A random number between 0 inclusive to 232 exclusive.

Processing
At the first call of this function it seeds itself, always with the same value. It then returns
the same sequence of pseudo-random values with each use.

fun_RandRanged (Function)
This function randomly seeds itself and returns a pseudo-random number between mini-
mum to maximum, inclusive.

Inputs
Name IEC 61131 Type Description
minimum UDINT The lower limit of the return value.
maximum UDINT The upper limit of the return value.

Return Value
IEC 61131 Type Description
UDINT A random number between minimum and maximum, inclusive.

Processing
At the first call of this function, randomly seeds itself. It then continually returns pseudo-
random values within the requested range.

Programming Reference Instruction Manual Date Code 20190830


SELRand 25.3
Benchmarks

fun_RandRangedRepeatable (Function)
This function always seeds itself with the same value and subsequently returns a pseudo-
random number between minimum to maximum, inclusive.

Inputs
Name IEC 61131 Type Description
minimum UDINT The lower limit of the return value.
maximum UDINT The upper limit of the return value.

Return Value
IEC 61131 Type Description
UDINT A random number between minimum and maximum, inclusive.

Processing
At the first call of function it seeds itself, always with the same value. It then continually
returns the same sequence of pseudo-random values within the requested range.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530
â R134-V0 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 1 GB DDR ECC SDRAM
â SEL-3532 RTAC Conversion Kit
â R132-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware

Date Code 20190830 Instruction Manual Programming Reference


25.4 SELRand
Examples

Benchmark Test Descriptions


All benchmark tests are based on an average of 100 calls to the function.

fun_Rand()
The posted time is the average execution time of 100 consecutive calls.

fun_RandRanged()
The posted time is the average execution time of 100 consecutive calls with a range of 1 to
100.

fun_RandRepeatable()
The posted time is the average execution time of 100 consecutive calls.

fun_RandRangedRepeatable()
The posted time is the average execution time of 100 consecutive calls with a range of 1 to
100.

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3530 SEL-3354 SEL-3555
fun_Rand() 1 1 1
fun_RandRanged() 2 1 1
fun_RandRepeatable() 1 1 1
fun_RandRangedRepeatable() 1 1 1

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Programming Reference Instruction Manual Date Code 20190830


SELRand 25.5
Examples

Getting a Random Integer Between 10 and 50


Objective
A user knows the input for a function will vary between 10 and 50 and would like demon-
strate the behavior of a function in a non-linear progression.

Assumptions
This example assumes that there is a user specified IEC 61131 function that is defined as
shown in Code Snippet 25.1.

Code Snippet 25.1 fun_SomeFunction


FUNCTION fun_SomeFunction :REAL
VAR_INPUT
num : UDINT;
END_VAR

Solution
The user can create the program in Code Snippet 25.2 to run the function 1000 times with
assorted input.

Code Snippet 25.2 prg_RandomWalk


PROGRAM prg_RandomWalk
VAR
i : UDINT;
results : ARRAY [1 .. 1000] OF REAL;
randomNum : UDINT;
END_VAR

FOR i := 1 to 1000 DO
//This gives a random number from 10 to 50;
randomNum := fun_RandRanged(10, 51);
//Call the function with the random number
results[i] := fun_SomeFunction(randomNum);
END_FOR

Testing With Assorted Input


Objective
A user wants to vary inputs for testing but would like to be able to recreate the inputs in
case something goes wrong.

Date Code 20190830 Instruction Manual Programming Reference


25.6 SELRand
Examples

Assumptions
This example assumes that there is a user-specified IEC 61131 function that is defined as
shown in Code Snippet 25.3

Code Snippet 25.3 fun_TestFunction


FUNCTION fun_TestFunction :BOOL
VAR_INPUT
num : UDINT;
END_VAR

Solution
The user can create the program in Code Snippet 25.4 to run the function 1000 times with
assorted input but a set order.

Code Snippet 25.4 prg_RandomTest


PROGRAM prg_RandomTest
VAR
i : UDINT;
results : ARRAY [1 .. 1000] OF REAL;
randomNum : UDINT;
END_VAR

FOR i := 1 TO 1000 DO
//This gives a random number;
randomNum := fun_RandRepeatable();
//Call the function with the random number
results[i] := fun_TestFunction(randomNum);
END_FOR

Programming Reference Instruction Manual Date Code 20190830


SECTION 26

SELServerSimulators
Introduction
This library provides simulators for various SEL devices using the SEL Fast Meter protocol.
Since this library is primarily a testing and debugging tool, not all commands may be
supported for a particular device. There may also be variances in the responses generated
when compared to the real device.
See the ACSELERATOR RTAC Library Extensions Instruction Manual (LibraryExtension-
sIM) for an explanation of the concepts used by the object-oriented extensions to the IEC 61131-3
standard.

Special Considerations
Classes in this library have memory allocated inside them. As such, they should only be
created in environments of permanent scope (e.g., Programs, Global Variable Lists, or
VAR_STAT sections).
Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_Object"
myObject := otherObject;

// This is fine
someVariable := myObject.value;
// As is this
pt_myObject := ADR(myObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT members


in function blocks, functions, or methods. Place them in the VAR_IN_OUT section
or use pointers instead.

Supported Devices
This library contains simulators for the following devices:
ä SEL-351

Date Code 20190830 Instruction Manual Programming Reference


26.2 SELServerSimulators
Structures

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Version 3.5.0.1 can be used on RTAC firmware version R132 and higher.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_PointType
This enumeration defines all possible point types for a relay.

Enumeration Description
DIGITAL A digital (Boolean) point.
INT16 An analog point stored as a 16-bit integer value.
FLOAT32 An analog point stored as a 32-bit floating-point value.
FLOAT64 An analog point stored as a 64-bit floating-point value.
STRING80 A point stored as a string of as many as 80 characters.

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.
Because of the significant number of values in these structures, this document does not
provide a complete list of the values.

struct_SEL351_Analog
This structure defines the analog points available on an SEL-351. For example, this struc-
ture might contain the following:

Name IEC 61131 Type Description


_FREQ class_SELServerFloat32 System frequency
_IA class_SELServerFloat32 Phase A current magnitude
_IB class_SELServerFloat32 Phase B current magnitude
_IC class_SELServerFloat32 Phase C current magnitude

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.3
Interfaces

struct_SEL351_Binary
This structure defines the digital points available on an SEL-351.

struct_SEL351_Strings
This structure defines the string points available on an SEL-351.

Interfaces
I_Session
This interface defines a set of methods for interacting with a client session. A session is a
generic object that allows for reading and writing of bytes.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


Active BOOL R TRUE if the session is active and able to send and
receive bytes.
Echo BOOL R TRUE if the session is expecting ASCII characters
sent to the server to be echoed back.

Close (Method)
Closes the session to the client.

Inputs
Name IEC 61131 Type Description
forceClose BOOL Close the session without waiting for confirmation.

ReadData (Method)
Read data from the client.

Date Code 20190830 Instruction Manual Programming Reference


26.4 SELServerSimulators
Interfaces

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE Pointer to where the incoming data are written.
numBytes UDINT The maximum number of bytes to read.

Return Value
IEC 61131 Type Description
UDINT The number of bytes read from the session.

WriteData (Method)
Write data to the client.

Inputs
Name IEC 61131 Type Description
pt_source POINTER TO BYTE Pointer from where the outgoing data are read.
numBytes UDINT The number of bytes to read from pt_source and write to
the session.

Return Value
IEC 61131 Type Description
UDINT The number of bytes written to the session.

I_SessionManager
This interface defines a set of methods for an object that is able to manage multiple I_-
SessionProvider objects and their sessions.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


numSessions UDINT R The total number of sessions managed by this
object.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.5
Interfaces

AddSessionProvider (Method)
Adds an I_SessionProvider to this session manager.

Inputs
Name IEC 61131 Type Description
sessionProvider I_SessionProvider The object that is providing sessions to be managed.

Return Value
IEC 61131 Type Description
BOOL TRUE if the session provider was successfully added to the session man-
ager. FALSE if an error occurred.

NextSession (Method)
Iterates over all I_Session objects referenced within the session manager and returns the
next session.

Return Value
IEC 61131 Type Description
I_Session Reference to the next session object.

Run (Method)
This method processes all session activity and must be called once per scan.

I_SessionProvider
This interface defines a set of methods for an object that can provide I_Session objects to
an I_SessionManager object.

GetSessions (Method)
Provides pointers to all I_Session objects available from this provider.

Date Code 20190830 Instruction Manual Programming Reference


26.6 SELServerSimulators
Interfaces

Inputs/Outputs
Name IEC 61131 Type Description
sessionVector class_PointerVector All I_Session references in the session provider are writ-
ten to this vector.

Run (Method)
This method processes all session activity and must be called once per scan.

I_SELServerPoint
This interface defines common methods for all analog and digital points.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


PointName STRING R The name of the point.
PointType enum_PointType R The type of the point.
stValAsString STRING R The point value as a string.

I_SELServerAnalogPoint
This interface defines common methods unique to analog points. This interface extends
I_SELServerPoint.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


ChannelType BYTE R The channel type of the point.
ScaleFactorOffset WORD R The scale factor offset of the point.
ScaleFactorType BYTE R The scale factor type of the point.
stValAsInt INT R The point value as an integer.
stValAsLreal LREAL R The point value as a long real.
stValAsReal REAL R The point value as a real.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.7
Classes

Classes
class_TelnetServer
This object implements a Telnet server. This server will create and manage an internal
object for each Telnet session. These internal objects implement I_Session and can be
accessed via the I_SessionProvider interface. This server is not intended to be used as a
generic Telnet server and should only be used within the context of this library.
This Telnet server automatically attempts to negotiate the following Telnet features:
ä Binary Transmission
ä Suppress Go Ahead
ä Echo
No other Telnet features are supported.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SessionProvider

Initialization Inputs
Name IEC 61131 Type Description
listenIP STRING(15) The local IP address for the server to listen on. Set to
0.0.0.0 to listen on all available interfaces.
listenPort UINT The local port number on which the server listens.
numSessions USINT The maximum number of Telnet sessions to support.

Destroy (Method)
This method deallocates all memory allocated by this object. This method must be called
before the object goes out of scope, otherwise a memory leak will result.

Return Value
IEC 61131 Type Description
BOOL TRUE if all memory was successfully deallocated.

Date Code 20190830 Instruction Manual Programming Reference


26.8 SELServerSimulators
Classes

class_SELServerInt16
This class defines an analog point represented as a 16-bit integer value.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerAnalogPoint

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


stVal INT R/W The value of the point.

Initialize (Method)
This method initializes the point.

Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal INT The initial stVal of the point.
scaleFactorType BYTE The scale factor type for the point.
scaleFactorOffset WORD The scale factor offset for the point.

class_SELServerFloat32
This class defines an analog point represented as a 32-bit floating point value.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.9
Classes

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerAnalogPoint

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


stVal REAL R/W The value of the point.

Initialize (Method)
This method initializes the point.

Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal REAL The initial stVal of the point.
scaleFactorType BYTE The scale factor type for the point.
scaleFactorOffset WORD The scale factor offset for the point.

class_SELServerFloat64
This class defines an analog point represented as a 64-bit floating point value.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerAnalogPoint

Date Code 20190830 Instruction Manual Programming Reference


26.10 SELServerSimulators
Classes

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).

Name IEC 61131 Type Access Description


stVal LREAL R/W The value of the point.

Initialize (Method)
This method initializes the point.

Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal LREAL The initial stVal of the point.
scaleFactorType BYTE The scale factor type for the point.
scaleFactorOffset WORD The scale factor offset for the point.

class_SELServerDigital
This class defines a digital point.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerPoint

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


stVal BOOL R/W The value of the point.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.11
Classes

Initialize (Method)
This method initializes the point.

Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal INT The initial stVal of the point.
index UINT The index value for the digital point. This is used for deter-
mining the order of the Relay Word bits. The index is zero
for the MSB in Row 0, 8 for the MSB in Row 1, etc.

class_SELServerString
This class defines a point represented as a string.

Implemented Interfaces
An interface defines a required set of functionality as methods and properties. As an im-
plementer of any interface all methods and properties declared in that interface must exist
as members of this class. This allows multiple generally unrelated classes to be used inter-
changeably for a specific feature set.
ä I_SELServerPoint

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


stVal STRING R/W The value of the point.

Initialize (Method)
This method initializes the point.

Inputs
Name IEC 61131 Type Description
pointName STRING The name of the point.
initialStVal STRING The initial stVal of the point.

Date Code 20190830 Instruction Manual Programming Reference


26.12 SELServerSimulators
Classes

class_SEL351ServerSimulator
This class implements a server simulating an SEL-351 relay with firmware version R515.
The following ASCII commands are supported:

ä 2AC ä CAL ä CHI ä ID


ä ACC ä CAS ä DNA ä QUIT
ä BNA ä CEV ä EXIT ä SNS

The following binary commands are supported:

ä A546 ä A5C1 ä A5CD ä A5D2


ä A5B9 ä A5C2 ä A5CE ä A5D3
ä A5C0 ä A5C3 ä A5D1

Some commands have optional parameters that may not be supported by the simulator.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


RefNum UINT R/W The reference number for the next event. This
value will be incremented by the simulator each
time an event is created.

Input

Inputs
Name IEC 61131 Type Description
Analog struct_SEL351_Analog Analog points for an SEL-351.
Binary struct_SEL351_Binary Relay Word bits for an SEL-351.
Strings struct_SEL351_String Strings for an SEL-351.

Outputs
Name IEC 61131 Type Description
ENO BOOL TRUE if the simulator is initialized and enabled. FALSE if ini-
tialization failed or an error occurred during runtime.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.13
Classes

bootstrap_AddSessionManager
This method assigns the session manager that will manage all I_Session objects for this
simulator. This method assumes that the session manager already contains all desired ses-
sions. Once a session manager is added here, more session providers should not be added
to the session manager.

Inputs
Name IEC 61131 Type Description
sessionManager I_SessionManager The session manager containing I_Session objects for
the simulator.

CreateEvent (Method)
This method creates a new event within the simulator. When the event is created, it will be
automatically assigned the next available record number. The event created by this method
will contain four samples per cycle. The analog values, Relay Word bit values, and relay
settings will consist of internal hard-coded values and will not match the values already set
in the simulator.

Inputs
Name IEC 61131 Type Description
refNum UINT Reference number of the event
event STRING(8) Type of event
location REAL Location of the fault
current UINT Peak current detected during the fault
group USINT Group number
shot UINT Number of reclose events
targets STRING Target elements for the event

Return Value
IEC 61131 Type Description
BOOL TRUE if the event was successfully created.

DeleteEvent (Method)
This method deletes an event from the simulator that was created with CreateEvent().

Date Code 20190830 Instruction Manual Programming Reference


26.14 SELServerSimulators
Examples

Inputs
Name IEC 61131 Type Description
recNum UINT The record number for the event as provided by the CHI com-
mand.

Return Value
IEC 61131 Type Description
BOOL TRUE if the event was successfully deleted. FALSE if the event did not
exist or an error occurred.

Destroy (Method)
This method deallocates all memory allocated by this object. This method must be called
before the object goes out of scope; otherwise, a memory leak will result.

Return Value
IEC 61131 Type Description
BOOL TRUE if all memory was successfully deallocated.

Run (Method)
This method handles processing communication between the server and all connected
clients. This method must be called once per scan.

Processing
The Run() method does the following:
ä Reads any pending requests from clients.
ä If a valid command is received, the applicable response is generated and sent to the
client.

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.15
Examples

Simulating an SEL-351
Objective
This example creates a simulator for an SEL-351 Relay on an RTAC. Changing analog and
digital values is also demonstrated.

Assumptions
This example assumes that an Access Point has been defined for TCP Port 23 on the RTAC.
This is necessary for the simulator to communicate via Telnet to other RTACs or to a user’s
interactive Telnet session.

Solution
The program shown in Code Snippet 26.1 shows a minimal example of running a simulator
of the SEL-351. This example instantiates a Telnet server that can handle as many as ten
simultaneous connections. On the first scan, the system frequency of the simulator is set
to 60 Hz and the daylight-saving time Relay Word bit is set to TRUE.

Code Snippet 26.1 prg_SEL351


PROGRAM prg_SEL351
VAR
// Create a Telnet server. The server will bind to any available IP
// address. The server will listen on port 23 and allow up to 10
// simultaneous connections.
TelnetServer : class_TelnetServer('0.0.0.0', 23, 10);
// Create the session manager for the simulator.
SessionManager : class_SessionManager();
// The SEL-351 simulator object.
Sel351 : class_SEL351ServerSimulator();
FirstScan : BOOL := TRUE;
END_VAR

IF FirstScan then
// Add the Telnet server as a session provider to the session manager.
SessionManager.AddSessionProvider(TelnetServer);
// Add the session manager to the SEL-351 simulator.
Sel351.bootstrap_AddSessionManager(SessionManager);
// Set the simulator frequency to 60 Hz.
Sel351.Analog._FREQ.stVal := 60;
// Set the daylight saving time Relay Word bit to true.
Sel351.Binary._DST.stVal := TRUE;
FirstScan := FALSE;
END_IF

// Process communication on each scan.


Sel351.Run();

Date Code 20190830 Instruction Manual Programming Reference


26.16 SELServerSimulators
Examples

Simulating Multiple SEL-351 Relays


Objective
This example creates two simulators for SEL-351 Relays on a single RTAC.

Assumptions
This example assumes that an Access Point has been defined for TCP Port 23 on the RTAC.
This is necessary for the simulators to communicate via Telnet to other RTACs or to a user’s
interactive Telnet session. For this example, it is necessary to use two network interfaces
on the RTAC, one with the IP address 192.168.0.100 and the other with 192.168.1.100.

Solution
The program shown in Code Snippet 26.2 shows an example of running two distinct SEL-351
simulators on the same RTAC. One simulator listens on the network interface with the IP
address 192.168.0.100 and the other listens on the second interface with address 192.168.1.100.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.17
Examples

Code Snippet 26.2 prg_SEL351


PROGRAM prg_SEL351
VAR
// Create a Telnet server for each relay. Each server binds to a
specific
// IP address. Both servers listen on port 23 and allow up to 10
// simultaneous connections.
TelnetServer1 : class_TelnetServer('192.168.0.100', 23, 10);
TelnetServer2 : class_TelnetServer('192.168.1.100', 23, 10);
// Create a session manager for each simulator.
SessionManager1 : class_SessionManager();
SessionManager2 : class_SessionManager();
// The SEL-351 simulator objects.
Sel351_1 : class_SEL351ServerSimulator();
Sel351_2 : class_SEL351ServerSimulator();
FirstScan : BOOL := TRUE;
END_VAR

IF FirstScan then
// Add a Telnet server as a session provider to the respective session
manager.
SessionManager1.AddSessionProvider(TelnetServer1);
SessionManager2.AddSessionProvider(TelnetServer2);
// Add the respective session manager to the SEL-351 simulator.
Sel351_1.bootstrap_AddSessionManager(SessionManager1);
Sel351_2.bootstrap_AddSessionManager(SessionManager2);
// Set the first simulator frequency to 60 Hz.
Sel351_1.Analog._FREQ.stVal := 60;
// Set the second simulator frequency to 50 Hz.
Sel351_2.Analog._FREQ.stVal := 50;
FirstScan := FALSE;
END_IF

// Process communication on each scan.


Sel351_1.Run();
Sel351_2.Run();

Simulating an SEL-351 on Multiple Ports


Objective
This example creates a simulator for an SEL-351 relay on an RTAC that listens on multiple
network ports.

Assumptions
This example assumes that an Access Point has been defined for TCP Ports 23 and 8023 on
the RTAC. This is necessary for the simulator to communicate via Telnet to other RTACs
or to a user’s interactive Telnet session.

Date Code 20190830 Instruction Manual Programming Reference


26.18 SELServerSimulators
Examples

Solution
The program shown in Code Snippet 26.3 shows an example of running a simulator of the
SEL-351 that listens on Ports 23 and 8023. This example instantiates two Telnet servers,
one on each port, that can handle as many as ten simultaneous connections each. Connec-
tions to these simulators will be allowed on all network interfaces.

Code Snippet 26.3 prg_SEL351


PROGRAM prg_SEL351
VAR
// Create a Telnet server. The server will bind to any available IP
// address. The server will listen on port 23 and allow up to 10
// simultaneous connections. Connections will be accepted on all
interfaces
// due to the 0.0.0.0 IP address.
TelnetServer1 : class_TelnetServer('0.0.0.0', 23, 10);
// Create another server to listen on port 8023.
TelnetServer2 : class_TelnetServer('0.0.0.0', 8023, 10);
// Create the session manager for the simulator.
SessionManager : class_SessionManager();
// The SEL-351 simulator object.
Sel351 : class_SEL351ServerSimulator();
FirstScan : BOOL := TRUE;
END_VAR

IF FirstScan then
// Add both Telnet servers as session providers to the session manager.
SessionManager.AddSessionProvider(TelnetServer1);
SessionManager.AddSessionProvider(TelnetServer2);
// Add the session manager to the SEL-351 simulator.
Sel351.bootstrap_AddSessionManager(sessionManager);
FirstScan := FALSE;
END_IF

// Process communication on each scan.


Sel351.Run();

Creating Events on an SEL-351 Simulator


Objective
This example creates a simulator and an event for an SEL-351 Relay on an RTAC. After
adding an event, it can be viewed by issuing a CHI or CEV command via Telnet.

Assumptions
This example assumes that an Access Point has been defined for TCP Port 23 on the RTAC.
This is necessary for the simulator to communicate via Telnet to other RTACs or to a user’s
interactive Telnet session.

Programming Reference Instruction Manual Date Code 20190830


SELServerSimulators 26.19
Examples

Solution
The program shown in Code Snippet 26.4 shows a minimal example of running a simulator
of the SEL-351 and adding an event. This example instantiates a Telnet server that can
handle as many as ten simultaneous connections. On the first scan, an event is created.
The event date and time will be set to the present date and time of the RTAC system.

Code Snippet 26.4 prg_SEL351


PROGRAM prg_SEL351
VAR
// Create a Telnet server. The server will bind to any available IP
// address. The server will listen on port 23 and allow up to 10
// simultaneous connections.
TelnetServer : class_TelnetServer('0.0.0.0', 23, 10);
// Create the session manager for the simulator.
SessionManager : class_SessionManager();
// The SEL-351 simulator object.
Sel351 : class_SEL351ServerSimulator();
FirstScan : BOOL := TRUE;
END_VAR

IF FirstScan then
// Add the Telnet server as a session provider to the session manager.
SessionManager.AddSessionProvider(TelnetServer);
// Add the session manager to the SEL-351 simulator.
Sel351.bootstrap_AddSessionManager(SessionManager);
// Add an event to the simulator. The reference number is 1, type is
TRIG,
// location of zero, maximum current of zero, group 1, shot 1, and no
// targets. Other event values are set automatically.
Sel351.CreateEvent(1, 'TRIG', 0, 0, 1, 1, '');
FirstScan := FALSE;
END_IF

// Process communication on each scan.


Sel351.Run();

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 27

SELString
Introduction
The purpose of this library is to provide a single object for performing string manipulations.
It is intended to allow for a variety of string manipulations without requiring lengths to be
predefined.
References to ASCII characters within this document are given in base-10. Whitespace for
the scope of this document includes the following: spaces (32), tabs (9), and newlines (10).
Invalid Characters are any characters that fall in the ASCII range 0–8, 11–27, or ≥127.
This document refers to iterator methods in a state called locked out. This refers to the state
of the object being such that the user cannot retrieve non-NULL(0) values from Next() or
Previous() without a new call to Begin(), End(), or Position().

Special Considerations
ä To improve performance, this library manages a preallocated memory block for char-
acters and SELString objects. To ensure proper functionality of the objects here, the
Clear() methods of both SELString and SELStringList objects must be called be-
fore that object goes out of scope. For example, an SELString declared in the header
of a function must have Clear() called on it before the end of the function. Vari-
ables instantiated in programs or global variable lists have permanent scope and do
not need to be cleared unless it is desired to empty the data from them.
ä This library expects that all SELString objects are used exclusively within a single
IEC 61131 task. Using this library to instantiate objects on multiple tasks will create
undesired behavior. For example, if you instantiate a class_SELString on the Main
task of an RTAC, do not also instantiate a class_SELString on the automation task.
ä Copying a class_SELString will cause undesired behavior. This means:
1. The assignment operator “:=” must not be used on a class_SELString. Con-
sider assigning a pointer to the class_SELString instead.
2. class_SELString objects must never be VAR_INPUT or VAR_OUTPUT mem-
bers in function blocks, functions, or methods. Place them in the VAR_IN_-
OUT section or use pointers instead.
ä This library can return NULL(0) pointers. Any pointer returned by the library should
be validated to be non-NULL(0) before use, as shown in Code Snippet 27.5.

Date Code 20190830 Instruction Manual Programming Reference


27.2 SELString
Functions

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.3 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.

Name IEC 61131 Type Value Description


g_p_MaxIec61131StringSize UINT 255 The largest size IEC 61131
string that this library can con-
vert from/to.
g_p_SELStringInitialSize UDINT 80 The number of bytes to initially
allocate for a class_SELString.

Functions
fun_SELString_IsValidChar (Function)
This function takes a character in the form of a BYTE and returns FALSE if it is an invalid
character; otherwise, this function returns TRUE.

Inputs
Name IEC 61131 Type Description
char BYTE Character to be evaluated for being valid.

Return Value
IEC 61131 Type Description
BOOL TRUE if char is a valid character.

Processing
If char is an invalid character, this function returns FALSE; otherwise, this function returns
TRUE.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.3
Classes

fun_SELString_IsWhitespace (Function)
This function takes a character in the form of a BYTE and returns TRUE if it is a whitespace
character; otherwise, this function returns FALSE.

Inputs
Name IEC 61131 Type Description
char BYTE Character to be evaluated for being whitespace.

Return Value
IEC 61131 Type Description
BOOL TRUE if char is a whitespace character.

Processing
ä If char is a whitespace character, this function returns TRUE; otherwise, this function
returns FALSE.

Classes
class_SELString (Class)
class_SELString exists as the single class required to perform string manipulations. This
class maintains a sequence of characters and is initialized to an empty set of characters.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


Size UDINT R The number of characters in this class_SELString.

FromString (Method)
This method takes an IEC 61131 string, str, as an input to be stored within the class_-
SELString.

Date Code 20190830 Instruction Manual Programming Reference


27.4 SELString
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string to be stored and ma-
nipulated within the SELString.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The FromString method performs the following:
ä Accepts any valid IEC 61131 string up to g_p_MaxIec61131StringSize characters
in size.
ä Accepts all characters from the beginning of str until an invalid character, an end-
of-string character, or g_p_MaxIec61131StringSize characters are reached; and no
following characters.
ä Replaces all current characters within class_SELString with characters from str.
ä Populates all available characters with the leading characters in str if the library runs
out of memory. In this case, this method returns a pointer to an error string.
ä Returns 0 on success.

FromByteArray (Method)
This method takes a pointer to the beginning of a byte array and the number of bytes to be
copied. It then stores the byte array within the class_SELString object. This method stores
any values represented in the byte array—it does not check for valid characters.

Inputs
Name IEC 61131 Type Description
pt_byteArray POINTER TO BYTE The address returned by calling ADR() on the byte array
to copy data from.
numBytes UDINT The number of bytes to be copied from the byte array.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.5
Classes

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The FromByteArray method performs the following:
ä Accepts all characters from the beginning of pt_byteArray until numBytes bytes.
ä Replaces all current characters within this class_SELString with bytes from pt_-
byteArray.
ä Populates all available characters with the leading bytes in pt_byteArray if the library
runs out of memory and returns a pointer to an applicable error string.
ä Returns 0 on success.

ToString (Method)
This method outputs an IEC 61131 string representation of the data being stored within the
SELString.

Return Value
IEC 61131 Type Description
STRING(g_p_MaxIec61131StringSize) An IEC 61131 string equivalent of the data stored
within the SELString.

Processing
The ToString method:
ä Returns an IEC 61131 string, up to g_p_MaxIec61131StringSize characters in size,
that represents the first g_p_MaxIec61131StringSize characters of this class_SEL-
String.
ä If nothing has been assigned to this class_SELString, then the return value is an
empty IEC 61131 string.
ä The character immediately following the last character inserted into the IEC 61131
string is a string terminator character.

ToByteArray (Method)
This method copies the contents of the class_SELString to the address provided. It stops
copying once maxBytes is reached or the class_SELString is completely copied.

Date Code 20190830 Instruction Manual Programming Reference


27.6 SELString
Classes

Inputs
Name IEC 61131 Type Description
pt_destination POINTER TO BYTE The destination to which the content is copied.
maxBytes UDINT The maximum number of bytes to copy.

Return Value
IEC 61131 Type Description
UDINT The number of bytes successfully copied to the destination.

Processing
The ToByteArray method:
ä Writes the contents of the class_SELString to the address provided.
ä Copying stops when one of the following occurs:
1. The number of bytes copied is equal to maxBytes.
2. All bytes in the class_SELString have been copied.
ä The number of bytes copied before encountering one of the above criteria is returned
as an integer. This will be 0 if class_SELString is empty or maxBytes is 0.
ä No termination byte is appended.

Replace (Method)
This method replaces every occurrence of the string before with the string after.

Inputs/Outputs
Name IEC 61131 Type Description
before class_SELString The class_SELString containing the combination of characters
to be replaced.
after class_SELString The class_SELString containing the combination of characters
that will replace all characters of before.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.7
Classes

Processing
The Replace method:
ä Does not modify before or after.
ä Is case sensitive.
ä Replaces all occurrences of before with after in a single pass. This prevents an in-
finite loop in cases like before=“abc” and after=“abcabc” and produces a reliable
output in cases like before=“abcbcbef” and after=“bcb”.
ä If before or after is this object, then this method leaves all objects unchanged. It then
returns a pointer to an applicable IEC 61131 error string.
ä If the library runs out of memory, this method exits immediately in an undefined
state. It returns a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.

Split (Method)
This method splits the class_SELString into multiple class_SELStrings wherever sep oc-
curs and places the result in a class_SELStringList.

Inputs/Outputs
Name IEC 61131 Type Description
sep class_SELString The combination of characters defining where the string will
split.
stringlist class_SELStringList The string list to be populated.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The Split method:
ä Creates divisions at every occurrence of sep. For example:
â In “tgeadadagt”, using a sep of “ada” results in “tge”, “dagt”.
â In “tgeadadagt”, using a sep of “ad” results in “tge”, “”, “agt”.
â In “decide”, using a sep of “de” results in “”, “ci”, “”.
ä Is case sensitive.
ä If the class_SELString was never assigned a string or contains an empty string, it
fills stringlist with only an empty string in the first position.
ä Erases any prior contents of stringlist.

Date Code 20190830 Instruction Manual Programming Reference


27.8 SELString
Classes

ä If sep does not exist in this class_SELString, it places the full class_SELString into
the first position.
ä If sep is empty, it places each character of this class_SELString into its own string.
Example: “Hello” becomes: “H”, “e”, “l”, “l”, “o”.
ä Adds substrings to stringlist in order from left to right.
ä Empties this class_SELString object.
ä If sep is this object, leaves all objects unchanged. It then returns a pointer to an
applicable IEC 61131 error string.
ä If sep or this object exist within stringlist, it leaves all objects unchanged. It then
returns a pointer to an applicable IEC 61131 error string.
ä If the library runs out of memory, it assigns as many class_SELStrings to stringlist
as available, clearing itself of all characters that were transferred. All characters not
transferred to new class_SELStrings remain in this class_SELString. It then returns
a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.

Trim (Method)
This method removes excess whitespace from this class_SELString. In this method, whites-
pace includes any character that results in TRUE being returned from fun_SELString_-
IsWhitespace.

Processing
The Trim method performs the following:
ä Removes all whitespace from the beginning of the string to the first non-whitespace
character.
ä Removes all whitespace from the last non-whitespace character to the end of the
string.
ä Replaces any number of consecutive whitespace characters with a single space char-
acter.
ä Leaves a class_SELStrings containing no whitespace and empty strings unchanged.
ä Replaces strings containing only whitespace with an empty string.

Append (Method)
This method appends the input, str, onto the end of this class_SELString. The input, str, is
empty upon completion of this method.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.9
Classes

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that will be ap-
pended to this class_SELString.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The Append method:
ä Adds all characters from str after the last character of this class_SELString.
ä Removes all characters from str.
ä If this class_SELString is empty, moves the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in either class_SELString.
ä Changes nothing if str is this object. It then returns a pointer to an applicable
IEC 61131 error string.
ä Always appends as many characters as possible. If the library runs out of memory,
str is empty upon completion and it returns a pointer to an applicable IEC 61131
error string.
ä Returns 0 on success.

AppendString (Method)
This method appends the characters of the input, str, onto the end of this class_SELString.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters that will be appended to this class_-
SELString.

Date Code 20190830 Instruction Manual Programming Reference


27.10 SELString
Classes

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The AppendString method:
ä Adds all characters from str after the last character of this class_SELString.
ä If this class_SELString is empty, adds the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in this class_SELString.
ä Always appends as many characters as possible. If the library runs out of memory,
it returns a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.

Prepend (Method)
This method prepends the input, str, onto the beginning of this class_SELString. The input,
str, is empty upon completion of this method.

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters to be prepended
to this class_SELString.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The Prepend method:
ä Adds all characters from str before the first character of this class_SELString.
ä Removes all characters from str.
ä If this class_SELString is empty, moves the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in either class_SELString.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.11
Classes

ä Changes nothing if str is this object. It then returns a pointer to an applicable


IEC 61131 error string.
ä If the library runs out of memory, leaves all objects unchanged and returns a pointer
to an applicable IEC 61131 error string.
ä Returns 0 on success.

PrependString (Method)
This method prepends the characters of the input, str, to the beginning of this class_SEL-
String.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters to be prepended to this class_SEL-
String.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The PrependString method:
ä Adds all characters from str before the first character of this class_SELString.
ä If this class_SELString is empty, adds the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in this class_SELString.
ä If the library runs out of memory, leaves all objects unchanged and returns a pointer
to an applicable IEC 61131 error string.
ä Returns 0 on success.

Insert (Method)
This method inserts the input class_SELString, str, into this class_SELString at the index
specified by the user. The input str is empty upon completion of this method.

Date Code 20190830 Instruction Manual Programming Reference


27.12 SELString
Classes

Inputs
Name IEC 61131 Type Description
index UDINT The index where str will be inserted.

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that will be in-
serted to this class_SELString.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The Insert method:
ä Inserts at index, where an index of zero corresponds to immediately before the first
character and is incremented by one for each character thereafter.
ä Removes all characters from str.
ä Inserts all characters from str into this class_SELString at position index.
ä If index is larger than the size of this class_SELString, appends str at the end of this
class_SELString.
ä If this class_SELString is empty, moves the characters from str to this class_SEL-
String.
ä If str is empty, changes nothing in either class_SELString.
ä Changes nothing if str is this object. It then returns a pointer to an applicable
IEC 61131 error string.
ä If the library runs out of memory, places all characters of str into this class_SEL-
String, truncates the result, and returns a pointer to an applicable IEC 61131 error
string.
ä Returns 0 on success.

Find (Method)
This method returns the first position after the provided index where the character combi-
nation provided in str exists. If the character combination does not exist after the provided
index, a –1 is returned.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.13
Classes

Inputs
Name IEC 61131 Type Description
index UDINT The index where this class_SELString will begin to search.

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString containing the characters that are being
searched for within this class_SELString.

Return Value
IEC 61131 Type Description
DINT The index of the first match of str within this object. If str cannot be found,
this method will return ‘–1’. (This value is always ≥ ‘–1’)

Processing
The Find method:
ä Begins its search at index, where an index of zero corresponds to immediately before
the first character and is incremented by one for each character thereafter. The same
is true of the return value.
ä Is case sensitive.
ä Returns the index of the first occurrence of str appearing after the given index.
ä If index is larger than the size of this class_SELString, returns –1.
ä If str cannot be found, returns –1.
ä If str is empty, returns –1.
ä If str is this object, then –1 is returned.

FindString (Method)
This method returns the first position after the provided index where the character combi-
nation provided in str exists. If the character combination does not exist after the provided
index, a –1 is returned.

Date Code 20190830 Instruction Manual Programming Reference


27.14 SELString
Classes

Inputs
Name IEC 61131 Type Description
index UDINT The index where this class_SELString will begin to search.

Inputs/Outputs
Name IEC 61131 Type Description
str STRING(g_p_MaxIec61131StringSize) The IEC 61131 string containing the char-
acters that are being searched for within
this class_SELString.

Return Value
IEC 61131 Type Description
DINT The index of the first match of str within this object. If str cannot be found,
this method will return –1. (This value is always ≥ –1)

Processing
The FindString method:
ä Begins its search at index, where an index of zero corresponds to immediately before
the first character and is incremented by one for each character thereafter. The same
is true of the return value.
ä Is case sensitive.
ä Returns the index of the first occurrence of str appearing after the given index.
ä If index is larger than the size of this class_SELString, returns –1.
ä If str cannot be found, returns –1.
ä If str is empty, returns –1.
ä If str system state prevents the search, then –1 is returned.

Clear (Method)
This method removes all character data from the class_SELString.

Processing
The Clear method:
ä Removes all character data within the class_SELString.
ä Resets the size of the class_SELString to zero.
ä Resets the return value of ToString to an empty string.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.15
Classes

ä Any used memory is returned to the library.

Item (Method)
This method returns the character at the requested index.

Inputs
Name IEC 61131 Type Description
index UDINT The index of the character being requested.

Return Value
IEC 61131 Type Description
BYTE The ASCII value of the character at the requested index. If index is out of
range, returns NULL(0).

Processing
The Item method:
ä Treats the first character as index zero with each additional character being an addi-
tion of one.
ä Returns the character positioned at the user requested index.
ä If index is greater than or equal to the number of characters in this class_SELString,
returns NULL.
ä Returns NULL on an empty string.

Begin (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the first character of this class_SELString object.

Processing
The Begin method places the iterator such that:
ä The iterator is not locked out.
ä A subsequent Next() returns the first character.
ä A subsequent Previous() returns NULL and leaves the iterator locked out.
ä For an empty string, Next() and Previous() return NULL and leave the iterator
locked out.

Date Code 20190830 Instruction Manual Programming Reference


27.16 SELString
Classes

End (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator immediately after the last character of this class_SELString object.

Processing
The End method places the iterator such that:
ä The iterator is not locked out.
ä A subsequent Previous() returns the last character.
ä A subsequent Next() returns NULL and leaves the iterator locked out.
ä For an empty string Next() and Previous() return NULL and leave the iterator
locked out.

Position (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the character at index.

Inputs
Name IEC 61131 Type Description
index UDINT The location where the character iterator will be assigned.

Processing
The Position method places the iterator such that:
ä The first character in the class_SELString is index zero with each additional character
being an addition of one.
ä An index greater than or equal to the number of characters in this class_SELString
leaves the iterator locked out.
ä Otherwise the iterator is not locked out.
ä A subsequent Next() returns the character at the provided index.
ä A subsequent Previous() returns the character immediately before the provided
index.
ä For an empty string Next() and Previous() return NULL and leave the iterator
locked out.

Next (Method)
This method is used in conjunction with Begin(), Position(), End(), and Previous().
This method returns the character at the current internal iterator position then increments
the iterator.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.17
Classes

Return Value
IEC 61131 Type Description
BYTE The ASCII value of the character at the current iterator position. If no
character exists, returns NULL(0).

Processing
The Next method:
ä Returns the character at the current internal iterator position and then increments the
iterator.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iterator
increments to a position greater than the number of characters in this class_SEL-
String.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().

Previous (Method)
This method is used in conjunction with Begin(), Position(), End(), and Next(). This
method decrements the current internal iterator position and then returns the character at
the new position.

Return Value
IEC 61131 Type Description
BYTE The ASCII value of the character at the decremented iterator position. If
no character exists, returns NULL(0).

Processing
The Next method performs the following:
ä Decrements the internal iterator position then returns the character new position.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iterator
decrements to a position less than index 0.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().

Date Code 20190830 Instruction Manual Programming Reference


27.18 SELString
Classes

class_SELStringList (Class)
class_SELStringList exists to store and perform operations on a list of strings using 0-based
indexing.

Properties
Properties are internal values made visible through Get and Set accessors. Access is de-
fined as R (read), W (write), or R/W (read/write).

Name IEC 61131 Type Access Description


Size UDINT R The number of class_SELString objects in this
class_SELStringList.

Append (Method)
This method adds the requested string to the end of the list.

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The string to be added to the end of the class_SELStringList.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The Append method:
ä Places str at the end of the current list (position zero for an empty list) and increments
the size of the list.
ä Empties the contents of str.
ä Allows empty strings to be added to the list.
ä If the object str is already a member of the list, empties the contents of str and places
the contents of str at the end of the list.
For example: If this list is [“dog”,“cat”,“bird”] and Item 1 (“cat”) is appended, the
new list is: [“dog”,“”,“bird”,“cat”].
ä If the library runs out of memory, it leaves this object and str unchanged and returns
a pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.19
Classes

Insert (Method)
This method inserts the requested string into the list at the position specified.

Inputs
Name IEC 61131 Type Description
index UDINT The location where str will be inserted.

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString to be inserted into the class_SEL-
StringList.

Return Value
IEC 61131 Type Description
POINTER TO STRING A pointer to an error string or zero on success.

Processing
The Insert method:
ä Places the index zero immediately before the first class_SELString and increments
by one for each string thereafter.
ä Empties the contents of str.
ä Allows empty strings to be added to the list.
ä When index is equal to the length of list or more, behaves the same as Append().
ä If the object str is already a member of the list, empties the contents of str and places
the contents of str at the requested location.
For example: If this list is [“dog”,“cat”,“bird”] and Item 0 (“dog”) is inserted at
Position 2, the new list is: [“”,“cat”,“dog”,“bird”].
ä Increases the size of the list by one.
ä If the library runs out of memory, removes the final class_SELString from this object
and inserts str at the desired index except in the case where str would be appended,
in which case the Insert method behaves the same as Append(). It then returns a
pointer to an applicable IEC 61131 error string.
ä Returns 0 on success.

RemoveLast (Method)
This method removes the last string in the list.

Date Code 20190830 Instruction Manual Programming Reference


27.20 SELString
Classes

Processing
The RemoveLast method performs the following:
ä Removes the last class_SELString from the class_SELStringList.
ä Decrements the size of the class_SELStringList.
ä Does nothing if the class_SELStringList is empty.
ä Returns the freed memory.

Clear (Method)
This method removes all class_SELString objects from the list.

Processing
The Clear method performs the following:
ä Removes all class_SELStrings in the class_SELStringList.
ä Sets the size of the class_SELStringList to zero.
ä Causes all other methods to respond that there are no objects in the list.
ä Returns the freed memory.

Item (Method)
This method returns a pointer to the class_SELString at the requested index.

Inputs
Name IEC 61131 Type Description
index UDINT The location of the desired string in the list.

Return Value
IEC 61131 Type Description
POINTER TO class_SELString A pointer to the class_SELString located at index. If index
does not exist, returns NULL(0).

Processing
The Item method performs the following:
ä Returns a pointer to the class_SELString that exists at index.
ä Returns NULL if index is outside the bounds of the list.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.21
Classes

Begin (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the first string in the list.

Processing
The Begin method places the iterator such that:
ä The iterator is not locked out.
ä A subsequent Next() returns the first string in the list.
ä A subsequent Previous() returns NULL and leaves the iterator locked out.
ä For an empty list Next() and Previous() return NULL and leave the iterator
locked out.

End (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator immediately after the last string in the list.

Processing
The End method places the iterator such that:
ä The iterator is not locked out.
ä A subsequent Next() returns NULL and leaves the iterator locked out.
ä A subsequent Previous() returns the first string in the list.
ä For an empty list Next() and Previous() return NULL and leave the iterator
locked out.

Position (Method)
This method is used in conjunction with Next() and Previous(). This method places
the internal iterator on the string at index.

Inputs
Name IEC 61131 Type Description
index UDINT List location of the desired string.

Processing
The Position method places the iterator such that:
ä The first string in the class_SELStringList is index zero with each additional string
being an addition of one.

Date Code 20190830 Instruction Manual Programming Reference


27.22 SELString
Classes

ä An index greater than or equal to the number of strings in this class_SELStringList


leaves the iterator locked out.
ä Otherwise the iterator is not locked out.
ä A subsequent Next() returns the string at the provided index.
ä A subsequent Previous() returns the string immediately before the provided index.
ä For an empty string list, Next() and Previous() return NULL and leave the iterator
locked out.

Next (Method)
This method is used in conjunction with Begin(), Position(), End(), and Previous().
This method returns the string at the current internal iterator position then increments the
iterator.

Return Value
IEC 61131 Type Description
POINTER TO class_SELString A pointer to the string at the current iterator position. If no
string exists, returns NULL(0).

Processing
The Next method performs the following:
ä Returns the string at the current internal iterator position and then increments the
iterator.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iter-
ator increments to a position greater than the number of strings in this class_SEL-
StringList.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().

Previous (Method)
This method is used in conjunction with Begin(), Position(), End(), and Next(). This
method decrements the internal iterator position and returns a pointer to the string at the
new position.

Return Value
IEC 61131 Type Description
POINTER TO class_SELString A pointer to the string at the decremented iterator position. If
no string exists, returns NULL(0).

Programming Reference Instruction Manual Date Code 20190830


SELString 27.23
Classes

Processing
The Previous method performs the following:
ä Decrements the internal iterator position and returns a pointer to the string at the new
position.
ä Returns NULL if the iterator is locked out.
ä Locks out the iterator for subsequent calls to Next() and Previous() if the iterator
decrements below position 0.
ä Locks out the iterator if any method other than Next() or Previous() has been
called since the last Begin(), End(), or Position().

Join (Method)
This method creates a single string containing the full list of strings, each separated from
the other by the provided str. This object is empty upon successful completion.

Inputs/Outputs
Name IEC 61131 Type Description
str class_SELString The class_SELString to be inserted between each entry in the
class_SELStringList.

Return Value
IEC 61131 Type Description
class_SELString Returns a string containing all strings within the stringlist separated by str.

Processing
The Join method:
ä Returns a single string containing the full list of strings separated by str.
Example: If the class_SELStringList contains: [“b”,“n”,“n”,“s”] and str is “a” then
the return value is “bananas”.
ä Returns an empty string, if empty.
ä Returns a single string containing the full list of strings if str is an empty string.
For example: If the stringlist contains [“H”,“e”,“l”,“l”,“o”] and str is empty, the
return value is “Hello”.
ä Empties this class_SELStringList as per Clear().
ä If str is a member of this list, returns a valid class_SELString with undefined values.
ä If the library runs out of memory, returns a class_SELString containing all possi-
ble complete class_SELStrings in the list (strings will not be divided). This object
retains any strings not used in the Join.

Date Code 20190830 Instruction Manual Programming Reference


27.24 SELString
Benchmarks

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3530-4
â R132 firmware
ä SEL-3354
â Intel Pentium 1.4 GHz
â 1 GB DDR ECC SDRAM
â SEL-3532 RTAC Conversion Kit
â R132 firmware

Benchmark Test Descriptions class_SELString


The posted time for each test is the average execution time of 50 consecutive calls for the
test as described. The maximum number of characters used in any test was g_p_StringSize.
All times are recorded in microseconds.

FromString Replace
This test calls FromString() and replaces g_p_StringSize characters with g_p_StringSize
different characters.

FromString Populate
This test calls FromString() on an empty class_SELString and populates it with g_p_-
StringSize characters.

FromString Depopulate
This test calls FromString() on a class_SELString with g_p_StringSize characters and
populates it with zero characters.

ToString
This test calls ToString() on a class_SELString with g_p_StringSize characters.

FromByteArray Replace
This test calls FromString() and replaces g_p_StringSize characters with g_p_StringSize
different characters.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.25
Benchmarks

FromByteArray Populate
This test calls FromString() on an empty class_SELString and populates it with g_p_-
StringSize characters.

FromByteArray Depopulate
This test calls FromString() on a class_SELString with g_p_StringSize characters and
populates it with zero characters.

ToByteArray
This test calls ToString() on a class_SELString with g_p_StringSize characters.

Replace 1 Char Not Found


This test calls Replace() with a before of length one in a class_SELString of length g_-
p_StringSize without finding the result. It is designed to show the cost of a one-pass search
of a string.

Replace 1 Char Max Found


This test calls Replace() with a before of length one in a class_SELString of length g_-
p_StringSize, finding the result on every character. It is designed to show the cost of a
one-pass search and replace on a string.

Replace Max/2 Found


This test calls Replace() with a before of “aaaaaaab” and current of “aaaaaaaaaaaaaab”
but with sizes of g_p_StringSize/2 and g_p_StringSize respectively. It is designed to show
the cost of heavy recursive searching on a string.

Replace Max Char Found


This test calls Replace() with a before of “aaaaaaab” and current of “aaaaaaab” but with
sizes of g_p_StringSize. It is designed to show the cost of a one-pass ordered search on a
string.

Split 0 Char
This test calls Split() with an empty separator in a class_SELString of length g_p_-
StringSize. It is designed to show the cost of splitting a string into its constituent characters.

Date Code 20190830 Instruction Manual Programming Reference


27.26 SELString
Benchmarks

Split 1 Char Not Found


This test calls Split() with a one character separator in a length g_p_StringSize class_-
SELString without finding the result. It is designed to show the cost of a one-pass search
conversion of a string to a string list.

Split 1 Char Found


This test calls Split() with a one character separator in a length g_p_StringSize class_-
SELString, finding the result in every character. It is designed to show the cost of converting
a complete list to empty strings.

Split Max/2 Found


This test calls Split() with a sep of “aaaaaaab” and current of “aaaaaaaaaaaaab” but with
sizes of g_p_StringSize/2 and g_p_StringSize respectively. It is designed to show the cost
of heavy recursive searching and character removal using Split().

Split Max Found


This test calls Split() with a sep of “aaaaaaab” and current of “aaaaaaab” but with sizes of
g_p_StringSize. It is designed to show the cost of a one-pass ordered search and character
removal on a string using Split().

Trim No Whitespace
This test calls Trim() on a length g_p_StringSize class_SELString containing no whites-
pace. It is designed to show the cost of searching for whitespace.

Trim Every Other Whitespace


This test calls Trim() on a length g_p_StringSize class_SELString where every other char-
acter is whitespace. It is designed to show the cost of searching for and ignoring whitespace.

Trim All Whitespace


This test calls Trim() on a length g_p_StringSize class_SELString containing only whites-
pace. It is designed to show the cost of removal of whitespace.

Trim Half Whitespace


This test calls Trim() on a length g_p_StringSize class_SELString containing whitespace
to remove at the head, in the middle, and at the end of the class_SELString. It is designed
to show a more composite cost of whitespace removal.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.27
Benchmarks

Size
This test calls Size() on a length g_p_StringSize class_SELString.

Append
This test calls Append() with varying length class_SELString.

AppendString
This test calls AppendString() with a g_p_MaxIec61131StringSize length string.

Prepend
This test calls Prepend() with varying length class_SELString.

PrependString
This test calls PrependString() with a g_p_MaxIec61131StringSize length string.

Insert Either End


This test calls Insert() on the ends of a class_SELString.

Insert Middle
This test calls Insert() to place one character in the middle of a class_SELString.

Find 1 Char
This test calls Find() for a single character not found in a length g_p_StringSize class_-
SELString.

Find Max/2
This test calls Find() searching for “aaaaaaab” while having a current of “aaaaaaaaaaaaab”
but with sizes of g_p_StringSize/2 and g_p_StringSize respectively. It is designed to show
the cost of heavy recursive searching using Find().

Find Max
This test calls Find() searching for a length g_p_StringSize string inside a length g_p_-
StringSize class_SELString.

Date Code 20190830 Instruction Manual Programming Reference


27.28 SELString
Benchmarks

FindString 1 Char
This test calls FindString() for a single character not found in a length g_p_StringSize
class_SELString.

FindString Max/2
This test calls FindString() searching for “aaaaaaab” of size g_p_StringSize/2 while
having a current of “aaaaaaaaaaaaab” or size of g_p_StringSize. It is designed to show the
cost of heavy recursive searching using FindIecString().

FindString Max
This test calls FindString() searching for a length g_p_StringSize string inside a length
g_p_StringSize class_SELString.

Clear
This test calls Clear() on a class_SELString of length g_p_StringSize.

Item Either End


This test calls Item() on both ends of a length g_p_StringSize class_SELString.

Item Middle
This test calls Item() requesting the middle of a length g_p_StringSize class_SELString.

Begin
This test calls Begin().

End
This test calls End() on a length g_p_StringSize class_SELString.

Position Either End


This test calls Position() on both ends of a length g_p_StringSize class_SELString.

Position Middle
This test calls Position() requesting the middle of a length g_p_StringSize class_SEL-
String.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.29
Benchmarks

Next
This test calls Next() while both locked out and responsive.

Previous
This test calls Previous() while both locked out and responsive.

Benchmark Results class_SELString


Platform (time in µs)
Operation Tested
SEL-3354 SEL-3530
FromString Replace 9 89
FromString Populate 45 274
FromString Depopulate 16 79
ToString 8 75
FromByteArray Replace 7 75
FromByteArray Populate 42 241
FromByteArray Depopulate 16 77
ToByteArray 7 65
Replace 1 Char Not Found 16 165
Replace 1 Char Max Found 70 701
Replace Max/2 Found 535 4701
Replace Max Char Found 19 181
Split 0 Char 103 633
Split 1 Char Not Found 17 176
Split 1 Char Found 127 951
Split Max/2 Found 534 4673
Split Max Found 25 169
Trim No Whitespace 11 87
Trim Every Other Whitespace 11 92
Trim All Whitespace 29 206
Trim Half Whitespace 20 155
Size 1 1
Append 1 4
AppendString 49 272
Prepend 1 4
PrependString 45 276
Insert Either End 2 4
Insert Middle 1 6
Find 1 Char 16 170
Find Max/2 521 4617
Find Max 8 71
FindString 1 Char 16 164
FindString Max/2 567 4796
FindString Max 67 430

Date Code 20190830 Instruction Manual Programming Reference


27.30 SELString
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3354 SEL-3530
Clear 16 77
Item Either End 1 1
Item Middle 1 4
Begin 1 1
End 1 1
Position Either End 1 1
Position Middle 1 4
Next 1 1
Previous 1 1

Benchmark Test Descriptions class_SELStringList


The posted time for each test is the average execution time of 50 consecutive calls for the
test as described. The maximum number of characters used in any test was g_p_StringSize.
A maximum size class_SELStringList tested was also g_p_StringSize long, each string
containing one character. All times were recorded in microseconds.

Append
This test calls Append() on a class_SELStringList of g_p_StringSize class_SELStrings.

Insert Either End


This test calls Insert() on both ends of a class_SELStringList of g_p_StringSize class_-
SELStrings.

Insert Middle
This test calls Insert() requesting the middle of a class_SELStringList of length g_p_-
StringSize.

RemoveLast
This test calls RemoveLast() on a class_SELStringList of g_p_StringSize class_SEL-
Strings.

Size
This test calls Size() on a class_SELStringList of g_p_StringSize class_SELStrings.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.31
Benchmarks

Clear 1 Large String


This test calls Clear() on a class_SELStringList of one class_SELString of length g_p_-
StringSize.

Clear Max Strings


This test calls Clear() on a class_SELStringList containing the g_p_StringSize number
of one character class_SELStrings.

Item Either End


This test calls Item() requesting both ends of a class_SELStringList containing the g_p_-
StringSize number of one character class_SELStrings.

Item Middle
This test calls Item() requesting the middle of a class_SELStringList containing g_p_-
StringSize number of one character class_SELStrings.

Begin
This test calls Begin().

End
This test calls End() on a class_SELStringList of g_p_StringSize class_SELStrings.

Position Either End


This test calls Position() requesting each end of a class_SELStringList containing g_-
p_StringSize class_SELStrings.

Position Middle
This test calls Position() requesting the middle class_SELString of a class_SELStringList
containing g_p_StringSize class_SELStrings.

Next
This test calls Next() while both locked out and responsive.

Date Code 20190830 Instruction Manual Programming Reference


27.32 SELString
Examples

Previous
This test calls Previous() while both locked out and responsive.

Join Max Empties


This test calls Join() with a str of length one on a class_SELStringList containing g_p_-
StringSize empty strings.

Join Max 1 Chars


This test calls Join() with a str of length zero on a class_SELStringList containing g_p_-
StringSize one character strings.
This test calls Join() with a str of length g_p_StringSize on a class_SELStringList con-
taining two empty strings.

Benchmark Results class_SELStringList


Platform (time in µs)
Operation Tested
SEL-3354 SEL-3530
Append 1 4
Insert Either End 1 5
Insert Middle 2 14
RemoveLast 17 80
Size 1 1
Clear 1 Large String 15 79
Clear Max Strings 59 372
Item Either End 1 1
Item Middle 1 4
Begin 1 1
End 1 1
Position Either End 1 2
Position Middle 1 4
Next 1 1
Previous 1 1
Join Max Empties 100 814
Join Max 1 Chars 103 930
Join Max Str 47 317

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.

Programming Reference Instruction Manual Date Code 20190830


SELString 27.33
Examples

Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

class_SELString Examples
The following examples demonstrate simple uses of class_SELString.

FromString

Code Snippet 27.1 SELString FromString Example


PROGRAM prg_FromStringExample
VAR
normalString : STRING := 'This is a normal string';
selString : class_SELString;
END_VAR

// Populate the selString with the contents of normalString.


selString.FromString(normalString);

ToString

Code Snippet 27.2 SELString ToString Example


PROGRAM prg_ToStringExample
VAR
normalString : STRING := 'This is a normal string';
selString : class_SELString;
END_VAR

// Populate the SELString.


selString.FromString('This is a string');
// Converts the SELString to a normal string.
normalString := selString.ToString();

FromByteArray ToByteArray
If data is being read-in from, or out to a communication buffer, it is likely to contain non-
printable characters that are deliberately ignored by the FromString and ToString methods.
This example shows how to accomplish the same thing, using the FromByteArray and
ToByteArray methods, which are able to accept all byte values.

Date Code 20190830 Instruction Manual Programming Reference


27.34 SELString
Examples

Code Snippet 27.3 SELString To/From ByteArray Example


PROGRAM prg_ToAndFromByteArrayExample
VAR CONSTANT
c_StringLength : UDINT := 80;
END_VAR
VAR
InputString : STRING(c_StringLength) := 'This is a normal string';
OuptutString : STRING(c_StringLength);
NumberBytesRead : UDINT;
SelString : class_SELString;
END_VAR

Code Snippet 27.3 SELString To/From ByteArray Example (Continued)


// Populate the SELString.
SelString.FromByteArray(ADR(InputString), c_StringLength);
// Converts the SELString to a byte array .
NumberBytesRead := SelString.ToByteArray(ADR(OuptutString),
c_StringLength);
// Append the null character on the end, since it is omitted by
// ToByteArray.
OuptutString[c_StringLength] := 0;

Replace

Code Snippet 27.4 SELString Replace Example


PROGRAM prg_ReplaceExample
VAR
normalString : STRING := 'This is a normal string';
selString : class_SELString;
before : class_SELString;
after : class_SELString;
END_VAR

// Create an SELString with the text to be replaced.


before.FromString('normal');
// Create an SELString with the desired replacement text.
after.FromString('SEL');
// Populate the SELString.
selString.FromString(normalString);
// Replace the text in the SELString. This SELString now contains
// 'This is a SEL string'.
selString.Replace(before, after);

Programming Reference Instruction Manual Date Code 20190830


SELString 27.35
Examples

Split

Code Snippet 27.5 SELString Split Example


PROGRAM prg_SplitExample
VAR
normalString : STRING := 'This is a normal string';
selString : class_SELString;
selStringSpace : class_SELString;
selStringList : class_SELStringList;

pt_FirstString : POINTER TO class_SELString;


pt_SecondString : POINTER TO class_SELString;

firstString : STRING;
secondString : STRING;
END_VAR

// Populate the SELString.


selString.FromString(normalString);
// Create an SELString containing the delimiter.
selStringSpace.FromString(' ');
// Split the SELString into a list of SELStrings, where each SELString in
// the list is a word from the original SELString.
selString.Split(selStringSpace, selStringList);
//Get the items from the list
pt_FirstString := selStringList.Item(0);
pt_SecondString := selStringList.Item(1);
//Dereference the pointers and convert to IEC 61131 Strings
//Check for a valid pointer before deference
IF 0 <> pt_FirstString THEN
firstString := pt_FirstString^.ToString();
ELSE
; //Error Message
END_IF

IF 0 <> pt_SecondString THEN


secondString := pt_SecondString^.ToString();
ELSE
; //Error Message
END_IF

Date Code 20190830 Instruction Manual Programming Reference


27.36 SELString
Examples

Trim

Code Snippet 27.6 SELString Trim Example


PROGRAM prg_TrimExample
VAR
selString : class_SELString;
END_VAR

// Populate the SELString.


selString.FromString(' This string has excess whitespace.
');
// Trim the extra whitespace, resulting in,
// 'This string has excess whitespace.'.
selString.Trim();

Size

Code Snippet 27.7 SELString Size Example


PROGRAM prg_SizeExample
VAR
selString : class_SELString;
size : UDINT;
END_VAR

// Populate the SELString.


selString.FromString('This is a string.');
// Get the size of the string.
size := selString.Size;

Append

Code Snippet 27.8 SELString Append Example


PROGRAM prg_AppendExample
VAR
firstString : class_SELString;
secondString : class_SELString;
END_VAR

// Populate the first string.


firstString.FromString('This is a ');
// Populate the second string.
secondString.FromString('string.');
// Append the second string to the first string.
firstString.Append(secondString);

Programming Reference Instruction Manual Date Code 20190830


SELString 27.37
Examples

Prepend

Code Snippet 27.9 SELString Prepend Example


PROGRAM prg_PrependExample
VAR
firstString : class_SELString;
secondString : class_SELString;
END_VAR

// Populate the first string.


firstString.FromString('This is a ');
// Populate the second string.
secondString.FromString('string.');
// Prepend the first string to the second string.
secondString.Prepend(firstString);

Insert

Code Snippet 27.10 SELString Insert Example


PROGRAM prg_InsertExample
VAR
firstString : class_SELString;
secondString : class_SELString;
END_VAR

// Populate the first string.


firstString.FromString('This is a string.');
// Populate the second string.
secondString.FromString('SEL ');
// Insert the first string into the second string.
firstString.Insert(10, secondString);

Find

Code Snippet 27.11 SELString Find Example


PROGRAM prg_FindExample
VAR
firstString : class_SELString;
secondString : class_SELString;
index : DINT;
END_VAR

// Populate the first string.


firstString.FromString('This is an SEL string.');
// Populate the second string.
secondString.FromString('SEL ');
// Find the index of the string 'SEL' in the first string.
index := firstString.Find(0, secondString);

Date Code 20190830 Instruction Manual Programming Reference


27.38 SELString
Examples

Clear

Code Snippet 27.12 SELString Clear Example


PROGRAM prg_ClearExample
VAR
selString : class_SELString;
END_VAR

// Populate the string.


selString.FromString('This is an SEL string.');
// Clear the contents of the string.
selString.Clear();

Item

Code Snippet 27.13 SELString Item Example


PROGRAM prg_ItemExample
VAR
selString : class_SELString;
character : BYTE;
END_VAR

// Populate the string.


selString.FromString('This is an SEL string.');
// Get the ASCII value of the character located at index 11.
character := selString.Item(11);

Begin, End, Position, Next, and Previous

Code Snippet 27.14 SELString Iterator Example


PROGRAM prg_IteratorExample
VAR
selString : class_SELString;
firstCharacter : BYTE;
middleCharacter : BYTE;
lastCharacter : BYTE;
END_VAR

// Populate the string.


selString.FromString('This is an SEL string.');
// Get the first character.
selString.Begin();
firstCharacter := selString.Next();
// Get a middle character.
selString.Position(11);
middleCharacter := selString.Next();
// Get the last character
selString.End();
lastCharacter := selString.Previous();

Programming Reference Instruction Manual Date Code 20190830


SELString 27.39
Examples

class_SELStringList Examples
The following examples demonstrate simple uses of class_SELStringList.

Size

Code Snippet 27.15 SELStringList Size Example


PROGRAM prg_SizeExample
VAR
selString : class_SELString;
selStringList : class_SELStringList;
listSize : UDINT;
END_VAR

// Populate the string.


selString.FromString('This is an SEL string.');
// Append the string to the string list.
selStringList.Append(selString);
// Get the size of the string list.
listSize := selStringList.Size;

Append

Code Snippet 27.16 SELStringList Append Example


PROGRAM prg_AppendExample
VAR
selString : class_SELString;
selStringList : class_SELStringList;
END_VAR

// Populate the string.


selString.FromString('This is an SEL string.');
// Append the string to the string list.
selStringList.Append(selString);

Insert

Code Snippet 27.17 SELStringList Insert Example


PROGRAM prg_InsertExample
VAR
selString1 : class_SELString;
selString2 : class_SELString;
selString3 : class_SELString;
selStringList : class_SELStringList;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


27.40 SELString
Examples

Code Snippet 27.17 SELStringList Insert Example (Continued)


// Populate the strings.
selString1.FromString('String 1');
selString2.FromString('String 2');
selString3.FromString('String 3');

// Append the strings to the list.


selStringList.Append(selString1);
selStringList.Append(selString2);
// Insert a string to the list at index 1.
selStringList.Insert(1, selString3);

RemoveLast

Code Snippet 27.18 SELStringList RemoveLast Example


PROGRAM prg_RemoveLastExample
VAR
selString1 : class_SELString;
selString2 : class_SELString;
selStringList : class_SELStringList;
END_VAR

// Populate the strings.


selString1.FromString('String 1');
selString2.FromString('String 2');

// Append the strings to the list.


selStringList.Append(selString1);
selStringList.Append(selString2);
// Remove the last string from the list.
selStringList.RemoveLast();

Clear

Code Snippet 27.19 SELStringList Clear Example


PROGRAM prg_ClearExample
VAR
selString1 : class_SELString;
selString2 : class_SELString;
selStringList : class_SELStringList;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


SELString 27.41
Examples

Code Snippet 27.19 SELStringList Clear Example (Continued)


// Populate the strings.
selString1.FromString('String 1');
selString2.FromString('String 2');

// Append the strings to the list.


selStringList.Append(selString1);
selStringList.Append(selString2);
// Clear all strings from the list
selStringList.Clear();

Item

Code Snippet 27.20 SELStringList Item Example


PROGRAM prg_ItemExample
VAR
selStringList : class_SELStringList;
firstString : class_SELString;
middleString : class_SELString;
lastString : class_SELString;

ptFirstString : POINTER TO class_SELString;


ptMiddleString : POINTER TO class_SELString;
ptLastString : POINTER TO class_SELString;
END_VAR

// Populate the strings.


firstString.FromString('The first string.');
middleString.FromString('The middle string.');
lastString.FromString('The last string.');

// Add the strings to the list.


selStringList.Append(firstString);
selStringList.Append(middleString);
selStringList.Append(lastString);

// Get pointers to each of the strings.


ptFirstString := selStringList.Item(0);
ptMiddleString := selStringList.Item(1);
ptLastString := selStringList.Item(2);

Date Code 20190830 Instruction Manual Programming Reference


27.42 SELString
Examples

Begin, End, Position, Next, and Previous

Code Snippet 27.21 SELStringList Iterator Example


PROGRAM prg_IteratorExample
VAR
selStringList : class_SELStringList;
firstString : class_SELString;
middleString : class_SELString;
lastString : class_SELString;

ptFirstString : POINTER TO class_SELString;


ptMiddleString : POINTER TO class_SELString;
ptLastString : POINTER TO class_SELString;
END_VAR

// Populate the strings.


firstString.FromString('The first string.');
middleString.FromString('The middle string.');
lastString.FromString('The last string.');

// Add the strings to the list.


selStringList.Append(firstString);
selStringList.Append(middleString);
selStringList.Append(lastString);

// Get the first string.


selStringList.Begin();
ptFirstString := selStringList.Next();
// Get the middle string.
selStringList.Position(1);
ptMiddleString := selStringList.Next();
// Get the last string.
selStringList.End();
ptLastString := selStringList.Previous();

Join

Code Snippet 27.22 SELStringList Join Example


PROGRAM prg_JoinExample
VAR
selStringList : class_SELStringList;
firstString : class_SELString;
middleString : class_SELString;
lastString : class_SELString;
delimiter : class_SELString;
joinedString : class_SELString;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


SELString 27.43
Examples

Code Snippet 27.22 SELStringList Join Example (Continued)


// Populate the strings.
firstString.FromString('The');
middleString.FromString('joined');
lastString.FromString('string.');
delimiter.FromString(' ');

// Add the strings to the list.


selStringList.Append(firstString);
selStringList.Append(middleString);
selStringList.Append(lastString);

// Get the joined string, 'The joined string.'


joinedString := selStringList.Join(delimiter);

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 28

SELUtils
Introduction
The SELUtils library is a collection of utility functions and function blocks provided to
meet common RTAC user workflows.

Proportional-Integral-Derivative (PID) Function Block


Proportional Integral Derivative (PID) control is a typical feedback control algorithm widely
used in industrial control applications. It is used to regulate the parameters of many indus-
trial processes such as flow, temperature, and level. PID logic typically uses an analog
input to read the present value of the variable to be controlled (process variable) and uses
an analog output to operate an external control element (actuator), which in turn adjusts
the process variable. The logic compares the process variable with the desired value (set
point) and calculates the difference, which is known as the error. The PID logic uses this
error to calculate how much it needs to adjust the external control element to bring the
process variable to the desired set point. Examples of an external control element include
a motorized flow control valve, a device that regulates the speed of a motor, or a relay that
controls the power delivered to a heating element.
The PID logic computes the actuator output by summing up three different control actions:
ä Proportional action: The control reaction is based on how far the process variable
is away from the set point.
ä Integral action: The control reaction is based on how long the process variable has
been away from the set point.
ä Derivative action: The control reaction is based on how fast the error is changing.
Proportional action alone always leaves the process variable slightly off the set point, be-
cause an error must exist between the process variable and the set point to maintain a non-
zero controller output value. Consequently, the steady-state error is never zero. Integral
action eliminates the steady-state error by integrating all of the previous errors over time
so that the controller output continues to grow as long as any error is present. Derivative
action produces an output based on the rate of change of the error, acting as a brake on the
control action. If the process variable approaches the set point too quickly, the derivative
action counteracts this effect to reduce overshoot to an acceptable level.
Most applications do not require you to use all three control actions. Proportional-Integral
(PI) control is particularly common because Derivative action reacts quickly any time the
process variable changes, even if the change is only noise.

Date Code 20190830 Instruction Manual Programming Reference


28.2 SELUtils
Introduction

Terminology
The following table describes the terminology used in this PID function block section.

Term Description
Process Variable (PV) The actual value of the variable to be controlled. This value is
detected by a sensor and used as the feedback signal as the PID
control is taking place.
Set Point (SP) The target value such as a specific temperature or fluid level that
the PID control system is supposed to reach.
Error The difference between SP and PV.
Manipulated Variable (MV) The input of the process (i.e., the physical variable that the con-
troller output is adjusting).
Controller Output (CO) The output of the PID controller, which is equal to the sum of the
proportional, integral, and derivative control actions.

Figure 28.1 shows a PID control system block diagram that includes the terminology shown
in the previous table.

Figure 28.1 Block Diagram of a PID Control System

PID Algorithm
The PID function block in the RTAC implements the ideal (ISA) form of the PID positional
algorithm with dependent gains. In this PID equation form, the controller gain Kc equally
affects all three control actions. The standard time-domain PID equation with dependent
gains is shown in Equation 28.1 .
 Z 
1 d (E)
CO = Kc E + E · dt + Td (Equation 28.1)
Ti dt

where:
E is the error
Kc is the controller gain
Ti is the integral time
Td is the derivative time

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.3
Supported Firmware Versions

The PID algorithm on the RTAC implements different variations of this equation depending
on two input parameters: Source of derivative Source of Derivative on page 28.12) and
control action (Direct/Reverse Control Action on page 28.12). The user selects between
direct and reverse control action and selects the signal input for the derivative term (error
or PV). These two settings affect the terms of the equation, specifically the derivative term.
Table 28.1 contains the time-domain PID equations used by the PID function block.

Table 28.1 PID Equations


Source of Control Action PID Equation
Derivative

E · dt + Td d(E)
 1
R 
Error Direct/Reverse CO = Kc E + Ti dt
+ OutputBias

Reverse
E · dt − Td d(PdtV ) + OutputBias
 1
R 
(E = SP − P V ) CO = Kc E + Ti

Direct
E · dt + Td d(PdtV ) + OutputBias
 1
R 
PV (E = P V − SP ) CO = Kc E + Ti

Table 28.2 describes the constants of the PID equation.

Table 28.2 Parameters of the PID Equations


PID Term Data Type Units Description
%

Kc REAL Unitless %
Controller gain
Ti REAL Seconds per Integral Time
repeat Integral action may be disabled by setting Ti = 0
Td REAL Seconds Derivative time

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.

Functions
This library provides various utility functions, subroutines that can be utilized by the user.

fun_IsValidReal (Function)
This function accepts a value of type REAL and returns TRUE if it is a valid number.
The function outputs a STRING representation of the value. If the number is valid, the
STRING representation will be the result of calling REAL_TO_STRING on the input. Oth-
erwise, the function will return FALSE and the STRING representation will be 'Infinity',
'-Infinity', or 'NaN' ("Not a Number"), as the value dictates.

Date Code 20190830 Instruction Manual Programming Reference


28.4 SELUtils
Functions

Inputs
Name IEC 61131 Type Description
inReal REAL The value to validate.

Inputs/Outputs
Name IEC 61131 Type Description
stringRepresentation STRING STRING representation of inReal.

Return Value
IEC 61131 Type Description
BOOL TRUE if the value inReal is a valid number.

Processing
ä The function converts inReal to a STRING and assigns the result to output stringRep-
resentation. If inReal is not a valid number, the STRING representation will be
'Infinity', '-Infinity', or 'NaN' ("Not a Number"), as the value dictates.
ä If inReal is a valid number, the function returns TRUE. Otherwise the function re-
turns FALSE.

fun_IsValidLreal (Function)
This function accepts a value of type LREAL and returns TRUE if it is a valid number. The
function outputs a STRING representation of the value. If the number is valid, the STRING
representation will be the result of calling LREAL_TO_STRING on the input. Other-
wise, the function will return FALSE and the STRING representation will be 'Infinity',
'-Infinity', or 'NaN' ("Not a Number"), as the value dictates.

Inputs
Name IEC 61131 Type Description
inLreal LREAL The value to validate.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.5
Functions

Inputs/Outputs
Name IEC 61131 Type Description
stringRepresentation STRING STRING representation of inLreal.

Return Value
IEC 61131 Type Description
BOOL TRUE if the value inLreal is a valid number.

Processing
ä The function converts inLreal to a STRING and assigns the result to output stringRep-
resentation. If inLreal is not a valid number, the STRING representation will be
'Infinity', '-Infinity', or 'NaN' ("Not a Number"), as the value dictates.
ä If inLreal is a valid number, the function returns TRUE. Otherwise the function
returns FALSE.

REAL_TO_FORMATTED_STRING (Function)
This function takes a REAL variable, a BOOLEAN specifying either standard or scientific
notation, and the desired number of decimals to display. It returns a formatted STRING
representing the value of the floating-point number provided.

Inputs
Name IEC 61131 Type Description
inReal REAL The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..5) The number of decimal places to include in the
range [0..5]

Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.

Date Code 20190830 Instruction Manual Programming Reference


28.6 SELUtils
Functions

Processing
ä The number inReal is converted to a STRING in either standard or scientific notation,
specified by the useScientificNotation parameter, and with the number of decimal
places specified in the decimals parameter.
ä If the number of decimal places specified is outside of the range [0..5], it defaults to
3.
ä The formatted STRING is returned.

LREAL_TO_FORMATTED_STRING (Function)
This function takes an LREAL variable, a BOOLEAN specifying either standard or scien-
tific notation, and the desired number of decimals to display. It returns a formatted STRING
representing the value of the floating-point number provided.

Inputs
Name IEC 61131 Type Description
inLreal LREAL The value to format as a STRING.
useScientificNotation BOOL Set to FALSE for standard notation and TRUE for
scientific notation.
decimals UINT(0..13) The number of decimal places to include in the
range [0..13]

Return Value
IEC 61131 Type Description
STRING(255) The formatted number represented as a STRING.

Processing
ä The number inLreal is converted to a STRING in either standard or scientific nota-
tion, specified by the useScientificNotation parameter, and with the number of deci-
mal places specified in the decimals parameter.
ä If the number of decimal places specified is outside of the range [0..13], it defaults
to 3.
ä The formatted STRING is returned.

TIMESTAMP_TO_STRING (Function)
This function takes a timestamp_t structure and returns it as a STRING in the form YYYY-
MM-DD-hh:mm:ss.000000. For example, 2018-08-02-23:43:07.364814 represents the Au-
gust 2nd, 2018, at 43 minutes, 7 seconds, and 364814 microseconds into the 23rd hour.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.7
Functions

Inputs
Name IEC 61131 Type Description
inTimestamp timestamp_t The time stamp to convert to a STRING.

Return Value
IEC 61131 Type Description
STRING(80) The timestamp_t structure represented as a STRING.

Processing
ä The timestamp_t structure is returned as a STRING in the form YYYY-MM-DD-
hh:mm:ss.000000.

TIMESTAMP_TO_UTC (Function)
This function takes a timestamp_t structure and returns a timeStamp_t adjusted to UTC
time, based on the offsets in the timeStamp_t that is passed in.
The resulting timeStamp_t structure will be identical to the structure passed in, except that
the DST and UTC offsets will be set to zero, and the time will be adjusted to UTC.

Inputs
Name IEC 61131 Type Description
timeStampIn timeStamp_t The time stamp to convert to a UTC.

Return Value
IEC 61131 Type Description
timeStamp_t The timestamp_t structure adjusted to UTC.

Processing
ä The returned timestamp_t structure contains a timestamp in UTC which is derived
from the timestamp, DST offset (taking into account the DST enabled and active
statuses), and UTC offset of the timestamp_t structure that is passed in. The DST
and UTC offset for the returned timestamp_t structure are set to zero.

Date Code 20190830 Instruction Manual Programming Reference


28.8 SELUtils
Function Blocks

VALIDITY_TO_STRING (Function)
This function takes a validity_t enumeration and returns the validity as a STRING (good,
invalid, reserved, questionable, or undefined).

Inputs
Name IEC 61131 Type Description
inValidity validity_t The validity_t enumeration to convert to a STRING.

Return Value
IEC 61131 Type Description
STRING(80) The validity represented as a STRING.

Processing
ä The validity_t enumeration is returned as a STRING (good, invalid, reserved,
or questionable).
ä undefined will be returned for a malformed validity_t.

Function Blocks
This library provides the PID function block and the related CascadeControl function block.

PID (Function Block)


This function block implements the Proportional Integral Derivative control algorithms
described in the introduction.

Inputs
Name IEC 61131 Type Description
PV REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
Analog signal from the output of a process.
SP REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
Desired value of the PV.
Kc REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
Controller gain
Ti REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
Integral time in seconds. Set to 0 to disable integral ac-
tion.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.9
Function Blocks

Td REAL Range: (3.4E+38) to (+3.4E+38), Default = 0


Derivative time in seconds.
DoPV BOOL Default = TRUE
TRUE: Derivative on PV
FALSE: Derivative on error
Auto BOOL Default = TRUE
TRUE: Automatic mode
FALSE: Manual mode
ManualOut REAL Range: 0 to 100, Default = 0
PID function block output in manual mode
OutBias REAL Range: –100 to 100, Default = 0
Value, in percentage (%), manually added to the output
after the PID calculation
FilterTime REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
Derivative filter time. Set to 0 to disable derivative filter.
MaxEU REAL Range: (3.4E+38) to (+3.4E+38), Default = 100
Maximum engineering units of PV and SP
MinEU REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
Minimum engineering units of PV and SP
MaxOUT REAL Range: 0 to 100, Default = 100
Maximum output limit in percentage
MinOUT REAL Range: 0 to 100, Default = 0
Minimum output limit, in percentage
TimeBase UINT Default = 1
Execution rate of PID logic
(Execution Rate = Task Cycle Time • Time Base)
DirectAction BOOL Default = FALSE
TRUE: E = PV SP
FALSE: E = SP PV
Freeze_I BOOL Default = FALSE
TRUE: Suspends integral calculation and freezes
integral term.
FALSE: Resumes integral calculation
SPrate REAL Range: (3.4E+38) to (+3.4E+38), Default = 0
SP ramp rate in EU per PID cycle time
(0 to disable SP ramping)
Reset_I BOOL Default = FALSE
TRUE: Integral accumulation is reset to zero.
FALSE: Integral accumulates

Date Code 20190830 Instruction Manual Programming Reference


28.10 SELUtils
Function Blocks

Outputs
Name IEC 61131 Type Description
PIDout REAL PID Output. Result of the PID equation (0% to 100%).
Error_p REAL Error value as a percentage or EU range.
SPramp BOOL SP Ramping. TRUE if the function block is ramping to SP.
Pterm REAL Proportional Term. Kc • Error
Kc
P
Iterm REAL Integral Term. Ti
· Error · ∆T

Dterm REAL Derivative Term. Kc • Td • Derivative


Alarms PID_Alarms Tag structure composed by four Boolean alarm tags. See
Alarms on page 28.15.
DeltaT REAL Time (ms) elapsed since previous PID execution.

Processing
Manual/Automatic Modes and Bumpless Transfer
The PID function block has two operation modes, automatic and manual. In automatic
mode, the result of the PID equation determines the controller output value. In manual
mode, the operator sets the controller output value directly by setting the ManualOut input
(0–100 percent).
The PID function block provides bumpless transfer to avoid an abrupt change on the out-
put when switching from manual to automatic. It achieves bumpless transfer by enabling
set-point tracking and output tracking when the controller is in manual mode. Set-point
tracking overwrites the set point with the current PV. Consequently, when the controller
switches to automatic mode, it will begin control with zero error. Output tracking preloads
the integral term with the output value set by the operator. As a result, when the controller
switches to automatic mode, it will begin control from the last output value entered by the
operator.
The PID function block supports ramping to set point. Upon switching to automatic mode,
the function block ramps the set point of the controller at a specified rate (SPrate input) until
reaching the desired SP entered by the user. The SPrate input has to be set in engineering
units per PID execution time.

PV and SP During Manual Mode, Automatic Mode, and Ramp-to-Set Point Fig-
ure 28.2 illustrates the manual/automatic operation and ramp-to-set point.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.11
Function Blocks

Manual mode Automatic mode

0 1 2 k k+1k+2k+3k+4k+5k+6

Ramp-to-set point

Figure 28.2 Manual/Automatic and Ramp-to-Set Point Operation

As illustrated in Figure 28.2, the PID control starts in Manual mode at t = 0 and remains
operating in Manual mode until it is switched to automatic mode at t = k. In Manual
mode (t < k), the PID equation calculates a new value continuously, but this value does not
affect the PID output. Rather, the operator controls the output and directly adjusts its value,
which in turn adjusts the process variable. In Manual mode, the PID equation continuously
calculates the output value needed to smoothly start automatic control upon switching to
Automatic mode. The PID logic ignores the current value on the SP input (blue line) and
overwrites the set point with the current PV value (green line). Consequently, in Manual
mode, the PID equation uses a SP value equal to PV. This is set-point tracking, which allows
bumpless transfer to Automatic mode.
When the PID controller switches to Automatic mode (t = k), it stops set-point tracking
and ramp-to-set point starts (SPramp output goes to TRUE). Immediately after switching
to Automatic mode, the controller gradually increases the set-point value. This starts from
the last value read while in Manual mode (Point A in Figure 28.2) and increases to the
SP value configured by the user (Point B in Figure 28.2). PV follows SP according to the
PID tuning settings and the dynamics of the process. The controller ramps the set point
by an amount equal to SPrate (engineering units) every PID execution cycle. When SP
reaches the value configured by the user (Point B), ramp-to-set point ends (SPramp output
goes to FALSE). After ramp-to-set point ends, if the user makes a set-point change, the PID
equation will immediately use this new SP value to calculate the output value. Ramp-to-set
point will not start again until the next manual-to-automatic transition.

Output Bias
Output bias is an input parameter that you enter. The controller adds this value to the result
of the PID equation, as shown in Table 28.1.
You may use output bias to reset error offset when no integral action is used (P-only con-
trol). You may also use the output bias input for combining the PID controller with feed-
forward control to improve the response to disturbances. The PID controller accepts an
output bias value scaled from –100 to +100 percent. If the output bias is more than 100
percent or less than –100 percent, the controller will clamp it to 100 or –100 percent, re-
spectively.

Date Code 20190830 Instruction Manual Programming Reference


28.12 SELUtils
Function Blocks

Source of Derivative
Using the derivative of the error may cause large transients in the controller output because
of set-point changes. In practice, it is better to use the derivative of PV instead of using the
derivative of the error. The derivative of the error works well when SP does not change or
when it changes smoothly.
The DoPV input allows you to select between derivative of PV (DoPV = TRUE) or deriva-
tive of error (DoPV = FALSE).

Direct/Reverse Control Action


The PID function block supports direct and reverse control action. The difference between
a direct control action and a reverse control action is in the way the error is calculated, as
shown in Table 28.3.

Table 28.3 Error Calculation


Direct Control Action Reverse Control Action
(DirectAction = TRUE) (DirectAction = FALSE)
Error E = P V − SP E = SP − P V

Reverse control action will be used for controlling direct-acting processes, whereas direct
control action will be used for controlling inverse-acting process. Direct- and Reverse-
Acting Processes describes how to determine whether your process is direct-acting or
reverse-acting.

Direct- and Reverse-Acting Processes To determine whether your process is direct-


acting or reverse-acting, you have to analyze the relation between the manipulated variable
(MV) and the process variable (PV):
ä Direct-acting process: Increasing MV yields to an increase in PV
ä Inverse-acting process: Increasing MV yields to a decrease in PV.
Figure 28.3 illustrates the difference between direct- and reverse-acting processes.

Figure 28.3 Direct-Acting and Reverse-Acting Processes

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.13
Function Blocks

In both cases, we are controlling the level of the liquid in the tank by manipulating the
opening of the valve. Therefore, the manipulated variable is the opening of the valve and
the process variable is the liquid level. In the process shown on the left side of Figure 28.3,
an increase in the valve opening results in a decrease of the liquid level. Consequently, it
is a reverse-acting process and the PID controller must be configured for direct action. In
the process shown on the right side of Figure 28.3, an increase in the valve opening results
in an increase of the liquid level. Consequently, it is a direct-acting process and the PID
controller must be configured for reverse action. In summary:
ä If the increase of the manipulated variable results in an increase of the process vari-
able, then the process is direct-acting and the PID control shall be configured for
reverse action.
ä If the increase of the manipulated variable results in a decrease of the process vari-
able, then the process is reverse-acting and the PID control shall be configured for
direct action.

Derivative Filter
When derivative action is used, even small amounts of noise in PV may cause large unnec-
essary PID output movements. The PID function block implements a first-order filter to
reduce the noise reading and smooth the signal feeding the derivative term (PV or error).
The frequency-domain transfer function of the derivative filter is shown as follows:

1
H(s) =
1 + F ilterT ime · s

The cutoff frequency for the filter is as follows:

1
fc =
2π · F ilterT ime
where FilterTime is a PID input parameter.
Setting FilterTime to 0 disables the derivative filter.

Output Limiting
The PID function block allows you to set maximum (OutMAX) and minimum (OutMIN)
limits for the output (0–100 percent). The PID function block clamps the output at these
limits, preventing it from exceeding the maximum or minimum limits. An alarm bit is also
set if the calculated output is beyond these limits.

Anti-Integral Windup
Integral windup occurs when the actuator is at its maximum or minimum limit but the
set point has not been reached. The integral term gradually increases, increasing the out-
put more than 100 percent (or less than 0 percent), which is physically impossible for the
actuator.

Date Code 20190830 Instruction Manual Programming Reference


28.14 SELUtils
Function Blocks

Figure 28.4 Integral Windup

The problem with integral windup is that it may take a relatively long time to correct,
because the integral term needs to unwind. The top graph in Figure 28.4 illustrates integral
windup. The red line represents the output value that the PID equation is instructing to send.
The blue line represents the output value that is actually sent. A PID control with no integral
antiwindup implementation is not aware of the PID output limits. Consequently, if the error
persists long enough, the integral term may grow indefinitely, beyond the output limit,
driving the actuator to the maximum limit. At this point, the PID equation no longer has
an impact on the controller output or the actuator. When the error changes to the opposite
sign, the output may take a long time to wind down before getting to the operational range.
The bottom graph in Figure 28.4 illustrates a PID output with antiwindup implementation.
When the output reaches the limit, the integral calculation is suppressed and consequently
the output will not accumulate beyond this point. When the error changes to the opposite
sign, the output drops immediately to the operational range.
The PID function block prevents integral windup by switching off integration and keeping
the accumulated integral term constant in either of the following situations:
ä PID output is greater than or equal to the maximum output limit (MaxOUT) and the
error is positive.
ä PID output is less than or equal to the minimum output limit (MinOUT) and the error
is negative.
When the PID output returns to a value in the range between OutMIN and OutMAX, the
integral calculation resumes.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.15
Function Blocks

Freezing Integral Calculation


The Freeze_I input parameter, when TRUE, suspends the integral calculation and freezes
the integral term. When Freeze_I is set back to FALSE, the integral calculation resumes.
This feature may be helpful in case of cascade control to stop the integral calculation on
the primary PID loop when the secondary PID output hits the limit. See CascadeControl
(Function Block) on page 28.16 for more information on cascade control.

Alarms
The PID function block has an alarm output to alert you of an abnormal condition. The
alarm output is a tag structure of Boolean variables; each Boolean variable within the
structure represents a different alarm. The alarms that are implemented are shown in the
following table.

Alarm Description
Output_High_Limit PID output has reached the maximum limit.
Output_Low_Limit PID output has reached the minimum limit.
SP_Out_of_Range Set-point value is out of the engineering units range MinEU, MaxEU).
PV_Out_of_Range Process variable value is out of the engineering units range MinEU,
MaxEU).

PID Timing
The PID function block uses the Task Cycle Time as its time base, and is executed at a rate
equal to a multiple of this time base. The TimeBase input parameter defines the multiplier
value for the PID execution rate.
For example, if you configure the RTAC to run every 50 milliseconds (Task Cycle Time =
50) and the instance of the PID function block is configured with TimeBase = 10, the PID
code is executed every 500 milliseconds. This allows you to have in your logic multiple
instances of the PID function block running at different rates.

Date Code 20190830 Instruction Manual Programming Reference


28.16 SELUtils
Function Blocks

PID Block Diagram

Figure 28.5 Block Diagram of the PID Instruction

CascadeControl (Function Block)


The CascadeControl function block is part of the PID library and facilitates the implemen-
tation of a PID cascade system. By adding a CascadeControl function block to the logic
and properly connecting it to the primary and secondary PID controllers, it will handle an-
tiwindup logic (see Anti-Integral Windup on page 28.13), and switch between the different
PID cascade modes (see Cascade Control on page 28.22).

Figure 28.6 CascadeControl Function Block

In order to use this function block, set up a cascade control system using the CascadeControl
function block as follows:
1. Incorporate two PID function blocks (primary and secondary) and a CascadeCon-
trol function block in your ACSELERATOR RTAC project.
2. Connect the CascadeControl function block inputs and outputs to the corresponding
inputs and outputs of the primary and secondary PID blocks (refer to the Cascade-
Control Input Table).
3. Configure the individual PID settings (tuning constants, direct/reverse action, deriva-
tive filter, etc.) for the primary and secondary controller.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.17
Function Blocks

Inputs
Name IEC 61131 Type Description
Mode CascadeModes The mode input determines the operating mode of the
cascade system. The possible values for this input are
ManualMode, AutoMode, and CascadeMode. When this
input is ManualMode, both primary and secondary con-
trollers are placed in Manual mode. In Manual mode, you
directly determine the output of the secondary controller
by writing to the ManValue input (0–100 percent). When
this output is AutoMode, the primary controller is placed
in Manual mode and the secondary controller is placed
in Automatic mode. You can directly manipulate the set
point of the secondary controller by writing to the Au-
toValue input (0–100 percent). Finally, when this output
is CascadeMode, both primary and secondary controllers
are placed in Automatic mode for full cascade operation.
PVsec REAL Connect the PVsec input to the process variable (PV) sig-
nal of the secondary controller.
Note: The PV signal of the secondary controller must be
in percentage units (0–100 percent).
ManValue REAL The ManValue input determines the output of the sec-
ondary controller when the system is in Manual mode.
When the Mode input is ManualMode, the current value
of this ManValue input is sent to the output of the sec-
ondary controller. When the Mode input is AutoMode
or CascadeMode, the value of this ManValue input is ig-
nored.
AutoValue REAL The AutoValue input determines the set point of the sec-
ondary controller when the system is in Automatic mode.
When the Mode input is AutoMode, the current value of
this AutoValue input is sent to the set point (SP) input of
the secondary controller. When the Mode input is Man-
ualMode or CascadeMode, the value of this AutoValue
input is ignored.
ALARMSsec PID_Alarms Connect the ALARMSsec input to the Alarms output of
the secondary controller.

Outputs
Name IEC 61131 Type Description
AUTOpri BOOL Connect the AUTOpri output to the Auto input of the pri-
mary PID controller.
AUTOsec BOOL Connect the AUTOsec output to the Auto input of the
secondary PID controller.
MANOUTpri REAL Connect the MANOUTpri output to the ManualOut input
of the primary PID controller.
MANOUTsec REAL Connect the MANOUTsec output to the ManualOut in-
put of the secondary PID controller.
FIpri BOOL Connect the FIpri output to the Freeze_I input of the pri-
mary controller.

Date Code 20190830 Instruction Manual Programming Reference


28.18 SELUtils
Benchmarks

Cascade Control System Tuning


Tune a cascade control system by placing the primary controller in Manual mode and tuning
the secondary controller first. Once you have tuned the secondary controller, start tuning
the primary controller. When tuning the primary controller, the system will be placed in
Cascade mode (or Automatic mode, depending on the tuning recipe). The primary con-
troller will be tuned as if you are tuning a single control loop system, treating the secondary
controller as just another part of the process.
From the perspective of the primary controller, the secondary controller is part of the pro-
cess. Consequently, any tuning modification on the secondary controller may change the
process dynamics of the outer loop, and this, in turn, will impact the tuning of the primary
controller. After the secondary controller is tuned and tested, no modification will be made
on its tuning parameters.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R143-V0 firmware
ä SEL-3530
â R143-V0 firmware
ä SEL-3555
â R143-V0 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R143 firmware

Benchmark Test Descriptions


REAL_TO_FORMATTED_STRING Performance tests
This test runs the function REAL_TO_FORMATTED_STRING 1000 times with a task
cycle of 100 ms and the time to run the function is recorded. The average, maximum,
minimum, and standard deviation are recorded here.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.19
Benchmarks

LREAL_TO_FORMATTED_STRING Performance tests


This test runs the function LREAL_TO_FORMATTED_STRING 1000 times with a task
cycle of 100 ms and the time to run the function is recorded. The average, maximum,
minimum, and standard deviation are recorded here.

TIMESTAMP_TO_STRING Performance tests


This test runs the function TIMESTAMP_TO_STRING 1000 times with a task cycle of
100 ms and the time to run the function is recorded. The average, maximum, minimum,
and standard deviation are recorded here.

VALIDITY_TO_STRING Performance tests


This test runs the function VALIDITY_TO_STRING 1000 times with a task cycle of 100
ms and the time to run the function is recorded. The average, maximum, minimum, and
standard deviation are recorded here.

Benchmark Results
Platform (time in ns)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
REAL_TO_FORMATTED_STRING
Average 2540.4 1374.7 54.2
Maximum 10977.8 5904.3 321.1
Minimum 380.3 251.7 8.1
Std Deviation 2722.5 1366.7 55.9
LREAL_TO_FORMATTED_STRING
Average 314.6 204.9 16.7
Maximum 4636.9 1909.5 297.4
Minimum 102.1 76.5 3.8
Std Deviation 548.5 272.1 19.6
TIMESTAMP_TO_STRING
Average 1057.1 631.8 29.2
Maximum 6555.3 3841.6 399.1
Minimum 245.9 275.3 4.1
Std Deviation 749.7 376.6 36.6
VALIDITY_TO_STRING
Average 1057.1 631.8 29.2
Maximum 6555.3 3841.6 399.1
Minimum 245.9 275.3 4.1
Std Deviation 749.7 376.6 36.6

Date Code 20190830 Instruction Manual Programming Reference


28.20 SELUtils
Examples

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.

Using REAL_TO_FORMATTED_STRING Function (ST)


This example illustrates how the REAL_TO_FORMATTED_STRING function can be
used to convert a REAL quantity to a formatted STRING.

Code Snippet 28.1 REAL_TO_FORMATTED_STRING_Example


PROGRAM REAL_TO_FORMATTED_STRING_Example
VAR
Pi : REAL := 3.14159;
PiAsString : STRING(255);
END_VAR

// Convert Pi to a STRING in standard notation and with 3


// decimal places
PiAsString := R E AL _ T O _F O R M AT T E D _S T R I NG ( Pi , FALSE , 3) ;
// Result : PiAsString is set to '3.142 '

Using LREAL_TO_FORMATTED_STRING Function (ST)


This example illustrates how the LREAL_TO_FORMATTED_STRING function can be
used to convert an LREAL quantity to a formatted STRING.

Code Snippet 28.2 LREAL_TO_FORMATTED_STRING_Example


PROGRAM LREAL_TO_FORMATTED_STRING_Example
VAR
Pi : LREAL := 3.14159;
PiAsString : STRING(255);
END_VAR

// Convert Pi to a STRING in standard notation and with 3


// decimal places
PiAsString := L R E A L _ T O _ F O R M A T T E D_ S T R I N G ( Pi , FALSE , 3) ;
// Result : PiAsString is set to '3.142 '

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.21
Examples

Standard Process Control (CFC and ST)


This example illustrates how to configure a PID instruction by using Continuous Function
Chart (CFC) and Structured Text (ST) programming languages, respectively. The PID
instructions are configured under the following conditions:
ä The range of the analog sensor that measures the process variable is 100–1200.
ä The analog PV sensor is connected to an analog input module.
ä An analog output channel is used to adjust the final actuator.
ä RTAC Task Cycle time is 100 ms and the PID instruction has to be executed every
5 seconds.
ä You use a switch, connected to digital input channel, to select between Automatic
and Manual modes.
ä When in Manual mode, you use an RTAC HMI control to enter the PID output value.
ä When in Automatic mode, you use an RTAC HMI control to enter the set point.
ä Proportional-Integral (PI) control is required (no derivative action).
ä Proportional and integral tuning constants are stored in Global Variables named P_-
gain and I_time, respectively.
ä A digital output alarm contact closes when the PID output reaches the maximum or
minimum limit.
ä PID output cannot be greater than 85 percent or less than 10 percent.

PID Configuration in Continuous Function Chart (CFC)


PROGRAM Program1
VAR
TemperatureOven : PID ;
END_VAR

Figure 28.7 PID Configuration in CFC

Date Code 20190830 Instruction Manual Programming Reference


28.22 SELUtils
Examples

PID Configuration in Structured Text (ST)

Code Snippet 28.3 PIDcontrol


PROGRAM PIDcontrol
VAR
TemperatureOven : PID ;
END_VAR

// ///////////////// PID CONFIGURATION // // / // / // // / // / // / // //


TemperatureOven (
SP := VirtualTagList1 . APC_0000 . oper . setMag , // 7
PV := SE : _16AI_1_ECAT . INPUT_VALUE_001 . instMag , // 2
Kc := P_gain , Ti := I_time , // 9
Td := 0 , // 8
Auto := SEL_24DI_1_ECAT . INPUT_001 . stVal , // 5
ManualOut := VirtualTagList1 . APC_0001 . oper . setMag , // 6
MaxEU := 1200 , MinEU := 100 , // 1
MaxOUT := 85 , MinOUT := 10 , // 11
TimeBase := 50 , // 4
PIDout = > SEL_8AO_1_ECAT . AO_VALUE_001 ) ; // 3

// PID ALARMS
IF TemperatureOven . Alarms . Output_High_Limit
OR TemperatureOven . Alarms . Output_Low_Limit
THEN // 10
SEL_16DO_1_ECAT . OUTPUT_001 . operSet . ctlVal := TRUE ;
SEL_16DO_1_ECAT . OUTPUT_001 . operClear . ctlVal := FALSE ;
ELSE
SEL_16DO_1_ECAT . OUTPUT_001 . operSet . ctlVal := FALSE ;
SEL_16DO_1_ECAT . OUTPUT_001 . operClear . ctlVal := TRUE ;
END_IF

The input values that are not configured in the logic retain their default values.

Cascade Control
In some applications, two PID controllers are nested together and used in combination to
improve the control performance over the single-loop system. This is called cascade control
and is used to improve the response of the system to disturbances.
Figure 28.8 shows a typical example of cascade control. The variable to be controlled
(primary variable) is the water temperature leaving the heat exchanger. The operator sets
the desired temperature (set point) on the primary controller, which determines the desired
amount of steam flow to control the temperature. The output of the primary controller
manipulates the set point of the secondary controller, which maintains the steam flow at the
desired level, correcting any steam flow disruption before the primary variable is impacted.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.23
Examples

Figure 28.8 Cascade Control Example

A single PID controller could control the temperature of the water by reading its temper-
ature (PV) and setting the position of the valve without going through a secondary PID
controller. However, if any disturbance occurs on the steam flow, the effect of the distur-
bance has to flow through the water temperature process and move the temperature away
from the set point before it can be corrected by the single PID controller. Introducing a
secondary PID controller to control the steam flow makes the loop control more stable and
faster responding because a flow control loop reacts much faster than a temperature control
loop. Any disturbance that affects the secondary variable is detected and compensated by
the secondary controller before it affects the primary variable.
Cascade control may be implemented on the RTAC by adding two PID function block
instances into the project (primary and secondary controllers) and implementing additional
logic to prevent integral windup and to switch between the different cascade modes. The
way to implement this additional logic is described in Anti-Windup Logic and Cascade
Control Logic Using CascadeControl Function Block following.

Anti-Windup Logic
In a single-loop controller, when the output of the PID function block reaches the limit and
the error contributes to increase the output beyond this point, the integral accumulation is
suspended. When the output returns to the operational range, the integral accumulation
resumes. This is called anti-windup and is described in detail in Anti-Integral Windup on
page 28.13.
In cascade control, integral windup may occur in the primary controller because of the
interaction between the two controllers, and a different anti-windup technique is necessary
to prevent this problem from happening. Integrator windup will occur if the output of
the secondary controller hits the limit and the primary controller continues to integrate
the error. To prevent this, it is necessary to implement an external anti-windup logic to
automatically freeze the integral term of the primary controller when the output of the
secondary controller reaches the limit. The PID function block provides alarm output bits
to indicate that the output is saturated, and also provides a Boolean input to freeze the
integral term. Implementing the external anti-windup logic is straightforward if you use
these alarm output bits and Freeze_I input.
The Structured Text code in Code Snippet 28.4 shows a configuration example of a primary
PID controller. The highlighted line shows how to configure the Freeze_I input to suspend
the integral calculation when the output of the secondary PID controller hits the higher or
lower limit.

Date Code 20190830 Instruction Manual Programming Reference


28.24 SELUtils
Examples

Code Snippet 28.4 Configuration Example of Primary PID Controller


PROGRAM CascadeLogic
VAR
PrimaryPID : PID ;
Secondary : PID ;
END_VAR

PrimaryPID ( SP := VirtualTagList1 . APC_0000 . oper . setMag ,


PV := SEL_16AI_1_ECAT . INPUT_VALUE_001 . instMag
Kc := P_gain , Ti := I_time , Td := 0 ,
Auto := SEL_24DI_1_ECAT . INPUT_001 . stVal ,
ManualOut := VirtualTagList1 . APC_0001 . oper . setMag ,
MaxEU := 1200 , MinEU := 100 , MaxOut := 85 ,
MinOut := 10 , TimeBase := 50 ,

PIDout = > SEL_8AO_1_ECAT . AO_VALUE_ACTUAL_001 ,

// THIS IS THE IMPORTANT PART


Freeze_I := SecondaryPID . Alarms . Output_high_Limit
OR Secondary
OR SecondaryPID . Alarms . Output_Low_Limit ) ;

Implementation of PID Cascade Modes


Most cascade control applications require three different operating modes: manual, auto-
matic, and cascade. Manual and automatic modes are typically used during startup and
commissioning, whereas cascade is used for normal operation. These operating modes are
explained in Table 28.5.

Programming Reference Instruction Manual Date Code 20190830


SELUtils 28.25
Examples

Table 28.5 Cascade Operating Modes

Cascade Mode
ä The operator manipulates the set point of
the primary controller.
ä Both primary and secondary controllers are
in automatic mode.

Automatic Mode
ä The operator manipulates the set point of
the secondary controller.
ä Primary controller is in manual mode and
secondary controller is in automatic mode.

Manual Mode
ä The operator directly manipulates the final
control element (valve).
ä Both primary and secondary controllers are
in manual mode.

When implementing the operating modes, take the following considerations into account
to ensure there is no sudden change in the output to the final actuator.
ä Cascade Mode
â Both controllers (primary and secondary) must be placed in Automatic mode.
ä Automatic Mode
â The primary controller should be placed in Manual mode.
â The secondary controller should be placed in Automatic mode.
â The operator directly controls the set point of the secondary controller by set-
ting a value to the ManualOut input of the primary controller.
ä Manual Mode
â Both controllers (primary and secondary) must be placed in Manual mode.
â The operator directly controls the final actuator by setting a value to the Man-
ualOut input of the secondary controller.
â The output of the primary controller must track the process variable (PV) of
the secondary controller. This will allow a bumpless transfer to Automatic or
Cascade mode.

Date Code 20190830 Instruction Manual Programming Reference


28.26 SELUtils
Examples

Cascade Control Logic Using CascadeControl Function


Block
Connect the CascadeControl function block to the primary and secondary PID controllers.

NOTE: The secondary PID


controller process variable (PV) must
be in percentage units (0–100
percent). This scaling can be done
directly in the analog output module
settings, or by using programming
logic, as shown in Figure 28.9.

Figure 28.9 Cascade Configuration

Programming Reference Instruction Manual Date Code 20190830


SECTION 29

SVPplus
Introduction
The SVPplus (Synchrophasor Vector Processor Plus) library provides Prony Analysis of
signals, referred to here as modal analysis. The overall goal of this library is to encapsulate
algorithms that describe the dynamics of a substation or electrical grid.

Modal Analysis (MA)


Similar to Fourier series, modal analysis decomposes a signal into its individual frequencies
or modes. In addition, it also provides the damping rate of each frequency. Damping
information is vital when monitoring wide area power system stability as it can be used to
predict sustained or uncontrolled oscillations.

Sample Timing
The timing requirements of the modal analysis input signal are the responsibility of the
user of the library. The library does not check the times of the samples given. The interval
between each sample must be within acceptable error of the sample rate given in hertz.
For example, if 20 Hz is given, the period between samples should be 0.05 seconds. The
recommended error threshold is 5 percent.

Use Cases
Modal Analysis has been proven significantly useful in several areas of power system anal-
ysis.
Sometimes power system equipment or their controllers can be configured in such a way
that they unintentionally incite growing oscillations. Rapid detection of these forced oscil-
lations is important to guard against excessive mechanical fatigue and system instability.
Modal analysis can detect these events by noting the maximum modal amplitudes of a sys-
tem and triggering an alarm or control action based on larger than normal and/or increasing
magnitude of oscillatory modal amplitude.
Disturbances in the power system are often identifiable from the decaying oscillations vis-
ible from streaming synchrophasor measurements. These events provide an opportunity
to determine the natural system dynamic modes. The dynamic modes inform planners of
the inherent stability, or lack thereof, of the power system and help identify areas where
additional stabilizing devices could be installed.

Date Code 20190830 Instruction Manual Programming Reference


29.2 SVPplus
Introduction

Modal analysis performed on ambient data can identify the frequency of the natural dy-
namic modes. A change in the frequency component of these modes can indicate a system
change that may require further investigation.

Operation
The modal analysis function block in this library is responsible for two primary tasks. The
first task is to collect and store samples given to it. The second task is to analyze these stored
values once enough new samples are given and return the modes of the stored signal.
The samples are stored in a ring buffer. Once a certain percentage of new samples are
given, modal analysis is conducted on the stored array of samples. Figure 29.1 shows this
visually, where blue indicates old samples and red new samples. If the object has just been
initialized and there are no stored samples, modal analysis is not complete until the entire
buffer has been filled. After the initial filling of the buffer, modal analysis is done once the
percentage of new samples has been reached. For example, if the total number of samples
specified as the initialization variable numSamples is set to 100, and percentUpdate is set
to 10 percent, then the tenth call to GiveSample() will trigger another calculation. This
new modal calculation is performed on the most recent 90 old samples and the 10 new
samples, with the oldest 10 samples having been overwritten in the ring buffer.

Figure 29.1 Ring Buffer Used To Store Samples In Modal Analysis Object

Because modal analysis is very computationally expensive, the analysis is done over many
task cycles. The Run() method of each modal object does part of the analysis each cy-
cle until it is complete. If a new analysis has been triggered and the previous is not yet
complete, it is ignored until the previous analysis is finished. Once the current analysis
is complete, the ignored trigger causes a new analysis to begin immediately. The ignored
trigger is not a queue, but rather is a single request to restart once the previous analysis
completes.

Modes
Modes are returned from modal analysis, which is the decomposition of the input signal into
a series of modes. These modes consist of sinusoidal decaying signals that closely match
the original signal when summed together. The equation used to construct each mode from
their values is given in Equation 29.1 , where A is the amplitude, α is the decay, f is the
frequency, and θ is the angle phase.

Aeαt cos (2πf t + θ) (Equation 29.1)

The quality of the signal is determined by the signal-to-noise ratio (SNR) returned with
a call to GetModes(). Equation 29.2 shows how the SNR is calculated, where S is the
original signal and N is a signal reconstructed from the modes returned.

Programming Reference Instruction Manual Date Code 20190830


SVPplus 29.3
Global Constants

p !
S12 + S22 + ... + Sn2
SN R = 20 log10 p
(S1 − N1 )2 + (S2 − N2 )2 + ... + (Sn − Nn )2
(Equation 29.2)
The SNR is calculated by using the decibel logarithmic unit on the ratio of the root-mean-
square of the original signal over the root-mean-square of the difference between the origi-
nal signal and reconstructed signal. If the value is 20, then the amplitude of the signal is 10
times greater than the error; when the value is 40, the amplitude of the signal is 100 times
greater than the error, and so on.

Damping Ratio
The damping ratio ς is determined from the decay α and the frequency f (as seen in “Mod-
ern Solutions for Protection, Control, and Monitoring of Electric Power Systems” ISBN
978-0-9725026-3-4). Equation 29.3 is used to compute the damping ratio. A negative
damping ratio illustrates an increasing oscillation that can lead to power system instability.

α
ς = −p (Equation 29.3)
α2 + (2πf )2

Modal Analysis
Because of the computationally intensive nature of this algorithm, it is very important to
consider benchmarks while using this object. See Benchmarks on page 29.7 for benchmark
information.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.3 and older can be used on RTAC firmware version R132 and higher.

Global Constants
This section lists values of global constants provided for facilitating work with the library.

Name IEC 61131 Type Value Description


g_c_Infinity REAL ∞ Positive infinity.

Date Code 20190830 Instruction Manual Programming Reference


29.4 SVPplus
Classes

Structure Definitions
This section enumerates structures needed for the user to communicate with this library.

struct_Mode
This object contains the information for one sinusoidal mode returned from class_Modal-
Analysis.

Name IEC 61131 Type Description


Amplitude REAL Amplitude of this mode.
Frequency REAL Frequency of this mode.
Phase REAL Phase of this mode in radians.
Damping REAL Decay rate of this mode.
DampingRatio REAL Damping ratio of this mode.

Classes
This section enumerates the classes used to access the functionality of this library.

class_ModalAnalysis (Class)
This class conducts modal analysis on an input signal.

Initialization Inputs
Name IEC 61131 Type Description
numSamples UDINT Total number of samples this modal analysis object uses.
sampleRate UINT Rate at which samples are taken in hertz.
percentUpdate UDINT(10..100) Percentage of new samples this modal analysis collects
before performing analysis.
stepTime ULINT The amount of time in microseconds the Run() method
will run each time it is called.
numModes UDINT(1..16) Number of modes that are returned from analysis.

For any meaningful analysis of a digital input signal, a minimum number of sample history
must be stored in a buffer. numSamples is the size of this buffer for modal analysis.

Programming Reference Instruction Manual Date Code 20190830


SVPplus 29.5
Classes

Outputs
Name IEC 61131 Type Description
IsEnabled BOOL Flag that states if this class instance is active.
Error POINTER TO STRING(80) If class instance failed initialization, this points to a
string describing what failed.

These outputs give the status of the modal analysis object as a whole. If the initialization of
the class instance was successful, it is flagged and enabled and ready to take new samples
to analyze. If initialization failed, it is flagged as not enabled and the error string pointer
returns a pointer to a string which described what failed in initialization.

bootstrap_SetFilter (Method)
This initialization routine sets the filter that is used on the raw input provided by GiveSample().
This routine is optional to call, and if it is not called no filter is used and the raw samples
are fed directly into modal analysis.

Inputs
Name IEC 61131 Type Description
filter I_Filter Interface pointer to filter that will be used on raw input.

Return Value
IEC 61131 Type Description
BOOL Returns TRUE if the filter was successfully added to the object.

Processing
This routine takes the interface to the filter and confirms the pointer to it is real. If the
pointer to the filter is zero or the modal analysis object has already been initialized, it will
return FALSE as a failure.

GiveSample (Method)
This method gives a new sample as input to the modal analysis block. The sample rate
integrity of the signal must be verified by the user, as discussed in Sample Timing on
page 29.1.

Date Code 20190830 Instruction Manual Programming Reference


29.6 SVPplus
Classes

Inputs
Name IEC 61131 Type Description
sample REAL New sample.

Processing
This method takes the input sample and stores it within its internal buffer of samples. If
enough new samples have been given or the entire buffer of samples has been populated
for the first time, the method will trigger the calculation of new modes. This calculation is
done over many cycles in the run method.

Reset (Method)
Modal analysis is only effective on a continuous stream of evenly spaced samples. When a
gap in the stream has been detected, modal analysis must be reset. This causes it to discard
all previous samples. Additionally, a sample with unacceptably low quality is considered
a gap in the stream, and therefore, modal analysis must be reset.
Resetting modal analysis delays the next analysis as additional samples will need to be
gathered. A sample is considered bad if it does not meet the timing requirements defined
in Sample Timing on page 29.1 or if the quality of the sample is unacceptable.

Processing
This method will discard all saved samples and start with an empty buffer that needs to be
refilled for modal analysis to happen.

Run (Method)
This method must run once per cycle for each modal analysis object that exists. It is re-
sponsible for processing modal analysis of the samples. It performs a part of an analysis,
if one is pending, each time it is called.

Return Value
IEC 61131 Type Description
UDINT Percentage of completion for modal analysis task from 0 to 100.

Processing
Once the output complete has reached 100, the analysis is complete and GetModes can be
called.

Programming Reference Instruction Manual Date Code 20190830


SVPplus 29.7
Benchmarks

GetModes (Method)
Call this method to get the most recent modal analysis results. If no analysis has yet been
done, this method will return an array of structures whose values are all set to zero.
The range of the signal-to-noise ratio can be anywhere from 0 to the maximum number of
UINT. Anything under a value of 80 is considered a poor value and the returned modes
should be ignored. Increasing the number of modes returned will improve this signal-to-
noise ratio.

Inputs
Name IEC 61131 Type Description
pt_modes POINTER TO struct_Mode Address of array to copy modes to as returned by the
ADR() function. This array must contain numModes
structures as specified in the Initialization Inputs of
the class.

Return Value
IEC 61131 Type Description
REAL Signal-to-noise ratio that determines quality of modes returned.

Processing
If no analysis has yet been done, this method will set all structures to zero. If the number
of modes for this object has been initialized with a number n that is less than the global
value g_p_numModes, then all structures past n will be set to zero.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R134 firmware
ä SEL-3530
â R134 firmware
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V1 firmware

Date Code 20190830 Instruction Manual Programming Reference


29.8 SVPplus
Examples

Benchmark Test Descriptions


Because so much of the performance of this library is defined by the user, these benchmarks
attempt to give an overall feel for the cost of performing modal analysis in terms of number
of samples and number of modes requested. All results are presented as the number of
scans taken to perform the analysis where the ModalAnalysis object is given 5 ms of run
time each task cycle.
The following benchmarks are tested:
ä 4, 8, and 16 modes with 500 samples
ä 4 modes with 600 samples
ä 4, 8, and 16 modes with 5000 samples

Benchmark Results
Platform (time in µs)
Operation Tested
SEL-3505 SEL-3530 SEL-3555
4 Modes 500 Samples 27 16 2
8 Modes 500 Samples 114 64 6
16 Modes 500 Samples 462 253 21
4 Modes 600 Samples 34 17 3
4 Modes 5k Samples 155 93 2
8 Modes 5k Samples 460 276 23
16 Modes 5k Samples 1586 952 80

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Calculating Modes
Objective
The objective of this example is to calculate the modal frequencies and damping coefficients
of a synchrophasor frequency measurement for oscillation stability analysis at an update
rate of once per second. This example will cover the preconditioning of incoming time
stamps and how to call the ModalAnalysis methods in the appropriate sequence.

Programming Reference Instruction Manual Date Code 20190830


SVPplus 29.9
Examples

Assumptions
This example assumes the following are true:
ä The RTAC project incorporates both the SVPplus and Analog Conditioning libraries.
ä The RTAC is collecting synchrophasor measurements from one synchrophasor mea-
surement device, referenced here as a C37_118 RTAC client called PMU1.
ä The RTAC is performing no tasks other than those referred to in this example.
ä The nominal frequency of the power system is 60 Hz.
ä The synchrophasor message rate is 60 samples per second.
ä The RTAC Main Task cycle time, under which all programs are being run, is set to
8 ms.
ä The Deadband and Zero Deadband settings for the PMU1.FREQ tag are set to 0.
ä There are only four modes of interest in the system. Each is between 0.3 Hz and
10 Hz.
ä Data samples are filtered with a 10 Hz cutoff low-pass filter before being processed
with MA. The ArmaFilter class from the Analog Conditioning library is used to
implement this filter. This is also demonstrated in the example.
ä The global variable list and sample flagging programs shown in Code Snippet 29.1
and Code Snippet 29.2, respectively, are included in the project.

Code Snippet 29.1 Global Variable List


VAR_GLOBAL CONSTANT
g_c_NumModes : UINT := 4;
//Using coefficients for a 10Hz cutoff low pass filter.
g_c_Acoeff : ARRAY[1..g_p_MaxFilterOrder] OF REAL :=
[-1.96299, 1.40000, -0.34641];
g_c_Bcoeff : ARRAY[0..g_p_MaxFilterOrder] OF REAL :=
[0.011325, 0.033975, 0.033975, 0.011325];
END_VAR

VAR_GLOBAL
g_SampleQuality, g_SampleUpdated, g_SampleTimeValid, g_SampleValid :
BOOL;
g_SNR : REAL;
g_ModeResults : ARRAY [1..g_c_NumModes] OF struct_Mode;
g_DampingAlarm : ARRAY [1 .. g_c_NumModes] OF BOOL;
END_VAR

Code Snippet 29.2 prg_SampleFlagging


PROGRAM prg_SampleFlagging
VAR
dTime : DINT; //current day and time of PMU1_C37_118
us, timeNow, timeLast, timeDiff : LREAL;
END_VAR

Date Code 20190830 Instruction Manual Programming Reference


29.10 SVPplus
Examples

Code Snippet 29.2 prg_SampleFlagging (Continued)


//Establish the quality of the sample.
g_SampleQuality := NOT(DINT_TO_BOOL(PMU1_C37_118.FREQ.q.validity)) AND
NOT(PMU1_C37_118.FREQ.t.quality.clockNotSynchronized);
//Calculate the time difference between the current and previous samples.
dTime := DT_TO_DINT(PMU1_C37_118.FREQ.t.value.dateTime);
us := UDINT_TO_LREAL(PMU1_C37_118.FREQ.t.value.uSec) / 1000000;
timeNow := dTime + us;
timeDiff := (timeNow - timeLast)*1000; //Sample time difference in ms
timeLast := timeNow;
//Determine if the sample has updated.
IF (timeDiff > 0) THEN
g_SampleUpdated := TRUE;
ELSE
g_SampleUpdated := FALSE;
END_IF
//Validate the sample time difference against +-2.5 % of a 60Hz period.
IF (timeDiff > 17.08 OR timeDiff < 16.25) THEN
g_SampleTimeValid := FALSE;
ELSE
g_SampleTimeValid := TRUE;
END_IF
//Assign overall sample validity.
IF (g_SampleQuality AND g_SampleTimeValid) THEN
g_SampleValid := TRUE;
ELSE
g_SampleValid := FALSE;
END_IF

Solution
Having flagged the incoming samples for quality and continuity, the samples can be filtered
and processed with MA as shown in Code Snippet 29.3.

Code Snippet 29.3 prg_ModeCalc


PROGRAM prg_ModeCalc
VAR
modal : class_ModalAnalysis( numSamples := 600, sampleRate := 60,
percentUpdate := 10, stepTime := 4000,
numModes := g_c_NumModes);
inputSample : REAL;
filter : class_ArmaFilter(g_c_Acoeff, g_c_Bcoeff, 3, 4);
analysisComplete : R_TRIG;
doneLatch : BOOL;
init : BOOL := TRUE;
END_VAR

Programming Reference Instruction Manual Date Code 20190830


SVPplus 29.11
Examples

Code Snippet 29.3 prg_ModeCalc (Continued)


//Update inputSample.
inputSample := PMU1_C37_118.FREQ.instMag;
//Initialize: Load filter into the MA object.
IF init THEN
modal.bootstrap_SetFilter(filter);
init := FALSE;
END_IF

//Load the sample into MA only if it has updated and is valid.


IF(g_SampleUpdated) THEN
IF(g_SampleValid) THEN
modal.giveSample(inputSample - 60); //Factor out the 60Hz offset
ELSE
modal.reset();
END_IF;
END_IF;

(*If Run() method is at 100 % completion, populate g_ModeResults and


return SNR.
Use an edge trigger to guarantee that getModes() is only called once per
analysis.*)
doneLatch := modal.Run() = 100;
analysisComplete(CLK := doneLatch);
IF analysisComplete.Q THEN
g_SNR := modal.getModes(ADR(g_ModeResults));
END_IF

Analyzing Modes
Objective
The objective of this example is to demonstrate how the output of the ModalAnalysis class
can be processed to flag a necessary control action.

Assumptions
This example extends the previous example. Thus, it is assumed that the getModes()
method has been called successfully. It is further assumed that the program in this example
will accesses the global variable list defined in the previous example.

Solution
The code below shows a simple example which asserts a per-mode alarm bit if the given
mode meets the user-specified criteria. The signal-to-noise ratio output of the getModes()
method is used to validate the accuracy of the modal estimation.

Date Code 20190830 Instruction Manual Programming Reference


29.12 SVPplus
Examples

Code Snippet 29.4 prg_ModeAnalyze


PROGRAM prg_ModeAnalyze
VAR
dmpThr : REAL; //Define damping ratio threshold here.
ampThr : REAL; //Define oscillation amplitude threshold here.
SNRFail : BOOL;
i : UINT;
END_VAR

IF g_SNR > 80 THEN


SNRFail := FALSE;
FOR i := 1 TO g_c_NumModes DO
IF g_ModeResults[i].DampingRatio < dmpThr
AND g_ModeResults[i].Amplitude > ampThr
AND g_ModeResults[i].Frequency > 0 //Factor out DC
modes.
THEN
g_DampingAlarm[i] := TRUE;
ELSE
g_DampingAlarm[i] := FALSE;
END_IF
END_FOR
ELSE
SNRFail := TRUE;
END_IF

Programming Reference Instruction Manual Date Code 20190830


SECTION 30

SnmpLite
Introduction
This library encapsulates common communications management responsibilities that in-
dustrial control and monitoring equipment are expected to perform on the communications
fabric of a control system using Simplified Network Management Protocol (SNMP).
The common use for these devices is to annunciate failures within the system. Therefore,
this library only provides basic network interface descriptions and port states to allow detec-
tion and annunciation of device failures. More advanced diagnostic and system description
tools that fully use SNMP are outside the scope of this library, and are not considered to
be common requirements of an automation controller.

Glossary
Abstract Syntax Notation One (ASN.1) A standard that provides rules and a notation
for representing, encoding, transmitting, and decoding data in telecommunications. SNMP
uses this standard to represent the data within a UDP packet.
Management Information Base (MIB) A hierarchical description of the structure and
data available in a device that supports SNMP.
Object Identifier (OID) A unique identifier for an object or leaf in a hierarchically de-
fined namespace, where a “.” specifies the next object as the child of the previous. For
example, the OID 1.3.6.1.2.1.2.2.1 identifies the entries in a table of interfaces. In the con-
text of this library, OIDs uniquely identify information found in communication with the
network devices.
SNMP Trap Unsolicited information SNMP agents send to SNMP managers. Events that
trigger SNMP Traps and the Trap content are configured on the SNMP agent device and
utilize Port 162.
Simplified Network Management Protocol (SNMP) An Internet standard protocol for
managing devices on IP networks. This protocol is generally supported by network-fabric
devices such as Ethernet switches and routers, and it is often used by other network-centric
devices. There are many versions of SNMP. All SNMP traffic, except SNMP traps, is sent
and received on Port 161.
Simple Network Management Protocol Version 2, Community-Based SNMPv2c)
This version of the protocol transmits all data, including the community strings used to
group SNMP agents and managers, in raw form with no encryption.
User Datagram Protocol (UDP) A connectionless, packet-based protocol used to stream
data between two devices without requiring responses. UDP does not implement handshak-
ing, packet ordering, or confirmation of packet delivery.

Date Code 20190830 Instruction Manual Programming Reference


30.2 SnmpLite
Introduction

Special Considerations
Consider the following topics when implementing this library in a project.

Versions of SNMP
This version of the library only supports SNMPv2c, which is an unsecured implementation
that transmits all data on the wire without encryption or security.

Open SNMP Ports


This library does not have the ability to open ports in the RTAC firewall to communicate
with the various devices. When the class_SnmpManager is instantiated in an ACSELERA-
TOR RTAC project, the creator of that project is responsible for creating two access points
that allow the class_SnmpManager object to communicate with the specified devices.
ä UDP Port 161 Ethernet Listener Access Point must be created for all normal SNMP
traffic.
ä UDP Port 162 Ethernet Listener Access Point must be created to receive SNMP traps.

Declaring Objects in Global Variable Lists


This library uses variables in a Global Variable List (GVL) set to Global Initialization Slot
1 as the registry mechanism for its classes.
Instantiating a class in this library as a global variable and forcing it to be initialized at
Global Initialization Slot 1 or lower will cause undefined behavior. Declaring classes in a
normal global variable list causes no issues because the default Global Initialization Slot
is 50000 (unless explicitly set otherwise).

All SNMP Objects in a Single, Non-Time Critical Task


This library expects that all instantiated objects are in the same task. Care has been taken
in designing this library to evenly distribute processing load, and the library scales to man-
agement of many devices without incurring additional processing. However, the execution
time to parse arbitrarily large and complex responses from agent devices is, by nature, not
deterministic. Therefore, this library should not be used on the same task with logic that
must execute deterministically.

Put all SNMP Objects in a Single Program


Consider instantiating all of these objects in a single IEC 61131 program to mitigate the
concerns described in Declaring Objects in Global Variable Lists on page 30.2 and All
SNMP Objects in a Single, Non-Time Critical Task on page 30.2.

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.3
Supported Firmware Versions

Copying Instantiated Objects


Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type class_SnmpObject"
mySnmpObject := otherSnmpObject;

// This is fine
someVariable := mySnmpObject.value;
// As is this
pt_mySnmpObject := ADR(mySnmpObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT members


in function blocks, functions, or methods. Place them in the VAR_IN_OUT section
or use pointers instead.

Scope of Instantiated Objects


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).

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
Versions 3.5.0.3 and older can be used on RTAC firmware version R133 and higher.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

NOTE: See
enum_InterfaceStatus http://tools.ietf.org/html/rfc2863 for
more information about the interface
states.

This enumeration provides a textual representation of the statuses possible for any individ-
ual port.

Enumeration Description

Date Code 20190830 Instruction Manual Programming Reference


30.4 SnmpLite
Structures

NONE Interface specified is out of range for this device.


UP Interface status is up.
DOWN Interface status is down.
TESTING Interface is in test configuration.
UNKNOWN Port link status is unknown.
DORMANT The interface is ready to transmit and receive network traffic, but
is waiting on some external event.
NOT_PRESENT Interface is not configured in this hardware.
LOWER_LAYER_DOWN The dependent interface is not up, a condition relevant only if
stacked interfaces are employed.

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.

NOTE: iso(1) . org(3) . dod(6) .


struct_InterfaceInfo internet(1) . mgmt(2) . mib-2(1) .
interfaces(2) ifTable(2) . ifEntry(1) .
item(N)
This structure contains some of the commonly used information available in the table OID
1.3.6.1.2.1.2.2.1.N.

Name IEC 61131 Type Description


ifIndex UDINT The index the manufacturer provides from OID
1.3.6.1.2.1.2.2.1.1.N.
ifDescr STRING(255) First 255 characters of description from OID
1.3.6.1.2.1.2.2.1.2.N.
ifType UDINT The integer value of the interface type from OID
1.3.6.1.2.1.2.2.1.3.N.
ifSpeed UDINT The bandwidth this interface report during initial-
ization from OID 1.3.6.1.2.1.2.2.1.5.N.
ifPhysicalAddress STRING(80) Usually the MAC address. Obtained from OID
1.3.6.1.2.1.2.2.1.6.N.
ifOperStatus enum_InterfaceStatus The operational status of this link from OID
1.3.6.1.2.1.2.2.1.8.N. This updates periodically, or
when this library receives a trap.

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.5
Classes

Classes
class_SnmpManager (Class)
A single class_SnmpManager object is instantiated to manage the UDP traffic on Port 161
for SNMP get and set requests and responses to these requests. The same object listens on
Port 162, which is the SNMP trap listening port. If two or more class are instantiated, all
but one of the classes will fail to initialize and display an appropriate error state.
This object issues SNMP requests queued by instantiated SNMP agent classes. It sends
responses to these requests and forwards SNMP traps received from a given IP address to
the SNMP agent class associated with the sending IP. The agent class is responsible for the
processing of the message.
The manager issues no more than one SNMP request per call to the Run() method. This
constraint evenly distributes the load per scan and allows support for an arbitrary number
of agents. However, this constraint also means that the more devices that this manager
supervises, the more time it takes to cycle through the pending requests from all of the
agent classes. This result can be mitigated by configuring traps on the SNMP agent devices
because the manager also processes one trap per call to the Run() method; a trap event will
update the status of the SNMP device immediately and the delay in getting new information
is not affected by the number of devices being monitored. Instead, only the number of traps
received simultaneously affects the latency of updates to the agent monitoring classes.

Run (Method)
Call this method once every scan on a low-priority task where real-time performance is not
critical.

Processing
The Run() method does the following:
ä Issues a pending poll:
â Get the next registered agent class.
â Issue the queued request.
ä Dequeues a maximum of two SNMP traps from the Port 162 socket and then sends
the traps to the agent class designated to the IP address of the sender for parsing.
ä Dequeues a maximum of two SNMP responses from the Port 161 socket and then
send the responses to the agent class designated to the IP address of the sender for
parsing.

class_SnmpAgentMonitor (Class)
When instantiated, this class registers itself with the active class_SnmpManager. There is
no need to call methods on this class or to run it periodically because the manager class is
responsible for refreshing the state of all agent monitors.

Date Code 20190830 Instruction Manual Programming Reference


30.6 SnmpLite
Classes

This class monitors a generic SNMP agent device that has a list of network interfaces listed
under OID 1.3.6.1.2.1.2.2.1 1 . It also displays the number of interfaces the SNMP agent
provides in response to requesting the Integer32 value at OID 1.3.6.1.2.1.2.1 2 .
The list of interfaces is initially obtained by walking through all of the table objects. If
the number of interfaces returned by walking the interface table is less than the number of
interfaces OID 1.3.6.1.2.1.2.1 advertises, the device will not enable. If the interface infor-
mation from all interfaces can be obtained, then the object enables itself. Subsequently,
the agent only requests port statuses via OID 1.3.6.1.2.1.2.2.1.8.N 3 .
The port information obtained by GetInterfaceInfo() updates only during initializa-
tion, with the exception of ifOperStatus, which continually updates.
In the event that (a) the agent does not receive replies to requests for ifOperStatus, (b) the
quantity of interfaces changes, or (c) the indexing of the monitored interfaces changes, this
block sets ENO to FALSE and attempts to reinitialize.
This basic SNMP agent monitor discards SNMP traps it receives from the class_Snmp-
Manager object because the contents of SNMP traps are highly dependent on the MIB of
the particular device sending the traps.

Initialization Inputs
Name IEC 61131 Type Description
ipAddress STRING(15) The IP address of the monitored agent as a string.
communityString STRING(80) A string that designates the community this agent de-
vice has been assigned. This ID is included in every
packet the agent and manager send.

Outputs
Name IEC 61131 Type Description
IpAddress STRING(15) The IP address as a string.
ENO BOOL The class was initialized.
NumInterfaces UDINT The number of interfaces the agent device has.
MessagesReceived UDINT The total number of responses and traps re-
ceived from the manager object since ENO last
became true.
TimeSinceLastMessage TIME The elapsed time since the last message from
this device.
Error STRING(255) The last error encountered will be described
here. It will not be cleared.

GetInterfaceStatus (Method)
This method provides the status of the specified interface.

1 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifTable(2) . ifEntry(1).


2 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifNumber(1).
3 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifTable(2) . ifEntry(1) . ifOperSta-

tus(8) . item(N).

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.7
Classes

Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.

Return Value
IEC 61131 Type Description
enum_InterfaceStatus The state of the requested interface.

Processing
ä Check that interfaceIndex is within the specified range. Return NONE if it is not.
ä Return the state of the specified interface.

GetInterfaceInfo (Method)
This method returns the information obtained from walking OID 1.3.6.1.2.1.2.2.1 before
the ENO output was true. NOTE: iso(1) . org(3) . dod(6) .
internet(1) . mgmt(2) . mib-2(1) .
interfaces(2) . ifTable(2) . ifEntry(1)

Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.

Outputs
Name IEC 61131 Type Description
info struct_InterfaceInfo The structure containing the interface information.

Return Value
IEC 61131 Type Description
BOOL TRUE if the object is initialized and the interfaceIndex is in range.

Processing
ä Check that interfaceIndex is within the specified range. Return FALSE if it is not,
leaving the output in an undefined state.

Date Code 20190830 Instruction Manual Programming Reference


30.8 SnmpLite
Classes

ä Copy internal information to the output and return true.

Reinitialize (Method)
Returns the agent to an uninitialized state, resulting in the ENO output being set to false.
From this point, the agent automatically tries to re-initialize, refreshing all port information
in the process.

class_SEL2730MAgent (Class)
This class has all of the functionality of the class_SnmpAgentMonitor. However, because
the number of ports are known in advance, the class also displays the port statuses as pins.
Because this class contains knowledge of the device, future changes to SEL-2730M firmware
may change interface enumerations in SNMP. All versions of SEL-2730M firmware that
do not impact the assumptions in SEL-2730M Assumptions on page 30.8 will work.

SEL-2730M Assumptions
1. Port F up/down status is not accessible via SNMP get request. Where all other
ports default to NONE and then report the status of SNMP get requests, this port
defaults to UNKNOWN until a trap is received and then changes to UP or DOWN
as appropriate.
2. Ports 1–24 can be accessed through use of a GetNextRequest SNMP command.
The order of the ports is unimportant.
3. The description field of Ports 1–24 always ends with the port number. The OID
order is randomly defined at every boot, so the class uses the description to associate
the OID with the physical port index.
When instantiated, this class registers itself with the active class_SnmpManager. There is
no need to call methods on this class or to run it periodically because the manager class is
responsible for refreshing the state of all agent monitors.
This class monitors a generic SNMP agent device that has a list of network interfaces listed
under OID 1.3.6.1.2.1.2.2.1 4 . It also displays the number of interfaces the SNMP agent
provides in response to requesting the Integer32 value at OID 1.3.6.1.2.1.2.1 5 .
The list of interfaces is initially obtained by walking through all of the table objects. If
the number of interfaces returned by walking the interface table is less than the number of
interfaces OID 1.3.6.1.2.1.2.1 advertises, the device will not enable. If the interface infor-
mation from all interfaces can be obtained, then the object enables itself. Subsequently,
the agent only requests port statuses via OID 1.3.6.1.2.1.2.2.1.8.N 6 .
The port information obtained by GetInterfaceInfo() updates only during initializa-
tion, with the exception of ifOperStatus, which continually updates.
In the event that (a) the agent does not receive replies to requests for ifOperStatus, (b) the
quantity of interfaces changes, or (c) the indexing of the monitored interfaces changes, this
block sets ENO to FALSE and attempts to reinitialize.
4 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifTable(2) . ifEntry(1).
5 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifNumber(1).
6 iso(1) . org(3) . dod(6) . internet(1) . mgmt(2) . mib-2(1) . interfaces(2) . ifTable(2) . ifEntry(1) . ifOperSta-

tus(8) . item(N).

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.9
Classes

Traps from SEL-2730M devices have a known structure, so traps sent to this agent monitor
from the class_SnmpManager are parsed. The textual message contained in a trap that is
displayed in the LastMessage output. If the trap indicates a port status change, the state of
the indicated port updates accordingly.
Whether by traps or periodic queries, the output pin statuses update automatically without
the implementer having to call any methods or the body of the class.

Initialization Inputs
Name IEC 61131 Type Description
ipAddress STRING(15) The IP address of the monitored agent as a string.
communityString STRING(80) A string that designates the community this agent de-
vice has been assigned. This ID is included in every
packet the agent and manager send.

Outputs
Name IEC 61131 Type Description
IpAddress STRING(15) The IP address as a string.
ENO BOOL The class was initialized.
NumInterfaces UDINT The number of interfaces the agent de-
vice has.
MessagesReceived UDINT The total number of responses and
traps received from the manager ob-
ject since ENO last became true.
TimeSinceLastMessage TIME The elapsed time since the last mes-
sage from this device.
Error STRING(255) The last error encountered will be de-
scribed here. It will not be cleared.
LastMessage STRING(255) The first 255 characters of the last
string message from this device.
PortStatus ARRAY[0..24] OF The state of all ports. Index 0 is ETHF,
enum_InterfaceStatus Index 1 is Port 1, Index 24 is Port 24.

GetPortInfo (Method)
This method returns the information obtained from walking OID 1.3.6.1.2.1.2.2.1 before
the ENO output was true. The index provided is the port number for the SEL-2730M NOTE: iso(1) . org(3) . dod(6) .
internet(1) . mgmt(2) . mib-2(1) .
instead of an arbitrary order. interfaces(2) . ifTable(2) . ifEntry(1).

Inputs
Name IEC 61131 Type Description
portNumber UDINT(0..24) The port index on the switch. portNumber 0 is for ETHF,
1 is for Port 1, and 24 is for Port 24.

Date Code 20190830 Instruction Manual Programming Reference


30.10 SnmpLite
Classes

Outputs
Name IEC 61131 Type Description
info struct_InterfaceInfo The structure containing the interface information.

Return Value
IEC 61131 Type Description
BOOL TRUE if the object is initialized and the requested port number is in range.

GetInterfaceStatus (Method)
This method provides the status of the specified interface.

Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.

Return Value
IEC 61131 Type Description
enum_InterfaceStatus The state of the requested interface.

Processing
ä Check that interfaceIndex is within the specified range. Return NONE if it is not.
ä Return the state of the specified interface.

GetInterfaceInfo (Method)
This method returns the information obtained from walking OID 1.3.6.1.2.1.2.2.1 before
the ENO output was true. NOTE: iso(1) . org(3) . dod(6) .
internet(1) . mgmt(2) . mib-2(1) .
interfaces(2) . ifTable(2) . ifEntry(1)

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.11
Benchmarks

Inputs
Name IEC 61131 Type Description
interfaceIndex UDINT A numeric identifier of the interface. It must be greater
than 0 and less than or equal to NumInterfaces.

Outputs
Name IEC 61131 Type Description
info struct_InterfaceInfo The structure containing the interface information.

Return Value
IEC 61131 Type Description
BOOL TRUE if the object is initialized and the interfaceIndex is in range.

Processing
ä Check that interfaceIndex is within the specified range. Return FALSE if it is not,
leaving the output in an undefined state.
ä Copy internal information to the output and return true.

Reinitialize (Method)
Returns the agent to an uninitialized state, resulting in the ENO output being set to false.
From this point, the agent automatically tries to re-initialize, refreshing all port information
in the process.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R134-V0 firmware
ä SEL-3530-4
â R133-V0 firmware

Date Code 20190830 Instruction Manual Programming Reference


30.12 SnmpLite
Benchmarks

ä SEL-3505
â R133-V0 firmware

Benchmark Test Descriptions


class_SnmpManager.Run()
The posted time is the average execution time of 100 method calls when no traps are being
received.

class_SnmpAgentMonitor.GetInterfaceStatus()
The posted time is the average execution time of 100 method calls.

class_SnmpAgentMonitor.GetInterfaceInfo()
The posted time is the average execution time of 100 method calls.

class_SnmpAgentMonitor.Reinitialize()
The posted time is the average execution time of 100 method calls.

class_SEL2730MAgent.GetPortInfo()
The posted time is the average execution time of 100 method calls.

class_SEL2730MAgent.GetInterfaceStatus()
The posted time is the average execution time of 100 method calls.

class_SEL2730MAgent.GetInterfaceInfo()
The posted time is the average execution time of 100 method calls.

class_SEL2730MAgent.Reinitialize()
The posted time is the average execution time of 100 method calls.

Benchmark Results

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.13
Examples

Platform (time in µs)


Operation Tested
SEL-3555 SEL-3530-4 SEL-3505
class_SnmpManager.Run() 22 409 644
class_SnmpAgentMonitor.GetInterfaceStatus() 1 11 49
class_SnmpAgentMonitor.GetInterfaceInfo() 1 4 92
class_SnmpAgentMonitor.Reinitialize() 1 65 12
class_SEL2730MAgent.GetPortInfo() 1 8 47
class_SEL2730MAgent.GetInterfaceStatus() 1 8 37
class_SEL2730MAgent.GetInterfaceInfo() 1 6 18
class_SEL2730MAgent.Reinitialize() 1 19 21

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Monitoring Port Status of Three SEL-2730M Switches


Objective
A user has an SEL-RTAC that he wants to use to monitor link status of Ports 5–24 on three
switches. He wants an alarm if one of those ports is inactive or if an additional port has a
device plugged in.

Assumptions
ä The RTAC being programmed can access three SEL-2730M devices configured on
the network. These SEL-2730M devices have the following IP addresses:
â 10.203.50.1
â 10.203.50.101
â 10.203.50.201
ä The user has configured these switches to communicate with the RTAC via SNMP.
This means the following:
â The user has added a v2c profile to the switch with the community string
“Switches” and at least Read permissions.
â The user has added the RTAC to the switch as a trap server using the desired
profile.
ä The RTAC, configured as the SNMP manager, has an IP address 10.203.50.2.
ä The Main task of the RTAC is not used for real-time critical purposes, making it
appropriate to instantiate the SNMP manager object on the Main task.

Date Code 20190830 Instruction Manual Programming Reference


30.14 SnmpLite
Examples

ä The RTAC has two access points configured to allow UDP traffic as follows:
â UDP incoming on Port 161 for normal SNMP
â UDP incoming on Port 162 for SNMP traps

Solution
On the Main task, the user can create a program as shown in Code Snippet 30.1.

Programming Reference Instruction Manual Date Code 20190830


SnmpLite 30.15
Examples

Code Snippet 30.1 prg_SnmpManagerWith3Agents


PROGRAM prg_SnmpManagerWith3Agents
VAR CONSTANT
c_NumSwitches : UDINT := 3;
END_VAR
VAR
SnmpManager : class_SnmpManager;
Switch1 : class_SEL2730MAgent( iPAddress := '10.203.50.1',
communityString := 'Switches');
Switch2 : class_SEL2730MAgent( iPAddress := '10.203.85.101',
communityString := 'Switches');
Switch3 : class_SEL2730MAgent( iPAddress := '10.203.85.201',
communityString := 'Switches');
Alarm : BOOL;
SwitchPointers : ARRAY[1..c_NumSwitches] OF POINTER TO
class_SEL2730MAgent := [ ADR(Switch1),
ADR(Switch2), ADR(Switch3)];
END_VAR
VAR_TEMP
i, j : UDINT; // Iterators used.
END_VAR

// Run the SnmpManager, which is responsible for doing all the required
work.
SnmpManager.Run();

// Initialize to success, so any unexpected result can flag failure.


Alarm := FALSE;
// Check that statuses match expected.
IF SwitchPointers[i]^.PortStatus[0] = SnmpLite.UP THEN
// Alarm if something is plugged into the front port.
// Note that ETHF status cannot be polled, so it will remain in
// UNKNOWN state until a trap is received.
Alarm := TRUE;
END_IF
FOR i := 1 TO c_NumSwitches DO
FOR j := 1 TO 4 DO
IF SwitchPointers[i]^.PortStatus[j] <> SnmpLite.DOWN THEN
// Alarm if something plugged into the gigabit ports.
Alarm := TRUE;
END_IF
END_FOR
FOR j := 5 TO 24 DO
IF SwitchPointers[i]^.PortStatus[j] <> SnmpLite.UP THEN
// Alarm if something unplugged from ports 5-24.
Alarm := TRUE;
END_IF
END_FOR
END_FOR

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
SECTION 31

SyslogCollector
Introduction
This library allows the RTAC to receive syslog messages from other devices. Once the
RTAC receives a syslog message, the contents of the message are available to the IEC 61131
logic engine. Logic can be performed on the syslog messages to accomplish the following:
ä Store syslog messages into the SOE log of the RTAC.
ä Create a custom syslog file with the FileIO library.
ä Map syslog data into protocol servers.
ä Display syslog messages on RTAC HMI screens.
ä Generate an email or text message.
ä Generate syslog messages based on received syslog messages with modified content.
The syslog message is presented to the logic engine as a string data type. Anything that
can be done with a string in the logic engine can be done with the received syslog message.
This library offers the ability to filter received syslog messages based on its origin IP ad-
dress. It also allows for automatically logging the received syslog messages into the RTAC
SOE.

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.

Structures
Structures provide a means to group together several memory locations (variables), making
them easier to manage.

Date Code 20190830 Instruction Manual Programming Reference


31.2 SyslogCollector
Enumerations

struct_syslogMessageFormat

Name IEC 61131 Type Description


ReceivedIPAddress String(15) IP address from which the syslog message was re-
ceived.
FacilityLevel enum_facility The facility level of the syslog message.
SeverityLevel enum_severity The severity level of the syslog message.
SyslogMessage STRING(2000) The content of syslog message.

Enumerations
Enumerations make code more readable by allowing a specific number to have a readable
textual equivalent.

enum_severity
This enumeration lists the different severity levels allowed in syslog.

Enumeration Value Description


Emergency 0 System is unusable
Alert 1 Action must be taken immediately
Critical 2 Critical conditions
Error 3 Error conditions
Warning 4 Warning conditions
Notice 5 Normal but significant conditions
Informational 6 Informational messages
Debug 7 Debug-level messages
None 8 No severity selected

enum_facility
This enumeration lists the different facility levels allowed in syslog.

Enumeration Value Description


kern 0 Kernel messages
user 1 User-level messages
mail 2 Mail system
daemon 3 System daemons
auth 4 Security/authorization messages

Programming Reference Instruction Manual Date Code 20190830


SyslogCollector 31.3
Function Blocks

syslog 5 Messages generated internally by syslogd


lpr 6 Line printer subsystem
news 7 Network news subsystem
uucp 8 UUCP subsystem
clock 9 Clock daemon
authpriv 10 Security/authorization messages
ftp 11 FTP daemon
NTP 12 NTP subsystem
logAudit 13 Log audit
logAlert 14 Log alert
cron 15 Scheduling daemon
local0 16 Local use 0
local1 17 Local use 1
local2 18 Local use 2
local3 19 Local use 3
local4 20 Local use 4
local5 21 Local use 5
local6 22 Local use 6
local7 23 Local use 7
None 24 No facility selected

Function Blocks
fb_syslogCollector (Function Block)
This function block makes syslog messages that were received on one of the IP addresses
of the RTAC available to the IEC 61131 logic engine.

Date Code 20190830 Instruction Manual Programming Reference


31.4 SyslogCollector
Function Blocks

Inputs
Name IEC 61131 Type Description
LocalIPAddress STRING(15) Specify an RTAC IP address on which to
listen. Default is 0.0.0.0, which listens
on all interfaces.
LocalPortNumber UINT Defaults to 514, which is the standard
syslog port.
LogReceivedSyslog BOOL If TRUE, received syslog data will be en-
tered into the RTAC SOE log.
FilterOnSeverity enum_Severity If set to a value other than NONE, the
RTAC will only log syslog messages that
have a severity of NONE or higher. De-
fault value is NONE.
UseSeverityInSyslogMessage enum_Severity If set to a value other than NONE, re-
ceived syslog messages will use this
severity when logged. If set to NONE,
logged syslog messages will use the
severity received in message. Default
value is NONE.
IPAddressFilterList STRING(1600) Enter a comma-separated list of IP ad-
dresses for the RTAC to process syslog
messages from. If left empty, the RTAC
processes all received syslog messages.

Outputs
Name IEC 61131 Type Description
RecSyslogMessage ARRAY[1..50] OF struct_SyslogMessageFormat Received syslog
messages.
InvalidInputPin STRING Lists an incorrectly
configured input pin.

Processing
ä This function block will log received syslog messages in the RTAC SOE if the Lo-
gReceivedSyslog input is set to TRUE. If the syslog message is longer than 255
characters, the logged message will be truncated and MessageTruncated will be
appended to the end of the SOE message.
ä This function block filters received syslog messages based upon the originating IP
address. These addresses can be entered into the IPAddressFilterList input. If this
value is left empty or set to 0.0.0.0 (which is the default setting), the function block
will process all received syslog messages.
ä This function block will process as many as 50 received syslog messages per process-
ing cycle. If the RTAC receives more than 50 syslog messages in a single processing
cycle, the excess messages will be buffered and processed in a subsequent process-
ing interval. The function block displays processed messages for a single processor
cycle.

Programming Reference Instruction Manual Date Code 20190830


SyslogCollector 31.5
Examples

ä By default, Port 514 is used to listen for syslog messages. This can be changed by
configuring the LocalPortNumber input to a desired port to listen for syslog mes-
sages.
ä This function block only processes UDP-based syslog messages. No TCP syslog
messages are processed with this function block.
ä This function block must be used in conjunction with an Ethernet listening UDP
incoming access point that matches the LocalPortNumber input. Unless the input pin
is configured to a nondefault value, this port must be 514 on the Ethernet listening
UDP incoming access point.

Examples
These examples demonstrate the capabilities of this library. Do not mistake them as sug-
gestions or recommendations from SEL.
Implement the best practices of your organization when using these libraries. As the user
of this library, you are responsible for ensuring correct implementation and verifying that
the project using these libraries performs as expected.

Receiving Syslog Messages


Objective
A user would like to collect all syslog messages from other devices in their substation
network.

Assumptions
A UPD incoming access point needs to be included in the project configuration. The Local
Port Number setting input of the port must match the LocalPortNumber setting on the
syslog function block, as shown in Figure 31.1 and Code Snippet 31.1.

Figure 31.1 UDP Incoming Access Point

Solution
The syslog function block can be used as shown in Code Snippet 31.1. This example shows
the function block processing all received syslog messages on a specified interface (by
entering the IP address used on that interface). This example also shows the function block
storing all received messages with their received severity levels into the SOE log of the
RTAC.

Date Code 20190830 Instruction Manual Programming Reference


31.6 SyslogCollector
Examples

Code Snippet 31.1 prg_SyslogCollector


PROGRAM prg_SyslogRec
VAR
_syslogCollector : fb_SyslogCollector;
END_VAR

_syslogCollector(LocalIPAddress := '192.168.1.2',
LocalPortNumber := 514,
LogReceivedSyslog := TRUE,
FilterOnSeverity := SyslogCollector.enum_severity.None,
UseSeverityInSyslogMessage := SyslogCollector.enum_severity.None,
IPAddressFilterList := '');

Figure 31.2 shows the same program but in a CFC program.

Figure 31.2 prg_SyslogCollector in CFC Form

Programming Reference Instruction Manual Date Code 20190830


SECTION 32

TrendRecorder
Introduction
This library provides flexible and scalable analog trend recording capability to the RTAC. It
can provide ACSELERATOR TEAM® SEL-5045 Software Load Data Profile (LDP) records,
which are viewable via ACSELERATOR Meter Reports SEL-5630 Software.
By using intuitive function blocks, users can configure as many as 12 different recorders,
each capable of recording 16 analog values. Two types of recorders are available: an inter-
val recorder and a monitor recorder. The interval recorder uses a recording interval setting
and records all 16 analog values each interval. The monitor recorder has a record time and
a trigger input. Recording occurs when the rising edge of the trigger is observed and the
time provided by the record time input is associated with the record (instead of the internal
time source of the RTAC). Each recorder records the value of each analog at the time the
record occurs (also known as an end-of-Interval recorder).
This document provides detailed information about the purpose and functionality of each
function block (along with its inputs and outputs). It also provides a configuration example.

Special Considerations
Record Storage Space
The TrendRecorder library uses files stored on the RTAC file system to record data. The
amount of data that can be retained is dependent on the available hard drive space as well
as the recording interval configured for each recorder.

Recommended Library Class Usage


Copying classes from this library causes unwanted behavior. This means the following:
1. The assignment operator “:=” must not be used on any class from this library; con-
sider assigning pointers to the objects instead.

// This is bad and in most cases will provide a compiler error such
as:
// "C0328: Assignment not allowed for type
class_ProfileRecorderObject"
myProfileRecorderObject := otherProfileRecorderObject;

// This is fine
someVariable := myProfileRecorderObject.value;

Date Code 20190830 Instruction Manual Programming Reference


32.2 TrendRecorder
Supported Firmware Versions

// As is this
pt_myProfileRecorderObject := ADR(myProfileRecorderObject);

2. Classes from this library must never be VAR_INPUT or VAR_OUTPUT members


in function blocks, functions, or methods. Place them in the VAR_IN_OUT section
or use pointers instead.
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).

Supported Firmware Versions


You can use this library on any device configured using ACSELERATOR RTAC® SEL-5033
Software with firmware version R143 or higher.
To enable TrendRecorder library support, the device number of your RTAC must include
the feature in its model option table (MOT). You cannot download projects including this
library to RTACs that do not support the library. Use the SEL website MOT configura-
tion (https://www.selinc.com/onlinemot/) to ensure that a particular part number has Tren-
dRecorder support enabled.
Versions 3.5.0.3 and older can be used on RTAC firmware version R136-V2 and higher.

Usage
The purpose of this library is to provide analog trend recording capability to the RTAC in a
way that requires as little configuration as possible. All settings required for recorder setup
are completed with only three function blocks (see Function Blocks on page 32.4 for more
detail). This section provides information about the intended usage of the TrendRecorder
library as well as some details about operations that occur in the background.

Theory of Operation
The TrendRecorder library is designed to interface with TEAM. TEAM collects the recorded
data in LDP format and saves it into the ACSELERATOR Database. The collected data is then
available for other software solutions, such as ACSELERATOR Meter Reports SEL-5630
Software.
It is important to note that the TrendRecorder library can record analog values from any
capable source—it is not limited only to typical load profile or even electrical) values. As
long as the analog is of type REAL, it can be recorded.

Programming Reference Instruction Manual Date Code 20190830


TrendRecorder 32.3
Usage

The core of the TrendRecorder library user interface consists of two profile recorder func-
tion blocks: ProfileIntervalRecorder and ProfileTriggerRecorder. Contained within these
two function blocks is everything the RTAC needs to collect and record analog data. Simply
instantiate one or more of them in a Continuous Function Chart (CFC) program, connect
each recorder to the ProfileManager function block, create a Telnet Access Point, and start
collecting recorded data. Each recorder records 16 analogs, and as many as 12 recorder
function blocks can be instantiated (192 total analogs can be recorded in a single RTAC).
Each ProfileIntervalRecorder records data at an interval specified by its RecordingInterval
setting. If possible, the recorder will align the recording interval with the current time. For
example, if an interval of 5 seconds is specified, the recorder will record data at 0, 5, 10,
15, 20 seconds, and so on. If 900 seconds is specified (equal to 30 minutes), the recorder
will record data at the top of the hour and the bottom of the hour (at 0 and 30 minutes of
the hour). A full list of auto-aligned intervals is available in Table 32.1.
Each ProfileTriggerRecorder records data when the rising edge of an external trigger is
observed, at a frequency as high as once per second. It is capable of accepting an external
time stamp to associate with the data record. This allows the RTAC to save data with the
same time stamp provided by a remote IED with the data over a protocol that supports
time-stamped data (such as Distributed Network Protocol (DNP)).
The ProfileManager function block is responsible for providing the Telnet command line
interface that TEAM uses to collect recorded data. It is also responsible for compiling and
transmitting records via a binary data format to TEAM via YMODEM.
Note: TEAM collects trend record data from the RTAC via Telnet. An Access Point config-
ured for Telnet Port 23 must exist within the RTAC project to facilitate this communication.

Date Code 20190830 Instruction Manual Programming Reference


32.4 TrendRecorder
Function Blocks

Figure 32.1 Example Recorder Usage

Function Blocks
This library provides three function blocks for use in setting up trend recorders: ProfileIn-
tervalRecorder, ProfileTriggerRecorder, and ProfileManager. You only need these function
blocks to configure fully functional profile recording in the RTAC.

ProfileIntervalRecorder (Function Block)


This function block records 16 analogs of type REAL at a specified interval from 1 to 7200
seconds. Any unused channels record a zero at each recording interval.

Programming Reference Instruction Manual Date Code 20190830


TrendRecorder 32.5
Function Blocks

Inputs
Name IEC 61131 Type Description
ConnectToProfileManager This pin must be connected to the ProfileM-
anager. This connection is required for the
recorder to save data and for the manager to
retrieve data when TEAM requests it.
RecorderNumber UINT The recorder number (1–12) to assign to
the recorder. Any recorder with a recorder
number outside of this range will not record
data. Any recorders that duplicate a recorder
number will not record data.
RecordingInterval UINT The interval (1–7200, in seconds) at which
to record data. If no RecordingInterval is
provided, the recorder will default to a set-
ting of 60 seconds. Any interval value less
than one will be forced to a setting of one.
Any interval value greater than 7200 will be
forced to a setting of 7200.
Channel[n]_Data REAL The analog inputs to be recorded, where n
is the channel number from 1–16. Zeros are
recorded for all disconnected channel data
inputs.
Channel[n]_Name STRING(15) The names of analogs to be recorded, where
n is the channel number from 1–16. Chan-
nel names longer than 15 characters will be
truncated to the first 15 characters. If no
value is assigned, the channel name will be
set to Chan [n] Rec [x], where n is the chan-
nel number and x is the recorder number.

Outputs
Name IEC 61131 Type Description
SettingsError BOOL This output asserts if the recorder has a settings error. If
this output is asserted, the recorder will not function.

ProfileTriggerRecorder (Function Block)


This function block records 16 analogs of type REAL any time the rising edge of the record
trigger input is observed, at a frequency as high as once per second. Any unused channels
will record a zero at each recording interval.

Date Code 20190830 Instruction Manual Programming Reference


32.6 TrendRecorder
Function Blocks

Inputs
Name IEC 61131 Type Description
ConnectToProfileManager This pin must be connected to the ProfileM-
anager. This connection is required for the
recorder to save data and for the manager to
retrieve data when TEAM requests it.
RecorderNumber UINT The recorder number (1–12) to assign to
the recorder. Any recorder with a recorder
number outside of this range will not record
data. Any recorders that duplicate a recorder
number will not record data.
RecordTrigger UINT The recording trigger. Asserting this trigger
at a rate as high as once per second will re-
sult in data being recorded.
RecordTime DT The record time that will be used when
recording data. If this input is not provid-
ing a valid time or is left disconnected, the
internal time of the RTAC will be used in-
stead.
Channel[n]_Data REAL The analog inputs to be recorded, where n
is the channel number from 1–16. Zeros are
recorded for all disconnected channel data
inputs.
Channel[n]_Name STRING(15) The names of analogs to be recorded, where
n is the channel number from 01–16. Chan-
nel names longer than 15 characters will be
truncated to the first 15 characters. If no
value is assigned, the channel name will be
set to Chan [n] Rec [x], where n is the chan-
nel number and x is the recorder number.

Outputs
Name IEC 61131 Type Description
SettingsError BOOL This output asserts if the recorder has a settings er-
ror. If this output is asserted, the recorder will not
function.
RecordingBlocked BOOL This output asserts immediately following an asser-
tion of the RecordTrigger input and remains asserted
for one second. When asserted, no recording occurs,
and any assertion of the RecordTrigger input is ig-
nored.

Programming Reference Instruction Manual Date Code 20190830


TrendRecorder 32.7
Function Blocks

ProfileManager (Function Block)


This function block is used to provide files to TEAM. It also helps manage RTAC stor-
age space for all configured recorders. It has three inputs—DeviceID, TerminalID, and
FID—which are used by Meter Reports software to label reports generated using data col-
lected from the RTAC. Do not create more than one instance of ProfileManager, as doing
so results in undesired behavior. All configured recorders must be connected to it via their
ConnectToProfileManager pins.

Inputs/Outputs
Name IEC 61131 Type Description
DeviceID STRING(22) The RTAC device description. Inputs greater than 22 char-
acters are truncated to 22 characters.
TerminalID STRING(22) A description of the function or location of the RTAC. In-
puts greater than 22 characters are truncated to 22 charac-
ters.
FID STRING The Firmware ID of the RTAC. SystemTags.FID must be
connected to this input. If this input is not connected, no
recording occurs.

Outputs
Name IEC 61131 Type Description
ConnectToRecorders The connection point for the ConnectToProfileM-
anager pins on each configured recorder. Each
recorder must be connected to this pin in order to
function.
DataStorageWarning BOOL This output asserts when not enough storage
space is available to meet the requirements of the
current recorder configurations. When this out-
put asserts recorders will run out of storage space
within 30 days. To resolve this issue either free
up hard drive space on the RTAC or reduce the
number of configured recorders.
DataStorageError BOOL This output asserts when no storage space is avail-
able, indicating no new data are being saved.
SettingsError BOOL This output asserts if the manager has a settings
error. If asserted, none of the recorders will func-
tion.

Telnet Communications
The ProfileManager function block uses Telnet to provide trend data to external clients
such as TEAM. To be able to communicate via Telnet on the RTAC, an Access Point with
Network Connection Type of Telnet and Local Port Number of 23 must be added to the
RTAC project.

Date Code 20190830 Instruction Manual Programming Reference


32.8 TrendRecorder
Recorder Operation

Recorder Operation
Recording Interval Functionality
The ProfileIntervalRecorder attempts to time-align the recording interval with the top of
minute, top of hour, or top of day. This makes for cleaner chart generation and data visu-
alization. The following table describes how each interval setting is adjusted.

Interval Setting (seconds) Time Alignment Behavior


1 Top of second
2 Top of second AND current second MOD 2 = 0
3 Top of second AND current second MOD 3 = 0
4 Top of second AND current second MOD 4 = 0
5 Top of second AND current second MOD 5 = 0
6 Top of second AND current second MOD 6 = 0
10 Top of second AND current second MOD 10 = 0
15 Top of second AND current second MOD 15 = 0
20 Top of second AND current second MOD 20 = 0
30 Top of second AND current second MOD 30 = 0
60 Top of minute
120 Top of minute AND current minute MOD 2 = 0
180 Top of minute AND current minute MOD 3 = 0
240 Top of minute AND current minute MOD 4 = 0
300 Top of minute AND current minute MOD 5 = 0
360 Top of minute AND current minute MOD 6 = 0
600 Top of minute AND current minute MOD 10 = 0
900 Top of minute AND current minute MOD 15 = 0
1800 Top of minute AND current minute MOD 30 = 0
3600 Top of hour
7200 Top of hour AND current hour MOD 2 = 0
All others Start recording immediately (no time alignment)

Effect of Task Cycle Time on TrendRecorder Functionality


Like all user logic executing on an RTAC, the Trend Recorder library executes at a speed
defined by the Cycle Time setting of the task it is running on. It is highly recommended NOTE: The slower the Task Cycle
setting, the longer it will take for the
that configured recorders be run on a task with a cycle time as fast as possible (i.e., 100 RTAC to communicate with TEAM. The
milliseconds or less). collection interval configured in TEAM
should be adjusted to account for this.

ProfileTriggerRecorder RecordTime Input Requirements


The ProfileTriggerRecorder function block can associate record data with an external time
stamp provided via the RecordTime input. This input is of type DT and in order to be valid
must be greater than midnight on January 1, 2000.

Programming Reference Instruction Manual Date Code 20190830


TrendRecorder 32.9
Benchmarks

Settings Changes
When the settings of a recorder are changed, all of the saved data for that recorder is re-
moved from the RTAC. A loss of data in other recorders could also occur because of storage
reallotment caused by the addition of a new recorder.
Changes to settings elsewhere in the RTAC (i.e., not recorder settings) will not result in
deleted data. The only data loss that may occur would be caused by a missed recording
interval during the sending of the new settings to the RTAC.
Do not remove or modify the files stored in the LDP folder on the RTAC. These files contain
settings and record data. Tampering with or removing these files may result in recorder data
loss or deletion.

Loss of Data Because of File System Use


Because of the flexibility of the RTAC, its file system usage is dependent on the specifics
of the application. If the file system is used for more than just the TrendRecorder library
(such as for file storage, FTP operations, or file retrieval), it is possible that not enough file
space will be available to store TrendRecorder data. If this occurs, recorders will not be
able to record new data.

Trend Recorder Data Files


Each recorder saves data to the RTAC hard drive in a binary file. A new file is created at
the top of each day, for as many as 30 days of record data. These files are viewable from
the RTAC web interface, but are saved in a binary format and are not human-readable. Do
not delete these files—doing so will cause recorder data loss. The TrendRecorder library
limits itself to 1 GB of space on the RTAC file system. Each recorder is given an equal
share of that space and will use as much of that space as is required based on its recording
interval setting or record trigger frequency.

Benchmarks
Benchmark Platforms
The benchmarking tests recorded for this library are performed on the following platforms.
ä SEL-3505
â R136-V0
ä SEL-3530
â R136-V0
ä SEL-3555
â Dual-core Intel i7-3555LE processor
â 4 GB ECC RAM
â R136-V0

Date Code 20190830 Instruction Manual Programming Reference


32.10 TrendRecorder
Benchmarks

Benchmark Test Descriptions


All tests were run on a 100-millisecond task cycle time with ProfileRecorders running at
the default interval of 60 seconds.
The posted times include the minimum, mean, maximum, and standard deviation of exe-
cution time in microseconds over 5000 samples.

Benchmark Results
Note: The benchmarks were not found to be different in any statistically significant way
from those for the previous release, so the numbers have not been updated.

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
Min 23 18 1
Mean 571 233 27
ProfileManager
Max 154315 1546 627
σ 2875 152 34
Min 26 19 1
Mean 978 556 26
1 ProfileIntervalRecorder
Max 2572 1120 80
σ 285 176 8
Min 25 18 1
Mean 854 311 37
ProfileManager
Max 186153 1567 568
σ 5422 214 42
Min 84 60 1
Mean 3633 2103 63
4 ProfileIntervalRecorders
Max 5462 3263 129
σ 834 641 14
Min 27 18 1
Mean 359 316 38
ProfileManager
Max 312459 2318 578
σ 4416 274 42
Min 252 164 4
Mean 10320 5642 179
12 ProfileIntervalRecorders
Max 16134 7944 328
σ 3972 1668 51
Min 24 19 1
Mean 233 278 34
ProfileManager
Max 88357 9557 717
σ 1259 259 43
Min 25 19 1
Mean 1026 565 23
1 ProfileTriggerRecorder
Max 2779 1100 60
σ 263 131 6

Programming Reference Instruction Manual Date Code 20190830


TrendRecorder 32.11
Benchmarks

Platform (time in µs)


Operation Tested
SEL-3505 SEL-3530 SEL-3555
Min 25 19 1
Mean 778 191 43
ProfileManager
Max 142039 13522 780
σ 3505 259 46
Min 87 60 2
Mean 3979 2182 66
4 ProfileTriggerRecorders
Max 5852 3450 151
σ 876 473 13
Min 27 18 1
Mean 216 265 11
ProfileManager
Max 90038 14945 92
σ 1284 310 5
Min 236 236 4
Mean 11434 6230 190
12 ProfileTriggerRecorders
Max 14799 8152 330
σ 2496 1201 37

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
APPENDIX A

Release Notes
AnalogCond

Version Summary of Revisions Date Code


3.5.2.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC type “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.1.1 ä Added class_ArmaFilter_LREAL. 20150722
3.5.1.0 ä Changed I_LimitedSplpf to inherit from I_Filter. 20141107
ä Modified class_LimitedSplpfStepToDefault to implement updated
I_LimitedSplpf.
ä Modified class_LimitedSplpfRampToDefault to implement up-
dated I_LimitedSplpf.
ä Added advanced ARMA filter.
ä Added dummy class_PassThroughFilter.
3.5.0.1 ä Initial release. 20140701

ChannelMonitoring

Version Summary of Revisions Date Code


3.5.1.2 ä Modified behavior of fb_ChannelIntegral EN input to allow inte- 20191024
gration pausing.
ä Made ExcursionThreshold dynamically settable for fb_Chan-
nelAlert and fb_MultiChannelAlert.
ä Added LatchAlarm input to fb_ChannelAlert and fb_MultiChan-
nelAlert.
ä Addressed an issue that could cause an unexpected Integral result
after a manual reset to fb_ChannelIntegral while the PeriodicPro-
cessing input is true.
3.5.1.1 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
ä Added fb_ChannelDerivative.
ä Added fb_ChannelIntegral.
ä Added fb_IndicatorTimeDelta.
3.5.0.0 ä Initial release. 20151223

Date Code 20190830 Instruction Manual Programming Reference


A.2 Release Notes
Dictionaries

CrossTaskData

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Copy operations between tasks have been optimized to be more 20160708
efficient for large cross task data sets.
3.5.0.2 ä Corrected catching of SysMem internal errors. 20140828
3.5.0.1 ä Initial release. 20140701

Dictionaries

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.1 ä Initial release. 20140811

Programming Reference Instruction Manual Date Code 20190830


Release Notes A.3
DynamicVectors

DynamicDisturbanceRecorder

Version Summary of Revisions Date Code


3.5.2.1 ä Fixes an issue where boolean data types could not be recorded in 20190726
a COMTRADE file.
ä Optimized the COMTRADE class so that files greater than 10 MB
can be created.
ä Must be used with R144 firmware or later.
3.5.2.0 ä Adds support for simple data types. 20190218
ä Increases maximum triggered COMTRADE file size from 1 MB
to 10 MB.
ä Extends COMTRADE pre- and post-trigger sample counts to
18,000.
ä Updates class_ComtradeFloat32 and class_TimeAlignedCsv to al-
low the LoggingInterval setting to change during runtime.
ä COMTRADE files are now compressed to reduce file size.
ä Must be used with R144 firmware or later.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release of class_ComtradeFloat32. 20170601
ä Initial release of class_SoeClass.
ä Initial release of class_TimeAlignedCsv.

DynamicVectors

Version Summary of Revisions Date Code


3.5.2.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.1.0 ä Added typed vectors for REAL, LREAL, LWORD, and POINTER. 20150511
3.5.0.2 ä Initial release. 20140811

Date Code 20190830 Instruction Manual Programming Reference


A.4 Release Notes
FTPSync

Email

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.6 ä Full SMTP client/server handshaking implemented. 20150722
ä Added fb_SimpleEmailClient2 and class_EmailClient2. These
items extend the basic objects, providing destination and source
port initialization parameters.
ä Attachment functionality added for multiple files and raw data.
ä Very large emails, over 10 KB in size, send correctly.
3.5.0.3 ä Added correct HELO syntax when using local ip “0.0.0.0”. 20141212
ä Allow up to 10 seconds to connect with a mail server instead of a
single scan.
3.5.0.2 ä Improved sending of long emails. 20141110
3.5.0.1 ä Initial release. 20141010

FTPSync

Version Summary of Revisions Date Code


3.5.0.0 ä Initial release. 20190830

Programming Reference Instruction Manual Date Code 20190830


Release Notes A.5
FileIo

FileIo

Version Summary of Revisions Date Code


3.5.4.1 ä Added facility to filter a directory listing to only return files newer 20190201
than or equal to the date and time specified.
ä Added new class_BasicDirectoryManager, which rotates the con-
tents of a given directory based on maximum size constraints.
ä Must be used with R144-V1 firmware or later.
3.5.3.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
ä Increased default g_p_FileIo_MaxBufferSize size from 1 MB to
10 MB
3.5.2.2 ä Added note recommending not using FileIO with RTAC firmware 20161221
versions R136-V0 and R136-V1.
ä Added class_TimeBasedDirectoryManager to provide directory
management capabilities for the user to keep files for a set number
of days rather than a maximum number of files.
ä Fixed an issue in class_DirectoryManger and class_LogDirectory-
Manager in which a system performing large quantities of FileIO
tasks could result in early deletion of managed files.
ä Added class_TimeBasedDirectoryManager to provide directory
management capabilities for the user to keep files for a set number
of days rather than a maximum number of files.
ä Fixed an issue in class_DirectoryManger and class_LogDirectory-
Manager in which a system performing large quantities of FileIO
tasks could result in early deletion of managed files.
ä Rebranded the FileIo library to uppercase the “o” and be: “FileIO”
(literature change only, no changes made to actual library name or
namespaces).
3.5.2.0 ä Added class_DirectoryManager to provide directory management 20160610
capabilities without the file content helps and constraints found in
class_LogDirectoryManager.
ä Added ability to write to directory manager files from vectors, byte
arrays, and SELStrings in addition to the strings previously possi-
ble.
ä Added functions to facilitate accessing SOEs monotonically in or-
der of SOE creation.
ä Added function to query for available file system free space.
ä Modified file deletion algorithm for the directory manager classes
to recover space faster in the case that the directory size is ex-
ceeded.
ä Modified class_LogDirectoryManager to remove metadata for
deleted files from the .unsent file both when FTP is configured
and when it is not.
ä Modified library to ensure that calling the StartNewLog()
method on class_LogDirectoryManger multiple times during
startup always appends the time-stamped file close message.
ä Modified BytesLeft in class_FileWriter to show all pending work,
where before it did not include bytes to be written to a new file
name.

Date Code 20190830 Instruction Manual Programming Reference


A.6 Release Notes
GridConnect

ä Modified class_LogDirectoryManager to prevent a condition


where dates before the year 2000 cause constant writing and ro-
tating of files.
ä Modified class_Filewriter property Filename to no longer require
file content before allowing Filename to be modified again.
ä Removed deprecated features from class_FileReader because of
loss of file system support. Use of these features now results in
compilation errors.
ä Removed deprecated class_EventReportListing because of loss of
file system support. Use of this class now results in compilation
errors.
3.5.1.0 ä Added class_FileReader2 that replaces deprecated dependency 20150930
with new sel_file features for accessing events.
ä Added functions and documentation to wrapping underlying
firmware API.
ä Removed documentation of underlying firmware API.
ä Added ability to read from the SOE database into the logic engine.
3.5.0.10 ä Made class_LogDirectoryManager able to delete files more 20150717
quickly, facilitating a faster file creation rate and larger number
of files.
ä Fixed issue in class_FileWriter where changing Filename in quick
succession caused the class to get stuck writing to a single file.
3.5.0.9 ä Fixed issue where an invalid Filename followed immediately by a 20150213
valid Filename locked out class_FileWriter.
3.5.0.7 ä Added the Filename property to class_FileWriter. 20141205
ä Added a new class_LogDirectoryManager.
3.5.0.4 ä Internal parts of the library are now hidden. 20141008
ä Tested with sel_file V1.0.1.0 -released with R133 firmware (see
RTAC firmware release notes for more details).
3.5.0.3 ä Initial release. 20140812

GridConnect

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Updated internal calculations to better handle cases where inverter
ratings are inadvertently set to zero.
ä Must be used with R143 firmware or later.
3.5.0.2 ä Renamed library components to conform to library extensions 20180427
naming conventions.
ä Add quick stop feature.
ä Add control mode: VAR control.
ä Add control mode: PF Compensation.
ä Add control mode: Voltage Compensation.
ä Updated control mode: Voltage control now employs direct VAR
control of the inverters.
ä Add frequency regulation for plant response.
ä Add frequency regulation for storage system response.

Programming Reference Instruction Manual Date Code 20190830


Release Notes A.7
GridConnect

ä Add support for energy storage system.


ä Add downramp control (real power support for storage systems).
0.1.5.2 ä Fixed VAR Control mode. 20150708
ä Added an additional dead band detection exclusively for VAR
mode, because inverter control is only enabled if an out-of-dead-
band is signaled.
ä Corrected the initialized values in the instruction manual.
ä Added separate tuning parameters for VAR control mode.
0.1.5.1 ä Added ability to control multiple capacitors. 20150605
ä Added VAR control mode to types of POI control.
1.4.3 ä Added SEL-3555 and SEL-3532 to the MOT Checker. 20141231
1.4.2 ä Changed library dependencies to use the newest version always. 20140812
1.4.1 ä Added PL_MODE to GC_MSPC for user selection of one of three 20140122
power limit modes.
â“NoLimit” means all power limit outputs are set to 100%.
â“Simple” means the power Limit setpoint is converted to a per-
centage of the P ratings of the available invertersg. The same
percent output limit is sent to each inverter. This simplification
does not address any non-uniform cloud cover issues.
â“Advanced” means use the PI controller based limiter (requires
inverter data updates <5 seconds).
1.3.1 ä Added INV_PL_DELAY input pin to GC_MSPC. 20131104
ä Delay time between inverter not responding to power set point and
application of the adaptive power limit.
1.2.2 ä Changed MSPC.V input default value to 1.0. 20130919
ä Changed MSPC.V_SP input default value to 1.0.
ä Changed MSPC.V_DB input default value to 0.02.
1.2.1 ä Add POI QUALITY and ENABLE pins. 20130722
ä Added ENABLED output pin to GC_MSPC.
1.1.8 ä Enhanced power limit control. Added per inverter power limit anti- 20130529
windup logic.
1.1.7 ä Modified set point bias logic during voltage or powerfactor excur- 20130506
sions beyond critical limits.
ä Decoupled PF control dead band and lag/lead alarm generation
from voltage limits.
1.1.6 ä Decrease power limit ramp rate output dead band to 0.01%/Sec. 20130412
ä Corrected predictive aggregate inverter response logic.
ä Limit power limit control output between 0 and 100% in open loop
and closed loop mode.
1.1.5 ä GC_INV - Corrected trigger logic to allow PF_TRIG output to 20130206
reset between control intervals.
1.1.4 ä GC_MSPC - Corrected closed loop cycle time pulse generation. 20130206
1.1.3 ä GC_MSPC Function Block Bug Fixes: 20130201
âCorrected Retry pulse generation.
âCorrected Closed loop cycle time pulse generation.
âCorrected Version output pin.
1.1.2 ä Added RTAC MOT support. 20121126
1.1.1 ä Initial release. 20120906

Date Code 20190830 Instruction Manual Programming Reference


A.8 Release Notes
MathMatrix

IPAliasRedundancy

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Initial release. 20180427

MathComplex

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.2 ä Corrected bug in struct_ComplexRect_TO_vector_t() that 20150925
returned a value of NaN due to rounding errors.
ä Defined the range of the angle returned by struct_-
ComplexRect_TO_vector_t() to be [–180, 180] degrees. Pre-
vious to this release, this was undefined but returning [0, 360].
3.5.0.1 ä Fixed negative return values in fun_ComplexAbs(). This also 20150722
corrected issues in fun_ComplexCmp() and fun_ComplexLn().
3.5.0.0 ä Initial release. 20150511

MathMatrix

Version Summary of Revisions Date Code


3.5.1.1 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.1 ä Initial release. 20150722

Programming Reference Instruction Manual Date Code 20190830


Release Notes A.9
PowerSystemModel

PacketEncodings

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Replaced the deprecated “POINTER_TO_ANY” type with
POINTER_TO_BYTE”.
ä Must be used with R143 firmware or later.
3.5.0.4 ä Added base64-MIME encoding and decoding functionality. 20150722
3.5.0.3 ä Initial release. 20141010

PowerMetering

Version Summary of Revisions Date Code


3.5.2.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.1.0 ä Added fb_KYZ. 20160415
ä Added fb_KY.
ä Resolved an issue that could cause the fb_Demand block to discard
the initialValue after the first five minutes, resulting in the Demand
calculation being reset.
ä Updated examples using retain values for clarity.
3.5.0.5 ä Initial release. 20140714

PowerSystemModel

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20150924

Date Code 20190830 Instruction Manual Programming Reference


A.10 Release Notes
Quicksort

PowerSystemProtection

Version Summary of Revisions Date Code


3.5.1.1 ä Removed licensing check, making PowerSystemProtection a free- 20191018
to-use library.
3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180619
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release of time-overcurrent function block. 20170517
ä Initial release of instantaneous-overcurrent function block.
ä Initial release of loss-of-potential function block.
ä Initial release of overvoltage function block.
ä Initial release of undervoltage function block.
ä Initial release of bus-line voltage check function block.
ä Initial release of conductor thermal overload function block.

Queue

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Replaced the deprecated POINTER_TO_ANY type with
POINTER_TO_BYTE.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20150511

Quicksort

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Replaced the deprecated POINTER_TO_ANY type with
POINTER_TO_BYTE.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20140812

Programming Reference Instruction Manual Date Code 20190830


Release Notes A.11
SELEthernetController

RecordingTriggers

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.2 ä Initial release of high-threshold function block. 20170908
ä Initial release of low-threshold function block.
ä Initial release of rate-of-change function block.
ä Initial release of digital trigger function block.

ReportGenerator

Version Summary of Revisions Date Code


3.5.0.1 ä Updated class_ReportGenerator for compatibility with SEL Server 20191024
FILE SHOW command.
ä Addressed an issue with the Report Generator extension that may
cause a logic engine restart when referencing REAL or LREAL
variables with the value NaN, +inf, or -inf.
ä Addressed an issue with the Report Generator extension that may
keep timeStamp_t data types from being rendered in the report.
3.5.0.0 ä Initial release. 20190830

SELEthernetController

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.6 ä Allow the class to recover instead of closing the socket when at- 20160501
tempting to send large amounts of data all at once.
3.5.0.5 ä Added queues as input and output mechanisms for socket data. 20150511
ä Allow TCP client ports to connect to a server without binding to a
specific local port.
3.5.0.3 ä Made TCP sockets not throw error when outgoing data buffer is 20141107
full.
3.5.0.2 ä Initial release. 20141010

Date Code 20190830 Instruction Manual Programming Reference


A.12 Release Notes
SELUtils

SELRand

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.0 ä Initial release. 20140811

SELServerSimulators

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.1 ä Initial release. 20150511

SELString

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Added FromByteArray and ToByteArray methods. 20140811
ä Added AppendString and PrependString methods.
ä Added FindString method.
ä Protected classes against assignment.
3.5.0.1 ä Initial release. 20140701

SELUtils

Version Summary of Revisions Date Code


3.5.1.1 ä Added validation functions for IP addresses, REALs, and LRE- 20191024
ALs.
3.5.1.0 ä Added functions for converting REAL, LREAL, timestamp_t, and 20180917
quality_t to STRING.
3.5.0.1 ä Initial release. 20180703

Programming Reference Instruction Manual Date Code 20190830


Release Notes A.13
TrendRecorder

SVPplus

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Improved precision of entire algorithm. 20150718
ä Improved performance for large matrices.
ä Hid internal variables of all function blocks.
3.5.0.0 ä Initial release. 20141101

SnmpLite

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.6 ä Improved management of Ethernet socket failure. 20150511
3.5.0.5 ä Removed limitation that number and SNMP ID of ports cannot 20150213
change.
3.5.0.4 ä Initial release. 20141010

SyslogCollector

Version Summary of Revisions Date Code


3.5.0.0 ä Initial release. 20180928

TrendRecorder

Version Summary of Revisions Date Code


3.5.1.0 ä Allows new versions of ACSELERATOR RTAC to compile projects 20180921
for previous firmware versions without SEL IEC types “Cannot
convert” messages.
ä Must be used with R143 firmware or later.
3.5.0.3 ä Resolved an issue where, under certain conditions, recorded data 20170412
were not provided to ACSELERATOR TEAM software.
ä Removed library version 3.5.0.2 from the installer.
3.5.0.2 ä Initial release. 20161216

Date Code 20190830 Instruction Manual Programming Reference


This page intentionally left blank
APPENDIX B

Developer Mode
Developer Mode can be enabled by going to the following location: SEL > Options >
Preferences.
Once the check box is selected and the RTAC software has been restarted, projects R135
and later will support the ability to create libraries.
Libraries are created via the POUs tab. Once the desired logic has been written, it can
be exported as a compiled library to be installed and included in other RTAC software
installations and project configurations.
Prior to saving the POUs as a .compiled-library, the following items in the project infor-
mation must be present.
ä Summary tab:
â Company must be filled out
â Title must be filled out
â Version must be filled out
â Released box must be checked

Figure B.1 Summary Tab for Project Information

ä Properties tab:
Step 1. Set Key to Public.
Step 2. SetType to Boolean.
Step 3. Set Value to True.
Step 4. Click Add.
This will allow logic in the library to be accessed by other logic in the RTAC project.

Date Code 20190830 Instruction Manual Programming Reference


B.2 Developer Mode

Figure B.2 Properties Tab for Project Information

Once project information is filled out properly, click POU > Save POUs as .compiled-
library.

Figure B.3 Save POUs as .compiled-library

Programming Reference Instruction Manual Date Code 20190830

You might also like