Automation Interface: Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 179

Manual

Automation Interface

TwinCAT 3

Version: 1.3
Date: 2019-12-20
Table of Contents

Table of Contents
1 Foreword .................................................................................................................................................... 7
1.1 Notes on the documentation.............................................................................................................. 7
1.2 Safety instructions ............................................................................................................................. 8

2 Overview..................................................................................................................................................... 9
2.1 Product description ............................................................................................................................ 9
2.2 Version overview ............................................................................................................................. 11
2.3 Frequently Asked Questions ........................................................................................................... 14

3 Installation................................................................................................................................................ 16
3.1 System requirements....................................................................................................................... 16
3.2 Installation ....................................................................................................................................... 16

4 Configuration ........................................................................................................................................... 19
4.1 Quickstart......................................................................................................................................... 19
4.2 Basics .............................................................................................................................................. 19
4.2.1 Accessing TwinCAT configuration ...................................................................................  19
4.2.2 Browsing TwinCAT configuration.....................................................................................  22
4.2.3 Custom TreeItem Parameters .........................................................................................  25
4.2.4 TwinCAT Project Template..............................................................................................  25
4.2.5 Implementing a COM Message Filter ..............................................................................  26
4.2.6 Handling different Visual Studio versions ........................................................................  29
4.2.7 Silent Mode......................................................................................................................  30
4.3 Best practice .................................................................................................................................... 30
4.3.1 Visual Studio....................................................................................................................  30
4.3.2 System.............................................................................................................................  37
4.3.3 ADS .................................................................................................................................  49
4.3.4 PLC..................................................................................................................................  52
4.3.5 I/O ....................................................................................................................................  66
4.3.6 TcCOM ............................................................................................................................  89
4.3.7 C++ ..................................................................................................................................  93
4.3.8 Measurement...................................................................................................................  97
4.3.9 Motion ............................................................................................................................  100
4.3.10 Safety.............................................................................................................................  102

5 API........................................................................................................................................................... 103
5.1 Reference ...................................................................................................................................... 103
5.2 ITcSysManager ............................................................................................................................. 104
5.2.1 ITcSysManager..............................................................................................................  104
5.2.2 ITcSysManager::NewConfiguration ...............................................................................  106
5.2.3 ITcSysManager::OpenConfiguration .............................................................................  106
5.2.4 ITcSysManager::SaveConfiguration ..............................................................................  107
5.2.5 ITcSysManager::ActivateConfiguration .........................................................................  107
5.2.6 ITcSysManager::IsTwinCATStarted ..............................................................................  107
5.2.7 ITcSysManager::StartRestartTwinCAT..........................................................................  108
5.2.8 ITcSysManager::LinkVariables ......................................................................................  108
5.2.9 ITcSysManager::UnlinkVariables...................................................................................  109

Automation Interface Version: 1.3 3


Table of Contents

5.2.10 ITcSysManager2::GetTargetNetId.................................................................................  109


5.2.11 ITcSysManager2::SetTargetNetId .................................................................................  110
5.2.12 ITcSysManager2::GetLastErrorMessages.....................................................................  110
5.2.13 ITcSysManager::LookupTreeItem .................................................................................  110
5.2.14 ITcSysManager3::LookupTreeItemById ........................................................................  111
5.2.15 ITcSysManager3::ProduceMappingInfo ........................................................................  112
5.2.16 ITcSysManager3::ConsumeMappingInfo ......................................................................  112
5.3 ITcSmTreeItem .............................................................................................................................. 113
5.3.1 ITcSmTreeItem ..............................................................................................................  113
5.3.2 ITcSmTreeItem Item Types ...........................................................................................  114
5.3.3 Tree item sub types .......................................................................................................  118
5.3.4 ITcSmTreeItem::ProduceXml ........................................................................................  146
5.3.5 ITcSmTreeItem::ConsumeXml ......................................................................................  147
5.3.6 ITcSmTreeItem::CreateChild .........................................................................................  148
5.3.7 ITcSmTreeItem::DeleteChild .........................................................................................  150
5.3.8 ITcSmTreeItem::ImportChild..........................................................................................  151
5.3.9 ITcSmTreeItem::ExportChild .........................................................................................  151
5.3.10 ITcSmTreeItem::LookupChild ........................................................................................  152
5.3.11 ITcSmTreeItem::GetLastXmlError .................................................................................  152
5.4 ITcPlcProject.................................................................................................................................. 153
5.4.1 ITcPlcProject..................................................................................................................  153
5.4.2 ITcPlcProject::GenerateBootProject ..............................................................................  154
5.5 ITcPlcPou ...................................................................................................................................... 154
5.5.1 ITcPlcPou ......................................................................................................................  154
5.5.2 IECLanguageTypes .......................................................................................................  154
5.6 ITcPlcDeclaration .......................................................................................................................... 155
5.7 ITcPlcImplementation .................................................................................................................... 156
5.8 ITcPlcIECProject............................................................................................................................ 157
5.8.1 ITcPlcIECProject............................................................................................................  157
5.8.2 PlcImportOptions ...........................................................................................................  158
5.8.3 ITcPlcIECProject::PlcOpenExport .................................................................................  158
5.8.4 ITcPlcIECProject::PlcOpenImport..................................................................................  158
5.8.5 ITcPlcIECProject::SaveAsLibrary ..................................................................................  159
5.9 ITcPlcLibraryManager ................................................................................................................... 159
5.9.1 ITcPlcLibraryManager....................................................................................................  159
5.9.2 ITcPlcLibraryManager::AddLibrary ................................................................................  161
5.9.3 ITcPlcLibraryManager::AddPlaceholder ........................................................................  162
5.9.4 ITcPlcLibraryManager::InsertRepository .......................................................................  162
5.9.5 ITcPlcLibraryManager::InstallLibrary .............................................................................  163
5.9.6 ITcPlcLibraryManager::MoveRepository........................................................................  163
5.9.7 ITcPlcLibraryManager::RemoveReference....................................................................  163
5.9.8 ITcPlcLibraryManager::RemoveRepository ...................................................................  164
5.9.9 ITcPlcLibraryManager::ScanLibraries............................................................................  164
5.9.10 ITcPlcLibraryManager::SetEffectiveResolution .............................................................  165
5.9.11 ITcPlcLibraryManager::UninstallLibrary.........................................................................  165
5.10 ITcPlcReferences .......................................................................................................................... 166

4 Version: 1.3 Automation Interface


Table of Contents

5.11 ITcPlcLibrary.................................................................................................................................. 166
5.12 ITcPlcLibraries ............................................................................................................................... 167
5.12.1 ITcPlcLibraries ...............................................................................................................  167
5.12.2 ITcPlcLibraries::get_Item ...............................................................................................  167
5.13 ITcPlcLibRef .................................................................................................................................. 167
5.14 ITcPlcPlaceholderRef .................................................................................................................... 168
5.15 ITcPlcLibRepository....................................................................................................................... 168
5.16 ITcPlcLibRepositories .................................................................................................................... 169
5.16.1 ITcPlcLibRepositories ....................................................................................................  169
5.16.2 ITcPlcLibRepositories::get_Item ....................................................................................  169
5.17 ITcPlcTaskReference .................................................................................................................... 170

6 Samples .................................................................................................................................................. 171
6.1 Sample downloads ........................................................................................................................ 171
6.2 Scripting Container ........................................................................................................................ 171
6.2.1 Scripting Container ........................................................................................................  171
6.2.2 Projects..........................................................................................................................  172
6.3 CodeGenerationDemo................................................................................................................... 175
6.4 Visual Studio Plugin - PlcVersionInfo ............................................................................................ 177

7 Appendix ................................................................................................................................................ 179
7.1 Miscallaneous error codes............................................................................................................. 179

Automation Interface Version: 1.3 5


Table of Contents

6 Version: 1.3 Automation Interface


Foreword

1 Foreword

1.1 Notes on the documentation


This description is only intended for the use of trained specialists in control and automation engineering who
are familiar with applicable national standards.
It is essential that the documentation and the following notes and explanations are followed when installing
and commissioning the components.
It is the duty of the technical personnel to use the documentation published at the respective time of each
installation and commissioning.

The responsible staff must ensure that the application or use of the products described satisfy all the
requirements for safety, including all the relevant laws, regulations, guidelines and standards.

Disclaimer

The documentation has been prepared with care. The products described are, however, constantly under
development.
We reserve the right to revise and change the documentation at any time and without prior announcement.
No claims for the modification of products that have already been supplied may be made on the basis of the
data, diagrams and descriptions in this documentation.

Trademarks

Beckhoff®, TwinCAT®, EtherCAT®, EtherCAT G®, EtherCAT G10®, EtherCAT P®, Safety over EtherCAT®,
TwinSAFE®, XFC®, XTS® and XPlanar® are registered trademarks of and licensed by Beckhoff Automation
GmbH.
Other designations used in this publication may be trademarks whose use by third parties for their own
purposes could violate the rights of the owners.

Patent Pending

The EtherCAT Technology is covered, including but not limited to the following patent applications and
patents:
EP1590927, EP1789857, EP1456722, EP2137893, DE102015105702
with corresponding applications or registrations in various other countries.

EtherCAT® is a registered trademark and patented technology, licensed by Beckhoff Automation GmbH,
Germany

Copyright

© Beckhoff Automation GmbH & Co. KG, Germany.


The reproduction, distribution and utilization of this document as well as the communication of its contents to
others without express authorization are prohibited.
Offenders will be held liable for the payment of damages. All rights reserved in the event of the grant of a
patent, utility model or design.

Automation Interface Version: 1.3 7


Foreword

1.2 Safety instructions


Safety regulations

Please note the following safety instructions and explanations!


Product-specific safety instructions can be found on following pages or in the areas mounting, wiring,
commissioning etc.

Exclusion of liability

All the components are supplied in particular hardware and software configurations appropriate for the
application. Modifications to hardware or software configurations other than those described in the
documentation are not permitted, and nullify the liability of Beckhoff Automation GmbH & Co. KG.

Personnel qualification

This description is only intended for trained specialists in control, automation and drive engineering who are
familiar with the applicable national standards.

Description of symbols

In this documentation the following symbols are used with an accompanying safety instruction or note. The
safety instructions must be read carefully and followed without fail!

DANGER
Serious risk of injury!
Failure to follow the safety instructions associated with this symbol directly endangers the life and health of
persons.

WARNING
Risk of injury!
Failure to follow the safety instructions associated with this symbol endangers the life and health of per-
sons.

CAUTION
Personal injuries!
Failure to follow the safety instructions associated with this symbol can lead to injuries to persons.

NOTE
Damage to the environment or devices
Failure to follow the instructions associated with this symbol can lead to damage to the environment or
equipment.

Tip or pointer
This symbol indicates information that contributes to better understanding.

8 Version: 1.3 Automation Interface


Overview

2 Overview

2.1 Product description


The TwinCAT Automation Interface enables the automatic creation and manipulation of TwinCAT XAE
configurations via programming/scripting code. The automation of a TwinCAT configuration is available
through so-called automation interfaces which can be accessed from all COM-capable programming
languages (e.g. C++ or .NET) and also from dynamic script languages - e.g. Windows PowerShell,
IronPython or even legacy VBscript. These automation interfaces are bound to the Visual Studio Automation
Model and extend Visual Studio with TwinCAT3 features.

TwinCAT Automation Interface enables an efficient engineering process by giving customers the possibility
to automate the configuration of a full TwinCAT solution.

Traditionally, a machine configuration had to be manually adapted to each new project or had even to be
created from scratch, which could not only involve a tremendous amount of engineering time and therefore
costs but is also error-prone because of human mistakes.

Automation Interface Version: 1.3 9


Overview

With TwinCAT Automation Interface, the process of adapting TwinCAT configurations to a new environment
or even create new TwinCAT configurations from scratch can be automated according to the customers
needs.

Readers should continue with the following topics:

Basics

Topic Description
Creating/Loading TwinCAT XAE configurations [} 19] Describes how to create or open a TwinCAT
configuration
Navigating TwinCAT XAE [} 22] Describes how to navigate through a TwinCAT
configuration
Custom tree item parameters [} 25] Describes how to access custom parameters of an
item. This is important to access configuration
parameters of a TwinCAT tree item.
Implementing a COM message filter [} 26] Describes how to implement an own COM message
filter to circumvent rejected COM calls

10 Version: 1.3 Automation Interface


Overview

Best practice

Topic Description
Creating and handling PLC projects [} 52] Describes how to handle PLC projects
Creating and handling PLC POUs [} 61] Describes how to handle PLC objects/code
Creating and handling PLC Libraries [} 57] Describes how to handle PLC libraries, repositories
and placeholder
Creating and handling MOTION projects [} 100] Describes how to create TwinCAT Motion projects
(NC-Task, Axes, ...)
Creating and handling EtherCAT devices [} 66] Describes how to create EtherCAT devices and
connect them to an EtherCAT topology
Creating and handling TwinCAT Measurement [} 97] Describes how to handle TwinCAT Measurement
projects.
Creating and handling TcCOM modules [} 89] Describes how to handle TcCOM modules.
Using templates Describes the process of template generation and
template usage.
Creating and handling network variables [} 72] Describes how to create network variables (publisher/
subscriber variables)
Creating and handling Tasks [} 40] Describes how to create Tasks and link them with
other objects (PLC-Projects, ...)
From offline to online configurations [} 47] Some IO devices need physical address information
before the configuration can be activated. This article
explains how to retrieve and set this information.
Accessing the Error List window of Visual Studio The Error List can be very helpful for debugging and
[} 36] diagnostic purposes
Accessing window tabs in Visual Studio [} 35] Describes how to get access to Visual Studio
windows.
Handling different versions of Visual Studio [} 29] Describes how different Versions of Visual Studio can
be used for Automation Interface
Attaching to running Visual Studio instances [} 34] Demonstrates how you can attach to existing
(already running) Visual Studio instances to use
Automation Interface
Setting TwinCAT target platform [} 33] Describes how to set the TwinCAT target platform for
compilation.

Additionally, this documentation also includes a full API reference [} 103] of all interfaces. The How to and
Sample [} 171] sections offer a free composition of script code fragments, configuration steps and demo
projects. They also contain an unsorted and growing list of "real-world" samples.

Also see about this


2 Using Templates [} 42]

2.2 Version overview


The following table gives an overview about the available features of the Automation Interface related to
TwinCAT 2.11, TwinCAT 3.0, TwinCAT 3.1 and a look-out to future TwinCAT versions which may be subject
to change.

Automation Interface Version: 1.3 11


Overview

Feature TwinCAT 2.11 TwinCAT 3.0 TwinCAT 3.1 Future versions


General settings
Importing
configuration
templates
TwinCAT System
Service handling
(Run-/Config-
mode)
Load/Save/Create/
Activate
configurations
Support for remote
TwinCAT targets
Configuring tasks
with process image
Configuring tasks - -
without process
image
Multicore support -
for tasks
Handling of - - -
TwinCAT licenses

Route
management
Adding/Removing
ADS routes
Broadcast Search

I/O
Scanning for online
devices
Adding/removing
devices, boxes and
terminals
Parameterization of
devices, boxes and
terminals
EtherCAT
topologies
Network variables

PLC
Mapping of
variables, e.g. with
I/Os or axes
Adding/removing
PLC projects
Adding/removing - -
PLC POUs, DUTs,
GVLs

12 Version: 1.3 Automation Interface


Overview

Feature TwinCAT 2.11 TwinCAT 3.0 TwinCAT 3.1 Future versions


Getting/setting PLC - -
code of POUs,
DUTs, GVLs
Adding/removing - -
PLC libraries
Adding/removing - -
PLC placeholders
Adding/removing - -
PLC repositories
Adding/removing - -
PLC libaries to
repositories
Saving PLC - -
projects as a PLC
library
Compiler and error - -
output handling
PLCopen XML - -
import/export
Programing - -
2 2
language:
Structured Text
(ST)
Programing - -
1 1
language:
Sequential function
chart (SFC)

C++
Adding/Removing - - -
C++ project
templates
Compiler and error - - -
output handling

Motion
Adding/Removing - -
NC-Tasks
Adding/Removing - -
axes
Parameterization of - -
3 3
axes settings
Mapping of - -
variables, e.g. with
PLC

TcCOM modules
Adding/Removing - -
TcCOM modules
Parameterization of - -
TcCOM modules

Measurement

Automation Interface Version: 1.3 13


Overview

Feature TwinCAT 2.11 TwinCAT 3.0 TwinCAT 3.1 Future versions


Adding/Removing - -
TwinCAT
Measurement
projects
Adding/Removing - -
charts
Adding/Removing - -
axes
Adding/Removing - -
channels
Parameterization of - -
charts, axes and
channels
Starting/Stopping - -
records

Notes
1
possibility to implement via PLCopen XML
2
possibility to implement source code either in clear-
text or PLCopen XML
3
with limitations. Some settings are stored in a binary
format and cannot be edited.

2.3 Frequently Asked Questions


• What is TwinCAT Automation Interface?

TwinCAT Automation Interface is an interface to access the configuration of TwinCAT from an external
application. This enables customers to automate the configuration of TwinCAT.
• Can I create an offline TwinCAT configuration (without any attached devices)?

Yes. You can create the TwinCAT configuration offline by manually attaching (without "Scan Devices) all
devices and then providing online values, e.g. addresses, later after all devices have been attached. Please
see our samples [} 171] page for more information. There is also an How-To sample [} 87] which shows
you how to provide addressing information for pre-configured I/O devices.
• Which programming and scripting languages are supported?

Every programming or scripting language that supports the COM object model is supported. Please see our
system requirements [} 16] page for more information.
• Which TwinCAT features are accessible via Automation Interface?

Please see our version overview [} 11] page for more information about which TwinCAT features are
accessible via Automation Interface.
• What if I don't find an appropriate programming method or property for a specific setting?

If you don't find an appropriate Automation Interface method or property for a specific setting, you may use
the Import/Export feature of TwinCAT to read/write this setting. Please refer to our article about custom tree
item parameters [} 25] for more information.
• Can I automate the configuration of TwinCAT PLC?

Yes. This feature will be available with TwinCAT 3.1. Please refer to our version overview [} 11] page for
more information.
• Can I execute Automation Interface code on TwinCAT XAR (Runtime-only) computers?

14 Version: 1.3 Automation Interface


Overview

No. To execute Automation Interface code, TwinCAT XAE (Engineering) is needed, because Automation
Interface directly accesses the Visual Studio COM object to communicate with the TwinCAT configuration.
However, you can use a TwinCAT XAE computer to remotely connect to a TwinCAT runtime and configure it.
• When should I use ADS and when Automation Interface?

This is a question which cannot be answered easily because it heavily depends on what you would like to
achieve. TwinCAT Automation Interface has been designed primarily to help customers to automate the
configuration of TwinCAT. If you want to cyclically read/write values to IOs or PLC variables, our ADS APIs
are probably better suited.
• Do I need to modify my Automation Interface code if I switch languages in TwinCAT XAE, e.g.
from English to German?

All TwinCAT XAE items that are language dependent (Devices, Boxes, Axes, Channels, ...) can either be
accessed via the currently set XAE language or via their english name. For example, if the XAE language is
changed from English to German, the term "Channel" will be displayed in XAE as "Kanal" but is still available
under the name "Channel" via Automation Interface. To be fully compatible, we recommend to build your
Automation Interface code based on english terminology.

Please note: This feature comes with TwinCAT 3.x only! Systems based on TwinCAT 2.x are not language
independent!
• I'm a machine builder and use a TwinCAT configuration template for all machine types and only
enable/disable certain I/Os. Can I also do that with Automation Interface?

Yes. There is an How-To sample [} 88] which shows you exactly how to do that.
• Can I also create ADS routes or execute a Broadcast Search?

Yes. Please see our samples [} 171] and How-To pages for more information.

Automation Interface Version: 1.3 15


Installation

3 Installation

3.1 System requirements


The following chapter lists all hardware and software requirements for the TwinCAT Automation Interface
and gives some recommendations for programming and scripting languages.

Hardware and Software

TwinCAT Automation Interface will be automatically installed by TwinCAT setup. Therefore it needs the
same hardware and software system requirements as TwinCAT System Manager / TwinCAT 3 XAE
(Engineering). When using the Automation Interface to configure a remote TwinCAT device, it is important
that the remote version of TwinCAT equals or is higher than on the engineering computer.

Please note that you can execute Automation Interface scripts on 32-bit and 64-bit platforms, however you
need to make sure that your program/script has been compiled for and runs in 32-bit mode.

Recommended programming languages

The following programming languages are recommended to use with TwinCAT Automation Interface:
• .NET languages, such as C# or Visual Basic .NET

Please note: Although C++ implementations will also work, we highly recommend using one of the
languages above because of their easy and straight-forward programming concepts regarding COM. Most of
the sample code in this documentation is based on C#.

Recommended scripting languages

Although every scripting language with COM support may be used to access TwinCAT Automation Interface,
we recommend to use the Windows Powershell as it provides the best level of integration between Operating
System and application. Please note that at least TwinCAT 3.1 Build 4020.0 is required to use dynamic
languages like the Windows Powershell.

3.2 Installation
All files needed for the TwinCAT Automation Interface will be installed automatically during TwinCAT setup.
As mentioned in the introduction, the Automation Interface communicates with TwinCAT via COM. All
needed COM objects are configured automatically so that COM-capable programming and scripting
languages can access these objects.

16 Version: 1.3 Automation Interface


Installation

Using the Automation Interface within a .NET application (C#, VB.NET, ...)

To access the Automation interface from a .NET application, you need to add a reference to the
corresponding COM object Beckhoff TwinCAT XAE Base (depending on your TwinCAT version, see table
below) within the Visual Studio project.

After the reference has been added, you can access the COM object via the namespace
TCatSysManagerLib .

Please proceed with the article Accessing TwinCAT configuration [} 19] which explains all further steps in
more detail.

Using the Automation Interface within scripting languages

TwinCAT Automation Interface can also be used with COM-capable scripting languages, for example
Windows PowerShell or IronPython. As scripting languages are being interpreted at runtime and not
compiled, they always have access to all currently registered COM objects in the operating system.
Therefore a reference is not needed.

Please proceed with the article Accessing TwinCAT configuration [} 19] which explains all further steps in
more detail.

Type library versions

During the TwinCAT product lifecycle, the type library mentioned above may be delivered in different
versions because of added functionalities and/or big TwinCAT versions steps. The table below gives an
overview about all different type library versions.

Automation Interface Version: 1.3 17


Installation

Type library name Type library version TwinCAT version


Beckhoff TCatSysManager 1.1 1.1 TwinCAT 2.11
Type Library
Beckhoff TwinCAT XAE Base 2.0 2.0 TwinCAT 3.0
Type Library
Beckhoff TwinCAT XAE Base 2.1 2.1 TwinCAT 3.1
Type Library
Beckhoff TwinCAT XAE Base 3.1 3.1 TwinCAT 3.1 Build 4020.0 and
Type Library above

18 Version: 1.3 Automation Interface


Configuration

4 Configuration

4.1 Quickstart
Because the TwinCAT Automation Interface provides a lot of possibility, it might sometimes be hard to
understand where to start. This quickstart provides a step-by-step introduction into the TwinCAT Automation
Interface and the different articles in this documentation.

We recommend to read the following in-depth articles:

Step Article Content


1 Visual Studio ProgIDs [} 29] Describes how different Visual Studio versions can be
accessed via the Visual Studio API
2 Accessing TwinCAT configuration [} 19] Describes how to use the Automation Interface in
order to create a new TwinCAT project. It also covers
the co-existence of Visual Studio API and TwinCAT
Automation Interface and how they correlate with each
other.
3 Navigating TwinCAT configuration [} 22] Describes how to navigate through an opened
TwinCAT configuration by using different Automation
Interface functionalities.
4 The necessity of a COM MessageFilter Describes why every Automation Interface application
[} 26] should implement a custom COM MessageFilter.
5 Silent Mode [} 30] Describes how to turn the Automation Interface “silent”

After these basic articles, the Best Practice [} 30] articles may be consulted for different topics like PLC or I/
O access via the Automation Interface.

4.2 Basics

4.2.1 Accessing TwinCAT configuration


This chapter describes how to create and access a TwinCAT XAE configuration project via Automation
interface. The objective of this creation process is to get access to a TwinCAT XAE project (formerly known
as a TwinCAT System Manager configuration). The new TwinCAT XAE project is more sophisticated than
the TwinCAT System Manager configuration known from TwinCAT2, which implies a slight concept change
of project / configuration handling. TwinCAT 3 supports an extra hierarchical level combining several
configurations into a Visual Studio solution container. This can for example be used to organize the
configurations of distributed resources into a solution or for packaging HMI projects together with the system
configuration. The solution is able to bind together all types of Visual Studio and/or TwinCAT XAE projects.
When using the TwinCAT XAE Automation inferface, this means an extra level of possiblities.

Basic information

TwinCAT 3 has been fully integrated into Visual Studio to provide users with a standardized and most
flexible editor to create and manage TwinCAT projects. To create and/or access a TwinCAT configuration,
the combined use of Visual Studio and TwinCAT Automation Interface is possible. For example: If you want
to create a new TwinCAT configuration via Automation Interface, you first need to call methods of the Visual
Studio API to create a Visual Studio solution container and then add a TwinCAT project by using methods of
the TwinCAT Automation Interface. This scenario will be covered in some code snippets below.

Automation Interface Version: 1.3 19


Configuration

In addition, the Visual Studio API (so-called Visual Studio DTE ) provide developers with many more
features, e.g. accessing the error output window. [} 36] For more information about Visual Studio DTE
please see the Microsoft MSDN website.

Please note:
• When creating a new TwinCAT project within a Visual Studio solution, you need to specify a path to
the TwinCAT project template [} 25]. Please adapt this path in the code snippets below according to
your environment.
• The following code snippets use dynamic linking for the Visual Studio DTE objects, which means that
the actual type of the object will be determined during the application runtime. In case you do not want
to use dynamic linking but instead specify the data type in advance, you need to include the
namespace EnvDTE.DTE to your project.

Creating TwinCAT Projects via templates

Please note that you need to add a reference to the COM object TcatSysManagerLib and EnvDTE.DTE
(Microsoft Developement) in order to be able to use the TwinCAT Automation Interface and the Visual Studio
API. The ProgID that is used in the GetTypeFromProdID() method depends on the Visual Studio version that
should be used. Please have a look at this [} 29] documentation article for more information about the
different ProgIDs.

Code Snippet (C#):


Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
EnvDTE.DTE dte = System.Activator.CreateInstance(t);

dte.SuppressUI = false;
dte.MainWindow.Visible = true;

if (Directory.Exists(@"C:\Temp\SolutionFolder"))
     Directory.Delete(@"C:\Temp\SolutionFolder", true);
Directory.CreateDirectory(@"C:\Temp\SolutionFolder");
Directory.CreateDirectory(@"C:\Temp\SolutionFolder\MySolution1");

dynamic solution = dte.Solution;


solution.Create(@"C:\Temp\SolutionFolder", "MySolution1");
solution.SaveAs(@"C:\Temp\SolutionFolder\MySolution1\MySolution1.sln");

string template = @"C:\TwinCAT\3.1\Components\Base\PrjTemplate\TwinCAT Project.tsproj"; //path to


project template
dynamic project = solution.AddFromTemplate(template, @"C:\Temp\SolutionFolder\MySolution1",
"MyProject");

ITcSysManager sysManager = project.Object;

sysManager.ActivateConfiguration();
sysManager.StartRestartTwinCAT();

project.Save();
solution.SaveAs(@"C:\Temp\SolutionFolder\MySolution1\MySolution1.sln");

Code Snippet (Powershell):

20 Version: 1.3 Automation Interface


Configuration

You can copy and paste the following code snippet into a textfile and save it as "someName.ps1". After that
you can execute it directly via Windows PowerShell.
$targetDir = "C:\tmp\TestSolution"
$targetName = "TestSolution.tsp"
$template = "C:\TwinCAT\3.1\Components\Base\PrjTemplate\TwinCAT Project.tsproj"

$dte = new-object -com VisualStudio.DTE.10.0


$dte.SuppressUI = $false
$dte.MainWindow.Visible = $true

if(test-path $targetDir -pathtype container)


{
     Remove-Item $targetDir -Recurse -Force
}

New-Item $targetDir –type directory

$sln = $dte.Solution
$project = $sln.AddFromTemplate($template,$targetDir,$targetName)
$systemManager = $project.Object

$targetNetId = $systemManager.GetTargetNetId()
write-host $targetNetId

$systemManager.ActivateConfiguration()
$systemManager.StartRestartTwinCAT()

$project.Save()
$solutionPath = $targetDir + "\" + $targetName
$sln.SaveAs($solutionPath)

Code Snippet (C++):

Within appropriate Header file (e.g the stdafx.h):


//the following #import imports EnvDTE based on its LIBID.
#import"libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("10.0") lcid("0") raw_interfaces_only
named_guids
// Imports die "Beckhoff TCatSysManager 1.1 Type Library"
#import"libid:3C49D6C3-93DC-11D0-B162-00A0248C244B" version("1.1") lcid("0")

Because a known issue within VisualStudio 2010 (SP1), the generated proxy code will not be included into
the C++ project. Please use the workaround described in #import Known Issue import Known Issue.
#include

using namespace std


using namespace TCatSysManagerLib;
using namespace EnvDTE;

int _tmain(int argc, _TCHAR* argv[])


{
    CoInitialize(NULL); // COM initialisieren
    cout << "Creating VisualSTudio.DTE.10.0 ...";

    // creating a new instance of Visual Studio


    CComPtr<_DTE> m_pDTE;
    HRESULT hr = m_pDTE.CoCreateInstance(L"VisualStudio.DTE.10.0", 0, CLSCTX_ALL);
    if (FAILED(hr)) { cout << " FAILED"; return 1; }
    cout << " created." << endl;

    // retrieves the EnvDTE.Solution-Objekt


    CComPtr<_Solution> pSolution;
    m_pDTE->get_Solution(&pSolution);
    CComBSTR strSolutionFolder(_T("C:\\SolutionFolder")); // Solution-main directory (has to exist)
    CComBSTR strSolutionName(_T("MySolution1"));
    CComBSTR strTemplatePath(_T("C:\\TwinCAT\\3.1\\Components\\Base\\PrjTemplate\\TwinCAT
Project.tsproj"));

    CComBSTR strSolutionPath; // Solution-Pfad (doesn’t exist!)


    strSolutionPath=strSolutionFolder;
    strSolutionPath.Append(_T("\\"));
    strSolutionPath.Append(strSolutionName);
    strSolutionPath.Append(_T(".sln"));

    // create the solution


    hr = pSolution->Create(strSolutionFolder,strSolutionName);

Automation Interface Version: 1.3 21


Configuration

    CComBSTR strProjectPath(strSolutionFolder); // project path


    strProjectPath.Append(_T("\\"));
    strProjectPath.Append(strSolutionName);
    CComBSTR strProjectName = "MyProject"; // project name // create projekt from a template
    CComPtr pProject;
    hr = pSolution-
>AddFromTemplate(strTemplatePath,strProjectPath,strProjectName,VARIANT_FALSE,&pProject);
    // Wenn z.B. Projekt bereits besteht >> error
    if (FAILED(hr)) { cout << " Project creation FAILED"; return 1; }
    cout << "Project created" << endl;

    // define project automation class (here the Coclass TcSysManager)


    CComPtr pDispatch;
    hr = pProject->get_Object(&pDispatch);

    // retrieve ITcSysManager interface


    CComPtr pSystemManager;
    hr = pDispatch.QueryInterface(&pSystemManager);
    
    // operate with SystemManager interface
    CComBSTR netId;
    netId = (pSystemManager->GetTargetNetId()).GetBSTR();
    cout << "TargetNetId: " << netId << endl;
    hr = pSystemManager->ActivateConfiguration();
    hr = pSystemManager->StartRestartTwinCAT();

    // save project and solution


    hr = pProject->Save(CComBSTR());
    hr = pSolution->SaveAs(strSolutionPath);
    cout << "Succeeded";
    return 0;
}

import Known Issue:


    CComPtr<_DTE> m_pDTE;
    CLSID clsid;
    CLSIDFromProgID(L"VisualStudio.DTE.10.0",&clsid);
    CComPtr punk;
    HRESULT hr = GetActiveObject(clsid,NULL,&punk); // retrieve actual instance of Visual
Studio .NET
    m_pDTE = punk;

Please note:

ITcSysManager::NewConfiguration [} 106], ITcSysManager::OpenConfiguraiton [} 106] and


ITcSysManager::SaveConfiguration [} 107] will create error messages in this case, because the project
handling is delegated to the Visual Studio IDE (the Solution and Project instances realized by the DTE
object).

Also see about this


2 Accessing TwinCAT configuration [} 20]
2 Sample downloads [} 171]

4.2.2 Browsing TwinCAT configuration


In a separate article, we have already shown you how to access TwinCAT [} 19] via the Visual Studio
Automation Model. This reference to TwinCAT is being represented by an object of type ITcSysManager
[} 104]. From this point on we would like to discuss now how you can navigate through the TwinCAT
configuration.

General information

It is important to understand that all information in TwinCAT is ordered in a tree-like structure. In Automation
Interface, every tree node, and therefore every element of a TwinCAT configuration, is represented by the
interface ITcSmTreeItem [} 113].

22 Version: 1.3 Automation Interface


Configuration

Navigating the TwinCAT data model can be done in different ways, depending on the sort of information that
should be retrieved.
• Lookup-Methods are searching for specific tree items via specified search criterias, e.g. the path to a
tree item
• Iterators or browsing functions iterate over a set of retrieved tree items

Both methods are now being discussed in the following article.

LookupMethods

The Lookup methods are always working on the whole data model (unfiltered).
• ITcSysManager::LookupTreeItem [} 110] determines a tree item with the specified absolute path name.
• ITcSysManager3::LookupTreeItemById [} 111] determines a tree item with the specified item type and
item Id.
• ITcSmTreeItem::LookupChild [} 152] determines a tree item within a subtree specifed by a relative path
name.

Each tree item in TwinCAT can be identified by its unique pathname. The pathname of a tree item is based
on the hierarchical order of its parent item (its name) and its own name, separated by circumflex accents
('^'). To shorten the pathnames and to avoid language dependencies, the top level tree items have special
abbreviations which are listed in ITcSysManager::LookupTreeItem [} 110].

Iterators

At the moment, three different types of iteration functions are supported:


• Browsing all tree items (unfiltered)
• Browsing main tree items
• Browsing variables / symbols only

Browsing all tree items (unfiltered)

To browse all tree items in an unfiltered way, the property ITcSmTreeItem [} 113]:NewEnum may be used.
_NewEnum iterates over all subnodes of the currently referenced ITcSmTreeItem [} 113]. This (COM-)
property is used by many Programming and Script languages that support the COM Enumerator model
(e.g. .NET languages, VB6 or script languages) by a 'foreach' statement. For non-supporting languages like
C++ the foreach loop must be implemented manually by using the IEnumVariant-interface.

We recommend to use this way to iterate through child nodes.

Automation Interface Version: 1.3 23


Configuration

Sample (C#):
ITcSmTreeItem parent = sysMan.LookupTreeItem("TIID^Device1^EK1100");
foreach(ITcSmTreeItem child in parent)
{
 Console.WriteLine(child.Name);
}

Sample (C++):
...
#import "C:\TwinCAT3\Components\Base\TCatSysManager.tlb" // imports the System Manager / XAE Base
type library
// uses automatically created auto-pointer (see MSDN documentation of #import command)
...

void CSysManDialog::IterateCollection(TCatSysManagerLib::ITcSmTreeItemPtr parentPtr)


{
     IEnumVARIANTPtr spEnum = parentPtr->_NewEnum;
     ULONG nReturned = 0;
     VARIANT variant[1] = {0};
     HRESULT hr = E_UNEXPECTED;
        
     do
     {
         hr = spEnum->Next(1, &variant[0], &nReturned);
         if(FAILED(hr))
             break;
         for(ULONG i = 0; i < nReturned; ++i)
         {
             IDispatchPtr dispatchPtr;
             IDispatch* pDispatch;
             TCatSysManagerLib::ITcSmTreeItemPtr childPtr;
             HRESULT hr;
             if(variant[0].vt == VT_DISPATCH)
             {
                 TCatSysManagerLib::ITcSmTreeItem* pChild = 0;
                 dispatchPtr.Attach((variant[0].pdispVal));
                 hr = dispatchPtr.QueryInterface(__uuidof(TCatSysManagerLib::ITcSmTreeItem),
reinterpret_cast(&pChild));
                 childPtr.Attach(pChild);
                 _bstr_t strName = pChild->GetName();
             }
         }
     }
     while(hr != S_FALSE); // S_FALSE zeigt Ende der Sammlung an
}

Sample (PowerShell):
$systemItem = $systemManager.LookupTreeItem("TIRC")
foreach($child in $systemItem)
{
write-host$child.Name
}

Browsing Main Tree Items (Filtered)

For browsing only the main childs of the current tree item use the ITcSmTreeItem::ChildCount [} 113] and
ITcSmTreeItem:Child(n) [} 104] pair of properties. These methods only work on the direct childs (non-
recursive).

Browsing Variables / Symbols only

To Browse the Variables / Symbols use the ITcSmTreeItem::VarCount(x) [} 113] , ITcSmTreeItem::Var(x,n)


[} 113] pair of properties. A selection of the variable type (input variables or output variables) can be done by
parameter.

24 Version: 1.3 Automation Interface


Configuration

4.2.3 Custom TreeItem Parameters


The ITcSmTreeItem [} 113] interface is supported by every TwinCAT tree item and has a very generic
character. To support the specification of all the devices, boxes and terminals, together with many other
different types of tree items, all custom parameters of a tree item are accessible via the XML representation
of the tree item. This XML-String can be accessed by the method ITcSmTreeItem::ProduceXml [} 146] and its
counterpart ITcSmTreeItem::ConsumeXml [} 147]. This function pair has the same functionality as the "Export
XML Description ..." and "Import XML Description ..." commands from the main menu of the TwinCAT IDE
(see snapshot below).

Fig. 1: TcSysMan_AutomationXmlParameters

With this Import/Export functionset, many parts of a script or automation code can be tested and tailored
conveniently, before it is developed within the coding language - simply by the process of exporting tree item
data, changing its content and re-importing it.

Best practice is to export the XML content first, change its content, importing it within the IDE and then, if
everything goes successfully, package it into the programming/script code for handling it via the methods
ProduceXml and ConsumeXml.

4.2.4 TwinCAT Project Template


When creating a new TwinCAT solution, you need to specify the path to the TwinCAT Project template - see
also our article about Accessing TwinCAT XAE configuration [} 19].

Basics

TwinCAT version Path to TwinCAT project template*


TwinCAT 3.0 C:\TwinCAT\3.0\Components\Base\PrjTemplate
\TwinCAT Project.tsp
TwinCAT 3.1 C:\TwinCAT\3.1\Components\Base\PrjTemplate
\TwinCAT Project.tsproj

* Please note: The paths mentioned above are based on the default TwinCAT installation directory and may
be different if you installed TwinCAT in another folder.

Automation Interface Version: 1.3 25


Configuration

4.2.5 Implementing a COM Message Filter


Message filtering is a mechanism by which server applications can decide if and when an incoming method
call is safe to execute on one of their objects. COM is generally unaware of your application's reentrancy
requirements, and by default does not filter messages. Although message filtering is no longer as significant
as it was with 16-bit applications because the size of the message queue is now virtually unlimited, you still
should implement message filtering as a way of resolving deadlocks. COM will call your implementation of
the interface IMessageFilter to find out if an application (a COM server) is blocking, so you can react to it
and deal with the situation. For example, when accessing TwinCAT XAE via COM, the Visual Studio
instance rejects further COM calls while it still executes a previously issued COM call. As a result, the client
application throws a RPC_E_CALL_REJECTED exception and, without further intervention, does not repeat
the call. Writing a customized message filter gives a programmer the opportunity to repeat the COM call if
the client application receives a notification of a rejected COM call by the COM server.

The following screenshot shows a typical exception thrown by the Visual Studio COM server when the
instance is still executing a previously issued COM call.

To avoid this situation and implement a Message Filter which reacts to this rejected COM call, the application
engineer needs to implement the IMessageFilter interface. This interface consists of three methods:
• HandleIncomingCall(): Provides a single entry point for incoming calls
• MessagePending(): Indicates that a message has arrived while COM is waiting to respond to a
remote call.
• RetryRejectedCall(): Provides the opportunity to react to a rejected COM call.

Please note that message filters can only be applied to STA-Threads and only one filter can be applied to
each thread. Multithreaded apartments, for example console applications, cannot have message filters.
These applications need to run in a STA-Thread to apply a message filter. For more information about COM-
Threading, please view the appendix of this documentation.

The following code snippet shows an example of how to use the IMessageFilter interface in C#. Please note
that this code is also used in many samples of our Samples [} 171] section and is also available as a
separate sample download.
[ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IOleMessageFilter
{

[PreserveSig]
int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);

[PreserveSig]
int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);

[PreserveSig]

26 Version: 1.3 Automation Interface


Configuration

int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);


}

The following class implements this interface and adds two more methods to it: Register() and Revoke().
public class MessageFilter : IOleMessageFilter
{
public static void Register()
{
IOleMessageFilter newFilter = newMessageFilter();
IOleMessageFilter oldFilter = null;
int test = CoRegisterMessageFilter(newFilter, out oldFilter);

if (test != 0)
{
Console.WriteLine(string.Format("CoRegisterMessageFilter failed with error : {0}", test));
}
}

public static void Revoke()


{
IOleMessageFilter oldFilter = null;
int test = CoRegisterMessageFilter(null, out oldFilter);
}

int IOleMessageFilter.HandleInComingCall(int dwCallType, System.IntPtr hTaskCaller, int dwTickCount,


System.IntPtr lpInterfaceInfo)
{
//returns the flag SERVERCALL_ISHANDLED.
return 0;
}

int IOleMessageFilter.RetryRejectedCall(System.IntPtr hTaskCallee, int dwTickCount, int


dwRejectType)
{
// Thread call was refused, try again.
if (dwRejectType == 2)
// flag = SERVERCALL_RETRYLATER.
{
// retry thread call at once, if return value >=0 &
// <100.
return 99;
}
return -1;
}

int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee, int dwTickCount, int dwPendingType)


{
//return flag PENDINGMSG_WAITDEFPROCESS.
return 2;
}

// implement IOleMessageFilter interface.


[DllImport("Ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, outIOleMessageFilter
oldFilter);

An application engineer now only needs to call the methods Register() and Revoke() from another class to
initialize and discard the MessageFilter. As a result, rejected COM calls will be repeated, as defined in the
RetryRejectedCall() method.

The following code snippet shows how to call these methods from within a console application written in C#.
As mentioned above, console applications by default run in a MTA-Thread. Therefore the Main() method
needs to be configured to run in a STA apartment so that the message filter can be applied.
[STAThread]
static void Main(string[] args)
{
MessageFilter.Register();

/* =============================================================
* place COM calls for the Automation Interface here
* ...

Automation Interface Version: 1.3 27


Configuration

* ...
* ============================================================= */

MessageFilter.Revoke();
}

If you try to apply a message filter to an application running in a MTA apartment, the following exception will
be thrown when trying to execute the method CoRegisterMessageFilter() during runtime:

For more information about the different COM threading models, please read the MSDN article about
Understanding and Using COM Threading models. To get more detailed information about the
IMessageFilter interface, please read the MSDN documentation about IMessageFilter.

The following code snippet demonstrates how to implement a COM MessageFilter for Windows Powershell,
although you could also implement the MessageFilter by writing an own Powershell Cmdlets with C# and
using the code from above.

Code Snippet (Powershell):


function AddMessageFilterClass
{
$source = @"
namespace EnvDteUtils
{
using System;
using System.Runtime.InteropServices;

public class MessageFilter : IOleMessageFilter


{
public static void Register()
{
IOleMessageFilter newFilter = new MessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
}

public static void Revoke()


{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
}

int IOleMessageFilter.HandleInComingCall(int dwCallType, System.IntPtr hTaskCaller, int dwTickCount,


System.IntPtr lpInterfaceInfo)
{
return 0;
}

int IOleMessageFilter.RetryRejectedCall(System.IntPtr hTaskCallee, int dwTickCount, int


dwRejectType)
{
if (dwRejectType == 2)
{
return 99;
}
return -1;
}

int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee, int dwTickCount, int dwPendingType)

28 Version: 1.3 Automation Interface


Configuration

{
return 2;
}

[DllImport("Ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter
oldFilter);
}

[ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);

[PreserveSig]
int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);

[PreserveSig]
int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}
}
"@
Add-Type -TypeDefinition $source
}

4.2.6 Handling different Visual Studio versions


This article explains how to use the TwinCAT Automation Interface with different versions of Visual Studio,
e.g. Visual Studio 2010 and 2012, in case you have installed two or more versions in parallel. It consists of
the following topics:
• Visual Studio Program ID
• Specify Visual Studio version in Automation Interface code

Visual Studio Program ID

As you have already seen in our basic articles, you need to create a Visual Studio DTE object before
implementing Automation Interface code because of the TwinCAT 3 integration into the Visual Studio
environment. If you have installed more than one Visual Studio version on your Engineering PC and would
like to choose which version should be used along with the Automation Interface code, you need to
determine the so-called Program ID (ProgID) of the corresponding Visual Studio version. The ProgID is
located in the Windows Registry under HKEY_CLASSES_ROOT and has the following format:
VisualStudio.DTE.X.Y.

The following table shows the ProgIDs for the currently supported versions of Visual Studio:

Version ProgID
Visual Studio 2010 VisualStudio.DTE.10.0
Visual Studio 2012 VisualStudio.DTE.11.0
Visual Studio 2013 VisualStudio.DTE.12.0
Visual Studio 2015 VisualStudio.DTE.14.0
Visual Studio 2017 VisualStudio.DTE.15.0
TwinCAT XAE Shell TcXaeShell.DTE.15.0

Specify Visual Studio version in Automation Interface code

To specify the Visual Studio version in Automation Interface code, you need to use the ProgID as a
paremeter of the GetTypeDromProgID() method during the creation process of the DTE object.

Code Snippet (C#):


Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.15.0");
EnvDTE.DTE dte = (EnvDTE.DTE)System.Activator.CreateInstance(t);

Code Snippet (Powershell):

Automation Interface Version: 1.3 29


Configuration

$dte = new-object-com VisualStudio.DTE.15.0

4.2.7 Silent Mode


Sometimes an Automation Interface script or program should operate silently, which means without any
message boxes or other visible interruptions. Although the Visual Studio DTE command “dte.Visible = true/
false” may seem sufficient in most use cases, the TwinCAT Automation Interface introduces a new Silent
Mode switch, which is available since TwinCAT 3.1 Build 4020.0 and above.

This new switch can be activated as follows.

Code snippet (C#):


var settings = dte.GetObject("TcAutomationSettings");
settings.SilentMode = true;

Code snippet (Powershell):


$settings = $dte.GetObject("TcAutomationSettings")
$settings.SilentMode = $true

This will suppress message box dialogs during usage of the TwinCAT Automation Interface.

4.3 Best practice

4.3.1 Visual Studio

4.3.1.1 Select projects for build process


The Visual Studio API provides all mechanisms required to select projects for a Solution Configuration. The
necessary methods are part of the SolutionBuild2 class of the EnvDTE namespace. The following example
demonstrates how to use the method BuildProject() from that class.

Code Snippet (Powershell):


$sln = $dte.Solution
$prj = $dte.Projects.Item(1) #SysMan Project
$sysManProjectName = $prj.FullName
$plcPrjProjectName = PathToPlcProjFile 
$sln.SolutionBuild.BuildProject("Release|TwinCAT RT (x64)",$sysManProjectName,$true)
$sln.SolutionBuild.BuildProject("Release|TwinCAT RT (x64)",$plcPrjProjectName,$true)

The placeholder “pathToPlcProjFile” represents the full path to a *.plcproj file which represents a TwinCAT 3
PLC project.

4.3.1.2 Accessing TeamFoundationServer source control


This chapter provides an overview about how to access a Microsoft Team Foundation Server (TFS)
programmatically by using the corresponding DLLs that are supplied by Visual Studio. This documentation
has been written for your convenience and to make first steps easier when trying to combine TwinCAT
Automation Interface code with TFS DLLs. For a more detailed documentation about the TFS API, we highly
recommend to visit the corresponding MSDN articles.

This documentation covers the following topics:


• Connecting to a TFS Server
• Connecting to TeamProjects
• Working with workspaces
• Creating working folders
• Get latest version of an item

30 Version: 1.3 Automation Interface


Configuration

• Getting a list of pending changes


• Checking In and Checking Out
• Undo an operation

The following TFS API DLLs are being used within this documentation:
• Microsoft.TeamFoundation.Client
• Microsoft.TeamFoundation.VersionControl.Client

Connecting to a TFS Server

The Microsoft TFS API lets you connect your application containing TwinCAT Automation Interface code to
your development repository on a remote server. The connection requires a string describing the address,
the port and the collection of your remote server e.g. http://your-tfs:8080/tfs/DefaultCollection.

Before you connect, define an instance of Uri class and TfsConfigurationServer class. Assign the remote
server link to the configuration server:

Code Snippet (C#):


string tfsServerUrl = "http://your-server:8080/tfs/DefaultCollection";
Uri configurationServerUri = new Uri(tfsServerUrl);
TfsTeamProjectCollection teamProjects =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(configurationServerUri);
VersionControlServer verControlServer = teamProjects.GetService<VersionControlServer>();

Connecting to TeamProjects

You can get a list of team projects or a specific team project on the server by executing the following code
snippets:

Code Snippet (C#):


// Get all Team projects
TeamProject[] allProjects = verControlServer.GetAllTeamProjects(true);

// Get specific Team Project


TeamProject project = verControlServer.TryGetTeamProject("TeamProjectName");

Working with workspaces

Team foundation deals with workspaces which comprises mappings to working folders. These mappings link
server-side folders to local folders on your hard-drive. It additionally also stores the name of the owner and
the name of your computer as a part of the workspace name. A workspace is a must before performing any
version control task because it stores information about files, versions and list of pending changes.

To begin with TFS Client API offers a Workspace class which stores the information mentioned above and
offers extensive suit of methods to interact with the files and folders. Suppose you wish to create a
workspace for a folder named, folderName, then create a string containing the computer name and the
folder:

Code Snippet (C#):


// Specify workspace name for later use
String workspaceName = String.Format("{0}-{1}", Environment.MachineName, "Test_TFSAPI");

// Create new workspace


Workspace newWorkspace = verControlServer.CreateWorkspace(workspaceName,
verControlServer.AuthorizedUser);

A mapping can now exist between the server-side folder and your local folder specified by folderName under
workspace. To get an existing or delete a workspace, simply execute the following methods:

Code Snippet (C#):


// Delete workspace
bool workspaceDeleted = verControlServer.DeleteWorkspace(workspaceName,
verControlServer.AuthorizedUser);

Automation Interface Version: 1.3 31


Configuration

// Get existing workspace


Workspace existingWorkspace = verControlServer.GetWorkspace(workspaceName,
verControlServer.AuthorizedUser);

Creating working folders

To connect to a specified project folder, you need a path to the project relative to the root.

For instance, if the project is stored on: your-server\Development\TcSampleProjectX, then the relative path
to that folder is $\Development\TcSampleProjectX.

To match this folder to the projects on the server, you can iterate over a set of all registered projects on the
server. A registered project is the root of project collections found underneath.

Code Snippet (C#):


// Create mapping between server and local folder
string serverFolder = String.Format("$/{0}", teamProject.Name + "/Folder/SubFolder");
string localFolder = Path.Combine(@"C:\tfs", workspaceName);
WorkingFolder workingFolder = new WorkingFolder(serverFolder, localFolder);
existingWorkspace.CreateMapping(workingFolder);

Get latest version of an item

As mentioned earlier Workspace class offers a rich set of methods to execute the TFS commands from
within the code. But before illustrating, here is an example of creating a link to an item in the working folder.
To create a relative path:

Code Snippet (C#):


String existingItemPath = "$/Developement/TcSampleProject/Examples/Samples00/TestPlc/POUs/
MAIN.TcPOU";

Or an absolute path:
String existingItemPath = C:/tfs/Developement/TcSampleProject/Examples/TestPlc/POUs/MAIN.TcPOU";

To get the latest version of the item in the example, add following line of code:

Code Snippet (C#):


String existingItemPath = "$/TeamProjectName/Folder/SubFolder";
GetRequest itemRequest = new GetRequest(new ItemSpec(existingItemPath, RecursionType.Full),
VersionSpec.Latest);
existingWorkspace.Get(itemRequest, GetOptions.GetAll);

Here the RecursionType.Full executes the request on all the items under the item node but you can select it
depending on your application’s requirement and existing item hierarchy. For more information please refer
to the API documentation on MSDN.

Getting a list of pending changes

You can also get a list of pending changes made to the item or a collection of items with following line of
code:

Code Snippet (C#):


PendingChange[] pendingChanges = existingWorkspace.GetPendingChanges(existingItemPath,
RecursionType.Full);

For collection of items, consider the overloaded variance with Item[] as argument.

Checking-In and Checking-Out

You can check out an item or a collection of items for editing:

Code Snippet (C#):


int checkoutResult = existingWorkspace.PendEdit(existingItemPath, RecursionType.Full);

To check-in the collection of pending changes to an item by:

Code Snippet (C#):

32 Version: 1.3 Automation Interface


Configuration

int checkinResult = workspace.CheckIn(pendingChanges, usercomment);

Undo an operation

To Undo an operation, simply execute:

Code Snippet (C#):


int undoResult = existingWorkspace.Undo(existingItemPath, RecursionType.Full);

4.3.1.3 Setting TwinCAT target platform


This article describes how to set the TwinCAT target platform via Automation Interface code. The target
platform determines for which target the TwinCAT configuration should be compiled, e.g. TwinCAT x86 or
TwinCAT x64, and is usually set from within a TwinCAT XAE toolbar in Visual Studio.

The following code snippet assumes that you already have a DTE instance that links to a TwinCAT
configuration. It checks for the currently set target platform and re-sets it to another platform.

Code Snippet (C#):


ITcSysManager systemManager = pro.Object;
ITcSysManager7 sysManPlatform = (ITcSysManager7) systemManager;
ITcConfigManager configManager = (ITcConfigManager) sysManPlatform.ConfigurationManager;
if (configManager.ActiveTargetPlatform == "TwinCAT RT (x86)")
configManager.ActiveTargetPlatform = "TwinCAT RT (x64)";
else
configManager.ActiveTargetPlatform = "TwinCAT RT (x86)";

Code Snippet (Powershell):


$configManager = $systemManager.ConfigurationManager
if ($configManager.ActiveTargetPlatform -eq "TwinCAT RT (x86)"){
  $configManager.ActiveTargetPlatform = "TwinCAT RT
(x64)"} else {$configManager.ActiveTargetPlatform = "TwinCAT RT (x86)"}

Note This article describes how to change the target hardware platform. If you want to change the
actual remote target to which the TwinCAT configuration should be written, please use the
ITcSysManager::SetTargetNetId() method.

The following code snippet demonstrates how to acquire access to the Visual Studio Configuration Manager
and enable or disable single TwinCAT sub projects (PLC, C++, …) for the build process. The snippet
assumes that the currently opened TwinCAT project is named “TwinCAT Project1” and that it includes a PLC
project “Untitled1”. It then disables the PLC project for the build process.

Code Snippet (C#):


EnvDTE.SolutionContexts solutionContexts =
solution.SolutionBuild.ActiveConfiguration.SolutionContexts;
foreach (EnvDTE.SolutionContext solutionContext in solutionContexts)
{
switch(solutionContext.ProjectName)
{
case "TwinCAT Project13\\Untitled1\\Untitled1.plcproj":
solutionContext.ShouldBuild = false;
break;
}
}

Code Snippet (Powershell):


$solutionContexts = $sln.SolutionBuild.ActiveConfiguration.SolutionContexts
foreach ($solutionContext in $solutionContexts)
{
  if($solutionContext.ProjectName -eq "TestSolution\\Untitled1\\Untitled1.plcproj")
  {
    $solutionContext.ShouldBuild = $false

Automation Interface Version: 1.3 33


Configuration

  }
}

4.3.1.4 Attaching to an existing Visual Studio instance


The following code snippets demonstrate how to attach to an existing (already running) instance of Visual
Studio. The snippets have been written in C#.

The sample consists of three different methods that depend on each other. Of course, you may change this
accordingly so that it better fits your application environment.The following table explains each method in
more detail.

Method Description
getRunningObjectTable() Queries the Running Object Table (ROT) for a
snapshot of all running processes in the table.
Returns all found processes in a Hashtable, which
are then used by getIdeInstances() for further filtering
for DTE instances.
getIdeInstances() Searches for DTE instances in the ROT snapshot
and returns a Hashtable with all found instances. This
Hashtable may then be used by the method
attachToExistingDte() to select single DTE instances.
You may change the query for candidateName
according to a more specific Visual Studio progId
[} 29] , e.g. "VisualStudio.DTE.11.0" to query for
Visual Studio 2012 instances.
attachToExistingDte() Uses the getIdeInstances() method to select a DTE
instance based on its solution path and, when found,
attaches a new DTE object to this instance.

getRunningObjectTable()
public static Hashtable GetRunningObjectTable()
{
    Hashtable result = new Hashtable();
    int numFetched;
    UCOMIRunningObjectTable runningObjectTable;
    UCOMIEnumMoniker monikerEnumerator;
    UCOMIMoniker[] monikers = new UCOMIMoniker[1];
    GetRunningObjectTable(0, out runningObjectTable);
    runningObjectTable.EnumRunning(out monikerEnumerator);
    monikerEnumerator.Reset();
    while (monikerEnumerator.Next(1, monikers, out numFetched) == 0)
    {
        UCOMIBindCtx ctx;
        CreateBindCtx(0, out ctx);
        string runningObjectName;
        monikers[0].GetDisplayName(ctx, null, out runningObjectName);
        object runningObjectVal;
        runningObjectTable.GetObject(monikers[0], out runningObjectVal);
        result[runningObjectName] = runningObjectVal;
    }
    return result;
}

Please note that you need to explicitely reference the CreateBindCtx() method as a DllImport from the
ole32.dll, e.g.:
[DllImport("ole32.dll")]
private static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);

getIdeInstances()
public static Hashtable GetIDEInstances(bool openSolutionsOnly, string progId)
{
  Hashtable runningIDEInstances = new Hashtable();
  Hashtable runningObjects = GetRunningObjectTable();
  IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator();

34 Version: 1.3 Automation Interface


Configuration

  while (rotEnumerator.MoveNext())
  {
    string candidateName = (string)rotEnumerator.Key;
    if (!candidateName.StartsWith("!" + progId))
      continue;
    EnvDTE.DTE ide = rotEnumerator.Value as EnvDTE.DTE;
    if (ide == null)
      continue;
    if (openSolutionsOnly)
    {
      try
      {
        string solutionFile = ide.Solution.FullName;
        if (solutionFile != String.Empty)
          runningIDEInstances[candidateName] = ide;
      }
      catch { }
    }
    else
      runningIDEInstances[candidateName] = ide;
  }
  return runningIDEInstances;
}

attachToExistingDte()
public EnvDTE.DTE attachToExistingDte(string solutionPath)
{
EnvDTE.DTE dte = null;
Hashtable dteInstances = GetIDEInstances(false, progId);
IDictionaryEnumerator hashtableEnumerator = dteInstances.GetEnumerator();

while (hashtableEnumerator.MoveNext())
{
EnvDTE.DTE dteTemp = hashtableEnumerator.Value as EnvDTE.DTE;
if (dteTemp.Solution.FullName == solutionPath)
{
Console.WriteLine("Found solution in list of all open DTE objects. " + dteTemp.Name); dte = dteTemp;
}
}
return dte;
}

4.3.1.5 Accessing window tabs in Visual Studio


The Visual Studio Automation Interface provides methods and properties to access active windows in Visual
Studio. The following chapter demonstrates some sample code. However, we also suggest to investigate the
webpages of the Microsoft Developer Network (MSDN) for more detailed information about the Visual Studio
object model. This chapter provides sample code for the following tasks:
• Accessing active windows
• Closing active windows
• Opening windows from TwinCAT PLC configuration

Accessing active windows

The DTE interface provides a property called "ActiveWindow", which returns the currently active window in
Visual Studio as an object of type EnvDTE.Window.

Code Snippet (C#):


EnvDTE.Window activeWin = dte.ActiveWindow;

Code Snippet (Powershell):


$activeWin = $dte.ActiveWindow

Closing active windows

Depending on the customers application, it may be necessary to close all active windows in Visual Studio
before proceeding with the TwinCAT configuration via Automation Interface. The following code snippet
closes all active windows but the "Solution Explorer".

Automation Interface Version: 1.3 35


Configuration

Code Snippet (C#):


try
{
while (!dte.ActiveWindow.Caption.Contains("Solution Explorer"))
dte.ActiveWindow.Close();
}
catch (InvalidOperationException ex)
{
// use DTE.Quit() to close main window
}

Opening windows from TwinCAT PLC configuration

It is also possible to open windows from TwinCAT PLC, e.g. a visualization. The following code snippet
opens an existing TwinCAT visualization from PLC project "Untitled1" and makes it the currently active
window.

Code Snippet (C#):


string fileName = @"C:\TwinCAT Project1\TwinCAT Project1\Untitled1\VISUs\Visu.TcVIS";
dte.ItemOperations.OpenFile(fileName);

Code Snippet (Powershell):


$fileName = @"C:\TwinCAT Project1\TwinCAT Project1\Untitled1\VISUs\Visu.TcVIS"
dte.ItemOperations.OpenFile($fileName)

4.3.1.6 Accessing the Error List window of Visual Studio


This chapter describes how to get access to the Visual Studio Error List window. Because TwinCAT 3
integrates itself into the Visual Studio shell, reading the content of this window can be essential for
debugging and diagnostic purposes. To read the content of this window, you need to access the Visual
Studio COM interface. Because this COM interface is also needed to access TwinCAT XAE (e.g. as
described in our article Accessing TwinCAT configuration [} 19]), you don't need to add any additional
references to your program code.

The following documentation describes how to access the Error List window, which can be very helpful, for
example if you want to compile a PLC project and want to check the compile process for any error
messages. The Error List window displays status messages for various features in the Visual Studio (and
therefore TwinCAT) development environment. These features for example include build errors that occur
when a project is compiled or licensing issues.

Reading the content of this window can be essential, e.g. to check if any errors occured while compiling a
PLC project. The following code snippet shows how to read the content of this window using a C#
application.

Code Snippet (C#):


ErrorItems errors = dte.ToolWindows.ErrorList.ErrorItems;
for (int I = 0; i < errors.Count; i++)
{
  ErrorItem item = errors.Item(i);
}

Please note that the property “ToolWindows” is available in namespace EnvDTE80.DTE2.

Code Snippet (Powershell):

36 Version: 1.3 Automation Interface


Configuration

$errors = $dte.ToolWindows.ErrorList.ErrorItems
for ($i=0; $i –lt $errors.Count; $i++)
{
  $item = $errors.Item($i);
}

As you can see, the property ErrorItems returns a collection of all items in the Error List, where each item is
of type ErrorItem. You can iterate through this collection for example by making use of its Count property.
Each ErrorItem object has the following properties, which are identical to the columns in the ErrorList window
(compare to screenshot above):

Property Description
Description Describes the error message.
FileName Filename where the error occured.
Line Line in which the error occured.
Column Column in which the error occured.
Project Project in which the error occured.

Please note that the last four properties are not always used or don't make sense in every situation. For
example, when looking at the screenshot above, the error message "No license found" is not bound to a
specific file, line or column because it is a general TwinCAT error message.

4.3.2 System

4.3.2.1 Opening and activating existing configurations


To activate a previously created configuration, an instance of the TwinCAT XAE has to be created, the
configuration has to be loaded and activated.

Procedure

The ProgId "VisualStudio.DTE.10.0" is used to create an instance of Visual Studio. Via Visual Studios DTE
object a full control of Visual Studio is possible. The Procedure to create the ITcSysManager [} 104] interface
(the 'sysMan' instance here) is described in the chapter Accessing TwinCAT Configurations. [} 19]

Sample (CSharp):

Please note, that, for this sample, you need to add both a reference to "Microsoft Developer Environment
10.0" and "Beckhoff TwinCAT XAE Base" to your project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE100;
using System.IO;
using TCatSysManagerLib;

namespace ActivatePreviousConfiguration
{
class Program
{
static void Main(string[] args)
{
Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
EnvDTE.DTE dte = (EnvDTE.DTE)System.Activator.CreateInstance(t);
dte.SuppressUI = false;
dte.MainWindow.Visible = true;

EnvDTE.Solution sol = dte.Solution;


sol.Open(@"C:\Temp\SolutionFolder\MySolution1\MySolution1.sln");

EnvDTE.Project pro = sol.Projects.Item(1);

ITcSysManager sysMan = pro.Object;

sysMan.ActivateConfiguration();

Automation Interface Version: 1.3 37


Configuration

sysMan.StartRestartTwinCAT();
}
}
}

Sample (PowerShell):
$prjDir = "C:\tmp\TestSolution\"
$prjName = "TestSolution.sln"
$prjPath = $prjDir += $prjName
$dte = new-object -com VisualStudio.DTE.10.0
$dte.SuppressUI = $false
$dte.MainWindow | %{$_.gettype().InvokeMember("Visible","SetProperty",$null,$_,$true)}

$sln = $dte.Solution
$sln.Open($prjPath)

$project = $sln.Projects.Item(1)
$systemManager = $project.Object

$systemManager.ActivateConfiguration()
$systemManager.StartRestartTwinCAT()

Sample (VBScript):
dim dte,sln,proj,sysMan
set dte = CreateObject("VisualStudio.DTE.10.0")
set sln = dte.Solution
call sln.Open("C:\SolutionFolder\MySolution1.sln")
set proj = sln.Projects(1)
set sysMan = proj.Object
call sysMan.ActivateConfiguration
call sysMan.StartRestartTwinCAT

4.3.2.2 Opening existing projects from a TwinCAT Target


This documentation article describes how to open existing TwinCAT projects from a connected TwinCAT
Target. The Target needs to be available, which means that ADS routes have to be present in order to be
able to retrieve the project from the Target.

The following code snippet demonstrates how to retrieve the TwinCAT project from a connected Target
Runtime.

Code snippet (C#):


dte.ExecuteCommand("File.OpenProjectFromTarget", "CX-123456 C:\\ProjectDir ProjectName");

Code snippet (Powershell):


$dte.ExecuteCommand("File.OpenProjectFromTarget", "CX-123456 C:\\ProjectDir ProjectName");

The method ExecuteCommand() from the Visual Studio API allows to trigger the TwinCAT command
(File.OpenProjectFromTarget) to open the project from a connected TwinCAT Target. The three parameters
are to be included in the second parameter of the ExecuteCommand() method. These three parameters are:
Route name to Target, local project directory (where the project files should be stored), local project name.
All three parameters are to be separated with a space from each other.

4.3.2.3 Creating and handling variable mappings


A very common scenario in which the TwinCAT Automation Interface is being used, is to automatically create
variable mappings, e.g. between PLC input/output variables and their corresponding I/O counterparts. The
Automation Interface provides several methods that simplify the task to create, delete or save variable
mappings. The following documentation article briefly describes these methods and gives examples on how
to use them. The following topics are covered:
• General information
• Link variables
• Unlink variables

38 Version: 1.3 Automation Interface


Configuration

• Get/Set all variable mappings


• Delete all variable mappings

General information

Variable mappings may occur between different input/output tree items in a TwinCAT project, for example:
• Between PLC input/output variables and I/O (and vice versa)
• Between PLC input/output variables and NC (and vice versa)
• Between PLC input/output variables and TcCOM objects (and vice versa)
• …

The information in this article describes Automation Interface mechanisms which may be used for all of these
use cases.

Link variables

From an Automation Interface point-of-view, variable mappings are always being performed between two
tree items, e.g. between a PLC input/output variable and its corresponding I/O counterpart. To link two tree
items, the Automation Interface provides the method ITcSysManager::LinkVariables() which links a given
source tree item with a given destination tree item.

Code snippet (C#):


string source = "TIPC^PlcProj^PlcProj Instance^PlcTask Inputs^bIn";
string destination = "TIID^EtherCAT^EK1100^EL1004^Channel 1^Input";
systemManager.LinkVariables(source, destination);

Code snippet (Powershell):


$source = "TIPC^PlcProj^PlcProj Instance^PlcTask Inputs^bIn"
$destination = "TIID^EtherCAT^EK1100^EL1004^Channel 1^Input"
$systemManager.LinkVariables($source, $destination)

Unlink variables

Similar to linking variables, the Automation Interface provides a method ITcSysManager::UnlinkVariables()


which releases the link between a given source tree item and a given destination tree item.

Code snippet (C#):


string source = "TIPC^PlcProj^PlcProj Instance^PlcTask Inputs^bIn";
string destination = "TIID^EtherCAT^EK1100^EL1004^Channel 1^Input";
systemManager.UnlinkVariables(source, destination);

Code snippet (Powershell):


$source = "TIPC^PlcProj^PlcProj Instance^PlcTask Inputs^bIn"
$destination = "TIID^EtherCAT^EK1100^EL1004^Channel 1^Input"
$systemManager.UnlinkVariables($source, $destination)

Save/Restore all variable mappings

To save or restore all variable mappings in a TwinCAT project, the methods


ITcSysManager2::ProduceMappingInfo() and ITcSysManager2::ConsumeMappingInfo() can be used. The
former reads all variable mappings in a TwinCAT project and returns them in an XML structure that can be
re-imported later by using the latter method.

Code snippet (C#):


ITcSysManager2 systemManager2 = (ITcSysManager2)systemManager;
string mappingInfo = systemManager2.ProduceMappingInfo();
systemManager2.ConsumeMappingInfo(mappingInfo);

Code snippet (Powershell):


$mappingInfo = $systemManager.ProduceMappingInfo()
$systemManager.ConsumeMappingInfo($mappingInfo)

Automation Interface Version: 1.3 39


Configuration

Delete all variable mappings

To delete all variable mappings in a TwinCAT project, the method ITcSysManager2.ClearMappingInfo() may
be used.

Code snippet (C#):


ITcSysManager2 systemManager2 = (ITcSysManager2)systemManager;
systemManager2.ClearMappingInfo();

Code snippet (Powershell):


$systemManager.ClearMappingInfo()

4.3.2.4 Creating and handling Tasks


This article explains how to create and handle Tasks via TwinCAT Automation Interface. It consists of the
following topics:
• General information
• Inserting Tasks
• Inserting input/output variables

General information

There are two types of Tasks which can be configured in TwinCAT XAE and therefore also via Automation
Interface: Tasks with Process Image and without. When you insert a new Task in TwinCAT XAE, you can
decide whether you want to include a Process Image or not by selecting the corresponding checkbox in the
"Insert Task" dialog.

As a result, the inserted Task either includes three more child nodes (Image, Inputs, Outputs) or not - as the
following example shows (Task 1 = With Image, Task 2 = Without Image).

40 Version: 1.3 Automation Interface


Configuration

Inserting Tasks

To insert a Task via Automation Interface, you can make use of the ITcSmTreeItem [} 113]::CreateChild()
[} 148] method and the corresponding SubTypes for "With Image" (SubType = 0) and "Without
Image" (SubType = 1).

Code Snippet (C#)


ITcSmTreeItem tasks = systemManager.LookupTreeItem("TIRT");
tasks.CreateChild("Task 1 (With Image)", 0, null, null);

Code Snippet (Powershell):


$tasks = $systemManager.LookupTreeItem("TIRT")
$tasks.CreateChild("Task 1 (With Image)", 0, $null, $null)

Code Snippet (C#)


ITcSmTreeItem tasks = systemManager.LookupTreeItem("TIRT");
tasks.CreateChild("Task 2 (Without Image)", 1, null, null);

Code Snippet (Powershell):


$tasks = $systemManager.LookupTreeItem("TIRT")
$tasks.CreateChild("Task 1 (Without Image)", 1, $null, $null)

Inserting input/output variables

You can add Input/Output variables to process images (Task "With Image"), which can then be linked with I/
O devices or variables from other Tasks. The corresponding dialog from TwinCAT XAE lets you choose e.g.
the data type and address of the input/output variable in the process image. By clicking on "Ok", the variable
will be added to the process image.

This procedure can also be triggered via Automation Interface by using the ITcSmTreeItem
[} 113]::CreateChild() [} 148] method with the corresponding variable data type as vInfo. In this case the
SubType specifies the "Start Address", as shown in the dialog above.

Code Snippet (C#):


ITcSmTreeItem task1 = systemManager.LookupTreeItem("TIRT^Task 1 (With Image)^Inputs");
task1.CreateChild("bInput", -1, null, "BOOL");

Code Snippet (Powershell):

Automation Interface Version: 1.3 41


Configuration

$task1 = $systemManager.LookupTreeItem("TIRT^Task 1 (With Image)^Inputs")


$task1.CreateChild("bInput", -1, $null, "BOOL")

By using SubType = -1, TwinCAT automatically attaches the new variable at the end of the variable list.

4.3.2.5 Using Templates


The following article describes how to use templates instead of configuring every single setting separately
via Automation Interface. The usage of templates provides many advantages: they are easier to maintain,
easier to replace with new templates, and they provide great possibilities when working with multiple teams
on one TwinCAT project. This document describes the usage of templates and covers the following topics:
• The general idea behind templates and its different levels
• Working with I/O templates
• Working with Motion templates (axes)
• Working with PLC templates

The general idea behind templates and its different levels

The idea behind the usage of templates is to simplify Automation Interface code and the Automation
Interface application itself. Most users are not aware that, in a TwinCAT configuration, templates can exist on
multiple levels. These include:
• Templates on “configuration level”
• Templates on configuration level may exist as several TwinCAT configurations (*.sln or *.tszip file).
Each configuration may include different content and can be opened and activated by Automation
Interface code.
• Templates on “(PLC) project level”
• Templates on (PLC) project level may exist as several TwinCAT PLC Projects, either as an unpacked
folder structure (*.plcproj file) or as a container (*.tpzip) file. These PLC Projects can then be imported
on demand via Automation Interface code.
• Templates on “tree item level”
• Templates on tree item level may exist as so-called TwinCAT export files (*.xti). These files can be
imported on demand via Automation Interface code and contain all settings of a tree item, e.g. settings
that have been made to an EtherCAT Master I/O device.

As the description from above might suggest, all different template levels have one thing in common: the
templates exist as files in the file system. It is best practice that, at the beginning of implementing an own
Automation Interface application, one clearly defines what kind of “template pool” is being used. A template
pool describes a repository, where all template files (which might also be a mix of different template levels)
are being stored. This could simply be the local (or remote) file system, or might also be a source control
system (e.g. Team Foundation Server), from which template files are automatically retrieved, checked out
and put together to a new TwinCAT configuration. For your convenience and to make the first steps easier
for you, we have prepared a separate documentation article that demonstrates how to use the Visual Studio
Object Model (DTE) to connect to a Team Foundation Server (TFS) and execute these operations via
program code. However, to get more information about using TFS via Automation Interface code, we heavily
suggest to read the corresponding articles from the Microsoft Developer Network (MSDN).

The following topics describe how each template level can be used in Automation Interface for a different
TwinCAT area (I/O, PLC, …).

Working with configuration templates

Templates on configuration level provide the most basic way of using templates. In this scenario, a template
pool holds two or more pre-configured TwinCAT configurations and provides them as TwinCAT Solution files
(*.sln or *.tszip). These files can be opened via Automation Interface by using the Visual Studio method
AddFromTemplate().

Code Snippet (C#):


project = solution.AddFromTemplate(@"C:\TwinCAT Project.tszip", destination, projectName);

42 Version: 1.3 Automation Interface


Configuration

Code Snippet (Powershell):


$project = $solution.AddFromTemplate(@"C:\TwinCAT Project.tszip", $destination, $projectName)

OR

Code Snippet (C#):


project = solution.Open(@"C:\TwinCAT Project 1.sln");

Code Snippet (Powershell):


$project = $solution.Open(@"C:\TwinCAT Project 1.sln")

Working with I/O templates

When working with I/O devices, users often experience the same tasks on I/O devices over and over again.
That means, making the same settings to I/O devices with each TwinCAT configuration. TwinCAT provides a
mechanism that stores all these settings in a special file format, the so-called XTI file (*.xti). This file format
can be used by Automation Interface code to be imported to a new configuration by using the method
ImportChild() which is defined in the interface ITcSmTreeItem.

Code Snippet (C#):


ITcSmTreeItem io = systemManager.LookupTreeItem("TIID");
ITcSmTreeItem newIo = io.ImportChild(@"C:\IoTemplate.xti", "", true, "SomeName");

Code Snippet (Powershell):


$io = $systemManager.LookupTreeItem("TIID")
$newIo = $io.ImportChild(@"C:\IoTemplate.xti", "", true, "SomeName")

It is important to note that, if you export an I/O device from within TwinCAT XAE, that all sub devices are
automatically exported and included in the export file as well. The following screenshot shows how to export
I/O devices into an export file.

Please note that you could also use the Automation Interface to export an I/O device into an XTI file. For this,
the method ExportChild() from the ITcSmTreeItem interface is provided.

Working with Motion templates (axes)

The usage of Motion axes templates is very similar to I/O devices. Axes can also be exported into an XTI-file,
either via TwinCAT XAE or via Automation Interface code by using ExportChild().

Automation Interface Version: 1.3 43


Configuration

By using ImportChild(), these export files can later be imported again.

Code Snippet (C#):


ITcSmTreeItem motionAxes = systemManager.LookupTreeItem("TINC^NC-Task^Axes");
motionAxes.ImportChild(@"C:\AxisTemplates.xti", "", true, "Axis 1");

Code Snippet (Powershell):


$motionAxes = $systemManager.LookupTreeItem("TINC^NC-Task^Axes")
$motionAxes.ImportChild(@"C:\AxisTemplates.xti", "", true, "Axis 1")

Working with PLC templates

PLC templates are available in two units: You can either use the complete PLC projects as a whole or each
POU individually as a templates. To integrate the former into an existing TwinCAT project, simply use the
CreateChild() method of the ITcSmTreeItem interface.

Code Snippet (C#):


ITcSmTreeItem plc = systemManager.LookupTreeItem("TIPC");
plc.CreateChild("NewPlcProject", 0, null, pathToTpzipOrTcProjFile);

Code Snippet (Powershell):


$plc = $systemManager.LookupTreeItem("TIPC")
$plc.CreateChild("NewPlcProject", 0, $null, $pathToTpzipOrTcProjFile)

More options to import existing PLC projects can be found in the best practice article about “Accessing,
creating and handling PLC projects”.

The next granularity level of importing template files for the PLC is to import existing POUs, like function
blocks, structs, enums, global variable lists, etc. One of the reasons a developer may choose individual
POUs as templates, is that it is easier to build a pool of existing functionalities and encapsulate them in
separate POUs, e.g. different function blocks covering different sorting algorithms. Upon project creation, the
developer simply chooses which functionality he needs in his TwinCAT project and accesses the template
tool to retrieve the corresponding POU and import it to his PLC project.

Code Snippet (C#):


ITcSmTreeItem plcProject = systemManager.LookupTreeItem(“TIPC^Name^Name Project”);
plcProject.CreateChild(“NameOfPou”, 58, null, pathToPouFile);
plcProject.CreateChild(null, 58, null, stringArrayWithPathsToPouFiles);

Code Snippet (Powershell):


$plcProject = $systemManager.LookupTreeItem("TIPC^Name^Name Project")
$plcProject.CreateChild("NameOfPou", 58, $null, $pathToPouFile)
$plcProject.CreateChild($null, 58, $null, $stringArrayWithPathsToPouFiles)

44 Version: 1.3 Automation Interface


Configuration

Note A POU template file may not only be a .TcPou file but also the corresponding files for DUTs and/
or GVLs. The example above demonstrates two common ways to import POU template files. The first
is to import a single file, the second to import multiple files at once by storing the file paths to a
string array and using this string array as the vInfo parameter of CreateChild().

4.3.2.6 Accessing TwinCAT Remote Manager


This documentation article describes how to access the TwinCAT Remote Manager functionality via
Automation Interface. The TwinCAT Remote Manager allows to switch between different TwinCAT 3 XAE
versions that have been installed on the same engineering computer. To access the Remote Manager via
Automation Interface, simply execute the following code snippets.

Code Snippet (C#):


ITcRemoteManager remoteManager = dte.GetObject("TcRemoteManager");
remoteManager.Version = "3.1.4020.0";

Code Snippet (Powershell):


$remoteManager = $dte.GetObject("TcRemoteManager")
$remoteManager.Version = "3.1.4020.0"

4.3.2.7 Assigning tasks to CPU cores

Procedure
• Enabling the Cores for realtime usage.
• Paremetrization of the Cores with the LoadLimit, base cycle time (BaseTime) and a Latency Watchdog
• Assignment of Tasks to CPU resources.

The following code snippets are also available for download in our Samples section.

Sample (C#):
ITcSysManager3 systemManager = null;
[Flags()]
public enum CpuAffinity : ulong
{
CPU1 = 0x0000000000000001,
CPU2 = 0x0000000000000002,
CPU3 = 0x0000000000000004,
CPU4 = 0x0000000000000008,
CPU5 = 0x0000000000000010,
CPU6 = 0x0000000000000020,
CPU7 = 0x0000000000000040,
CPU8 = 0x0000000000000080,
None = 0x0000000000000000,
MaskSingle = CPU1,
MaskDual = CPU1 | CPU2,
MaskQuad = MaskDual | CPU3 | CPU4,
MaskHexa = MaskQuad | CPU5 | CPU6,
MaskOct = MaskHexa | CPU7 | CPU8,
MaskAll = 0xFFFFFFFFFFFFFFFF
}

public void AssignCPUCores()


{
ITcSmTreeItem realtimeSettings = systemManager.LookupTreeItem("TIRS");
// CPU Settings
// <TreeItem>
// <RTimeSetDef>
// <MaxCPUs>3</MaxCPUs>
// <Affinity>#x0000000000000007</Affinity>
// <CPUs>
// <CPU id="0">
// <LoadLimit>10</LoadLimit>
// <BaseTime>10000</BaseTime>
// <LatencyWarning>200</LatencyWarning>
// </CPU>
// <CPU id="1">

Automation Interface Version: 1.3 45


Configuration

// <LoadLimit>20</LoadLimit>
// <BaseTime>5000</BaseTime>
// <LatencyWarning>500</LatencyWarning>
// </CPU>
// <CPU id="2">
// <LoadLimit>30</LoadLimit>
// <BaseTime>3333</BaseTime>
// <LatencyWarning>1000</LatencyWarning>
// </CPU>
// </CPUs>
// </RTimeSetDef>
// </TreeItem>

string xml = null;


MemoryStream stream = new MemoryStream();
StringWriter stringWriter = new StringWriter();
using(XmlWriter writer = XmlTextWriter.Create(stringWriter))
{     
writer.WriteStartElement("TreeItem");
writer.WriteStartElement("RTimeSetDef");
writer.WriteElementString("MaxCPUs", "4");     
string affinityString = string.Format("#x{0}",((ulong)
cpuAffinity.MaskQuad).ToString("x16"));
writer.WriteElementString("Affinity", affinityString);
writer.WriteStartElement("CPUs");
writeCpuProperties(writer, 0, 10, 1000, 10000, 200);
writeCpuProperties(writer, 1, 20, 5000, 10000, 500);
writeCpuProperties(writer, 2, 30, 3333, 10000, 1000);
writer.WriteEndElement();     // CPUs     
writer.WriteEndElement();     // RTimeSetDef     
writer.WriteEndElement();     // TreeItem
}
xml = stringWriter.ToString();
realtimeSettings.ConsumeXml(xml);
ITcSmTreeItem tasks = systemManager.LookupTreeItem("TIRT");
ITcSmTreeItem task1 = tasks.CreateChild("TaskA",1);
setTaskProperties(task1,CpuAffinity.CPU1);
ITcSmTreeItem task2 = tasks.CreateChild("TaskB",1);
setTaskProperties(task2, CpuAffinity.CPU2);
    
ITcSmTreeItem task3 = tasks.CreateChild("TaskC", 1);
setTaskProperties(task3, CpuAffinity.CPU3);
}

private void setTaskProperties(ITcSmTreeItem task, CpuAffinity affinityMask)


{
// <TreeItem>
// <TaskDef>
// <CpuAffinity>#x0000000000000004</CpuAffinity>
// </TaskDef>
// </TreeItem>

StringWriter stringWriter = new StringWriter();


using(XmlWriter writer = new XmlTextWriter(stringWriter))
{
    writer.WriteStartElement("TreeItem");
    writer.WriteStartElement("TaskDef");
    string affinityString = string.Format("#x{0}", ((ulong)affinityMask).ToString("x16"));
    writer.WriteElementString("CpuAffinity",affinityString);
    writer.WriteEndElement();
    writer.WriteEndElement();
}

string xml = stringWriter.ToString();


task.ConsumeXml(xml);
}

private void writeCpuProperties(XmlWriter writer, int id, int loadLimit, int baseTime, int
latencyWarning)
{
writer.WriteStartElement("CPU");
writer.WriteAttributeString("id", id.ToString());
writer.WriteElementString("LoadLimit", loadLimit.ToString());
writer.WriteElementString("BaseTime", baseTime.ToString());
writer.WriteElementString("LatencyWarning", latencyWarning.ToString());
writer.WriteEndElement();
}

46 Version: 1.3 Automation Interface


Configuration

4.3.2.8 Configuring TwinCAT Boot settings


The following documentation article describes how to configure the TwinCAT Boot settings via Automation
Interface. For this the methods ITcSmTreeItem::ProduceXml() and ITcSmTreeItem::ConsumeXml() can be
used to generate or import the following XML structure, which represents the corresponding settings in
TwinCAT XAE.
<TreeItem>
  <System>
    <BootSettings>
      <AutoRun>true</AutoRun>
      <AutoLogon>true</AutoLogon>
      <LogonUserName>UserName</LogonUserName>
      <LogonPassword>Password</LogonPassword>
      <BootFileEncryptionType>None</BootFileEncryptionType>
    </BootSettings>
  </System>
</TreeItem>

4.3.2.9 Activate or deactivate IndependentProjectFile setting


To enhance engineering experience with regard to Source Control integration, TwinCAT 3 provides the
possibility to store settings in separate project files – called “IndependentProjectFile”. This tree item based
setting can also be activated/deactivated via TwinCAT Automation Interface. The interface ITcSmTreeItem6
provides the necessary property.

The following code snippet demonstrates how to activate this setting if it is deactivated, e.g. on an EtherCAT
Master device.

Code Snippet (C#):


ITcSmTreeItem6 etherCatMaster = (ITcSmTreeItem6)systemManager.LookupTreeItem("TIID^Device 1
(EtherCAT)");
if (etherCatMaster.SaveInOwnFile == false)
  etherCatMaster.SaveInOwnFile = true;

Code Snippet (Powershell):


$etherCatMaster = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)")
if ($etherCatMaster.SaveInOwnFile -eq $false)
{
  $etherCatMaster.SaveInOwnFile = $true
}

4.3.2.10 From offline to online configurations


This article explains how to convert a TwinCAT configuration, which has been created 'offline', via TwinCAT
Automation Interface to an online configuration. The term "offline" means that no physical I/Os are present at
the time of configuration creation and therefore the real address information is not available, e.g. for an
EtherCAT Master . The following topics are part of this article:
• General information
• Creating an offline configuration
• Switching to an online configuration

General information

When creating a TwinCAT configuration, there are two common scenarios:


• Scenario 1: this scenario is based on the real physical device, on which the TwinCAT configuration
should run later. Therefore, all I/Os are online and already available and attached to the device.
• Scenario 2: this scenario could involve to create the configuration offline (that means without any I/Os
attached to the engineering device) and later switch to an online configuration when the I/Os are
available. This is the scenario which will be the primary focus of this article.

Automation Interface Version: 1.3 47


Configuration

Both scenarios are possible via TwinCAT Automation Interface. However, as scenario 2 lacks some
important information about some of the I/Os, e.g. their physical addresses, this scenario could be slightly
more complex because you need to hand in the required (address) information later.

The familiar TwinCAT XAE functionality "Scan Devices" plays a significant role in this use-case because it
scans for all available I/O devices and automatically attaches them to the configuration - together with all
needed additional information, e.g. physical addresses.

On a physical controller, this functionality can also be called via Automation Interface and then returns an
XML representation of all found I/O devices including their corresponding address information.

When a TwinCAT configuration should be activated on the controller, the required address information needs
to be set for all I/O devices that are part of the configuration. This can be done by calling the "Scan Devices"
functionality via Automation Interface and setting the address information for the I/O devices in the
configuration. This will be explained in more detail now.

Creating an offline configuration

There are several articles which explain how to create an offline TwinCAT configuration. Please refer to our
Product Description [} 9] page to get an overview.

Switching to an online configuration

If you finally have created a TwinCAT configuration that should now be activated on the physical controller,
the following steps need to be taken to ensure that all required address information is available before
downloading the configuration:
• Step 1 [optional]: Connecting to the target device
• Step 2: Scanning the device for available I/Os
• Step 3: Iterating through XML and configuring address information of I/Os
• Step 4: Activating the configuration

Of course, you can also always create an online configuration directly by using the ScanDevices
functionality. There is an own sample [} 87] which shows you exactly how to do that.

Step 1 [optional]: Connecting to the target device

If the physical controller is not located on the same machine as the Automation Interface code runs on, you
can use the ITcSysManager [} 104]::SetTargetNetId() [} 110] method to connect to the remote device and
then continue with the next steps.

48 Version: 1.3 Automation Interface


Configuration

Step 2: Scanning the device for available I/Os

The "Scan Devices" functionality mentioned above can be triggered via Automation Interface by calling the
ITcSmTreeItem::ProduceXml() method on the I/O devices node.

Code Snippet (C#):


ITcSmTreeItem ioDevices = systemManager.LookupTreeItem("TIID");
string foundDevices = ioDevices.ProduceXml();

Step 3: Iterating through XML and configuring address information of I/Os

In this example we want to update the address information of an EtherCAT device which is already part of
our offline configuration. The ProduceXml() in step 2 has already returned the available I/O devices on the
system, which is now available in the variable 'foundDevices'. We will identify the EtherCAT device in this
XML via its item sub type (111) and then update the address information of the EtherCAT Master in our
configuration.

Code Snippet (C#):


XmlDocument doc = new XmlDocument();
doc.LoadXml(foundDevices);
XmlNodeList devices = doc.SelectNodes("TreeItem/DeviceGrpDef/FoundDevices/Device");
foreach (XmlNode device in devices)
{
xmlNode typeNode = device.SelectSingleNode("ItemSubType");
int subType = int.Parse(typeNode.InnerText);
if (subType == 111)
    {
     XmlNode addressInfo = device.SelectSingleNode("AddressInfo");
     ITcSmTreeItem deviceToUpdate = systemManager.LookupTreeItem("TIID^EtherCAT Master");
     string xmlAddress = string.Format("<TreeItem><DeviceDef>{0}</DeviceDef></TreeItem>",
addressInfo.OuterXml);
     deviceToUpdate.ConsumeXml(xmlAddress);
}
}

Step 4: Activating the configuration

The last step only involves activating the configuration on the target device. Simply use the
ITcSysManager::ActivateConfiguration() method to do that.

Code Snippet (C#):


sysManager.ActivateConfiguration();

4.3.3 ADS

4.3.3.1 Creating and handling ADS routes


Adding ADS routes via the Automation Interface can be achieved by using the ConsumeXml() method of the
ITcSmTreeItem interface. However, it is important to understand the underlying XML structure before adding
routes to a remote target.

XML structure

The following code snippets represent sample XML structures for adding routes to a remote target. Please
note that you can either specify the IP address or the hostname of the remote target.

This code snippet will add a regular route to a remote target.

Code Snippet (XML):


<TreeItem>
  <ItemName>Route Settings</ItemName>
  <PathName>TIRR</PathName>
  <RoutePrj>

Automation Interface Version: 1.3 49


Configuration

    <TargetList>
      <BroadcastSearch>true</BroadcastSearch>
    </TargetList>
    <AddRoute>
      <RemoteName>RouteName</RemoteName>
      <RemoteNetId>1.2.3.4.5.6</RemoteNetId>
      <RemoteIpAddr>1.2.3.4</RemoteIpAddr>
      <UserName>userName</UserName>
      <Password>password</Password>
      <NoEncryption></NoEncryption>
      <LocalName>LocalName</LocalName>
    </AddRoute>
  </RoutePrj>
</TreeItem>

This code snippet will add a project route to a remote target.

Code Snippet (XML):


<TreeItem>
  <ItemName>Route Settings</ItemName>
  <PathName>TIRR</PathName>
  <RoutePrj>
    <TargetList>
      <BroadcastSearch>true</BroadcastSearch>
    </TargetList>
    <AddProjectRoute>
      <Name>RouteName</Name>
      <NetId>1.2.3.4.5.6</NetId>
      <IpAddr>1.2.3.4</IpAddr>
    </AddProjectRoute>
  </RoutePrj>
</TreeItem>

The following code snippet will use the hostname instead of the IP address.

Code Snippet (XML):


<TreeItem>
  <ItemName>Route Settings</ItemName>
  <PathName>TIRR</PathName>
  <RoutePrj>
    <TargetList>
      <BroadcastSearch>true</BroadcastSearch>
    </TargetList>
    <AddRoute>
      <RemoteName>RouteName</RemoteName>
      <RemoteNetId>1.2.3.4.5.6</RemoteNetId>
      <RemoteHostName>CX-12345</RemoteHostName>
      <UserName>userName</UserName>
      <Password>password</Password>
      <NoEncryption></NoEncryption>
      <LocalName>LocalName</LocalName>
    </AddRoute>
  </RoutePrj>
</TreeItem>

And for project routes.

Code Snippet (XML):


<TreeItem>
  <ItemName>Route Settings</ItemName>
  <PathName>TIRR</PathName>
  <RoutePrj>
    <TargetList>
      <BroadcastSearch>true</BroadcastSearch>
    </TargetList>
    <AddProjectRoute>
      <Name>RouteName</Name>
      <NetId>1.2.3.4.5.6</NetId>
      <HostName>1.2.3.4</HostName>
    </AddProjectRoute>
  </RoutePrj>
</TreeItem>

Please note that the XML structure for regular and project routes may be used simultaneously.

50 Version: 1.3 Automation Interface


Configuration

The following code snippet creates an ADS route to a remote target that has been specified by its IP address
(10.1.128.217) and its AMS NetId (10.1.128.217.1.1).

Code Snippet (C#):


string xmlString ="<TreeItem><ItemName>Route Settings</ItemName><PathName>TIRR</
PathName><RoutePrj><TargetList><BroadcastSearch>true</BroadcastSearch></
TargetList><AddRoute><RemoteName>RouteName</RemoteName><RemoteNetId>10.1.128.217.1.1</
RemoteNetId><RemoteIpAddr>10.1.128.217</RemoteIpAddr><UserName>Administrator</UserName><Password>1</
Password><NoEncryption></NoEncryption></AddRoute></RoutePrj></TreeItem>";
ITcSmTreeItem routes = systemManager.LookupTreeItem("TIRR");
routes.ConsumeXml(xmlString);

Code Snippet (Powershell):


$xmlString ="<TreeItem><ItemName>Route Settings</ItemName><PathName>TIRR</
PathName><RoutePrj><TargetList><BroadcastSearch>true</BroadcastSearch></
TargetList><AddRoute><RemoteName>RouteName</RemoteName><RemoteNetId>10.1.128.217.1.1</
RemoteNetId><RemoteIpAddr>10.1.128.217</RemoteIpAddr><UserName>Administrator</UserName><Password>1</
Password><NoEncryption></NoEncryption></AddRoute></RoutePrj></TreeItem>"
$routes = $systemManager.LookupTreeItem("TIRR")
$routes.ConsumeXml($xmlString)

Also see about this


2 Sample downloads [} 171]

4.3.3.2 Execute an ADS broadcast search


To trigger a TwinCAT Broadcast search and find unknown remote ADS devices, the ConsumeXml() and
ProduceXml() methods from the ITcSmTreeItem interface may be used.

General broadcast search

Code Snippet (C#):


string xmlString = "<TreeItem><RoutePrj><TargetList><BroadcastSearch>true</BroadcastSearch></
TargetList></RoutePrj></TreeItem>";
ITcSmTreeItem routes = sysMan.LookupTreeItem("TIRR");
routes.ConsumeXml(xmlString);
string result = routes.ProduceXml();

Code Snippet (Powershell):


$xmlString = "<TreeItem><RoutePrj><TargetList><BroadcastSearch>true</BroadcastSearch></TargetList></
RoutePrj></TreeItem>"
$routes = $systemManager.LookupTreeItem("TIRR")
$routes.ConsumeXml($xmlString)
$result = $routes.ProduceXml()

The variable “result” now contains an XML representation of all found ADS devices on the network. To select
a specific device from that list, regular .NET mechanisms for XML handling may be used.

Code Snippet (C#):


XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(result);
string amsNetId = xmlDocument.SelectSingleNode("//TreeItem/RoutePrj/TargetList/Target/IpAddr[text()=
\"" + ipAddress + "\"]/../NetId").InnerText;
string name = xmlDocument.SelectSingleNode("//TreeItem/RoutePrj/TargetList/Target/IpAddr[text()=\""
+ ipAddress + "\"]/../Name").InnerText;

Code Snippet (Powershell):


$xmlDocument = [xml]$result
$localAmsNetId = $xmlDocument.TreeItem.RoutePrj.Target

This information might then be used to add a route to that ADS device, as described in a separate
documentation article.

Direct broadcast search

Requires at least TwinCAT 3.1 Build 4020.10 or higher.

Automation Interface Version: 1.3 51


Configuration

To execute a broadcast search with a given hostname or IP address, the following XML structures can be
used in ConsumeXml().

XML - Search for Hostname:


<TreeItem>
  <RoutePrj>
    <TargetList>
      <Search>CX-12345</Search>
    </TargetList>
  </RoutePrj>
</TreeItem>

XML - Search for IP address:


<TreeItem>
  <RoutePrj>
    <TargetList>
      <Search>172.17.60.153</Search>
    </TargetList>
  </RoutePrj>
</TreeItem>

A subsequent ProduceXml() will return the found host as follows:

XML - Found host:


<TreeItem>
  <RoutePrj>
    <TargetList>
      <Target>
        <Name>CX-12345</Name>
        <NetId>172.17.60.153.1.1</NetId>
        <IpAddr>172.17.60.153</IpAddr>
        <Version>3.1.4020</Version>
        <OS>Windows 7</OS>
      </Target>
    </TargetList>
  </RoutePrj>
</TreeItem>

4.3.4 PLC

4.3.4.1 Accessing, creating and handling PLC projects


This chapter explains in-depth how to create, access and handle PLC projects. The following list shows all
chapters in this article:
• General information about PLC projects
• Creating and handling PLC projects
• Opening existing PLC projects
• Nested projects and project instances
• Saving the PLC project as a library
• Handling online functionalities (Login, StartPlc, StopPlc)
• Setting Boot project options
• Saving project and/or solution as archive
• Calling CheckAllObjects()

52 Version: 1.3 Automation Interface


Configuration

General information about PLC projects

PLC projects are specified by their so-called project template. TwinCAT currently deploys two templates
which are represented by a template file in the TwinCAT directory. The following table shows which PLC
templates are available and the corresponding template file:

Template name Template file


Standard PLC template C:\TwinCAT\3.x\Components\Plc\PlcTemplate\Plc
Templates\Standard PLC Template.plcproj
Empty PLC template C:\TwinCAT\3.x\Components\Plc\PlcTemplate\Plc
Templates\Empty PLC Template.plcproj

Creating and handling PLC projects

To create a new PLC project via Automation Interface, you need to navigate to the PLC node and then
execute the CreateChild() method with the corresponding template file as a parameter.

Code snippet (C#):


ITcSmTreeItem plc = systemManager.LookupTreeItem("TIPC");
ITcSmTreeItem newProject = plc.CreateChild("NameOfProject", 0, "", pathToTemplateFile);

Code snippet (Powershell):


$plc = $systemManager.LookupTreeItem("TIPC")
$newProject = $plc.CreateChild("NameOfProject", 0, "", pathToTemplateFile)

Please note
When using standard PLC templates as provided by Beckhoff, please make sure to only use the
template name instead of the full path, e.g. “Standard PLC Template”.

All subsequent operations, like creating and handling POUs and filling them with code, are described in a
separate article.

After the PLC project has been created, it can be further handled by casting it to the special interface
ITcPlcIECProject [} 157], which provided more functionalities and access to the projects specific attributes:

Code snippet (C#):


ITcSmTreeItem plcProject = systemManager.LookupTreeItem("TIPC^NameOfProject^NameOfProject Project");
ITcPlcIECProject iecProject = (ITcPlcIECProject) plcProject;

Code snippet (Powershell):


$plcProject = $systemManager.LookupTreeItem("TIPC^NameOfProject^NameOfProject Project")

The object "iecProject" can now be used to access the methods of the ITcPlcIECProject interface, e.g. to
save the PLC project as a PLC library.

Opening existing PLC projects

To open an existing PLC-Project via Automation Interface, you need to navigate to the PLC node and then
execute the CreateChild() method with the path to the corresponding PLC project file file as a parameter.

You can use three different values as SubType:


• 0: Copy project to solution directory
• 1: Move project to solution directory
• 2: Use original project location (when used, please use "" as project name parameter)

Basically, these values represent the functionalities (Yes, No, Cancel) from the following MessageBox in
TwinCAT XAE:

Automation Interface Version: 1.3 53


Configuration

In place of the template file you need to use the path to the PLC project (to its plcproj file) that needs to be
added. As an alternative, you can also use a PLC project archive (tpzip file).

Code snippet (C#):


ITcSmTreeItem plc = systemManager.LookupTreeItem("TIPC");
ITcSmTreeItem newProject = plc.CreateChild("NameOfProject", 1, "", pathToProjectOrTpzipFile);

Code snippet (Powershell):


$plc = $systemManager.LookupTreeItem("TIPC")
$newProject = $plc.CreateChild("NameOfProject", 1, "", pathToProjectOrTpzipFile)

TwinCAT PLC Projects consist of two different areas – the so-called Nested Project and the Project
Instance. The Nested Project (tree item sub type 56) contains the source code of the PLC program whereas
the Project Instance contains the declared input and output variables of the PLC program.

The following code snippet demonstrates a common way to generically access both tree items, if the full path
name is not known.

Code Snippet (C#):


ITcSmTreeItem plc = sysManager.LookupTreeItem("TIPC");
foreach (ITcSmTreeItem plcProject in plc)
{
    ITcProjectRoot projectRoot = (ITcProjectRoot)plcProject;
    ITcSmTreeItem nestedProject = projectRoot.NestedProject;
    ITcSmTreeItem projectInstance = plcProject.get_Child(1);
}

Code snippet (Powershell):


$plc = $sysManager.LookupTreeItem("TIPC")
ForEach( $plcProject in $plc)
{
    $nestedProject = $plcProject.NestedProject
    $projectInstance = $plcProject.get_Child(1)
}

Please note
A minimum of TwinCAT 3.1 Build 4018 is required to access the interface ITcProjectRoot.

54 Version: 1.3 Automation Interface


Configuration

Saving the PLC project as a library

To save a PLC project as a PLC library, you need to make use of the ITcPlcIECProject
[} 157]::SaveAsLibrary() [} 159] method.

Code snippet (C#):


iecProject.SaveAsLibrary(pathToLibraryFile, false);

Code snippet (Powershell):


$plcProject.SaveAsLibrary(pathToLibraryFile, $false)

The second parameter determines whether the library should be installed to the default repository after it has
been saved as a file.

Handling online functionalities (Login, StartPlc, StopPlc, ResetCold, ResetOrigin)

Required version: TwinCAT 3.1 Build 4010 and above

The Automation Interface also provides you with PLC online features, for example to login to a PLC runtime
and start/stop/reset the PLC program. These features can be accessed via the ITcSmTreeItem
[} 113]::ProduceXml() [} 146] and ITcSmTreeItem [} 113]::ConsumeXml() [} 147] methods. These functions
can be used on a ITcPlcIECProject [} 157] node.

XML structure:
<TreeItem>
<IECProjectDef>
<OnlineSettings>
<Commands>
    <LoginCmd>false</LoginCmd>
    <LogoutCmd>false</LogoutCmd>
    <StartCmd>false</StartCmd>
    <StopCmd>false</StopCmd>
</Commands>
</OnlineSettings>
</IECProjectDef>
</TreeItem>

Code snippet (C#):


string xml = "<TreeItem><IECProjectDef><OnlineSettings><Commands><LoginCmd>true</LoginCmd></
Commands></OnlineSettings></IECProjectDef></TreeItem>";
ITcSmTreeItem plcProject = systemManager.LookupTreeItem("TIPC^NameOfProject^NameOfProject Project");
plcProject.ConsumeXml(xml);

Code snippet (Powershell):

The following table describes every XML node in more detail:

XML Description
LoginCmd true = in SPS-Laufzeit einloggen
LogoutCmd true = aus SPS-Laufzeit ausloggen
StartCmd true = Starten des aktuell in die Laufzeit geladenen
SPS-Programms
StopCmd true = Stoppen des aktuell in die Laufzeit geladenen
SPS-Programms

Please note: In order to use commands like ResetOriginCmd, you must first execute a LoginCmd - similar
to TwinCAT XAE.

Setting Boot project options

The following code snippet demonstrates how to use the ITcPlcProject interface to set Boot project options
for a PLC project.

Code Snippet (C#):

Automation Interface Version: 1.3 55


Configuration

ITcSmTreeItem plcProjectRoot = systemManager.LookupTreeItem(“TIPC^PlcGenerated”);


ITcPlcProject plcProjectRootIec = (ITcPlcProject) plcProjectRoot;
plcProjectRootIec.BootProjectAutostart = true;
plcProjectRootIec.GenerateBootProject(true);

Code snippet (Powershell):


$plcProject = $systemManager.LookupTreeItem(“TIPC^PlcGenerated“)
$plcProject.BootProjectAutostart = $true
$plcProject.GenerateBootProject($true)

Saving project and/or solution as archive

To save the whole TwinCAT solution in an ZIP compatible archive (*.tszip), the ITcSysManager9 interface
may be used.

Code Snippet (C#):


ITcSysManager9 newSysMan = (ITcSysManager9)systemManager;
newSysMan.SaveAsArchive(@"C:\test.tszip");

Code snippet (Powershell):


$systemManager.SaveAsArchive("C:\test.tszip")

To reload a previously saved TSZIP file, the DTE method AddFromTemplate() may be used.

Code Snippet (C#):


dte.Solution.AddFromTemplate("C:\test.tszip",@"C:\tmp","CreatedFromTemplate");

Code snippet (Powershell):


$dte.Solution.AddFromTemplate("C:\test.tszip","C:\tmp","CreatedFromTemplate")

To save a specific PLC project in an ZIP compatible archive (*.tpzip), the method
ITcSmTreeItem::ExportChild() may be used.

Code Snippet (C#):


ITcSmTreeItem plc= sysManager.LookupTreeItem("TIPC");
plc.ExportChild("PlcProject",@"C:\PlcTemplate.tpzip");

Code snippet (Powershell):


$plc = $systemManager.LookupTreeItem("TIPC")
$plc.ExportChild("PlcProject", "C:\PlcTemplate.tpzip")

To reload a previously saved TPZIP file, the ITcSmTreeItem::CreateChild() method may be used.

Code Snippet (C#):


plcConfig.CreateChild("PlcFromTemplate", 0, null, @"C:\PlcTemplate.tpzip");

Code snippet (Powershell):


$plc.CreateChild("plcFromTemplate", 0, $null, "C:\PlcTemplate.tpzip")

Calling CheckAllObjects()

To call the CheckAllObjects() method on the PLC Nested Project, you can use the corresponding method
that is available in interface ITcPlcIECProject2.

Code snippet (C#):


ITcSmTreeItem plcProject = systemManager.LookupTreeItem("TIPC^NameOfProject^NameOfProject Project");
ITcPlcIECProject2 iecProject = (ITcPlcIECProject2) plcProject;
iecProject.CheckAllObjects();

Code snippet (Powershell):


$plcProject = $systemManager.LookupTreeItem("TIPC^NameOfProject^NameOfProject Project")
$plcProject.CheckAllObjects()

56 Version: 1.3 Automation Interface


Configuration

4.3.4.2 Accessing, creating and handling PLC-Libraries and -Placeholde


This chapter explains in-depth how to access and handle PLC libraries and PLC placeholders. The following
list shows all chapters in this article:
• General information about PLC libraries and placeholders
• Navigating through references
• Adding references
• Removing references
• Scanning available libraries
• Freezing placeholder version
• Working with repositories

General information about PLC libraries and placeholders

In TwinCAT 3 there are two types of library objects: Libraries and Placeholders. For more information about
both types please see the TwinCAT 3 documentation about Library Management.

In a TwinCAT 3 PLC project, references to libraries and placeholders are added as child items to the
References node under the corresponding PLC project. When choosing the "Standard PLC Project"
template, some libraries and placeholders are being added to the project by default, e.g. Tc2_Standard,
Tc2_System, ... .

Using Automation Interface, you can navigate to the References node simply by using the ITcSysManager
[} 104]::LookupTreeItem() [} 113] method.

Code snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");

Code snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")

Automation Interface Version: 1.3 57


Configuration

To be able to handle this object correctly, you need to type cast it to the ITcPlcLibraryManager interface.
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;

Please note that this step is not required in Windows Powershell.

Navigating through references

You can iterate through all references by making use of the ITcPlcLibraryManager [} 159]::References
property. This property returns an ITcPlcReferences collection of either library objects (represented by
ITcPlcLibrary [} 166]) or placeholder objects (represented by ITcPlcPlaceholderRef).

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
foreach (ITcPlcLibRef libRef in libManager.References)
{
if (libRef is ITcPlcLibrary)
{
    ITcPlcLibrary library = (ITcPlcLibrary) libRef;
    // do something
}
else if (libRef is ITcPlcPlaceholderRef)
{
    ITcPlcPlaceholderRef placeholder = (ITcPlcPlaceholderRef) libRef;
    // do something
}
}

The object libRef, which is used for the iteration, is of type ITcPlcLibRef. This is a common base class for
ITcPlcLibrary and ITcPlcPlaceholderRef objects. To work with one of these specific classes, we need to type
cast the object accordingly, as shown in the code snippet above.

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
ForEach( $libRef in $references )
{
  $libRef.LanguageIndependentName
}

Adding references

There are two methods in the ITcPlcLibraryManager [} 159] class which allow you to add a library or
placeholder reference to a PLC project: AddLibrary() and AddPlaceholder().

Adding a library can be achieved in two ways:


• Either by specifying the library name, version and distributor
• or by using the library display name
• or (in case of a placeholder) by using the placeholder name

The display name of a library can be determined in the properties window of a library or placeholder:

58 Version: 1.3 Automation Interface


Configuration

Adding libraries:

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
libManager.AddLibrary("Tc2_MDP", "*", "Beckhoff Automation GmbH"); // name, version, distribution
list
libManager.AddLibrary("Tc2_Math, * (Beckhoff Automation GmbH)"); //monitored name

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
$references.AddLibrary("Tc2_MDP", "*", "Beckhoff Automation GmbH")
$references.AddLibrary("Tc2_Math, * (Beckhoff Automation GmbH)")

Adding a placeholder can be achieved in two ways:


• Either by specifying the placeholder name, library name, library version and library distributor
• or by using the placeholder name if the placeholder already exists

Adding placeholders:

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
libManager.AddPlaceholder("Tc2_MC2_Camming"); // add existing place holder with name
libManager.AddPlaceholder("Placeholder_NC", "Tc2_NC", "*", "Beckhoff Automation GmbH");

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
$references.AddPlaceholder("Tc2_MC2_Camming")
$references.AddPlaceholder("Placeholder_NC", "Tc2_NC", "*", "Beckhoff Automation GmbH")

Please note: When adding a new placeholder, the parameters of the AddPlaceholder() method specify its
Default Resolution. To set the Effective Resolution, simply use the ITcPlcLibraryManager
[} 159]::SetEffectiveResoltion() method.

Removing references

To remove a reference, simply use the method ITcPlcLibraryManager [} 159]::RemoveReference(). Because


this method operates on ITcPlcLibRef items (which is the base class for ITcPlcLibrary and
ITcPlcPlaceholderRef objects), you can use this method both for library and placeholder references.

Library references can be removed by either specifying their name, version and distributor or by specifying
their display name.

Placeholder references can be removed by the placeholder name.

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
libManager.RemoveReference("Tc2_Math"); // delete library
libManager.RemoveReference("Placeholder_NC"); // delete a placeholder

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
$references.RemoveReference("Tc2_Math")
$references.RemoveReference("Placeholder_NC")

Scanning available libraries

To scan the system for all available PLC libraries, simply use the ITcPlcLibraryManager
[} 159]::ScanLibraries() [} 164] method. This method returns an ITcPlcReferences collection of libraries (type
ITcPlcLibrary).

Automation Interface Version: 1.3 59


Configuration

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
ITcPlcReferences libraries = libManager.ScanLibraries();
foreach(ITcPlcLibrary library in libraries)
{
// do something
}

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
$libraries = $references.ScanLibraries()
ForEach( $lib in $libraries )
{
  $lib.Name
}

Freezing placeholder version

It is possible to freeze the used version of a placeholder to a specific version. This can be achieved by using
the method ITcPlcLibraryManager [} 159]::FreezePlaceholder(). This method is called on an object that
points to the References node.

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
libManager.FreezePlaceholder(); // freezes the version of all place holders
libManager.FreezePlaceholder("Placeholder_NC"); // freezes the version of a specific place holder

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
$references.FreezePlaceholder()
$references.FreezePlaceholder("Placeholder_NC")

Please note: The version is freezed to the Effective Resolution. If the Effective Resolution points to "*", then
the newest version in the system is used.

Working with repositories

The Automation Interface provides method for handling PLC library repositories. A default repository is part
of every TwinCAT installation. To create additional repositories, you can use the ITcPlcLibraryManager
[} 159]::InsertRepository() [} 162] method.

Code Snippet (C#):


ITcSmTreeItem references = systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1
Project^References");
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) references;
libManager.InsertRepository("TestRepository", @"C:\Temp", 0);

Code Snippet (Powershell):


$references = $systemManager.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References")
$references.InsertRepository("TestRepository", "C:\Temp", 0)

When installing a new library into the system, the library needs to be part of a repository. This insertion can
be achieved by using the ITcPlcLibraryManager [} 159]::InstallLibrary() [} 163] method.

Code Snippet (C#):


libManager.InstallLibrary("TestRepository", @"C:\SomeFolder\TcTestLibrary.library", false);

Code Snippet (Powershell):


$references.InstallLibrary("TestRepository", "C:\SomeFolder\TcTestLibrary.library", $false)

To uninstall a library from the repository, use the ITcPlcLibraryManager [} 159]::UninstallLibrary() [} 165]
method.

60 Version: 1.3 Automation Interface


Configuration

Code Snippet (C#):


libManager.UninstallLibrary("TestRepository", "Tc2_MDP", "*", "Beckhoff Automation GmbH");

Code Snippet (Powershell):


$references.UninstallLibrary("TestRepository", "Tc2_MDP", "*", "Beckhoff Automation GmbH")

To remove a repository, use the ITcPlcLibraryManager [} 159]::RemoveRepository() [} 164] method.

Code Snippet (C#):


libManager.RemoveRepository("TestRepository");

Code Snippet (Powershell):


$references.RemoveRepository("TestRepository")

4.3.4.3 Accessing, creating and handling PLC POUs


This chapter explains in-depth how to access PLC objects, for example POUs, Methods, Transitions,
Properties, and how to access their corresponding implementation and declaration areas to handle PLC
code. It also covers how to import/export PLC objects in PLCopen XML. The following list shows all chapters
in this article:
• General information about PLC objects
• Accessing the implementation / declaration area of a POU
• Accessing Sub-POUs (Actions, Properties, ...)
• Creating PLC objects
• PLC access modifier
• Importing / Exporting PLCopen XML
• Import existing POUs (templates)

General information about PLC objects

Although every tree item is considered to be of type ITcSmTreeItem [} 113], some items need to be casted to
a more special interface to gain access to all of their methods and properties, for example POUs which need
to be casted to the interface ITcPlcPou [} 154] to get access to their unique methods and properties.

Code snippet (C#):


ITcSmTreeItem plcPousItem = systemManager.LookupTreeItem("TIPC^PlcGenerated^PlcGenerated
Project^POUs");
ITcSmTreeItem newFb = plcPousItem.CreateChild("FB_TEST", 604, "", IECLANGUAGETYPES.IECLANGUAGE_ST);
ITcPlcPou fbPou = (ITcPlcPou)newFb;

Code snippet (Powershell):


$plcPousItem = $systemManager.LookupTreeItem("TIPC^PlcGenerated^PlcGenerated Project^POUs")
$newFb = $plcPousItem.CreateChild("FB_TEST", 604, "", 6)

In this example, the POU MAIN is being created in a PLC-Project. The object programPou references this
POU and can now be used to access specific methods and properties of the POU by using the
corresponding method/property of the ITcPlcPou interface.

Accessing the implementation / declaration area of a POU

You can also get read/write access to either the implementation or declaration area of a POU by using the
interfaces ITcPlcImplementation [} 156] or ITcPlcDeclaration [} 155], as the following example shows.

Code snippet (C#):


ITcPlcDeclaration fbPouDecl = (ITcPlcDeclaration) fbPou;
ITcPlcImplementation fbPouImpl = (ITcPlcImplementation) fbPou;
string decl = fbPouDecl.DeclarationText;
string impl = fbPouImpl.ImplementationText;
string implXml = fbPouImpl.ImplementationXml;

Automation Interface Version: 1.3 61


Configuration

Code snippet (Powershell):


$decl = $newFb.DeclarationText
$impl = $newFb.ImplementationText
$implXml = $newFb.ImplementationXml

When comparing both interfaces, you will notice that the accessible properties in both interfaces differ from
each other. For example the ITcPlcImplementation interface offers a property "Language" whereas
ITcPlcDeclaration doesn't. This is because, according to IEC, the declaration area is not based on a real
programming language (e.g. ST), therefore this property does not make sense when used on a declaration
area.

Accessing Sub-POUs (Actions, Properties, ...)

POUs may have more sub-items like Methods, Transitions, Actions and Properties. It is important to
understand that not every sub-item of a POU also has both an implementation and a declaration area.
Actions and Transitions, for example, only have an implementation area. Therefore, casting to one of the
interfaces mentioned above is only valid if the corresponding sub-object has this area. The following table
gives an overview about which areas are available in the different types of POUs.

Tree Item Type Declaration Area Implementation Area


Program POU Yes Yes
Function POU Yes Yes
Function Block POU Yes Yes
Action POU No Yes
Method POU Yes Yes
Property (Get/Set) POU Yes Yes
Transition POU No Yes
Enum DUT Yes No
Struct DUT Yes No
Union DUT Yes No
Alias DUT Yes No
Interface Interface Yes No
Property (Get/Set) Interface Yes Yes
Global variables GVL Yes No

Creating PLC-Objects

The creation of PLC-Objects is simple and can be achieved via the CreateChild() [} 148] method of the
ITcSmTreeItem [} 113] interface. Depending on the type of POU, the parameters of this method need to be
interpreted differently. The following table gives the necessary information to be able to create different POU
types. Please note that the vInfo parameter may be a string array, if more than one parameter is needed.
Each array position and whether it is optional or not, is marked as [...] below.

62 Version: 1.3 Automation Interface


Configuration

Tree Item Type Parameter "nSubType" Parameter "vInfo"


Program POU 602 [0, optional]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: May be used for derivation (keywords
"Extends" or "Implements"). If keywords "Extends" AND
"Implements" should be used, this field specifies the
keyword "Extends".
[2, optional]: Interface or POU name which should be
extended/implemented (mandatory, if [1] is used). If
keywords "Extends" AND "Implements" should be used,
this field specifies the library to extend..
[3, optional]: If keywords "Extends" AND "Implements"
should be used, this field specifies the keyword
"Implements".
[4, optional]: If keywords "Extends" AND "Implements"
should be used, this field specifies the interface used for
derivation.
Function POU 603 [0]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154].
[1]: Return data type of function. May be a PLC data
type, e.g. DINT, BOOL, ...
Function POU 604 [0, optional]: IEC programming language, as definied by
Block IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: May be used for derivation (keywords
"Extends" or "Implements"). If keywords "Extends" AND
"Implements" should be used, this field specifies the
keyword "Extends".
[2, optional]: Interface or POU name which should be
extended/implemented (mandatory, if [1] is used). If
keywords "Extends" AND "Implements" should be used,
this field specifies the library to extend..
[3, optional]: If keywords "Extends" AND "Implements"
should be used, this field specifies the keyword
"Implements".
[4, optional]: If keywords "Extends" AND "Implements"
should be used, this field specifies the interface used for
derivation.
Action POU 608 [0, optional]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: May contain PLCopen XML string with
code for Action
Method POU 609 [0, optional]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: Return data type
[2, optional]: Access modfier, e.g. PUBLIC. By default,
PUBLIC is used.
[3, optional]: May contain PLCopen XML string with
code for Action
Property POU 611 [0]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]
[1]: Return data type
[2, optional]: Access modifier, e.g. PUBLIC. By default,
PUBLIC is used.

Automation Interface Version: 1.3 63


Configuration

Tree Item Type Parameter "nSubType" Parameter "vInfo"


Property Get POU 613 [0, optional]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: Access modifier, e.g. PUBLIC. By default,
PUBLIC is used.
[2, optional]: May contain PLCopen XML string with
code for Action
Property Set POU 614 [0, optional]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: Access modifier, e.g. PUBLIC. By default,
PUBLIC is used.
[2, optional]: May contain PLCopen XML string with
code for Action
Transition POU 616 [0, optional]: IEC programming language, as definied by
IECLANGUAGETYPES [} 154]. By default, ST (Structured
Text) is used.
[1, optional]: May contain PLCopen XML string with
code for Action
Enum DUT 605 [0, optional]: May contain declaration text
Struct DUT 606 [0, optional]: May contain declaration text
Union DUT 607 [0, optional]: May contain declaration text
Alias DUT 623 [0, optional]: May contain declaration text
Interface Interfa 618 [0, optional]: Extending type
ce
Property Interfa 612 [0]: Return data type
ce
Property Get Interfa 654 No vInfo parameter is needed and "null" can be used.
ce
Property Set Interfa 655 No vInfo parameter is needed and "null" can be used.
ce
Method Interfa 610 [0]: Return data type
ce
Global GVL 615 [0, optional]: May contain declaration text
variables
PLC Folder Folder 601 No vInfo parameter is needed and "null" can be used.
Parameter PL 629 [0, optional]: May contain declaration text
List
UML Class POU 631 ---
Diagram

Example: The following code snippet shows how to use the vInfo parameter to create a Functionblock
"FB_Test" with the keywords extends and/or implements, depending on the value of the bool variables
bExtends and bImplements. The extended library is ADSRDSTATE and the implemented interface ITcADI.

Code snippet (C#):


string[] vInfo;
bool bExtends = true;
bool bImplements = true;

if (bExtends && bImplements)


{
  vInfo= new string[5];
}
else
{
  if (bExtends || bImplements)
  {
    vInfo= new string[3];
  }

64 Version: 1.3 Automation Interface


Configuration

  else
  {
    vInfo= new string[1];
  }
}
vInfo[0] = language.AsString();
if (bExtends && bImplements)
{
  vInfo[1] = "Extends";
  vInfo[2] = "ADSRDSTATE";
  vInfo[3] = "Implements";
  vInfo[4] = "ITcADI";
}
else
{
  if (bExtends)
  {
    vInfo[1] = "Extends";
    vInfo[2] = "ADSRDSTATE";
  }
  else
  {
    if (bImplements)
    {
      vInfo[1] = "Implements";
      vInfo[2] = "ITcADI";
    }
  }
}

ITcSmTreeItem newPOU = parent.CreateChild("FB_Test", 604,


"", fbVInfo);

Please note
If the paramerter vInfo includes only one value (marked as [0] in the table above), you shouldn't cre-
ate an array of size 1, instead just use a regular variable. Example: When using nSubType 618 (In-
terface), you should use vInfo as follows.

Code snippet (C#):


ITcSmTreeItem interface1 = pou.CreateChild("NewInterface1", 618, "", null); // no expansion type
ITcSmTreeItem interface2 = pou.CreateChild("NewInterface2", 618, "", "ITcUnknown"); // expands
ITcUnknown interface

PLC access modifier

The following access modifiers are valid and may be used as a vInfo parameter, as shown in the table
above: PUBLIC, PRIVATE, PROTECTED, INTERNAL.

Importing / Exporting PLCopen XML

You can also import/export PLC elements in PLCopen XML, which can be achieved via the ITcPlcIECProject
[} 157] interface. Methods and properties of this interface can only be executed directly on a PLC project
node, for example:

Code snippet (C#):


ITcSmTreeItem plcProject =
systemManager.LookupTreeItem("TIPC^PlcGenerated^PlcGenerated
Project");
ITcPlcIECProject importExport = (ITcPlcIECProject)
plcProject;
importexport.PlcOpenExport(plcOpenExportFile,
"MyPous.POUProgram;MyPous.POUFunctionBlock");
importExport.PlcOpenImport(plcOpenExportFile,
(int)PLCIMPORTOPTIONS.PLCIMPORTOPTIONS_NONE);

Code snippet (Powershell):


$plcProject = $systemManager.LookupTreeItem("TIPC^PlcGenerated^PlcGenerated
Project")
$plcProject.PlcOpenExport(plcOpenExportFile, "MyPous.POUProgram;MyPous.POUFunctionBlock")
$plcProject.PlcOpenImport(plcOpenExportFile,0)

Automation Interface Version: 1.3 65


Configuration

This code snippet assumes that there is already a PLC project added to the TwinCAT configuration, which
will be referenced via the object plcProject. This reference is casted to the object importexport of type
ITcPlcIECProject, which is then used to export the POUs POUProgram and POUFunctionBlock (both reside
in the PLC folder "MyPOUs") into an XML file and then import them again.

The available options for import are: None (0), Rename (1), Replace (2), Skip (3)

Import existing POUs (templates)

PLC templates are available in two units: You can either use the complete PLC project as a whole or each
POU individually as a template. The later is covered in this chapter. One of the reasons a developer may
choose individual POUs as templates, is that it is easier to build a pool of existing functionalities and
encapsulate them in separate POUs, e.g. different function blocks covering different sorting algorithms. Upon
project creation, the developer simply chooses which functionality he needs in his TwinCAT project and
accesses the template tool to retrieve the corresponding POU and import it to his PLC project.

Code snippet (C#):


ITcSmTreeItem plcProject = systemManager.LookupTreeItem("TIPC^PlcGenerated^PlcGenerated Project");
plcProject.CreateChild("NameOfImportedPOU", 58, null, pathToPouFile);
plcProject.CreateChild(null, 58, null, stringArrayWithPathsToPouFiles);

Code snippet (Powershell):


$plcProject = $systemManager.LookupTreeItem(“TIPC^PlcGenerated^PlcGenerated Project")
$plcProject.CreateChild("NameOfImportedPOU", 58, $null, $pathToPouFile)
$plcProject.CreateChild($null, 58, $null, $stringArrayWithPathsToPouFiles)

Please note: A POU template file may not only be a .TcPou file but also the corresponding files for DUTs
and/or GVLs. The example above demonstrates two common ways to import POU template files. The first is
to import a single file, the second to import multiple files at once by storing the file paths to a string array and
using this string array as the vInfo parameter of CreateChild().

4.3.5 I/O

4.3.5.1 Creating and handling EtherCAT devices


This article explains how to build an EtherCAT topology via TwinCAT Automation Interface. It consists of the
following topics:
• General information
• Creating an EtherCAT device
• Creating EtherCAT boxes and insert into topology
• Creating EtherCAT terminals and insert into topology
• Exceptions to the ItemSubType 9099
• Changing the "Previous Port" of an EtherCAT terminal
• Adding EtherCAT slaves to a HotConnect group
• How to add EtherCAT SyncUnits
• Handle EtherCAT junction boxes (CU1128)

All of these topics cover the case of an offline configuration, which means the real addresses of all devices
ar not know at the time of config creation. The last chapter of this article therefore also explains how to
• Activate the configuration

General information

This documentation should give you an overview avout how to create and handle EtherCAT devices and
their corresponding topology via Automation Interface. For an in-depth understanding about how EtherCAT
works and how it is generally integrated in TwinCAT SystemManager/XAE, please consult the EtherCAT

66 Version: 1.3 Automation Interface


Configuration

System Documentation and the corresponding chapter about EtherCAT configuration in TwinCAT. EtherCAT
boxes and terminals, which are connected to an EtherCAT Master, share a common way of creation, which
is explained in a separate article about E-Bus sub types [} 119].

Creating an EtherCAT device

The first step in creating a TwinCAT EtherCAT configuration is to create an EtherCAT device, which may
involve either to create an EtherCAT Master, Slave or Automation Protocol (e.g. to use network variables, as
covered in a separate article [} 72]). To create an EtherCAT Master/Slave, simply make use of the
ITcSmTreeItem [} 148]::CreateChild() [} 148] method with the corresponding parameter for SubType
(EtherCAT Master = 111, EtherCAT Slave = 130).

EtherCAT Master - Code Snippet (C#)


ITcSmTreeItem devices = systemManager.LookupTreeItem("TIID");
ethercatMaster = devices.CreateChild("EtherCAT Master", 111, null, null);

EtherCAT Master - Code Snippet (Powershell)


$devices = $systemManager.LookupTreeItem("TIID")
$ethercatMaster = $devices.CreateChild("EtherCAT Master", 111, $null, $null)

EtherCAT Slave - Code Snippet (C#)


ITcSmTreeItem devices = systemManager.LookupTreeItem("TIID");
ethercatSlave = devices.CreateChild("EtherCAT Slave", 130, null, null);

EtherCAT Slave - Code Snippet (Powershell)


$devices = $systemManager.LookupTreeItem("TIID")
$ethercatSlave = $devices.CreateChild("EtherCAT Slave", 130, $null, $null)

Creating EtherCAT boxes

The second step involves creating EtherCAT boxes, for example an EK1100 EtherCAT Coupler. As the
article about E-Bus SubTypes [} 119] explains, every child item (there a few exceptions - see below) of an
EtherCAT Master uses a common SubType (9099) and will be identified via the Product Revision, which
needs to be used in the vInfo parameter of the ITcSmTreeItem [} 113]::CreateChild() [} 148] method.

Code Snippet (C#)


ITcSmTreeItem ethercatMaster = systemManager.LookupTreeItem("TIID^EtherCAT Master");
ethercatMaster.CreateChild("EK1100", 9099, "", "EK1100-0000-0017");

Code Snippet (Powershell)


$ethercatMaster = $systemManager.LookupTreeItem("TIID^EtherCAT Master")
$ethercatMaster.CreateChild("EK1100", 9099, "", "EK1100-0000-0017")

Automation Interface Version: 1.3 67


Configuration

Please note: In addition to the full product revision, you can also use a "wildcard". If you only specify
"EK1100" as vInfo, Automation Interface will automatically detect and use the newest revision number.
Example:

Code Snippet (C#):


ITcSmTreeItem ethercatMaster = systemManager.LookupTreeItem("TIID^EtherCAT Master");
ethercatMaster.CreateChild("EK1100", 9099, "", "EK1100");

Code Snippet (Powershell):


$ethercatMaster = $systemManager.LookupTreeItem("TIID^EtherCAT Master")
$ethercatMaster.CreateChild("EK1100", 9099, "", "EK1100")

Creating EtherCAT terminals and insert into topology

The creation of EtherCAT terminals is based on the same concepts as EtherCAT boxes. Every terminal also
shares a common SubType and will be identified via the Product Revision, which needs to be used in the
vInfo parameter of the ITcSmTreeItem [} 113]::CreateChild() [} 148] method. The parameter bstrBefore lets
you choose the position on which the terminal should be inserted into the configuration.

Code Snippet (C#):


ITcSmTreeItem ek1100 = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)^EK1100");
ek1100.CreateChild("Term 4 (EL2004)", 9099, "Term 3 (EL2004)", "EL2004-0000-0017");

Code Snippet (Powershell):


$ek1100 = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)^EK1100")
$ek1100.CreateChild("Term 4 (EL2004)", 9099, "Term 3 (EL2004)", "EL2004-0000-0017")

Please note: Should you have trouble using the bstrBefore parameter, please try to insert the terminal on a
"device-level", for example:

Code Snippet (C#):

68 Version: 1.3 Automation Interface


Configuration

ITcSmTreeItem device= systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)");


device.CreateChild("Term 4 (EL2004)", 9099, "Term 3 (EL2004)", "EL2004-0000-0017");

Code Snippet (Powershell):


$device= $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)")
$device.CreateChild("Term 4 (EL2004)", 9099, "Term 3 (EL2004)", "EL2004-0000-0017")

The new terminal will then be inserted before "Term 3 (EL2004)" under the last inserted EtherCAT box.

Please note: In addition to the full product revision, you can also use a "wildcard". If you only specify
"EL2004" as vInfo, Automation Interface will automatically detect and use the newest revision number.
Example:

Code Snippet (C#):


ITcSmTreeItem ek1100 = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)^EK1100");
ek1100.CreateChild("Term 4 (EL2004)", 9099, "Term 3 (EL2004)", "EL2004");

Code Snippet (Powershell):


$ek1100 = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT)^EK1100")
$ek1100.CreateChild("Term 4 (EL2004)", 9099, "Term 3 (EL2004)", "EL2004")

Exceptions to the ItemSubType 9099

There are a few exceptions to the ItemSubType 9099, e.g. the RS232 terminals EP6002 (ItemSubType
9101) and EL600X (ItemSubType 9101). The following table gives an overview about all exceptions and their
corresponding ItemSubType.

I/O ItemSubType
EP6002 9101
EL6001 9101
EL6002 9101
EP6001-0002 9101
EP6002-0002 9101
EL6021 9103
EL6022 9103
EL6021-0021 9103
BK1120 9081
ILXB11 9086
EL6731 9093
EL6751 9094
EL6752 9095
EL6731-0010 9096
EL6751-0010 9097
EL6752-0010 9098
EL6601 9100
EL6720 9104
EL6631 9106
EL6631-0010 9107
EL6632 9108
EL6652-0010 9109
EL6652 9110

Changing the "Previous Port" of an EtherCAT terminal

The Previous Port of an EtherCAT terminal determines the position of the terminal inside the EtherCAT
topology.

Automation Interface Version: 1.3 69


Configuration

In TwinCAT XAE, the DropDown box automatically includes all available previous ports. To configure this
setting via Automation Interface, you can make use of the ITcSmTreeItem [} 113]::ProduceXml() [} 146] and
ITcSmTreeItem [} 113]::ConsumeXml() [} 147] methods to modify the XML description [} 25] of the
corresponding EtherCAT terminal. This XML description therefore includes one or more XML nodes
<PreviousPort>, where its attribute "Selected=1" determines, which previous port has been currently
selected. Each previous port device is identified by its physical address.

Example (XML description)


<TreeItem>
...
<EtherCAT>
        ...
     <Slave>
         ...
         <PreviousPort Selected="1">
                 <Port>B</Port>
                 <PhysAddr>1045</PhysAddr>
         </PreviousPort>
         <PreviousPort>
             <Port>B</Port>
                 <PhysAddr>1023</PhysAddr>
         </PreviousPort>
         ...
     </Slave>
         ...
<EtherCAT>
...
</TreeItem>

If you want to change the Previous port you need to know the <PhysAddr> of the desired device, which can
also be determined via its XML description.

Adding EtherCAT slaves to a HotConnect group

EtherCAT HotConnect allows pre-configured sections to be removed from or added to the data traffic before
the start or during operation of the system. For more information about EtherCAT HotConnect please read
our EtherCAT System documentation.

In TwinCAT XAE, an EtherCAT slave can be added to a HotConnect group by clicking the corresponding
option in the context menu of the device.

70 Version: 1.3 Automation Interface


Configuration

In TwinCAT Automation Interface, the same can be achieved by consuming the following XML structure on
the EtherCAT slave:

Example (XML description):


<TreeItem>
<EtherCAT>
<Slave>
<HotConnect>
    <GroupName>Term 1 (EK1101)</GroupName>
    <GroupMemberCnt>4</GroupMemberCnt>
    <IdentifyCmd>
     <Comment>HotConnect-Identität lesen</Comment>
     <Requires>cycle</Requires>
     <Cmd>1</Cmd>
     <Adp>0</Adp>
     <Ado>4096</Ado>
     <DataLength>2</DataLength>
     <Cnt>1</Cnt>
     <Retries>3</Retries>
     <Validate>
     <Data>0000</Data>
     <Timeout>5000</Timeout>
     </Validate>
    </IdentifyCmd>
</HotConnect>
</Slave>
</EtherCAT>
</TreeItem>

Please note:
• The <GroupMemberCnt> tag needs to specify the exact amount of terminals plus the device itself

How to set EtherCAT Sync Units

EtherCAT SyncUnits can be set via ITcSmTreeItem::ConsumeXml() and by using the following XML
description.

Example (XML description):


<TreeItem>
  <EtherCAT>
    <Slave>
      <SyncUnits>
        <SyncUnit>SyncUnit1</SyncUnit>
      </SyncUnits>
    </Slave>
  </EtherCAT>
</TreeItem>

Handle EtherCAT junction boxes (CU1128)

EtherCAT junction boxes can be handled similar to all other tree items. The following sample code shows
how to add a CU1128 box and then add two EK1100 boxes below:

Code Snippet (C#)


ITcSmTreeItem cu1128 = ethercatMaster.CreateChild("CU1128", 9099, null, "CU1128");
ITcSmTreeItem cu1128_devA = cu1128.get_Child(1);
ITcSmTreeItem cu1128_devB = cu1128.get_Child(2);
ITcSmTreeItem ek1100_1 = cu1128_devA.CreateChild("EK1100-1", 9099, null, "EK1100");
ITcSmTreeItem ek1100_2 = cu1128_devB.CreateChild("EK1100-2", 9099, null, "EK1100");

Code Snippet (Powershell)


$cu1128 = $ethercatMaster.CreateChild("CU1128", 9099, $null, "CU1128")
$cu1128_devA = $cu1128.get_Child(1)
$cu1128_devB = $cu1128.get_Child(2)
$ek1100_1 = $cu1128_devA.CreateChild("EK1100-1", 9099, $null, "EK1100")
$ek1100_2 = $cu1128_devB.CreateChild("EK1100-2", 9099, $null, "EK1100")

Automation Interface Version: 1.3 71


Configuration

Activate the EtherCAT configuration

To activate a created TwinCAT configuration via Automation Interface, the ITcSysManager


[} 104]::ActivateConfiguration() [} 107] method may be used. However, the previous chapters only explained
how to create an offline configuration, which means that every device created does not have real addresses,
e.g. the EtherCAT Master has not been linked to a physical network interface card yet. Before activating the
configuration you therefore need to configure each device with online addresses. To determine the real
addresses, you can run a ScanDevices on the online system, determine the real addresses via the XML
description (ITcSmTreeItem [} 113]::ProduceXml() [} 146]) and then import the address information via
ITcSmTreeItem [} 113]::ConsumeXml() [} 147] into the created (offline) configuration. There are two HowTo
samples which help you exactly with this kind of configuration:
• Scan Devices [} 87] via Automation Interface

4.3.5.2 Creating and handling network variables


This chapter explains in-depth how to create and handle network variables. The following list shows all
chapters in this article:
• General information about network variables
• Creating an EtherCAT Automation Protocol device
• Creating a Publisher box
• Creating a Subscriber box
• Setting parameters for a Publisher/Subscriber box
• Creating Publisher variables
• Creating Subscriber variables
• Linking Publisher/Subscriber variables
• Reading Publisher/Subscriber variable IDs

Please note that the Scripting Container [} 171] contains a detailed sample about how to create and
configure network variables with the Automation Interface.

General information about network variables

Network variables may be used to send data between two TwinCAT devices via an IP-based network. One
device declares variables as a "Publisher" (sender) and the other device receives variable values as a
"Subscriber". Therefore we also speak in terms of Publisher/Subscriber variables. TwinCAT provides you
with the flexibility to configure network variables directly in a TwinCAT project so that you may map them to
your PLC or I/O.

72 Version: 1.3 Automation Interface


Configuration

Network variables use the EtherCAT Automation Protocol device to communicate via the local network.
Therefore, you need to add this device before you can configure a Publisher and/or Subscriber box together
with the corresponding variables.

More information about network variables and how they can be configured in TwinCAT may be found here.

Creating an EtherCAT Automation Protocol device

To create the EtherCAT Automation Protocol device, the method ITcSmTreeItem [} 113]::CreateChild()
[} 148] may be used together with the corresponding SubType of this device (112).

Code Snippet (C#):


ITcSmTreeItem devicesNode = systemManager.LookupTreeItem("TIID");
device = devicesNode.CreateChild("Device 1 (EtherCAT Automation Protocol)", 112, null, null);

Code Snippet (Powershell):


$devicesNode = $systemManager.LookupTreeItem("TIID")
$device = $devicesNode.CreateChild("Device 1 (EtherCAT Automation Protocol)", 112, $null, $null)

Creating a Publisher box

The Publisher box is the container for Publisher variables, which defines for example which type of
communication pattern should be used (Unicast, Multicast, Broadcast) for the variables contained within. To
add a Publisher box, simply use the ITcSmTreeItem [} 113]::CreateChild() [} 148] method again together with
the corresponding SubType (9051).

Code Snippet (C#):


ITcSmTreeItem eapDevice = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation
Protocol)");
pubBox = eapDevice.CreateChild("Box 1 (Publisher)", 9051, null, null);

Code Snippet (Powershell):


$eapDevice = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation Protocol)")
$pubBox = $eapDevice.CreateChild("Box 1 (Publisher)", 9051, $null, $null)

Automation Interface Version: 1.3 73


Configuration

This small code snippet adds a Publisher box to the EtherCAT Automation Protocol device created earlier.
To configure the communication pattern of this box, you need to customize its settings via the ITcSmTreeItem
[} 113]::ConsumeXml() [} 147], method. This is shown in more detail in the EtherCAT Automation Protocol
sample of the Scripting Container [} 171] or later on this page.

Creating a Subscriber box

The Subscriber box is the container for Subscriber variables, which defines for example which type of
communication pattern should be used (Unicast, Multicast, Broadcast) for the variables contained within. To
add a Publisher box, simply use the ITcSmTreeItem [} 113]::CreateChild() [} 148] method again together with
the corresponding SubType (9052).

Code Snippet (C#):


ITcSmTreeItem eapDevice = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation
Protocol)");
subBox = eapDevice.CreateChild("Box 1 (Subscriber)", 9052, null, null);

Code Snippet (Powershell):


$eapDevice = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation Protocol)")
$subBox = $eapDevice.CreateChild("Box 1 (Subscriber)", 9052, $null, $null)

This small code snippet adds a Subscriber box to the EtherCAT Automation Protocol device created earlier.
To configure the communication pattern of this box, you need to customize its settings via the ITcSmTreeItem
[} 113]::ConsumeXml() [} 147], method. This is shown in more detail in the EtherCAT Automation Protocol
sample of the Scripting Container [} 171] or later on this page.

Creating Publisher variables

After you have successfully added a Publisher box, you can add Publisher variables to this box by making
use of the ITcSmTreeItem [} 113]::CreateChild() [} 148] method together with the needed parameters for
SubType (0) and vInfo, which specifies the data type of the Publisher variable, e.g. "BOOL".

Code Snippet (C#):


ITcSmTreeItem pubBox = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation
Protocol)^Box 1 (Publisher)");
pubVar = pubBox.CreateChild("MAIN.bTestVar", 0, null, "BOOL");

Code Snippet (Powershell):


$pubBox = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation Protocol)^Box 1
(Publisher)")
$pubVar = $pubBox.CreateChild("MAIN.bTestVar", 0, $null, "BOOL")

Please see the Scripting Container [} 171] sample "EtherCAT Automation Protocol" for more information.

Setting parameters for a Publisher/Subscriber box

There are two communication patterns which need to be configured on a Publisher and/or Subscriber box:
RT-Ethernet or UDP/IP . The following screenshot shows the corresponding configuration tab from
TwinCAT XAE.

74 Version: 1.3 Automation Interface


Configuration

More detailed information about these options can be found here.

To configure the box for RT-Ethernet , you need to make use of the ITcSmTreeItem [} 113]::ConsumeXml()
[} 147] method to import the following XML structure:
<TreeItem>
<BoxDef>
<FieldbusAddress>1</FieldbusAddress>
<AmsAddress>
<AmsPort>0</AmsPort>
<AmsPortTimeout>5</AmsPortTimeout>
</AmsAddress>
<NvPubDef>
<Udp Enabled="false"/>
     <MacAddress>00 00 00 00 00 00</MacAddress>
<IoDiv>
    <Divider>1</Divider>
    <Modulo>0</Modulo>
</IoDiv>
<VLAN>
    <Enable>false</Enable>
    <Id>0</Id>
    <Prio>0</Prio>
</VLAN>
<ArpInterval>1000</ArpInterval>
<DisableSubscriberMonitoring>false</DisableSubscriberMonitoring>
<TargetChangeable>false</TargetChangeable>
</NvPubDef>
</BoxDef>
</TreeItem>

The following table shows how the bold marked nodes need to be adapted according to the desired
communication pattern.

RT-Ethernet Communication pat- <PublisherNetId> <MacAddress>


tern
Broadcast 0.0.0.0.0.0 FF FF FF FF FF FF
Multicast 0.0.0.0.0.0 Needs to contain a Multicast MAC
Address, please refer here for
more information.
Unicast - MAC Address 0.0.0.0.0.0 Needs to contain a Unicast MAC
Address, please refer here for
more information.
Unicast - AmsNetId Contains AmsNetId of target 00 00 00 00 00 00
computer.

Import the following XML structure if you want to use UDP/IP:

Automation Interface Version: 1.3 75


Configuration

<TreeItem>
<BoxDef>
<FieldbusAddress>1</FieldbusAddress>
<AmsAddress>
<AmsPort>0</AmsPort>
<AmsPortTimeout>5</AmsPortTimeout>
</AmsAddress>
<NvPubDef>
<Udp Enabled="true">
    <Address>0.0.0.0</Address>
    <Gateway>0.0.0.0</Gateway>
</Udp>
<IoDiv>
    <Divider>1</Divider>
    <Modulo>0</Modulo>
</IoDiv>
<VLAN>
    <Enable>false</Enable>
    <Id>0</Id>
    <Prio>0</Prio>
</VLAN>
<ArpInterval>1000</ArpInterval>
<DisableSubscriberMonitoring>false</DisableSubscriberMonitoring>
<TargetChangeable>false</TargetChangeable>
</NvPubDef>
</BoxDef>
</TreeItem>

The following table shows how the bold marked nodes need to be adapted according to the desired
communication pattern. On the node <Udp>, the attribute "Enabled" needs to be set to "true".

RT-Ethernet Communication pat- <Address> <Gateway>


tern
Broadcast 255.255.255.255 0.0.0.0
Multicast Needs to contain a Multicast IP May contain a default gateway
address. Please refer here for where the packets should be send
more information. to for routing. Otherwise you may
leave it at 0.0.0.0
Unicast Needs to contain an (Unicast) IP May contain a default gateway
address. Please refer here for where the packets should be send
more information. to for routing. Otherwise you may
leave it at 0.0.0.0

Creating Subscriber variables

After you have successfully added a Publisher box, you can add Publisher variables to this box by making
use of the ITcSmTreeItem [} 113]::CreateChild() [} 148] method together with the needed parameters for
SubType (0) and vInfo, which specifies the data type of the Publisher variable, e.g. "BOOL".

Code Snippet (C#):


ITcSmTreeItem subBox = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation
Protocol)^Box 1 (Subscriber)");
subVar = pubBox.CreateChild("MAIN.bTestVar", 0, null, "BOOL");

Code Snippet (Powershell):


$subBox = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation Protocol)^Box 1
(Subscriber)")
$subVar = $pubBox.CreateChild("MAIN.bTestVar", 0, $null, "BOOL")

Please see the Scripting Container [} 171] sample "EtherCAT Automation Protocol" for more information.

Linking Publisher/Subscriber variables

To link Publisher/Subscriber variables to PLC variables, simply use the ITcSysManager


[} 104]::Linkvariables() [} 108] method.

Code Snippet (C#):

76 Version: 1.3 Automation Interface


Configuration

systemManager.LinkVariales("TIPC^PLC Project^PLC Project Instance^PlcTask Outputs^MAIN.bTestVar",


"TIID^Device 1 (EtherCAT Automation Protocol)^Box 1 (Publisher)^MAIN.bTestVar^Outputs^VarData");

Code Snippet (Powershell):


$systemManager.LinkVariales("TIPC^PLC Project^PLC Project Instance^PlcTask Outputs^MAIN.bTestVar",
"TIID^Device 1 (EtherCAT Automation Protocol)^Box 1 (Publisher)^MAIN.bTestVar^Outputs^VarData")

Please see the Scripting Container [} 171] sample "EtherCAT Automation Protocol" for more information.

Reading Publisher/Subscriber variable IDs

The following code snippet reads all variable IDs from a Publisher box and stores them in the List-Array "ids".
This may also be used for Subscriber variables.

Code Snippet (C#):


List<uint> ids = new List<uint>();
ITcSmTreeItem pubBox = systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation
Protocol)^Box 1 (Publisher)");
foreach(ITcSmTreeItem var in pubBox)
{
if (var.ItemType == 35) // 35 = publisher variable, 36 = subscriber variable
{
string varStr = var.ProduceXml();
XmlDocument varXml = new XmlDocument();
varXml.LoadXml(varStr);
XmlNode id = varXml.SelectSingleNode("//TreeItem/NvPubVarDef/NvId");
ids.Add(Convert.ToUInt32(id.InnerXml));
}
}

Code Snippet (Powershell):


$ids = New-Object System.Collections.ArrayList
$pubBox = $systemManager.LookupTreeItem("TIID^Device 1 (EtherCAT Automation Protocol)^Box 1
(Publisher)")
foreach($var in $pubBox)
{
  if($var.ItemType –eq 35)
  {
    $varXml = [Xml]$var.ProduceXml()
    $id = $varXml.TreeItem.NvPubVarDef.NvId
    $ids.Add($id)
  }
}

4.3.5.3 Creating and handling Profinet devices


This article explains how to create and handle Profinet I/O devices via TwinCAT Automation Interface. The
following topics are being discussed:
• Creating Profinet devices
• Adding Profinet boxes
• Adding Profinet modules
• Adding Profinet Sub-Modules

Creating Profinet devices

To create Profinet I/O devices (Controller/Device), the ITcSmTreeItem::CreateChild() method can be used.
The Sub Type sets the actual type that should be added.

Automation Interface Version: 1.3 77


Configuration

Name Sub Type


Profinet Controller (RT) 113
Profinet Controller CCAT (RT) 140
Profinet Controller EL6631 (RT, EtherCAT) 119
Profinet Controller EL6632 (RT + IRT, EtherCAT) 126
Profinet Device (RT) 115
Profinet Device CCAT (RT) 142
Profinet Device CCAT (RT + IRT) 143
Profinet Device EL6631 (RT, EtherCAT) 118

Code Snippet (C#):


ITcSmTreeItem io = sysManager.LookupTreeItem("TIID");
ITcSmTreeItem profinetController = io.CreateChild("Profinet Controller", 113, null, null);

Code Snippet (Powershell):


$io = $sysManager.LookupTreeItem("TIID")
$profinetController = $io.CreateChild("Profinet Controller", 113, $null, $null)

Adding Profinet boxes

To create boxes below a Profinet device, the ITcSmTreeItem::CreateChild() may be used. The Sub Type
depends on the box that should be added. The following table gives an overview about possible values:

Name Sub Type


BK9102 9125
EK9300 9128
EL6631 9130

In addition some knowledge about the corresponding Profinet GSD file is required to use the vInfo parameter
properly. The vInfo parameter is composed of the following syntax:
PathToGSDfile#ModuleIdentNumber#BoxFlags#DAPNumber

The ModuleIdentNumber can be determined from within the GSD file, e.g. via the XML structure
<ProfileBody><ApplicationProcess><DeviceAccessPointList><DeviceAccessPointItem
ModuleIdentNumber>. The ModuleIdentNumber is usually unique. If not, the DAPNumber specifies the
position in the DeviceAccessPointList.

The following BoxFlags are currently interpreted:

Name Value Description


GENERATE_NAME_FROM_PAB 0x0004 Profinet name will be generated via process image
GET_STATIONNAME 0x0400 Profinet name from TC config will be used (tree item name)
SET_NOT_IP_TO_OS 0x4000 CE-only: Profinet IP will not be registered in OS

Code Snippet (C#):


ITcSmTreeItem profinetEL6631 = profinetController.CreateChild("EL6631", 9130, null, "C:\\TwinCAT\
\3.1\\Config\\Io\\Profinet\\GSDML-V2.31-beckhoff-EL6631-20140508.xml#0x3");

Code Snippet (Powershell):


$profinetEL6631 = $profinetController.CreateChild("EL6631", 9130, $null, "C:\\TwinCAT\\3.1\\Config\
\Io\\Profinet\\GSDML-V2.31-beckhoff-EL6631-20140508.xml#0x3")

Adding Profinet modules

Profinet modules are created below the API node of a Profinet box. The API node is automatically created
when adding a Profinet box to the TwinCAT configuration. To add Profinet modules the
ITcSmTreeItem::CreateChild() method may be used. The SubType determines the position of the module
within the <ProfileBody><ApplicationProcess><ModuleList> XML structure of the corresponding GSD file.

Code Snippet (C#):

78 Version: 1.3 Automation Interface


Configuration

ITcSmTreeItem profinetEL6631api = profinetEL6631.get_Child(1);


ITcSmTreeItem profinetModule1 = profinetEL6631api.CreateChild("", 30, null, null); // SubType 30 =
200 Byte In-Out
ITcSmTreeItem profinetModule2 = profinetEL6631api.CreateChild("", 12, null, null); // SubType 12 = 8
Byte In-Out
ITcSmTreeItem profinetModule3 = profinetEL6631api.CreateChild("", 8, null, null); // SubType 8 = 4
Byte Out

Code Snippet (Powershell):


$profinetEL6631api = $profinetEL6631.get_Child(1)
$profinetModule1 = $profinetEL6631api.CreateChild("", 30, $null, $null)
$profinetModule2 = $profinetEL6631api.CreateChild("", 12, $null, $null)
$profinetModule3 = $profinetEL6631api.CreateChild("", 8, $null, $null)

Adding Profinet Sub-Modules

Profinet Sub-Modules can be added below a so-called Profinet Modular Module. The handling is very similar
to when adding regular Profinet modules. The Sub Type determines the position of the Sub-Module within
the <ProfileBody><ApplicationProcess><ModuleList> XML structure of the corresponding GSD file.

Code Snippet (C#):


ITcSmTreeItem profinetModularModule = profinetEL6631api.CreateChild("", 98, null, null); // SubType
98 = Modular
ITcSmTreeItem modularModule1 = profinetModularModule.CreateChild("", 12, null, null); // SubType 12
= 8 Byte In-Out
ITcSmTreeItem modularModule2 = profinetModularModule.CreateChild("", 14, null, null); // SubType 14
= 16 Byte Out
ITcSmTreeItem modularModule3 = profinetModularModule.CreateChild("", 31, null, null); // SubType 31
= 8 Word In

Code Snippet (Powershell):


$profinetModularModule = $profinetEL6631api.CreateChild("", 98, $null, $null)
$modularModule1 = $profinetModularModule.CreateChild("", 12, $null, $null)
$modularModule2 = $profinetModularModule.CreateChild("", 14, $null, $null)
$modularModule3 = $profinetModularModule.CreateChild("", 31, $null, $null)

4.3.5.4 Creating and handling Profibus devices


This article explains how to create and handle Profibus Master and Slave devices via TwinCAT Automation
Interface. It consists of following main points:
• Creating and adding a Profibus Master
• Searching appropriate device (EL6731, FC310x, etc.) and configuring
• Creating and adding a Profibus Slave
• Searching appropriate Slave device (EL6731-0010, etc.) and configuring
• Changing fieldbus address

Creating and adding a Profibus Master


1. To create a Profibus Master device, open a new or an existing TwinCAT configuration

Automation Interface Version: 1.3 79


Configuration

2. Scan all the devices. (These actions can also be performed via Automation Interface.)

3. Create a system manager object and navigate to devices

Code Snippet (C#):


project = solution.Projects.Item(1);
sysman = (ItcSysManager)project.Object;
ITcSmTreeItem io = (ITcSmTreeItem)sysman.LookupTreeItem("TIID");

Code Snippet (Powershell):


$project = $sln.Projects.Items(1)
$sysman = $project.Object
$io = $sysman.LookupTreeItem("TIID")

To add a Profibus master, use ITcSmTreeItem:CreateChild method.

Code Snippet (C#):


ITcSmTreeItem5 profi_master = (ITcSmTreeItem5)io.CreateChild("Device 2 (EL6731)", 86, "", null);

Code Snippet (Powershell):


$profi_master = $io.CreateChild("Device 2 (EL6731) ", "86", "", $null)

For other Profibus Masters, enter the correct ItemSubtype listed here. This will add the new device as shown
in the screenshot:

80 Version: 1.3 Automation Interface


Configuration

Searching and claiming a Profibus Master device from the list:

It is necessary to configure the newly added Profibus master, which is usually done in TwinCAT by pressing
the search button and selecting the correct device from the list:

This can be done via Automation Interface:

Code Snippet (C#):


string availableMaster = profi_master.ResourcesCount;
profi_master.ClaimResources(1);

Code Snippet (Powershell):


$availableMaster = $profi_master.ResourcesCount
$profi_master.ClaimResources(1)

The ITcSmTreeItem5:ResourcesCount gives out the number of compatible Profibus master devices, and the
ITcSmTreeItem5:ClaimResources takes the index of the CANOpen device to be configured as the master.

Creating and adding a Profibus slave

A Profibus slave can be added to the current configuration as shown below:

Code Snippet (C#):


ITcSmTreeItem5 profi_slave = (ITcSmTreeItem5)io.CreateChild("Device 3 (EL6731-0010)", 97, null);

Code Snippet (Powershell):


$profi_slave = $io.CreateChild("Device 3 (EL6731-0010)", "97", "", $null)

Searching and claiming a Profibus slave

Similar to Profibus master, number of Profibus slaves can be published by following code:

Code Snippet (C#):


string availableSlaves = profi_slave.ResourcesCount;
profi_slave.ClaimResource(1);

Code Snippet (Powershell):

Automation Interface Version: 1.3 81


Configuration

$availableSlaves = $profi_slave.ResourcesCount
$profi_slave.ClaimResources(1)

The last line in code claims the EL6731-0010 as the Profibus slave, similar to the dialog box that appears in
TwinCAT user interface.

Fig. 2:

Changing fieldbus address

To change the the fieldbus address (station no.) of a profibus box in a configuration, an instance of the
TwinCAT System Manager has to be created and the configuration has to be opened. The LookupTreeItem
[} 110] method of the ITcSysManager [} 104] interface returns a ITcSmTreeItem [} 113] interface pointer
implemented by the tree item referenced by its pathname [} 9]. This interface contains a ConsumeXml
[} 147] method of the tree item.

Procedure

The Procedure to create the ITcSysManager [} 104] interface (the 'sysMan' instance here) is described in the
chapter Accessing TwinCAT Configurations. [} 19] This interface has a LookupTreeItem [} 110] method that
returns a ITcSmTreeItem [} 113] pointer to a specific tree item given by its pathname [} 9]. To change the the
fieldbus address (station no.) of a profibus box "TIID^Device 1 (FC310x)^Box 1 (BK3100)" to 44 the following
code can be used:

Code Snippet (C#):


ItcSmTreeItem item = sysMan.LookupTreeItem("TIID^Device 1 (FC310x)^Box 1 (BK3100)");
item.ConsumeXml("44");

Code Snippet (PowerShell):


$item = $sysMan.LookupTreeItem("TIID^Device 1 (FC310x)^Box 1 (BK3100)")
$item.ConsumeXml("44")

4.3.5.5 Creating and handling CANOpen devices


This article explains how to create and handle CANOpen Master and Slave devices via TwinCAT Automation
Interface. It consists of following main points:
• Creating and adding a CANOpen Master
• Searching appropriate devices (EL6751, FC510x, etc.) and configuring
• Creating and adding CANOpen Slave
• Searching appropriate devices (EL6751-0010, etc.) and configuring
• Importing DBC files via Automation Interface

Creating and adding a CANOpen Master

82 Version: 1.3 Automation Interface


Configuration

To create a CANOpen Master device, open a new or an existing TwinCAT configuration, scan all the
devices. Note that these actions can also be performed via Automation Interfaces

Create a system manager object, and navigate to devices.

Code Snippet (C#):


project = solution.Projects.Item(1);
sysman = (ITcSysManager)project.Object;
ITcSmTreeItem io = (ITcSmTreeItem)sysman.LookupTreeItem("TIID");

Code Snippet (Powershell):


$project = $sln.Projects.Items(1)
$sysman = $project.Object
$io = $sysman.LookupTreeItem("TIID")

To add a CANOpen Master, use ITcSmTreeItem:CreateChild method:

Code Snippet (C#):


ITcSmTreeItem5 can_master = (ITcSmTreeItem5)io.CreateChild("Device 2 (EL6751)", 87, "", null);

Code Snippet (Powershell):


$can_master = $io.CreateChild("Device 2 (EL6751)", "87", "", $null)

For other CANOpen master devices, enter the correct ItemSubtype listed here [} 121]. This will add the new
device as shown in the screenshot:

Automation Interface Version: 1.3 83


Configuration

Fig. 3: CANOpen Master added

Searching and claiming a CANOpen Master device from the list:

It is necessary to configure the newly added CANOpen master, which is usually done in TwinCAT by
pressing the search button and selecting the correct device from the list:

Fig. 4: CANOpen Master via Search button

This can be done via Automation Interface:

Code Snippet (C#):


String availableMaster = profi_master.ResourceCount;
can_master.ClaimResources(1);

84 Version: 1.3 Automation Interface


Configuration

Code Snippet (Powershell):


$availableMaster = $can_master.ResourceCount
$can_master.ClaimResources(1)

The ITcSmTreeItem5:ResourceCount gives out the number of compatible CANOpen master devices and the
ITcSmTreeItem5:ClaimResources takes the index of the CANOpen device to be configured as the master.

Creating and adding a CANOpen Slave

A CANOpen slave can be added to the current configuration as shown below:

Code Snippet (C#):


ITcSmTreeItem5 can_slave = (ITcSmTreeItem5)io.CreateChild("Device 3 (EL6751-0010)", "98", null);

Code Snippet (Powershell):


$can_slave = $io.CreateChild("Device 3 (EL6751-0010)", "98", $null)

Searching and claiming a CANOpen slave

Similar to CANOpen Master, a list of CANOpen slaves can be published by following code:

Code Snippet (C#) :


string availableSlaves = can_slave.ResourceCount;
can_slave.Claimresources(1);

Code Snippet (Powershell) :


$availableSlaves = $can_slave.ResourceCount
$can_slave.Claimresources(1)

The last line of code, claims the EL6751-0010 as the CANOpen slave, similar to the dialog box that appears
in TwinCAT user interface.

Fig. 5: CANOpen claim resources via dialog box

Importing DBC files via Automation Interface

Required Version: TwinCAT 3.1 Build 4018 or above

TwinCAT offers DBC file to be imported via dialog box as seen in the screenshot. On right clicking a
CANOpen Master e.g. EL6751 and selecting “Import dbc-file”, a dialog box prompts user to browse the DBC
file. Upon clicking okay, a CANOpen configuration is loaded automatically.

Automation Interface Version: 1.3 85


Configuration

Fig. 6: CANOpen DBC file importing

Automation Interface also supports DBC file import. To do this, navigate to the CANOpen Master tree item
and export the Xml file via ITcSmTreeItem:ProduceXml(). In the Xml file, add the path to the DBC file
to be imported along with the additional properties that are part of the dialog box shown above.
<DeviceDef>
<AmsPort>28673</AmsPort>
<AmsNetId>172.17.251.109.2.1</AmsNetId>
<AddressInfo>
<Ecat>
<EtherCATDeviceId>0</EtherCATDeviceId>
</Ecat>
</AddressInfo>
<MaxBoxes>126</MaxBoxes>
<ScanBoxes>false</ScanBoxes>
<CanOpenMaster>
<ImportDbcFile>
<FileName>c:\dbc_file_folder\dbc_file_to_be_imported.dbc</FileName>
<ImportExtendedMessages>false</ImportExtendedMessages>
<ImportMultiplexedDataMessages>false</ImportMultiplexedDataMessages>
<KeepUnchangedMessages>true</KeepUnchangedMessages>
<ExtBoxesSupport>false</ExtBoxesSupport>
<VectorXXXSupport>false</VectorXXXSupport>
<CommunicateWithSlavesFromDbcFile>true</CommunicateWithSlavesFromDbcFile>
</ImportDbcFile>
</CanOpenMaster>
<Fcxxxx>
<CalculateEquiTimes>0</CalculateEquiTimes>
<NodeId>127</NodeId>
<Baudrate>500 k</Baudrate>
<DisableNodeStateModification>false</DisableNodeStateModification>
</Fcxxxx>
</DeviceDef>

Import the modified Xml file back into the TwinCAT configuration via ITcSmTreeImte:ConsumeXml(). The
configuration will now be loaded below the CANOpen Master.

86 Version: 1.3 Automation Interface


Configuration

4.3.5.6 Creating and handling Devicenet devices


Just like any other I/O component, Devicenet devices may be added via the TwinCAT Automation Interface
by using the CreateChild() method of the ITcSmTreeItem interface. The SubType specifies the device that
should be added.

Code Snippet (C#):


ITcSmTreeItem io = sysManager.LookupTreeItem("TIID");
ITcSmTreeItem devicenet1 = io.CreateChild("Device 1 (EL6752)", 88, null, null);
ITcSmTreeItem devicenet2 = io.CreateChild("Device 2 (EL6752-0010)", 99, null, null);

Code Snippet (Powershell):


$io = $sysManager.LookupTreeItem("TIID")
$devicenet1 = $io.CreateChild("Device 1 (EL6752)", 88, $null, $null)
$devicenet2 = $io.CreateChild("Device 2 (EL6752-0010)", 99, $null, $null)

The following table gives an overview about all Devicenet I/O devices and their corresponding SubTypes. If a
device should be missing, you can always find out the SubType yourself by following our documentation
article about the XML description of a tree item [} 25].

Device SubType
Devicenet Master FC52xx PCI 41
Devicenet Master EL6752 EtherCAT 88
Devicenet Slave FC52xx PCI 62
Devicenet Slave EL6752 EtherCAT 99
Devicenet Master CX1500-M520 PC104 73
Devicenet Slave CX1500-B520-PC104 74
Devicenet Monitor FC52xx PCI 59

Devicenet boxes can also be attached via CreateChild(). The SubType specifies the box that should be
added.

Code Snippet (C#):


ITcSmTreeItem devicenet1box = devicenet1.CreateChild("Box 2 (EL6752-0010)", 5203, null, null);

Code Snippet (Powershell):


$devicenet1box = $devicenet1.CreateChild("Box 2 (EL6752-0010)", 5203, $null, $null)

To add variables to a Devicenet box, simply use the following code snippet. The vInfo parameter specifies
the data type of the variable.

Code Snippet (C#):


ITcSmTreeItem inputVars = devicenet1box.LookupChild("Inputs");
inputVars.CreateChild("TestVarInt", 0, null, "INT");
inputVars.CreateChild("TestVarBool", 0, null, "BOOL");

Code Snippet (Powershell):


$inputVars = $devicenet1box.LookupChild("Inputs")
$inputVars.CreateChild("TestVarInt", 0, $null, "INT")
$inputVars.CreateChild("TestVarBool", 0, $null, "BOOL")

4.3.5.7 Scanning for devices and boxes


When creating a new configuration it is often necessary to align the TwinCAT XAE configuration to the
actually available hardware. One option to fullfill this is to start a new TwinCAT XAE configuration from
scratch and process the following steps:
• Creation of a new TwinCAT XAE configuration
• Setting the address of the target system
• Scan of the available devices
• Addition and parametrization of the devices to be used

Automation Interface Version: 1.3 87


Configuration

• Scanning and insertion of boxes for each device

Procedure

The procedure to create the ITcSysManager [} 104] interface (the 'systemManager' instance here) is
described in the chapter Accessing TwinCAT Configurations. [} 19] This interface has a LookupTreeItem
[} 110] method that returns a ITcSmTreeItem [} 113] pointer to a specific tree item given by its pathname
[} 9], in this case the shortcut "TIID" which references the I/O devices node.

Code snippet (C#):


ITcSysManager3 systemManager = null;

public void ScanDevicesAndBoxes()


{     
  systemManager.SetTargetNetId("1.2.3.4.5.6");
  ITcSmTreeItem ioDevicesItem = systemManager.LookupTreeItem("TIID");
  string scannedXml = ioDevicesItem.ProduceXml(false);
  XmlDocument xmlDoc = newXmlDocument();     
  xmlDoc.LoadXml(scannedXml);
  XmlNodeList xmlDeviceList = xmlDoc.SelectNodes("TreeItem/DeviceGrpDef/FoundDevices/Device");     
  List<ITcSmTreeItem> devices = newList<ITcSmTreeItem>();
  int deviceCount = 0;
  foreach (XmlNode node in xmlDeviceList)     
  {
    int itemSubType = int.Parse(node.SelectSingleNode("ItemSubType").InnerText);         
    string typeName = node.SelectSingleNode("ItemSubTypeName").InnerText;
    XmlNode xmlAddress = node.SelectSingleNode("AddressInfo");     
    ITcSmTreeItem device = ioDevicesItem.CreateChild(string.Format("Device_{0}",+
+deviceCount),itemSubType,string.Empty,null);
    string xml = string.Format("<TreeItem><DeviceDef>{0}</DeviceDef></
TreeItem>",xmlAddress.OuterXml);
    device.ConsumeXml(xml);
    devices.Add(device);     
  }
  foreach (ITcSmTreeItem device in devices)     
  {
    string xml = "<TreeItem><DeviceDef><ScanBoxes>1</ScanBoxes></DeviceDef></TreeItem>";
    try
    {
      device.ConsumeXml(xml);
    }
    catch (Exception ex)         
    {
      Console.WriteLine("Warning: {0}",ex.Message);
    }
    foreach (ITcSmTreeItem box in device)
    {
      Console.WriteLine(box.Name);
    }
  }
}

4.3.5.8 Enabling and disabling I/O devices


To disable/enable a tree item in a configuration, an instance of the TwinCAT System Manager has to be
created and the configuration has to be opened. The LookupTreeItem [} 110] method of the ITcSysManager
[} 104] interface returns a ITcSmTreeItem [} 113] interface pointer implemented by the tree item referenced
by its pathname [} 9]. This interface contains a Disabled [} 113] property of the tree item.

Procedure

The Procedure to create the ITcSysManager [} 104] interface (the 'sysMan' instance here) is described in the
chapter Accessing TwinCAT Configurations. [} 19] This interface has a LookupTreeItem [} 110] method that
returns a ITcSmTreeItem [} 113] pointer to a specific tree item given by its pathname [} 9]. To disable/enable
the tree item "TIID^EtherCAT Master" the following code snippets can be used.

Sample (CSharp):

88 Version: 1.3 Automation Interface


Configuration

ITcSmTreeItem item = sysMan.LookupTreeItem("TIID^EtherCAT Master");


item.Disabled = DISABLED_STATE.SMDS_DISABLED;

Please note, that, for this sample, you need to add both a reference to "Microsoft Developer Environment
10.0" and "Beckhoff TCatSysManager Library 1.1" to your project.

Sample (PowerShell):
$DISABLED_STATE = @{"SMDS_NOT_DISABLED" = "0"; "SMDS_DISABLED" = "1"}
$item = $systemManager.LookupTreeItem("TIID^EtherCAT Master")
$item.Disabled = $DISABLED_STATE.SMDS_DISABLED

Sample (VBScript):
dim dte,sln,proj,sysMan
set dte = CreateObject("VisualStudio.DTE.10.0")
set sln = dte.Solution
call sln.Open("C:\SolutionFolder\MySolution1.sln")
set proj = sln.Projects(1)
set sysMan = proj.Object
set item = sysMan.LookupTreeItem("TIID^EtherCAT Master")
item.Disabled = SMDS_DISABLED '(oder item.Disabled = SMDS_NOT_DISABLED um Strukturelement zu
aktivieren)

4.3.6 TcCOM

4.3.6.1 Creating and handling TcCOM modules


This chapter explains how to add existing TcCOM modules to a TwinCAT configuration and parameterize
them. The following topics will be briefly covered in this chapter:
• Acquiring a reference to “TcCOM Objects” node
• Adding existing TcCOM modules
• Iterating through added TcCOM modules
• Setting CreateSymbol flag for parameters
• Setting CreateSymbol flag for Data Areas
• Setting Context (Tasks)
• Linking variables

Acquiring a reference to “TcCOM Objects” node

In a TwinCAT configuration, the “TcCOM Objects” node is located under “SYSTEM^TcCOM Objects”.
Therefore you can acquire a reference to this node by using the method ITcSysManager::LookupTreeItem()
in the following way:

Code Snippet (C#):


ITcSmTreeItem tcComObjects = systemManager.LookupTreeItem("TIRC^TcCOM Objects");

Code Snippet (Powershell):


$tcComObjects = $systemManager.LookupTreeItem("TIRC^TcCOM Objects")

The code above assumes that there is already a systemManager objects present in your AI code.

Adding existing TcCOM modules

To add existing TcCOM modules to your TwinCAT configuration, these modules need to be detectable by
TwinCAT. This can be achieved by either of the following ways:
• Copying TcCOM modules to folder %TWINCAT3.XDIR”\CustomConfig\Modules\
• Editing %TWINCAT3.XDIR”\Config\Io\TcModuleFolders.xml to add a path to a folder of your choice
and place the modules within that folder

Both ways will be sufficient to make the TcCOM modules detectable by TwinCAT.

Automation Interface Version: 1.3 89


Configuration

A TcCOM module is being identified by its GUID. This GUID can be used to add a TcCOM module to a
TwinCAT configuration via the ITcSmTreeItem::CreateChild() method. The GUID can be determined in
TwinCAT XAE via the properties page of a TcCOM module or programatically, which will be explained later
in this chapter.

Alternatively you can also determine the GUID via the TMC file of the TcCOM module.
<TcModuleClass>
  <Modules>
    <Module GUID="{8f5fdcff-ee4b-4ee5-80b1-25eb23bd1b45}">
    ...
    </Module>
  </Modules>
</TcModuleClass>

Let’s assume that we already own a TcCOM module that is registered in and detectable by TwinCAT. We
now would like to add this TcCOM module, which has the GUID {8F5FDCFF-
EE4B-4EE5-80B1-25EB23BD1B45} to our TwinCAT configuration. This can be done by the following way:

Code Snippet (C#):


Dictionary<string,Guid> tcomModuleTable = new Dictionary<string,Guid>();
tcomModuleTable.Add("TempContr",Guid.Parse("{8f5fdcff-ee4b-4ee5-80b1-25eb23bd1b45}"));
ITcSmTreeItem tempController = tcComObjects.CreateChild(“Test”, 0, "",
tcomModuleTable["TempContr"]);

Code Snippet (Powershell):


$tcomModuleTable = @""
$tcomModuleTable.Add("TempContr", "{8f5fdcff-ee4b-4ee5-80b1-25eb23bd1b45}")
$tempController = $tcComObjects.CreateChild("Test", 0, "", $tcomModuleTable["TempContr"])

Please note that the vInfo parameter of the method ItcSmTreeItem::CreateChild() contains the GUID of the
TcCOM module which is used to identify the module in the list of all registered TcCOM modules in that
system.

Iterating through added TcCOM modules

To iterate through all added TcCOM module instances, you may use the ITcModuleManager2 interface. The
following code snippet demonstrates how to use this interface.

Code Snippet (C#):


ITcModuleManager2 moduleManager = (ITcModuleManager2)systemManager.GetModuleManager();
foreach (ITcModuleManager2 moduleInstance in moduleManager)
{
  string moduleType = moduleInstance.ModuleTypeName;
  string instanceName = moduleInstance.ModuleInstanceName;
  Guid classId = moduleInstance.ClassID;
  uint objId = moduleInstance.oid;
  uint parentObjId = moduleInstance.ParentOID;
}

Code Snippet (Powershell):

90 Version: 1.3 Automation Interface


Configuration

$moduleManager = $systemManager.GetModuleManager()
ForEach( $moduleInstance in $moduleManager )
{
  $moduleType = $moduleInstance.ModuleTypeName
  $instanceName = $moduleInstance.ModuleInstanceName
  $classId = $moduleInstance.ClassID
  $objId = $moduleInstance.oid
  $parentObjId = $moduleInstance.ParentOID
}

Please note that every module object can also be interpreted as an ITcSmTreeItem, therefore the following
type cast would be valid:

Code Snippet (C#):


ITcSmTreeItem treeItem = moduleInstance As ITcSmTreeItem;

Please note: Powershell uses dynamic data types by default.

Setting CreateSymbol flag for parameters

The CreateSymbol (CS) flag for parameters of a TcCOM module can be set via its XML description. The
following code snippet demonstrates how to activate the CS flag for the Parameter “CallBy”.

Code Snippet (C#):


bool activateCS = true;
// First step: Read all Parameters of TcCOM module instance
string tempControllerXml = tempController.ProduceXml();
XmlDocument tempControllerDoc = new XmlDocument();
tempControllerDoc.LoadXml(tempControllerXml);
XmlNode sourceParameters = tempControllerDoc.SelectSingleNode("TreeItem/TcModuleInstance/Module/
Parameters");

// Second step: Build target XML (for later ConsumeXml())


XmlDocument targetDoc = new XmlDocument();
XmlElement treeItemElement = targetDoc.CreateElement("TreeItem");
XmlElement moduleInstanceElement = targetDoc.CreateElement("TcModuleInstance");
XmlElement moduleElement = targetDoc.CreateElement("Module");
XmlElement parametersElement = (XmlElement) targetDoc.ImportNode(sourceParameters, true);
moduleElement.AppendChild(parametersElement);
moduleInstanceElement.AppendChild(moduleElement);
treeItemElement.AppendChild(moduleInstanceElement);
targetDoc.AppendChild(treeItemElement);

// Third step: Look for specific parameter (in this case “CallBy”) and read its CreateSymbol
attribute
XmlNode destModule = targetDoc.SelectSingleNode("TreeItem/TcModuleInstance/Module ");
XmlNode callByParameter = destParameters.SelectSingleNode("Parameters/Parameter[Name='CallBy']");
XmlAttribute createSymbol = callByParameter.Attributes["CreateSymbol"];

createSymbol.Value = "true";

// Fifth step: Write prepared XML to configuration via ConsumeXml()


string targetXml = targetDoc.OuterXml;
tempController.ConsumeXml(targetXml);

Code Snippet (Powershell):


$tempControllerXml = [Xml]$tempController.ProduceXml()
$sourceParameters = $tempControllerXml.TreeItem.TcModuleInstance.Module.Parameters

[System.XML.XmlDocument] $targetDoc = New-Object System.XML.XmlDocument


[System.XML.XmlElement] $treeItemElement = $targetDoc.CreateElement("TreeItem")
[System.XML.XmlElement] $moduleInstanceElement = $targetDoc.CreateElement("TcModuleInstance")
[System.XML.XmlElement] $moduleElement = $targetDoc.CreateElement("Module")
[System.XML.XmlElement] $parametersElement = $targetDoc.ImportNode($sourceParameters, $true)
$moduleElement.AppendChild($parametersElement)
$moduleInstanceElement.AppendChild($moduleElement)
$treeItemElement.AppendChild($moduleInstanceElement)
$targetDoc.AppendChild($treeItemElement)

$destModule = $targetDoc.TreeItem.TcModuleInstance.Module
$callByParameter = $destmodule.SelectSingleNode("Parameters/Parameter[Name='CallBy']")

$callByParameter.CreateSymbol = "true"

Automation Interface Version: 1.3 91


Configuration

$targetXml = $targetDoc.OuterXml
$tempController.ConsumeXml($targetXml)

Setting CreateSymbol flag for Data Areas

The CreateSymbol (CS) flag for Data Areas of a TcCOM module can be set via its XML description. The
following code snippet demonstrates how to activate the CS flag for the Data Area “Input”. Please note that
the procedure is pretty much the same as for parameters.

Code Snippet (C#):


bool activateCS = true;
// First step: Read all Data Areas of a TcCOM module instance
string tempControllerXml = tempController.ProduceXml();
XmlDocument tempControllerDoc = new XmlDocument();
tempControllerDoc.LoadXml(tempControllerXml);
XmlNode sourceDataAreas = tempControllerDoc.SelectSingleNode("TreeItem/TcModuleInstance/Module/
DataAreas");

// Second step: Build target XML (for later ConsumeXml())


XmlDocument targetDoc = new XmlDocument();
XmlElement treeItem = targetDoc.CreateElement("TreeItem");
XmlElement moduleInstance = targetDoc.CreateElement("TcModuleInstance");
XmlElement module = targetDoc.CreateElement("Module");
XmlElement dataAreas = (XmlElement)
targetDoc.ImportNode(sourceDataAreas, true);
module.AppendChild(dataAreas);
moduleInstance.AppendChild(module);
treeItem.AppendChild(moduleInstance);
targetDoc.AppendChild(treeItem);

// Third step: Look for specific Data Area (in this case "Input") and read its CreateSymbol
attribute
XmlElement dataArea = (XmlElement)targetDoc.SelectSingleNode("TreeItem/TcModuleInstance/Module/
DataAreas/DataArea[ContextId=’0’ and Name=’Input’]");
XmlNode dataAreaNo = dataArea.SelectSingleNode("AreaNo");
XmlAttribute createSymbol = dataAreaNoNode.Attributes["CreateSymbols"];

// Fourth step: Set CreateSymbol attribute to true if it exists. If not, create attribute and set
its value
if (createSymbol != null)
string oldValue = createSymbol.Value;
else
{
createSymbol = targetDoc.CreateAttribute("CreateSymbols");
dataAreaNo.Attributes.Append(createSymbol);
}
createSymbol.Value = XmlConvert.ToString(activateCS);

// Fifth step: Write prepared XML to configuration via ConsumeXml()


string targetXml = targetDoc.OuterXml;
tempController.ConsumeXml(targetXml);

Code Snippet (Powershell):


$tempControllerXml = [Xml]$tempController.ProduceXml()
$sourceDataAreas = $tempControllerXml.TreeItem.TcModuleInstance.Module.DataAreas

[System.XML.XmlDocument] $targetDoc = New-Object System.XML.XmlDocument


[System.XML.XmlElement] $treeItem = $targetDoc.CreateElement("TreeItem")
[System.XML.XmlElement] $moduleInstance = $targetDoc.CreateElement("TcModuleInstance")
[System.XML.XmlElement] $module = $targetDoc.CreateElement("Module")
[System.XML.XmlElement] $dataAreas = $targetDoc.ImportNode($sourceDataAreas, $true)
$module.AppendChild($dataAreas)
$moduleInstance.AppendChild($module)
$treeItem.AppendChild($moduleInstance)
$targetDoc.AppendChild($treeItem)

$destModule = $targetDoc.TreeItem.TcModuleInstance.Module
[System.XML.XmlElement] $dataArea = $destModule.SelectSingleNode("DataAreas/DataArea[ContextId='0'
and Name='Input']")
$dataAreaNo = $dataArea.SelectSingleNode("AreaNo")
$dataAreaNo.CreateSymbols = "true"

// Fifth step: Write prepared XML to configuration via ConsumeXml()


$targetXml = $targetDoc.OuterXml
$tempController.ConsumeXml($targetXml)

92 Version: 1.3 Automation Interface


Configuration

Setting Context (Tasks)

Every TcCOM module instance needs to be run in a specific context (task). This can be done via the
ITcModuleInstance2::SetModuleContext() method. This method awaits two parameters: ContextId and
TaskObjectId. Both are equivalent to the corresponding parameters in TwinCAT XAE:

Please note that the TaskObjectId is shown in hex in TwinCAT XAE.

Code Snippet (C#):


ITcModuleInstance2 tempControllerMi = (ITcModuleInstance2) tempController;
tempControllerMi.SetModuleContext(0, 33619984);

You can determine the TaskObjectId via the XML description of the corresponding task, for example:

Code Snippet (C#):


ITcSmTreeItem someTask = systemManager.LookupTreeItem(“TIRT^SomeTask”);
string someTaskXml = someTask.ProduceXml();
XmlDocument someTaskDoc = new XmlDocument();
someTaskDoc.LoadXml(someTaskXml);
XmlNode taskObjectIdNode = someTaskDoc.SelectSingleNode(“TreeItem/ObjectId”);
string taskObjectIdStr = taskObjectId.InnerText;
uint taskObjectId = uint.Parse(taskObjectIdStr, NumberStyles.HexNumber);

Linking variables

Linking variables of a TcCOM module instance to PLC/IO or other TcCOM modules can be done by using
regular Automation Interface mechanisms, e.g. ITcSysManager::LinkVariables().

4.3.7 C++

4.3.7.1 Creating and handling C++ projects and modules


This chapter explains in-depth how to create, access and handle TwinCAT C++ projects. The following list
shows all chapters in this article:
• General information about C++ projects
• Creating new C++ projects
• Creating new module within a C++ project
• Opening existing C++ projects
• Creating module instances
• Calling TMC Code Generator
• Calling Publish Modules command

Automation Interface Version: 1.3 93


Configuration

• Setting C++ Project Properties


• Building project

General information about C++ projects

C++ projects are specified by their so-called project template, which are used by the “TwinCAT C++ Project
Wizard”. Inside a project multiple modules could be defined by module templates, which are used by the
“TwinCAT Class Wizard”.

TwinCAT-defined templates are documented in the Section C++ / Wizards.

The customer could define own templates, which is documented at the corresponding sub-section if C++
Section / Wizards.

Creating C++ projects

To create a new C++ project via Automation Interface, you need to navigate to the C++ node and then
execute the CreateChild() method with the corresponding template file as a parameter.

Code snippet (C#):


ITcSmTreeItem cpp = systemManager.LookupTreeItem("TIXC");
ITcSmTreeItem cppProject = cpp.CreateChild("NewCppProject", 0, "", pathToTemplateFile);

Code snippet (Powershell):


$cpp = $systemManager.LookupTreeItem("TIXC")
$newProject = $cpp.CreateChild("NewCppProject", 0, "", $pathToTemplateFile)

For instantiating a driver project please use "TcDriverWizard" as pathToTemplateFile.

Creating new module within a C++ project

Within a C++ project usually a TwinCAT Module Wizard is used to let the wizard create a module by a
template.

Code snippet (C#):


ITcSmTreeItem cppModule = cppProject.CreateChild("NewModule", 1, "", pathToTemplateFile);

Code snippet (Powershell):


$cppModule = $cppProject.CreateChild("NewModule", 0, "", $pathToTemplateFile);

As example for instantiating a Cyclic IO module project please use "TcModuleCyclicCallerWizard " as
pathToTemplateFile.

Opening existing C++ projects

To open an existing C++-Project via Automation Interface, you need to navigate to the C++ node and then
execute the CreateChild() method with the path to the corresponding C++ project file as a parameter.

You can use three different values as SubType:


• 0: Copy project to solution directory
• 1: Move project to solution directory
• 2: Use original project location (specify “” as NameOfProject parameter)

94 Version: 1.3 Automation Interface


Configuration

Basically, these values represent the functionalities (Yes, No, Cancel) from the following MessageBox in
TwinCAT XAE:

In place of the template file you need to use the path to the C++ project (to its vcxproj file) that needs to be
added. As an alternative, you can also use a C++ project archive (tczip file).

Code snippet (C#):


ITcSmTreeItem cpp = systemManager.LookupTreeItem("TIXC");
ITcSmTreeItem newProject = cpp.CreateChild("NameOfProject", 1, "", pathToProjectOrTczipFile);

 Code snippet (Powershell):


$cpp = $systemManager.LookupTreeItem("TIXC")
$newProject = $cpp.CreateChild("NameOfProject", 1, "", $pathToProjectOrTczipFile)

Please note that C++ projects can’t be renamed, thus the original project name needs to be specified. (cmp.
Renaming TwinCAT C++ projects)

Creating module instances

TcCOM Modules could be created at the System -> TcCOM Modules node. Please see documentation there
[} 89].

The same procedure could also be applied to the C++ project node to add TcCOM instances at that place
($newProject at the code on top of this page.).

Calling TMC Code Generator

TMC Code generator could be called to generate C++ code after changes at the TMC file of the C++ project.

Code snippet (C#):


string startTmcCodeGenerator = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<TreeItem>
<CppProjectDef>
<Methods>
<StartTmcCodeGenerator>
<Active>true</Active>
</StartTmcCodeGenerator>
</Methods>
</CppProjectDef>
</TreeItem>";
cppProject.ConsumeXml(startTmcCodeGenerator);

Code snippet (Powershell):


$startTmcCodeGenerator = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<TreeItem>
<CppProjectDef>
<Methods>
<StartTmcCodeGenerator>
<Active>true</Active>
</StartTmcCodeGenerator>
</Methods>

Automation Interface Version: 1.3 95


Configuration

</CppProjectDef>
</TreeItem>"
$cppProject.ConsumeXml($startTmcCodeGenerator)

Calling Publish Modules command

Publishing includes building the project for all platforms. The compiled module will be provided for Export like
described in the Module-Handling section of C++.

Code snippet (C#):


string publishModules = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<TreeItem>
<CppProjectDef>
<Methods>
<PublishModules>
<Active>true</Active>
</PublishModules>
</Methods>
</CppProjectDef>
</TreeItem>";
cppProject.ConsumeXml(publishModules);

Code snippet (Powershell):


$publishModules = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<TreeItem>
<CppProjectDef>
<Methods>
<PublishModules>
<Active>true</Active>
</PublishModules>
</Methods>
</CppProjectDef>
</TreeItem>"
$cppProject.ConsumeXml($publishModules)

Setting C++ Project Properties

C++ projects provide different options for the build and deployment process.
These are settable by the Automation Interface.

Code snippet (C#):


string projProps = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<TreeItem>
<CppProjectDef>
<BootProjectEncryption>Target</BootProjectEncryption>
<TargetArchiveSettings>
<SaveProjectSources>false</SaveProjectSources>
</TargetArchiveSettings>
<FileArchiveSettings>
<SaveProjectSources>false</SaveProjectSources>
</FileArchiveSettings>
</CppProjectDef>
</TreeItem>";
cppProject.ConsumeXml(projProps);

Code snippet (Powershell):


$projProps = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<TreeItem>
<CppProjectDef>
<BootProjectEncryption>Target</BootProjectEncryption>
<TargetArchiveSettings>
<SaveProjectSources>false</SaveProjectSources>
</TargetArchiveSettings>
<FileArchiveSettings>
<SaveProjectSources>false</SaveProjectSources>
</FileArchiveSettings>
</CppProjectDef>
</TreeItem>"
$cppProject.ConsumeXml($projProps)

For the BootProjectEncryption the values “None” and “Target” are valid.
Both other settings are “false” and “true” values.

96 Version: 1.3 Automation Interface


Configuration

Building project

To build the project or solution you can use the corresponding classes and methods of the Visual Studio API,
which are documented here [} 30].

4.3.8 Measurement

4.3.8.1 Creating and handling TwinCAT Measurement projects


The TwinCAT Automation Interface provides methods and properties to create and access TwinCAT
Measurement projects. The following chapter explains how to solve some basic tasks with that kind of
TwinCAT project and includes information about the following topics:
• Requirements
• Creating a TwinCAT Measurement project
• Creating a TwinCAT Scope configuration
• Creating, accessing and handling charts
• Creating, accessing and handling axes
• Creating, accessing and handling channels
• Starting and stopping records
• For more information about TwinCAT Measurement, please visit the corresponding webpage in our
Information System.

Requirements

Integrating TwinCAT Measurement projects via Automation Interface is available since TwinCAT 3.1 Build
4013.

As a prerequisite to use the Scope AI functionalities, a reference to the following COM interfaces is required:
• TwinCAT Measurement Automation Interface (registered as COM library)
• TwinCAT Scope2 Communications (.NET assembly: C:\Windows\Microsoft.NET\assembly\GAC_MSIL
\TwinCAT.Scope2.Communications\v4.0_3.1.3121.0__180016cd49e5e8c3\)

Creating a TwinCAT Measurement project

TwinCAT Measurement is a global "container" which can host one or more measurement projects, e.g. a
TwinCAT Scope configuration. Similar to a regular TwinCAT configuration, each project is first-of-all
described by a template-file. This template file is used when adding a new project to the solution, which can

Automation Interface Version: 1.3 97


Configuration

be achieved by calling the AddFromTemplate() method from the Visual Studio DTE object. Please note that
this procuedure is the same when adding a regular TwinCAT project. The following code snippet assumes
that you have already acquired a DTE instance and created a Visual Studio solution, as demonstrated in our
article about Accessing TwinCAT configurations. A reference to the DTE instance is stored in the object
"dte".

Code Snippet (C#):


EnvDTE.Project scopeProject = dte.Solution.AddFromTemplate(template, destination, name);

[template]: The default template files are stored under C:\TwinCAT\Functions\TE130X-Scope-View


\Templates\Projects\ and have the file type "tcmproj".

[destination]: Path where the new configuration should be stored on hard disk.

[name]: Name for the new configuration, as displayed in TwinCAT XAE.

Creating a TwinCAT Scope configuration

A TwinCAT Scope project stands for a recording configuration. This means that all elements inserted in that
project are subject to the same recording settings. You can add a Scope project via Automation Interface by
specifying the corresponding "TwinCAT Scope Project" template when adding a project using the
AddFromTemplate() method, as described above.

Creating, accessing and handling charts

Several charts can exist in parallel in a Scope configuration. To add charts to an existing Scope project,
simply use the CreateChild() method from the IMeasurementScope interface. The following code snippet
assumes that a TwinCAT Measurement Project has already been created and a reference to this project is
stored in the object "scopeProject".

Code Snippet (C#):


((IMeasurementScope)scopeProject.ProjectItems.Item(1).Object).ShowControl();
EnvDTE.ProjectItem newChart;
((IMeasurementScope)scopeProject.ProjectItems.Item(1).Object).CreateChild(out newChart);
IMeasurementScope newChartObj = (IMeasurementScope)newChart.Object;
newChartObj.ChangeName("NC Chart");

The object "newChartObj" now stores a reference to the newly added chart. At this point, please keep in
mind that we still need the original object "newChart" for later purposes, e.g. to set chart properties.

In TwinCAT XAE, chart properties are set via the Visual Studio properties window. The object "newChart"
gives access to these properties via its collection "Properties". The following code snippet iterates through all
properties of a chart and sets the property "StackedYAxis" to "true".

Code Snippet (C#):


foreach (EnvDTE.Property prop in newChart.Properties)
{
If (prop.Name = "StackedYAxis")
prop.Value = true;
}

Creating, accessing and handling axes

The following code snippet demonstrates how to add axes.

Code Snippet (C#):


EnvDTE.ProjectItem newAxis;
newChartObj.CreateChild(out newAxis);
IMeasurementScope newAxisObj = (IMeasurementScope)newAxis.Object;
newAxisObj.ChangeName(“Axis 1”);

Creating, accessing and handling channels

A Scope channel scribes a connection to a runtime symbol, e.g. a PLC variable. To add channels via
Automation Interface, you can use the CreateChild() method of the IMeasurementScope interface.

98 Version: 1.3 Automation Interface


Configuration

Code Snippet (C#):


EnvDTE.ProjectItem newChannel;
newAxisObj.CreateChild(out newChannel);
IMeasurementScope newChannelObj = (IMeasurementScope)newChannel.Object;
newChannelObj.ChangeName("Signals.Rectangle");

The object "newChannelObj" now stores a reference to the newly added channel. At this point, please keep
in mind that we still need the original object "newChannel" for later purposes, e.g. to set channel properties.

In TwinCAT XAE, channel properties are set via the Visual Studio properties window. The object
"newChannel" gives access to these properties via its collection "Properties". The following code snippet
iterates through all properties of a channel and sets multiple properties.

Code Snippet (C#):


foreach (EnvDTE.Property prop in newChannel.Properties)
{
switch (prop.Name)
{
case "TargetPorts":
prop.Value = "851";
break;

case "Symbolbased":
prop.Value = true;
break;

case "SymbolDataType":
prop.Value = TwinCAT.Scope2.Communications.Scope2DataType.BIT;
break;

case "SymbolName":
prop.Value = "MAIN.bSignal";
break;

case "SampleState":
prop.Value = 1;
break;

case "LineWidth":
prop.Value = 3;
break;
}
}

As you can see, the Scope2DataType enum defines several data types that are supported when configuring
a channel. At creation time of this document, this enum is defined as follows:

Code Snippet (C#):


public enum Scope2DataType
{
VOID = 0,
BIT = 1,
INT16 = 2,
INT32 = 3,
INT64 = 4,
INT8 = 5,
REAL32 = 6,
REAL64 = 7,
UINT16 = 8,
UINT32 = 9,
UINT64 = 10,
UINT8 = 11,
BIT_ARRAY_8 = 12,
}

Please use a DLL explorer (e.g. Visual Studio) for a more recent and up-to-date list.

Starting and stopping records

To start/stop a configured Scope record, the corresponding methods from the IMeasurementScope interface
can be used:

Code Snippet (C#):

Automation Interface Version: 1.3 99


Configuration

((IMeasurementScope)scopeProject.ProjectItems.Item(1).Object).StartRecord()
((IMeasurementScope)scopeProject.ProjectItems.Item(1).Object).StopRecord();

4.3.9 Motion

4.3.9.1 Creating and handling Motion projects


This chapter explains in-depth how to create and handle Motion projects. The following list shows all
chapters in this article:
• General information about TwinCAT 3 Motion
• Creating a NC-Task
• Creating axes
• Parameterize axes

General information about TwinCAT Motion

TwinCAT 3 Motion consists of the following three components: NC-I, NC-PTP and CNC. It is therefore an
assembly of function groups used for the control and regulation of axes or of synchronised axis groups. For
more information about TwinCAT Motion please see the TwinCAT 3 Motion documentation.

Creating a NC-Task

The first step to create a TwinCAT 3 Motion project is to create a so-called NC-Task. In TwinCAT Automation
Interface, you can create this task simply by calling the method ITcSmTreeItem [} 113]::CreateChild() [} 148]
and using the SubType parameter 1, as the following code snippet shows.

Code Snippet (C#):


ITcSmTreeItem ncConfig = systemManager.LookupTreeItem("TINC");
ncConfig.CreateChild("NC-Task", 1);

Code Snippet (Powershell):


$ncConfig = $systemManager.LookupTreeItem("TINC")
$ncConfig.CreateChild("NC-Task", 1)

Creating axes

As the NC-Task does not contain any axes by default. you need to add them, again by using the
CreateChild() method - this time on a reference to the Axes node below the NC-Task.

Code Snippet (C#):


ITcSmTreeItem axes = systemManager.LookupTreeItem("TINC^NC-Task^Axes");
axes.CreateChild("Axis 1", 1);

Code Snippet (Powershell):


$axes = $systemManager.LookupTreeItem("TINC^NC-Task^Axes")
$axes.CreateChild("Axis 1", 1)

100 Version: 1.3 Automation Interface


Configuration

Parameterize axes

Axes can be parameterized via their XML description [} 25]. To get a sample XML description, you could add
an axis manually in TwinCAT XAE and use the corresponding entry from the context menu or add the axis
via Automation Interface and use the ITcSmTreeItem [} 113]::ProduceXml() [} 146] method to get it.

Code Snippet (C#):


ITcSmTreeItem axis = systemManager.LookupTreeItem("TINC^NC-Task^Axes^Axis 1");
string xmlDescription = axis.ProduceXml();

Code Snippet (Powershell):


$axis = $systemManager.LookupTreeItem("TINC^NC-Task^Axes^Axis 1")
$xmlDescription = $axis.ProduceXml()

You can modify this XML description to your needs and then import it again via the method ITcSmTreeItem
[} 113]::ConsumeXml() [} 147] to parameterize your axis.

Code Snippet (C#):


ITcSmTreeItem axis = systemManager.LookupTreeItem("TINC^NC-Task^Axes^Axis 1");
axis.ConsumeXml(xmlDescription);

Code Snippet (Powershell):


$axis = $systemManager.LookupTreeItem("TINC^NC-Task^Axes^Axis 1")
$axis.ConsumeXml($xmlDescription)

Automation Interface Version: 1.3 101


Configuration

4.3.10 Safety

4.3.10.1 Creating and handling Safety projects


This chapter explains in-depth how to create, access and handle Safety projects. The following list shows all
chapters in this article:
• General information about Safety projects
• Opening existing Safety projects

General information about Safety projects


• The TwinCAT Automation Interface allows to import existing TwinCAT Safety projects into a TwinCAT
configuration. For this purpose, users can either use the corresponding *.splcproj file or the container
format *.tfzip as a source template.

Opening existing Safety projects

To open an existing Safety project via Automation Interface, you need to navigate to the Safety node and
then execute the CreateChild() method with the path to the corresponding, existing Safety project file file as
a parameter.

You can use three different values as SubType:


• 0: Copy project to solution directory
• 1: Move project to solution directory
• 2: Use original project location (when used, please use "" as project name parameter)

Basically, these values represent the functionalities (Yes, No, Cancel) from the following MessageBox in
TwinCAT XAE:

You can either use the path to the Safety project (to its *.splcproj file) that needs to be added or you can also
use a Safety project archive (*.tfzip).

Code Snippet (C#):


ITcSmTreeItem safety = systemManager.LookupTreeItem("TISC");
ITcSmTreeItem newProject = safety.CreateChild("NameOfProject", 0, null, pathToProjectOrTfzipFile);

Code Snippet (Powershell):


$safety = $systemManager.LookupTreeItem("TISC")
$newProject = $safety.CreateChild("NameOfProject", 0, "", pathToProjectOrTfzipFile)

102 Version: 1.3 Automation Interface


API

5 API

5.1 Reference
This chapter contains a documentation of all classes and methods of the TwinCAT Automation Interface.
The provided interfaces can be divided into different "levels" in which the higher level interfaces represent
the primary interfaces and therefore the basic interaction with the Automation Interface. Please note that this
differentiation comes only from a logical point-of-view, to get a better understanding about which interfaces
are most important and which interfaces are of secondary importance.

Level 1 interfaces

As mentioned in our introduction [} 9], there are only two main interfaces which are being used for
navigating and referencing tree items in TwinCAT configuration.

Main class Description Available since


ITcSysManager [} 104] Base class to create and TwinCAT 2.11
parameterize a TwinCAT
configuration
ITcSmTreeItem [} 113] Represents a tree item within a TwinCAT 2.11
TwinCAT configuration

Level 2 interfaces

These interfaces are considered as "helper classes" which are always used together with level 1 classes, for
example to cast an ITcSmTreeItem object into a more specific type of tree item, for example a POU
(ITcPlcPou) or a linked task (ITcTaskReference).

Automation Interface Version: 1.3 103


API

Helper class Description Available since


ITcPlcLibraryManager [} 159] Defines methods and properties for TwinCAT 3.1
PLC library management
ITcPlcPou [} 154] Defines methods and properties to TwinCAT 3.1
handle PLC POUs
ITcPlcDeclaration [} 155] Defines methods to read/write the TwinCAT 3.1
declaration area of a PLC POU
ITcPlcImplementation [} 156] Defines methods to read/write the TwinCAT 3.1
implementation area of a PLC POU
ITcPlcProject [} 153] Defines methods and properties TwinCAT 3.1
regarding a PLC project, e.g.
setting the project as a boot project
ITcPlcIECProject [} 157] Defines methods needed to import/ TwinCAT 3.1
export PLC projects in PLCopen
XML and also install them as a
PLC library
ITcPlcTaskReference [} 170] Defines methods and properties to TwinCAT 3.1
link the PLC project to a task
ITcPlcLibrary [} 166] Helper class which represents a TwinCAT 3.1
single PLC library
ITcPlcLibraries [} 167] Helper class which represents a TwinCAT 3.1
collection of PLC libraries
ITCPlcReferences [} 166] Helper class which represents a TwinCAT 3.1
collection of ITcPlcLibRef objects
(and therefore references in a PLC
project)
ITcPlcLibRef [} 167] Helper class which represents a TwinCAT 3.1
base class for ITcPlcLibrary and
ITcPlcPlaceholderRef objects
ITcPlcPlaceholderRef [} 168] Helper class which represents a TwinCAT 3.1
single PLC placeholder
ITcPlcLibRepository [} 168] Helper class which represents a TwinCAT 3.1
single PLC library repository
ITcPlcLibRepositories [} 169] Helper class which represents a TwinCAT 3.1
collection of PLC library
repositories

5.2 ITcSysManager

5.2.1 ITcSysManager
ITcSysManager is the main interface of the TwinCAT Automation Interface. This interface allows basic
operations to configure TwinCAT 3 XAE and consists of several methods for doing so. Over the years, the
ITcSysManager interface has been extended with more functionalities to give customers a better way to
access all Automation Interface features. However, due to restrictions in the COM object model, these
features needed to be added as separate interfaces to the Automation Interface. Therefore, each time a new
set of features was added, these features were assembled in a new interface which was named
ITcSysManagerX, where X is a number which is incremented each time a new interface was added. The
following tables explain which methods are part of the ITcSysManager interface and which have been added
to each new "feature-set" interface.

104 Version: 1.3 Automation Interface


API

Methods

ITcSysManager methods Description Available since


NewConfiguration [} 106] Generates a new configuration TwinCAT 2.11
OpenConfiguration [} 106] Loads a prior created configuration TwinCAT 2.11
file (WSM file)
SaveConfiguration [} 107] Saves the configuration in a file TwinCAT 2.11
with the given name or with the
current name
ActivateConfiguration [} 107] Activates the configuration (same TwinCAT 2.11
as "Save To Registry")
LookupTreeItem [} 110] Looks up to a configuration item TwinCAT 2.11
(item in the tree) by name and
returns a ITcSmTreeItem [} 113]
interface
StartRestartTwinCAT [} 108] Starts or Restarts the TwinCAT TwinCAT 2.11
System
IsTwinCATStarted [} 107] Evaluates if the TwinCAT System TwinCAT 2.11
is running
LinkVariables [} 108] Links two variables given by names TwinCAT 2.11
UnlinkVariables [} 109] Clears the link between two TwinCAT 2.11
variables given by names or all
links from one variable.

ITcSysManager2 methods Description Available since


SetTargetNetId [} 110] Set the target NetId of the currently TwinCAT 2.11
opened TwinCAT configuration.
GetTargetNetId [} 109] Gets the target NetId of the TwinCAT 2.11
currently opened TwinCAT
configuration.
GetLastErrorMessages [} 110] Get the last error messages which TwinCAT 2.11
occurred in the TwinCAT
subsystem.

ITcSysManager3 methods Description Available since


LookupTreeItemById [} 111] Looks for a configuration tree item TwinCAT 2.11
with the specifed Item id.
ProduceMappingInfo [} 112] Produces a Xml-Description of the TwinCAT 3.1
actual configuration mappings.
ClearMappingInfo Clears the mapping info. TwinCAT 2.11

Comments

The ITcSysManager interface contains two methods used for navigating within TwinCAT XAE:
ITcSysManager::LookupTreeItem [} 110] and ITcSysManager3::LookupTreeItemById [} 111]. A detailed
explanation of browsing TwinCAT XAE can be found in the chapter TreeItem Browsing Models [} 22].

Warning: The three methods ITcSysManager::NewConfiguration [} 106], ITcSysManager::OpenConfiguration


[} 106] and ITcsSysManager::SaveConfiguration [} 107] are only available in Compatiblity Mode [} 19].
Calling them in standard mode will throw an E_NOTSUPPORTED Exception.

The ITcSysmanager and the ITcSmTreeItem [} 113] interface allows full access to a TwinCAT configuration.
In the How to... section of this documentation there is a long (but incomplete) list of samples how to
manipulate a TwinCAT configuration automatically.

Automation Interface Version: 1.3 105


API

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 2.11 and above

5.2.2 ITcSysManager::NewConfiguration
The NewConfiguration() method generates a new TwinCAT configuration file.
HRESULT NewConfiguration();

Return Values

S_OK Function has returned a value.

E_ACCESSDENIED The actual document is locked in the System


Manager-Instance. This is if at least one reference to
the system manager-object or one of the Tree Items
is opened.
E_FAIL Function failed.

Comments

Warning: The three methods ITcSysManager::NewConfiguration [} 106], ITcSysManager::OpenConfiguration


[} 106] and ITcsSysManager::SaveConfiguration [} 107] are only available in Compatiblity Mode [} 19].
Calling them in standard mode will throw an E_NOTSUPPORTED Exception.

5.2.3 ITcSysManager::OpenConfiguration
The OpenConfiguration() method loads a previously created TwinCAT configuration file.
HRESULT OpenConfiguration(BSTRbstrFile);

Parameters

bstrFile [in, defaultvalue(L"")] contains the file path of the


configuration file that should be loaded or an empty
string if a new configuration should generated. The
currently running configuration of a target device may
also be read by using "CURRENTCONFIG".

Return Values

S_OK Function has returned a value.


E_ACCESSDENIED The actual document is locked in the system
manager-instance. This is if at least one reference tot
he system manager-object or one of the Tree Items is
opened.
E_INVALIDARG The path doesn’t point to a valid configfile.

Comments

Warning: The three methods ITcSysManager::NewConfiguration [} 106], ITcSysManager::OpenConfiguration


[} 106] and ITcsSysManager::SaveConfiguration [} 107] are only available in Compatiblity Mode [} 19].
Calling them in standard mode will throw an E_NOTSUPPORTED Exception.

106 Version: 1.3 Automation Interface


API

Also see about this


2 ITcSysManager [} 104]

5.2.4 ITcSysManager::SaveConfiguration
The SaveConfiguration() method saves a TwinCAT configuration in a file with the specified name.
HRESULT SaveConfiguration(BSTRbstrFile);

Parameters

bstrFile [in, defaultvalue(L"")] contains the path, where the


config file should be saved. When bstrFile is an
empty character string, the actual file name is used.

Return Values

S_OK Function has returned a value.


E_INVALIDARG The file path is invalid.

Comments

Warning: The three methods ITcSysManager::NewConfiguration [} 106], ITcSysManager::OpenConfiguration


[} 106] and ITcsSysManager::SaveConfiguration [} 107] are only available in Compatiblity Mode [} 19].
Calling them in standard mode will throw an E_NOTSUPPORTED Exception.

Also see about this


2 ITcSysManager [} 104]

5.2.5 ITcSysManager::ActivateConfiguration
The ActivateConfiguration() method activates the TwinCAT configuration (same as "Save To Registry"). A
following start or restart of the TwinCAT system must be performed to activate the configuration physically.
HRESULT ActivateConfiguration();

Return Values

S_OK Function has returned a value.


E_FAIL The function failed.

Also see about this


2 ITcSysManager [} 104]

5.2.6 ITcSysManager::IsTwinCATStarted
The IsTwinCATStarted() method evaluates if the TwinCAT System is running.
HRESULT IsTwinCATStarted(VARIANT_BOOL*pStarted);

Parameters

pStarted [out, retval] points to the storage location of the


boolean value, which contains the result.

Automation Interface Version: 1.3 107


API

Return Values

S_OK Function returned a value.

Also see about this


2 ITcSysManager [} 104]

5.2.7 ITcSysManager::StartRestartTwinCAT
The StartRestartTwinCAT() method starts or restarts the TwinCAT System. If TwinCAT is already started,
the function performs a restart, if TwinCAT is stopped it performs a start.
HRESULT StartRestartTwinCAT();

Return Values

Requirements

S_OK Function has returned a value.


E_FAIL TwinCAT couldn’t be started.

Also see about this


2 ITcSysManager [} 104]

5.2.8 ITcSysManager::LinkVariables
The LinkVariables() method links two variables, which are specified by their names. The two variables
represented by their tree path name will be linked. The path names must have the same syntax as described
in ITcSysManager::LookupTreeItem [} 110]. The same shortcuts [} 110] can be used.
HRESULT LinkVariables(BSTRbstrV1, BSTRbstrV2, longoffs1, longoffs2, longsize);

Parameters

bstrV1 [in] path name of the first variable. The full path name
is required and each branch must be separated by a
circumflex accent '^' or a tab.
bstrV2 [in] path name of the second variable. The full path
name is required and each branch must be separated
by a circumflex accent '^' or a tab.
offs1 [in, defaultvalue(0)] bit offset of the first variable (used
if the two variables have different sizes or not the
whole variable should be linked).
offs2 [in, defaultvalue(0)] bit offset of the second variable.
Größe [in, defaultvalue(0)] bit count how many bits should
linked. If size is 0 the minimum of the variable size of
variable one and two is used.

Return Values

S_OK function returns successfully.

TSM_E_ITEMNOTFOUND (0x98510001) one or both of the path name(s) does not qualify an
existing tree item.
TSM_E_INVALIDITEMTYPE (0x98510002) one or both of the tree item(s) is not a variable.

108 Version: 1.3 Automation Interface


API

TSM_E_MISMATCHINGITEMS (0x98510004) the two variables cannot linked together. May be you
have tried to link an output of one task with an output
of another task or an output of a task with an input of
a device or to variables of the same owner.
E_INVALIDARG the values of offs1, offs2 and/or size does not fit to
the variables.

Also see about this


2 ITcSysManager [} 104]

5.2.9 ITcSysManager::UnlinkVariables
The UnlinkVariables() method unlinks two variables, which are specified by their names, or clears all links
from the first variable if the name bstrV2 of the second variable is empty. The two variables represented by
their tree path name will be unlinked. The path names must have the same syntax as described in
ITcSysManager::LookupTreeItem [} 110]. The same shortcuts [} 110] can be used.
HRESULT UnlinkVariables(BSTRbstrV1, BSTRbstrV2);

Parameters

bstrV1 [in] path name of the first variable. The full path name
is required and each branch must be separated by a
circumflex accent '^' or a tab.
bstrV2 [in, defaultvalue(L"")] path name of the second
variable. If set the full path name is required and each
branch must be separated by a circumflex accent '^'
or a tab.

Return Values

S_OK function returns successfully.


S_FALSE the two variables have no link between them.
TSM_E_ITEMNOTFOUND (0x98510001) one or both of the path name(s) does not qualify an
existing tree item.
TSM_E_INVALIDITEMTYPE (0x98510002) one or both of the tree item(s) is not a variable.
TSM_E_CORRUPTEDLINK (0x98510005) the two variables cannot unlinked.

Comments

If bstrV2 is an empty string the function clears all links of variable given by bstrV1. If bstrV2 is not empty
only an existing link between both variables will be deleted.

Also see about this


2 ITcSysManager [} 104]

5.2.10 ITcSysManager2::GetTargetNetId
The GetTargetNetId() method returns the NetId of the current TwinCAT system.
HRESULT GetTargetNetId();

Parameters

None

Automation Interface Version: 1.3 109


API

Return Values

STRING returns target's NetId

Also see about this


2 ITcSysManager [} 104]

5.2.11 ITcSysManager2::SetTargetNetId
The SetTargetNetId() method sets the NetId of the current TwinCAT system.
HRESULT SetTargetNetId(STRING netId);

Parameters

netId represents the target's NetId.

Return Values

S_OK function returns successfully.

Also see about this


2 ITcSysManager [} 104]

5.2.12 ITcSysManager2::GetLastErrorMessages
The GetLastErrorMessages() metod returns the last error messages.
HRESULT GetLastErrorMessages();

Parameters

None

Return Values

STRING Returns last error messages.

Also see about this


2 ITcSysManager [} 104]

5.2.13 ITcSysManager::LookupTreeItem
The LookupTreeItem() method returns a ITcTreeItem pointer of a tree item given by it's full path name.
HRESULT LookupTreeItem(BSTRbstrItem, ITcSmTreeItem**pipItem);

Parameters

bstrItem [in] path name of the tree item looking for. The full
path name is required and each branch must be
separated by a circumflex accent '^' or a tab. A list of
shortcuts for the main tree items is listed below.
pipItem [out, retval] points to the location of a ITcSmTreeItem
[} 113] interface pointer on return. The interface
pointer gives access to specific methods belonging to
the tree item.

110 Version: 1.3 Automation Interface


API

Return Values

S_OK function returns successfully.


TSM_E_ITEMNOTFOUND (0x98510001) the path name does not qualify an existing tree item.

Shortcuts

The main tree items that exists in every configuration file can be accessed via shortcuts. These shortcuts are
language neutral and require less memory:
"TIIC": shortcut for "I/O Configuration"
“TIID": shortcut for "I/O Configuration^I/O Devices" or "I/O Configuration" TAB "I/O Devices"
“TIRC": shortcut for "Real-Time Configuration"
“TIRR": shortcut for "Real-Time Configuration^Route Settings"
“TIRT": shortcut for " Real-Time Configuration^Additional Tasks" or " Real-Time Configuration" TAB
"Additional Tasks"
“TIRS": shortcut for " Real-Time Configuration^Real-Time Settings" or " Real-Time Configuration" TAB
"Real-Time Settings"
“TIPC": shortcut for "PLC Configuration"
“TINC": shortcut for "NC Configuration"
“TICC": shortcut for "CNC Configuration"
“TIAC": shortcut for "CAM Configuration"

Sample (C++):
ITcSmTreeItem* ipItem;

BSTR bstrItem = L"TIID^Device 1 (C1220)";

if ( SUCCEEDED(spTsm->LookupTreeItem( bstrItem, &ipItem ))


)

// do anything with ipItem

ipItem->Release();

Sample (VB):Dim ipItem As ITcSmTreeItem


set ipItem = spTsm.LookupTreeItem("TIID^Device 1 (C1220)")
' do anything with ipItem

Comments

Also see about this


2 ITcSysManager [} 104]

5.2.14 ITcSysManager3::LookupTreeItemById
The LookupTreeItemById() method returns a ITcTreeItem pointer of a tree item given by it's full path name.
HRESULT LookupTreeItemById(longitemType, longitemId, ITcSmTreeItem**pipItem);

Parameters

itemType [in] Item type of the TreeItem to find.


itemId [in] ID of the TreeItem
pipItem [out, retval] points to the location of a ITcSmTreeItem
[} 113] interface pointer on return. The interface
pointer gives access to specific methods belonging to
the tree item.

Automation Interface Version: 1.3 111


API

Return Values

S_OK function returns successfully.


TSM_E_ITEMNOTFOUND (0x98510001) the itemType itemId combination doesn't qualify a
valid tree item.

Also see about this


2 ITcSysManager [} 104]

5.2.15 ITcSysManager3::ProduceMappingInfo
Generates an XML output that includes all currently configured mappings, e.g. between PLC and I/O.
HRESULT ProduceMappingInfo();

Parameters

none

Return Values

STRING: Returns XML structure that includes all configured mappings. The following snippet shows an
example for this structure:
<VarLinks>
    <OwnerA Name="TIID^Device 1 (EtherCAT)">
        <OwnerB Name="TIXC^Untitled2^Untitled2_Obj1 (CModule1)">
            <Link VarA="Term 1 (EK1100)^Term 3 (EL1008)^Channel 5^Input" VarB="Inputs^Value" />
            <Link VarA="Term 1 (EK1100)^Term 2 (EL2008)^Channel 4^Output" VarB="Outputs^Value" />
        </OwnerB>
    </OwnerA>
    <OwnerA Name="TIPC^Untitled1^Untitled1 Instance">
        <OwnerB Name="TIID^Device 1 (EtherCAT)^Term 1 (EK1100)^Term 2 (EL2008)">
            <Link VarA="PlcTask Outputs^MAIN.bOutput1" VarB="Channel 1^Output" />
            <Link VarA="PlcTask Outputs^MAIN.bOutput3" VarB="Channel 3^Output" />
            <Link VarA="PlcTask Outputs^MAIN.bOutput2" VarB="Channel 2^Output" />
        </OwnerB>
        <OwnerB Name="TIID^Device 1 (EtherCAT)^Term 1 (EK1100)^Term 3 (EL1008)">
            <Link VarA="PlcTask Inputs^MAIN.bInput1" VarB="Channel 1^Input" />
            <Link VarA="PlcTask Inputs^MAIN.bInput3" VarB="Channel 3^Input" />
            <Link VarA="PlcTask Inputs^MAIN.bInput2" VarB="Channel 2^Input" />
            <Link VarA="PlcTask Inputs^MAIN.bInput4" VarB="Channel 4^Input" />
        </OwnerB>
    </OwnerA>
</VarLinks>

This example shows mappings between PLC <--> I/O and TcCOM (C++) <--> I/O.

Also see about this


2 ITcSysManager [} 104]

5.2.16 ITcSysManager3::ConsumeMappingInfo
Consumes an XML structure that includes the mapping information for a project.
HRESULT ConsumeMappingInfo(BSTR bstrXml);

Parameters

bstrXml

[in]: String with XML structure. The XML mapping information can be acquired by using
ITcSysManager3::ProduceMappingInfo() [} 112].

Also see about this

112 Version: 1.3 Automation Interface


API

2 ITcSysManager [} 104]

5.3 ITcSmTreeItem

5.3.1 ITcSmTreeItem
Each tree item in a TwinCAT XAE configuration is represented by an instance of the ITcSmTreeItem
interface, which enables various interactions with the tree item.

A tree item of this interface will be, for example, returned by calling the ITCatSysManager::LookupTreeItem
[} 110] method, which is used to navigate through the tree.

Properties

ITcSmTreeItem Type Access Description


Property
Name BSTR RW Name of tree item
Comment BSTR RW Comment.
Disabled BOOL RW Get/Set state of tree item which can be one of the following
enum values:
• SMDS_NOT_DISABLED (item is enabled)
• SMDS_DISABLED (item is disabled)
• SMDS_PARENT_DISABLED (read only, set if one of its
parent is disabled)
PathName BSTR R Path of tree item in TwinCAT XAE. The branches are
separated by '^'. The PathName may be used in other method
calls, e.g. ITCatSysManager::LookupTreeItem [} 110]. Please
note that this property uniquely identifies a tree item in
TwinCAT XAE.
ItemType ENUM R Categorization of a tree item, e.g. Devices, Boxes, PLC, ... . As
defined by item types [} 114].
ItemSubType LONG RW Sub type [} 118] of a tree item.
Parent ITcSmTre R Pointer to the parent tree item.
eItem*
ChildCount LONG R Number of childs. Childs counted by this property enclose only
main childs of the tree item (e.g. boxes are main childs of a
device but not the device process image). To access all childs
use the _NewEnum property.
Child(LONG n) ITcSmTre R ITcSmTreeItem pointer of the n-th child
eItem*
VarCount((LONG x) LONG R Number of variables belonging to the tree item. x = 0 counted
the input variables, x = 1 the outputs
Var(LONG x, LONG ITcSmTre R ITcSmTreeItem pointer of the n-th variable. x = 0 uses the input
n) eItem* variables, x = 1 the outputs
_NewEnum IUnknown* R Returns a enum interface that enumerates all child tree items
(IEnumVar of the current tree item. This property may be used, for
iant*) example, by a For-Each statement.

Automation Interface Version: 1.3 113


API

Methods

ITcSmTreeItem Methods Description Available since


CreateChild [} 148] Creates a child tree item. TwinCAT 2.11
DeleteChild [} 150] Deletes a child tree item. TwinCAT 2.11
ImportChild [} 151] Imports a child item from the TwinCAT 2.11
clipboard or a previously exported
file.
ExportChild [} 151] Exports a child item to the TwinCAT 2.11
clipboard or a file.
ProduceXml [} 146] Returns a String containing the TwinCAT 2.11
XML representation of the item,
with all its item-specific data and
parameters.
ConsumeXml [} 147] Consumes a String containing the TwinCAT 2.11
XML representation of the tree
item, with all its item-specific data
and parameters.
GetLastXmlError [} 152] Gets the error message of the last TwinCAT 2.11
erroneous ConsumeXml() call.
LookupChild [} 152] Searches for a child with the TwinCAT 2.11
specified relative path.

ITcSmTreeItem2 Methods Description Available since


ResoucesCount For interal use only TwinCAT 2.11
ChangeChildSubType Changes the SubType of the TwinCAT 2.11
ITcSmTreeItem.
ClaimResources For internal use only TwinCAT 2.11

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 2.11 and above

5.3.2 ITcSmTreeItem Item Types


Every tree item in TwinCAT System Manager / TwinCAT XAE is being categorized into various groups ,
e.g. devices, boxes, task, ... . You can check the item type of a tree item by manually adding it to TwinCAT
System Manager or XAE and then exporting its XML description via the corresponding menu entry.
• TwinCAT System Manager: Actions --> Export XML description
• TwinCAT XAE: TwinCAT --> Selected item --> Export XML description

In the resulting XML file, the item type is represented by the node <ItemType>.

114 Version: 1.3 Automation Interface


API

General item types

Item type Tag Description


0 TREEITEMTYPE_UNKNOWN ---
1 TREEITEMTYPE_TASK ---
9 TREEITEMTYPE_IECPRJ ---
10 TREEITEMTYPE_CNCPRJ ---
11 TREEITEMTYPE_GSDMOD Module of a Profibus GSD device
12 TREEITEMTYPE_CDL ---
13 TREEITEMTYPE_IECLZS ---
14 TREEITEMTYPE_LZSGRP ---
15 TREEITEMTYPE_IODEF ---
16 TREEITEMTYPE_ADDTASKS ---
17 TREEITEMTYPE_DEVICEGRP ---
18 TREEITEMTYPE_MAPGRP ---
30 TREEITEMTYPE_CANPDO ---
31 TREEITEMTYPE_RTIMESET ---
32 TREEITEMTYPE_BCPLC_VARS ---
33 TREEITEMTYPE_FILENAME ---
34 TREEITEMTYPE_DNETCONNEC ---
T
37 TREEITEMTYPE_FLBCMD ---
43 TREEITEMTYPE_EIPCONNECTI ---
ON
44 TREEITEMTYPE_PNIOAPI ---
45 TREEITEMTYPE_PNIOMOD ---
46 TREEITEMTYPE_PNIOSUBMOD ---
47 TREEITEMTYPE_ETHERNETPR ---
OTOCOL
200 TREEITEMTYPE_CAMDEF ---
201 TREEITEMTYPE_CAMGROUP ---
202 TREEITEMTYPE_CAM ---
203 TREEITEMTYPE_CAMENCODER ---
204 TREEITEMTYPE_CAMTOOLGRP ---
205 TREEITEMTYPE_CAMTOOL ---
300 TREEITEMTYPE_LINEDEF ---
400 TREEITEMTYPE_ISGDEF ---
401 TREEITEMTYPE_ISGCHANNEL ---
402 TREEITEMTYPE_ISGAGROUP ---
403 TREEITEMTYPE_ISGAXIS ---
500 TREEITEMTYPE_RTSCONFIG ---
501 TREEITEMTYPE_RTSAPP ---
502 TREEITEMTYPE_RTSAPPTASK ---
503 TREEITEMTYPE_RTSADI ---
504 TREEITEMTYPE_CPPCONFIG ---
505 TREEITEMTYPE_SPLCCONFIG ---

Automation Interface Version: 1.3 115


API

I/O item types

Item type Tag Description


2 TREEITEMTYPE_DEVICE I/O Device
3 TREEITEMTYPE_IMAGE Process Image
4 TREEITEMTYPE_MAPPING ---
5 TREEITEMTYPE_BOX I/O Box (e.g. "BK2000", child of I/O
Devices)
6 TREEITEMTYPE_TERM I/O Terminal (child of terminal
couplers (box))
7 TREEITEMTYPE_VAR Variable
8 TREEITEMTYPE_VARGRP Variable Group (e.g. "Inputs")
35 TREEITEMTYPE_NVPUBLISHER ---
VAR
36 TREEITEMTYPE_NVSUBSCRIBE ---
RVAR

116 Version: 1.3 Automation Interface


API

PLC item types

Item type Tag Description


600 TREEITEMTYPE_PLCAPP PLC application (root PLC object) 1
601 TREEITEMTYPE_PLCFOLDER PLC folder 1
602 TREEITEMTYPE_PLCPOUPROG POU Program 1
603 TREEITEMTYPE_PLCPOUFUNC POU Function 1
604 TREEITEMTYPE_PLCPOUFB POU Function Block 1
605 TREEITEMTYPE_PLCDUTENUM DUT enum data type 1
606 TREEITEMTYPE_PLCDUTSTRUC DUT struct data type 1
T
607 TREEITEMTYPE_PLCDUTUNION DUT union data type 1
608 TREEITEMTYPE_PLCACTION PLC action 1
609 TREEITEMTYPE_PLCMETHOD PLC method 1
610 TREEITEMTYPE_PLCITFMETH PLC interface method 1
611 TREEITEMTYPE_PLCPROP PLC property 1
612 TREEITEMTYPE_PLCITFPROP PLC interface property 1
613 TREEITEMTYPE_PLCPROPGET PLC property getter 1
614 TREEITEMTYPE_PLCPROPSET PLC property setter 1
615 TREEITEMTYPE_PLCGVL GVL (Global variable list) 1
616 TREEITEMTYPE_PLCTRANS PLC Transition 1
617 TREEITEMTYPE_PLCLIBMAN PLC library manager 1
618 TREEITEMTYPE_PLCITF PLC interface 1
619 TREEITEMTYPE_PLCVISOBJ PLC visual object 1
620 TREEITEMTYPE_PLCVISMAN PLC visual manager 1
621 TREEITEMTYPE_PLCTASK PLC task object 1
622 TREEITEMTYPE_PLCPROGREF PLC program reference 1
623 TREEITEMTYPE_PLCDUTALIAS DUT Alias
624 TREEITEMTYPE_PLCEXTDATAT PLC external data type container 1
YPECONT
625 TREEITEMTYPE_PLCTMCDESC PLC TMC description file 1
RIPTION
654 TREEITEMTYPE_PLCITFPROPG PLC interface property getter
ET
655 TREEITEMTYPE_PLCITFPROPS PLC interface property setter
ET

Automation Interface Version: 1.3 117


API

NC item types

Item type Tag Description


19 TREEITEMTYPE_NCDEF ---
20 TREEITEMTYPE_NCAXISES ---
21 TREEITEMTYPE_NCCHANNEL NC Channel
22 TREEITEMTYPE_NCAXIS NC Axis
23 TREEITEMTYPE_NCENCODER ---
24 TREEITEMTYPE_NCDRIVE ---
25 TREEITEMTYPE_NCCONTROLL ---
ER
26 TREEITEMTYPE_NCGROUP ---
27 TREEITEMTYPE_NCINTERPRET ---
ER
40 TREEITEMTYPE_NCTABLEGRP ---
41 TREEITEMTYPE_NCTABLE ---
42 TREEITEMTYPE_NCTABLESLAV ---
E

Requirements

Notes
1
requires TwinCAT 3.1

5.3.3 Tree item sub types

5.3.3.1 ITcSmTreeItem Item Sub Types


Item sub types specify what kind of device , box or terminal is being used, for example a sub type of 2408
identifies a KL2408 digital output terminal. You can check the sub type of an item by manually adding it in
TwinCAT System Manager or XAE and then export its XML description via the corresponding menu entry.
• TwinCAT System Manager: Actions --> Export XML description
• TwinCAT XAE: TwinCAT --> Selected item --> Export XML description

In the resulting XML file, the sub type is represented by the node <ItemSubType>. In the above example, we
exported the XML description of an EL2008 terminal. The XML file shows that this terminal has a sub type of
9099.

118 Version: 1.3 Automation Interface


API

The following tables will give you a good overview about some of the available sub types. If your devices is
not listed, please perform the above steps to determine the sub type of your specific device.

Shortcuts:
• Devices [} 121]
• Boxes [} 128]
• Terminals: E-Bus [} 119] (ELxxxx)
• Terminals: K-Bus digital input [} 134] (KL1xxx)
• Terminals: K-Bus digital output [} 136] (KL2xxx)
• Terminals: K-Bus analog input [} 139] (KL3xxx)
• Terminals: K-Bus analog output [} 141] (KL4xxx)
• Terminals: K-Bus position measurement [} 141] (KL5xxx)
• Terminals: K-Bus communication [} 142] (KL6xxx)
• Terminals: K-Bus power [} 143] (KL8xxx)
• Terminals: K-Bus safety [} 145] (KLx90x)
• Terminals: K-Bus system [} 144] (KL9xxx)

5.3.3.2 ITcSmTreeItem Item Sub Types: E-Bus


Due to their architecture, E-Bus boxes , terminals and modules will be handled differently than their K-
Bus counterparts, e.g. during creation using the CreateChild() [} 148] method. As each K-Bus terminal will be
specified according to its specific sub type, E-Bus terminals are recognized via one common sub type and
then specified via their "Product Revision " which will be used as the vInfo parameter in the CreateChild()
method.

Sub type Description


9099 Generic sub type for all EtherCAT terminals. In case
of CreateChild() [} 148], a specific terminal will be
defined via vInfo parameter.

There are a few exceptions to this rule, e.g. for RS232 terminals. The following table gives an overview
about these exceptions:

Automation Interface Version: 1.3 119


API

I/O ItemSubType Description


EP6002 9101 RS232 / RS422 / RS485 interface
terminal
EL6001 9101 RS232 interface terminal
EL6002 9101 RS232 interface terminal (2-
Channel)
EL6021 9103 RS422 / RS485 interface terminal
EL6022 9103 RS422 / RS485 interface terminal
(2-Channel)

Code Snippet (C#)

ITcSmTreeItem ek1100 = systemManager.LookupTreeItem("TIID^EtherCAT Master^EK1100");


ek1100.CreateChild("EL2002 - 1", 9099, "", "EL2002-0000-0016");

Product revision

Each E-Bus box/terminal/module has its own product revision, which you can view either by exporting its
XML description [} 25] or in the "Add Device" dialog in TwinCAT XAE.

For example, the EL2002 digital output terminal has the product revision EL2002-0000-0016, as you can
also see in its XML description:

120 Version: 1.3 Automation Interface


API

To get the XML description of a tree item, simply do the following:


• TwinCAT 2: Add the item to System Manager, select it and, from the menu, choose "Actions" -->
"Export XML description"
• TwinCAT 3: Add the item to XAE, select it and, from the menu, choose "TwinCAT" --> "Selected item"
--> "Export XML description"

5.3.3.3 Devices

5.3.3.3.1 ITcSmTreeItem Item Sub Types: Devices

Devices: Miscellaneous

Sub type Tag Description


0 IODEVICETYPE_UNKNOWN ---
6 IODEVICETYPE_BKHFPC Beckhoff Industrial-PC C2001
9 IODEVICETYPE_LPTPORT LPT Port
10 IODEVICETYPE_DPRAM Generic DPRAM
11 IODEVICETYPE_COMPORT COM Port
18 IODEVICETYPE_FCXXXX Beckhoff-FeldbusCard
32 IODEVICETYPE_SMB Motherboard System Management
Bus
43 IODEVICETYPE_BKHFNCBP Beckhoff NC Rückwand
44 IODEVICETYPE_SERCANSPCI Sercos Master (SICAN/IAM PCI)
46 IODEVICETYPE_SERCONPCI Sercon 410B or 816 Chip Master or
Slave (PCI)
53 IODEVICETYPE_BKHFAH2000 Beckhoff AH2000 (Hydraulik
Backplane)
55 IODEVICETYPE_AH2000MC Beckhoff-AH2000 mit Profibus-MC

Automation Interface Version: 1.3 121


API

Devices: Beckhoff CX Terminal Devices

Sub type Tag Description


120 IODEVICETYPE_CX5000 CX5000 Terminal Device
135 IODEVICETYPE_CX8000 CX8000 Terminal Device
105 IODEVICETYPE_CX9000_BK CX9000 Terminal Device
65 IODEVICETYPE_CX1100_BK CX1100 Terminal Device
124 IODEVICETYPE_CCAT Beckhoff CCAT Adapter

Devices: Beckhoff CP Devices

Sub type Tag Description


14 IODEVICETYPE_BKHFCP2030 Beckhoff CP2030 (Pannel-Link)
31 IODEVICETYPE_BKHFCP9030 Beckhoff CP9030 (Pannel-Link with
UPS, ISA)
52 IODEVICETYPE_BKHFCP9040 Beckhoff CP9040 (CP-PC)
54 IODEVICETYPE_BKHFCP9035 Beckhoff CP9035 (Pannel-Link with
UPS, PCI)
116 IODEVICETYPE_BKHFCP6608 Beckhoff CP6608(IXP PC)

Devices: Beckhoff BC/BX Devices

Sub type Tag Description


77 IODEVICETYPE_BX_BK BX Klemmenbus Interface
78 IODEVICETYPE_BX_M510 BX SSB-Master
103 IODEVICETYPE_BC8150 BCXX50 Serial Slave
104 IODEVICETYPE_BX9000 BX9000 Ethernet Slave
107 IODEVICETYPE_BC9050 BC9050 Etherent Slave
108 IODEVICETYPE_BC9120 BC9120 Etherent Slave
110 IODEVICETYPE_BC9020 BC9020 Etherent Slave

Devices: Beckhoff EtherCAT

Sub type Tag Description


94 IODEVICETYPE_ETHERCAT Obsolete: EtherCAT Master. Use
"111" instead.
111 IODEVICETYPE_ETHERCATPRO EtherCAT Master
T
130 IODEVICETYPE_ETHERCATSLV EtherCAT Slave
106 IODEVICETYPE_EL6601 EtherCAT Automation Protocol via
EL6601
112 IODEVICETYPE_ETHERNETNVP EtherCAT Automation Protocol
ROT (Network variables)

122 Version: 1.3 Automation Interface


API

Devices: Beckhoff Lightbus Master/Slave

Sub type Tag Description


67 IODEVICETYPE_CX1500_M200 PC104 Lightbus-Master
68 IODEVICETYPE_CX1500_B200 PC104 Lightbus-Slave
36 IODEVICETYPE_FC200X Beckhoff-Lightbus-I/II-PCI-Card
114 IODEVICETYPE_EL6720 Beckhoff-Lightbus-EtherCAT-
Klemme
1 IODEVICETYPE_C1220 Beckhoff Lightbus ISA interface
card C1220
2 IODEVICETYPE_C1200 Beckhoff Lightbus ISA interface
card C1200

Devices: Beckhoff Profibus Master/Slave

Sub type Tag Description


69 IODEVICETYPE_CX1500_M310 PC104 ProfiBus-Master
70 IODEVICETYPE_CX1500_B310 PC104 ProfiBus-Slave
33 IODEVICETYPE_PBMON Beckhoff-PROFIBUS-Monitor
38 IODEVICETYPE_FC3100 Beckhoff-Profibus-PCI-Card
56 IODEVICETYPE_FC3100MON Beckhoff-Profibus-Monitor-PCI-
Karte
60 IODEVICETYPE_FC3100SLV Beckhoff-Profibus-PCI-Karte als
Slave
79 IODEVICETYPE_BX_B310 BX ProfiBus-Slave
83 IODEVICETYPE_BC3150 BCxx50 ProfiBus-Slave
86 IODEVICETYPE_EL6731 Beckhoff-Profibus-EtherCAT-
Klemme
97 IODEVICETYPE_EL6731SLV Beckhoff-Profibus-Slave-
EtherCAT-Klemme

Devices: Beckhoff CANopen Master/Slave

Sub type Tag Description


71 IODEVICETYPE_CX1500_M510 PC104 CANopen-Master
72 IODEVICETYPE_CX1500_B510 PC104 CANopen-Slave
39 IODEVICETYPE_FC5100 Beckhoff-CanOpen-PCI-Card
58 IODEVICETYPE_FC5100MON Beckhoff-CANopen-Monitor-PCI-
Karte
61 IODEVICETYPE_FC5100SLV Beckhoff-CanOpen-PCI-Karte als
Slave
81 IODEVICETYPE_BX_B510 BX CANopen-Slave
84 IODEVICETYPE_BC5150 BCxx50 CANopen-Slave
87 IODEVICETYPE_EL6751 Beckhoff-CanOpen-EtherCAT-
Klemme
98 IODEVICETYPE_EL6751SLV Beckhoff-CanOpen-Slave-
EtherCAT-Klemme

Automation Interface Version: 1.3 123


API

Devices: Beckhoff DeviceNet Master/Slave

Sub type Tag Description


73 IODEVICETYPE_CX1500_M520 PC104 DeviceNet-Master
74 IODEVICETYPE_CX1500_B520 PC104 DeviceNet-Slave
41 IODEVICETYPE_FC5200 Beckhoff-DeviceNet-PCI-Card
59 IODEVICETYPE_FC5200MON Beckhoff-DeviceNet-Monitor-PCI-
Karte
62 IODEVICETYPE_FC5200SLV Beckhoff-DeviceNet-PCI-Karte als
Slave
82 IODEVICETYPE_BX_B520 BX DeviceNet-Slave
85 IODEVICETYPE_BC5250 BCxx50 DeviceNet-Slave
88 IODEVICETYPE_EL6752 Beckhoff-DeviceNet-EtherCAT-
Klemme
99 IODEVICETYPE_EL6752SLV Beckhoff-DeviceNet-Slave-
EtherCAT-Klemme

Devices: Beckhoff Sercos Master/Slave

Sub type Tag Description


75 IODEVICETYPE_CX1500_M750 PC104 Sercos-Master
76 IODEVICETYPE_CX1500_B750 PC104 Sercos-Slave
48 IODEVICETYPE_FC7500 Beckhoff-SERCOS-PCI-Card

Devices: Ethernet

Sub type Tag Description


66 IODEVICETYPE_ENETRTMP Ethernet Real Time Miniport
109 IODEVICETYPE_ENETADAPTER Real-Time Ethernet Adapter
(Multiple Protocol Handler)
138 --- Real-Time Ethernet Protocol
(BK90xx, AX2000-B900)
45 IODEVICETYPE_ETHERNET Virtual Ethernet Interface

Devices: USB

Sub type Tag Description


57 IODEVICETYPE_USB Virtual USB Interface
125 --- Virtual USB Interface (Remote)

124 Version: 1.3 Automation Interface


API

Devices: Hilscher

Automation Interface Version: 1.3 125


API

Sub type Tag Description


4 IODEVICETYPE_CIF30DPM ISA ProfiBus-Master 2 kByte
(Hilscher Card)
5 IODEVICETYPE_CIF40IBSM ISA Interbus-S-Master 2 kByte
(Hilscher-Card)
12 IODEVICETYPE_CIF30CAN ISA CANopen-Master (Hilscher-
Card)
13 IODEVICETYPE_CIF30PB ISA ProfiBus-Master 8 kByte
(Hilscher-Card)
16 IODEVICETYPE_CIF30IBM ISA Interbus-S-Master (Hilscher-
Card)
17 IODEVICETYPE_CIF30DNM ISA DeviceNet-Master (Hilscher-
Card)
19 IODEVICETYPE_CIF50PB PCI ProfiBus-Master 8 kByte
(Hilscher-Card)
20 IODEVICETYPE_CIF50IBM PCI Interbus-S-Master (Hilscher-
Card)
21 IODEVICETYPE_CIF50DNM PCI DeviceNet-Master (Hilscher-
Card)
22 IODEVICETYPE_CIF50CAN PCI CANopen-Master (Hilscher-
Card)
23 IODEVICETYPE_CIF60PB PCMCIA ProfiBus-Master
(Hilscher-Card)
24 IODEVICETYPE_CIF60DNM PCMCIA DeviceNet-Master
(Hilscher-Card)
25 IODEVICETYPE_CIF60CAN PCMCIA CANopen-Master
(Hilscher-Card)
26 IODEVICETYPE_CIF104DP PC104 ProfiBus-Master 2 kByte
(Hilscher-Card)
27 IODEVICETYPE_C104PB PC104 ProfiBus-Master 8 kByte
(Hilscher-Card)
28 IODEVICETYPE_C104IBM PC104 Interbus-S-Master 2 kByte
(Hilscher-Card)
29 IODEVICETYPE_C104CAN PC104 CANopen-Master (Hilscher-
Card)
30 IODEVICETYPE_C104DNM PC104 DeviceNet-Master
(Hilscher-Card)
35 IODEVICETYPE_CIF60IBM PCMCIA Interbus-S-Master
(Hilscher-Card)
49 IODEVICETYPE_CIF30IBS ISA Interbus-S-Slave (Hilscher-
Card)
50 IODEVICETYPE_CIF50IBS PCI Interbus-S-Slave (Hilscher-
Card)
51 IODEVICETYPE_C104IBS PC104 Interbus-S-Slave (Hilscher-
Card)
89 IODEVICETYPE_COMPB COM ProfiBus-Master 8 kByte
(Hilscher-Karte)
90 IODEVICETYPE_COMIBM COM Interbus-S-Master (Hilscher-
Karte)
91 IODEVICETYPE_COMDNM COM DeviceNet-Master (Hilscher-
Karte)
92 IODEVICETYPE_COMCAN COM CANopen-Master (Hilscher-
Karte)
93 IODEVICETYPE_COMIBS COM CANopen-Slave (Hilscher-
Karte)

126 Version: 1.3 Automation Interface


API

Sub type Tag Description


100 IODEVICETYPE_C104PPB PC104+ ProfiBus-Master 8 kByte
(Hilscher-Karte)
101 IODEVICETYPE_C104PCAN PC104+ CANopen-Master
(Hilscher-Karte)
102 IODEVICETYPE_C104PDNM PC104+ DeviceNet-Master
(Hilscher-Karte)

Devices: Profinet / Profibus

Sub type Tag Description


3 IODEVICETYPE_SPC3 ProfiBus Slave (Siemens Card)
7 IODEVICETYPE_CP5412A2 ProfiBus-Master (Siemens-Card)
34 IODEVICETYPE_CP5613 PCI ProfiBus-Master (Siemens-
Card)
113 IODEVICETYPE_PROFINETIOCO PROFINET Master
NTROLLER
115 IODEVICETYPE_PROFINETIODE PROFINET Slave
VICE

Devices: Indramat

Sub type Tag Description


8 IODEVICETYPE_SERCANSISA Sercos Master (Indramat)

Devices: Phoenix

Sub type Tag Description


15 IODEVICETYPE_IBSSCIT Interbus-S-Master (Phoenix-Card)
47 IODEVICETYPE_IBSSCRIRTLK Interbus-S-Master with Slave-Part
LWL Basis (Phoenix-Card)
63 IODEVICETYPE_IBSSCITPCI PCI Interbus-S-Master (Phoenix-
Karte)
64 IODEVICETYPE_IBSSCRILKPCI PCIInterbus-S-Master mit Slave-
Teil auf LWL Basis (Phoenix-Karte)
80 IODEVICETYPE_IBSSCRIRTPCI PCIInterbus-S-Master mit Slave-
Teil auf Kupfer Basis (Phoenix-
Karte)

Automation Interface Version: 1.3 127


API

5.3.3.4 Boxes

5.3.3.4.1 ITcSmTreeItem Item Sub Types: Boxes

128 Version: 1.3 Automation Interface


API

Sub type Tag Description


0 BOXTYPE_UNKNOWN ---
1 BOXTYPE_BK2000 BK2000 Lightbus coupler
2 BOXTYPE_M1400 M1400 Lightbus digital input/output
module
3 BOXTYPE_M2400 M2400 Lightbus input/output
module
4 BOXTYPE_M3120_1 M3120 Lightbus incremental
encoder interface
5 BOXTYPE_M3120_2 M3120 Lightbus incremental
encoder interface
6 BOXTYPE_M3120_3 M3120 Lightbus incremental
encoder interface
7 BOXTYPE_M3120_4 M3120 Lightbus incremental
encoder interface
8 BOXTYPE_M3000 M3000 absolute / incremental
encoder
9 BOXTYPE_C1120 ---
10 BOXTYPE_BK2010 BK2010 Lightbus coupler
11 BOXTYPE_AX2000 ---
12 BOXTYPE_M2510 ---
20 BOXTYPE_BK2020 BK2020 Lightbus coupler
21 BOXTYPE_BC2000 ---
31 BOXTYPE_FOX20 ---
32 BOXTYPE_FOX50 ---
33 BOXTYPE_FOXRK001 ---
34 BOXTYPE_FOXRK002 ---
35 BOXTYPE_CP1001 ---
40 BOXTYPE_IPXB2 ---
41 BOXTYPE_ILXB2 ---
42 BOXTYPE_ILXC2 ---
50 BOXTYPE_TSMBOX_200 ---
51 BOXTYPE_BX2000 ---
52 BOXTYPE_CX1500_B200 ---
1001 BOXTYPE_BK3000 ---
1002 BOXTYPE_BK3100 ---
1003 BOXTYPE_PBDP_GSD ---
1004 BOXTYPE_BK3010 ---
1005 BOXTYPE_BK3110 ---
1006 BOXTYPE_BK3500 ---
1007 BOXTYPE_LC3100 ---
1008 BOXTYPE_PBDP_DRIVE ---
1009 BOXTYPE_BK3020 ---
1010 BOXTYPE_BK3120 ---
1011 BOXTYPE_BC3100 ---
1012 BOXTYPE_PBDP_DRIVE2 ---
1013 BOXTYPE_PBDP_DRIVE3 ---
1014 BOXTYPE_PBDP_DRIVE4 ---
1015 BOXTYPE_PBDP_DRIVE5 ---
1016 BOXTYPE_PBDP_DRIVE6 ---
1017 BOXTYPE_PBDP_DRIVE7 ---

Automation Interface Version: 1.3 129


API

Sub type Tag Description


1018 BOXTYPE_PBDP_DRIVE8 ---
1019 BOXTYPE_BK3150 ---
1020 BOXTYPE_BC3150 ---
1021 BOXTYPE_BK3XXX ---
1022 BOXTYPE_BC3XXX ---
1030 BOXTYPE_IPXB3 ---
1031 BOXTYPE_ILXB3 ---
1032 BOXTYPE_ILXC3 ---
1040 BOXTYPE_TSMBOX_310 ---
1041 BOXTYPE_BX3100 ---
1042 BOXTYPE_CX1500_B310 ---
1043 BOXTYPE_FC310X_SLAVE ---
1044 BOXTYPE_EL6731_SLAVE ---
1051 BOXTYPE_AX2000_B310 ---
1100 BOXTYPE_TCPBDPSLAVE ---
1101 BOXTYPE_TCFDLAGAG ---
1102 BOXTYPE_TCMPI ---
1103 BOXTYPE_TCPBMCSLAVE ---
1104 BOXTYPE_TCPBMCSLAVE2 ---
1105 BOXTYPE_TCPBMCSLAVE3 ---
1106 BOXTYPE_TCPBMCSLAVE4 ---
1107 BOXTYPE_TCPBMCSLAVE5 ---
1108 BOXTYPE_TCPBMCSLAVE6 ---
1109 BOXTYPE_TCPBMCSLAVE7 ---
1110 BOXTYPE_TCPBMCSLAVE8 ---
1111 BOXTYPE_TCPBMONSLAVE ---
2001 BOXTYPE_BK4000 ---
2002 BOXTYPE_IBS_GENERIC ---
2003 BOXTYPE_IBS_BK ---
2004 BOXTYPE_BK4010 ---
2005 BOXTYPE_BK4500 ---
2006 BOXTYPE_BK4510 ---
2007 BOXTYPE_IBS_SLAVEBOX ---
2008 BOXTYPE_BC4000 ---
2009 BOXTYPE_BK4020 ---
2020 BOXTYPE_CP2020 ---
2030 BOXTYPE_IPXB4 ---
2031 BOXTYPE_ILXB4 ---
2032 BOXTYPE_ILXC4 ---
3001 BOXTYPE_SERCOSAXIS ---
3011 BOXTYPE_BK7500 ---
3012 BOXTYPE_BK7510 ---
3013 BOXTYPE_BK7520 ---
3021 BOXTYPE_SERCOSMASTERBO ---
X
3031 BOXTYPE_SERCOSSLAVEBOX ---
4001 BOXTYPE_BK8100 BK8100 bus coupler
4002 BOXTYPE_BK8110 BK8110 bus coupler
4003 BOXTYPE_BK8000 BK8000 bus coupler

130 Version: 1.3 Automation Interface


API

Sub type Tag Description


4004 BOXTYPE_BK8010 BK8010 bus coupler
4005 BOXTYPE_CP9040 CP9040 PCB
4011 BOXTYPE_BC8000 BC8000 bus terminal controller
4012 BOXTYPE_BC8100 BC8100 bus terminal controller
4030 BOXTYPE_IPXB80 ---
4031 BOXTYPE_ILXB80 ---
4032 BOXTYPE_ILXC80 ---
4040 BOXTYPE_IPXB81 ---
4041 BOXTYPE_ILXB81 ---
4042 BOXTYPE_ILXC81 ---
4050 BOXTYPE_BC8150 BC8150 bus terminal controller
5001 BOXTYPE_BK5100 BK5100 bus coupler
5002 BOXTYPE_BK5110 BK5110 bus coupler
5003 BOXTYPE_CANNODE ---
5004 BOXTYPE_BK5120 BK5120 bus coupler
5005 BOXTYPE_LC5100 ---
5006 BOXTYPE_CANDRIVE ---
5007 BOXTYPE_AX2000_B510 ---
5008 BOXTYPE_BK5150 BK5150 bus coupler
5009 BOXTYPE_BK5151 BK5151 bus coupler
5011 BOXTYPE_BC5150 BC5150 bus terminal controller
5030 BOXTYPE_IPXB51 ---
5031 BOXTYPE_ILXB51 ---
5032 BOXTYPE_ILXC51 ---
5040 BOXTYPE_TSMBOX_510 ---
5041 BOXTYPE_BX5100 BX5100 CANopen bus terminal
controller
5042 BOXTYPE_CX1500_B510 ---
5043 BOXTYPE_FC510XSLV ---
5050 BOXTYPE_TCCANSLAVE ---
5051 BOXTYPE_CANQUEUE CAN Interface
5201 BOXTYPE_BK5200 ---
5202 BOXTYPE_BK5210 ---
5203 BOXTYPE_DEVICENET ---
5204 BOXTYPE_BK5220 ---
5205 BOXTYPE_LC5200 ---
5211 BOXTYPE_BK52XX ---
5212 BOXTYPE_BC52XX ---
5230 BOXTYPE_IPXB52 ---
5231 BOXTYPE_ILXB52 ---
5232 BOXTYPE_ILXC52 ---
5250 BOXTYPE_TCDNSLAVE ---
9001 BOXTYPE_BK9000 BK9000 Ethernet TCP/IP bus
coupler
9002 BOXTYPE_BK9100 BK9100 Ethernet TCP/IP bus
coupler
9005 BOXTYPE_BK9050 BK9050 Ethernet TCP/IP bus
coupler
9011 BOXTYPE_BC9000 BC9000 Ethernet TCP/IP bus
terminal controller

Automation Interface Version: 1.3 131


API

Sub type Tag Description


9012 BOXTYPE_BC9100 BC9100 Ethernet TCP/IP bus
terminal controller
9013 BOXTYPE_BX9000 BX9000 Ethernet TCP/IP bus
terminal controller
9014 BOXTYPE_BX9000SLV ---
9015 BOXTYPE_BC9050 BC9050 Ethernet TCP/IP bus
terminal controller
9016 BOXTYPE_BC9050SLV BC9050 Ethernet TCP/IP bus
terminal controller slave
9017 BOXTYPE_BC9120 BC9120 Ethernet TCP/IP bus
terminal controller
9018 BOXTYPE_BC9120SLV BC9120 Ethernet TCP/IP bus
terminal controller slave
9019 BOXTYPE_BC9020 BC9020 Ethernet TCP/IP bus
terminal controller
9020 BOXTYPE_BC9020SLV BC9020 Ethernet TCP/IP bus
terminal controller slave
9030 BOXTYPE_IPXB9 ---
9031 BOXTYPE_ILXB9 ---
9032 BOXTYPE_ILXC9 ---
9041 BOXTYPE_REMOTETASK ---
9051 BOXTYPE_NV_PUB Network Publisher.
9052 BOXTYPE_NV_SUB Network Subscriber.
9053 BOXTYPE_NV_PUBVAR Publisher variable.
9054 BOXTYPE_NV_SUBVAR Subscriber variable.
9055 BOXTYPE_NV_PUBDATA Publisher data object.
9056 BOXTYPE_NV_SUBDATA Subscriber data object.
9061 BOXTYPE_AX2000_B900 ---
9071 BOXTYPE_FLB_FRAME ---
9081 BOXTYPE_BK1120 ---
9085 BOXTYPE_IPXB11 ---
9086 BOXTYPE_ILXB11 ---
9087 BOXTYPE_ILXC11 ---
9105 BOXTYPE_FSOESLAVE ---
9121 BOXTYPE_PNIODEVICE ---
9122 BOXTYPE_PNIOTCDEVICE ---
9123 BOXTYPE_PNIODEVICEINTF Profinet TwinCAT Device Interface
9124 BOXTYPE_PNIO_DRIVE ---
9125 BOXTYPE_PNIOBK9103 ---
9126 BOXTYPE_PNIOILB903 ---
9132 BOXTYPE_BK9053 BK9053 K-Bus coupler, PROFINET
IO RT
9133 BOXTYPE_EIPSLAVEINTF ---
9143 BOXTYPE_PTPSLAVEINTF ---
9151 BOXTYPE_RAWUDPINTF ---
9500 BOXTYPE_BK9500 BK9500
9510 BOXTYPE_BK9510 BK9510
9520 BOXTYPE_BK9520 BK9520
9591 BOXTYPE_CPX8XX ---
9700 BOXTYPE_CX1102 ---

132 Version: 1.3 Automation Interface


API

Sub type Tag Description


9701 BOXTYPE_CX1103 ---
9702 BOXTYPE_CX1190 ---

Automation Interface Version: 1.3 133


API

5.3.3.5 Terminals

5.3.3.5.1 ITcSmTreeItem Item Sub Types: Terminals: K-Bus digital input (KL1)

134 Version: 1.3 Automation Interface


API

Sub type Description


1002 KL1002 2-Channel digital input terminal
1012 KL1012 2-Channel digital input terminal
1032 KL1032 2-Channel digital input terminal
1052 KL1052 2-Channel digital input terminal
1104 KL1104 4-Channel digital input terminal
1114 KL1114 4-Channel digital input terminal
1124 KL1124 4-Channel digital input terminal
1154 KL1154 4-Channel digital input terminal
1164 KL1164 4-Channel digital input terminal
1184 KL1184 4-Channel digital input terminal
1194 KL1194 4-Channel digital input terminal
1212 KL1212 2-Channel digital input terminal
1232 KL1232 2-Channel digital input terminal
1302 KL1302 2-Channel digital input terminal
1304 KL1304 4-Channel digital input terminal
1312 KL1312 2-Channel digital input terminal
1314 KL1314 4-Channel digital input terminal
1352 KL1352 2-Channel digital input terminal
1362 KL1362 2-Channel digital input terminal
1382 KL1382 2-Channel digital input terminal
1402 KL1402 2-Channel digital input terminal
1404 KL1404 4-Channel digital input terminal
1408 KL1408 8-Channel digital input terminal
1412 KL1412 2-Channel digital input terminal
1414 KL1414 4-Channel digital input terminal
1418 KL1418 8-Channel digital input terminal
1434 KL1434 4-Channel digital input terminal
1488 KL1488 8-Channel digital input terminal
1498 KL1498 8-Channel digital input terminal
1501 KL1501 1-Channel digital input terminal
1512 KL1512 2-Channel digital input terminal
1702 KL1702 2-Channel digital input terminal
1712 KL1712 2-Channel digital input terminal
16778928 KL1712-0060 2-Channel digital input terminal
1722 KL1722 2-Channel digital input terminal
1804 KL1804 4-Channel digital input terminal
1808 KL1808 8-Channel digital input terminal
1809 KL1809 16-Channel digital input terminal
1814 KL1814 4-Channel digital input terminal
1819 KL1819 16-Channel digital input terminal
1859 KL1859 8-Channel digital input terminal
1862 KL1862 16-Channel digital input terminal
16779078 KL1862-0010 16-Channel digital input terminal
1872 KL1872 16-Channel digital input terminal
1889 KL1889 16-Channel digital input terminal
1202 KL1202 2-Channel digital input terminal

Automation Interface Version: 1.3 135


API

5.3.3.5.2 ITcSmTreeItem Item Sub Types: Terminals: K-Bus digital output (KL2)

136 Version: 1.3 Automation Interface


API

Sub type Description


2408 KL2408 8-Channel digital output terminal
2012 KL2012 2-Channel digital output terminal
2022 KL2022 2-Channel digital output terminal
2032 KL2032 2-Channel digital output terminal
2114 KL2114 4-Channel digital output terminal
2124 KL2124 4-Channel digital output terminal
2134 KL2134 4-Channel digital output terminal
2184 KL2184 4-Channel digital output terminal
2212 KL2212 2-Channel digital output terminal
2404 KL2404 4-Channel digital output terminal
2212 KL2212 2-Channel digital output terminal
2404 KL2404 4-Channel digital output terminal
2408 KL2408 8-Channel digital output terminal
2284 KL2284 4-Channel digital output terminal
2424 KL2424 4-Channel digital output terminal
2442 KL2442 2-Channel digital output terminal
2488 KL2488 8-Channel digital output terminal
2502 KL2502 2-Channel PWM output terminal
2512 KL2512 2-Channel PWM output terminal
2521 KL2521 1-Channel Pulse Train output terminal
2531 KL2531 1-Channel Stepper Motor terminal
16779747 KL2531-1000 1-Channel Stepper Motor terminal
2532 KL2532 2-Channel DC Motor amplifier output
terminal
2535 KL2535 2-Channel PWM amplifier output terminal
2541 KL2541 1-Channel Stepper Motor terminal
16779757 KL2541-1000 1-Channel Stepper Motor terminal
2542 KL2542 2-Channel DC Motor amplifier terminal
2545 KL2545 2-Channel PWM amplifier output terminal
2552 KL2552 2-Channel DC Motor amplifier terminal
2602 KL2602 2-Channel output relay terminal
2612 KL2612 2-Channel output relay terminal
2622 KL2622 2-Channel output relay terminal
2631 KL2631 1-Channel power output relay terminal
2641 KL2641 1-Channel power output relay terminal
2652 KL2652 2-Channel power output relay terminal
2701 KL2701 1-Channel solid state load relay terminal
2702 KL2702 2-Channel output solid sate relay terminal
16779918 KL2702-0002 2-Channel output solid state relay
terminal
33557134 KL2702-0020 2-Channel output solid state relay
terminal
2712 KL2712 2-Channel triac output terminal
2722 KL2722 2-Channel triac output terminal
2732 KL2732 2-Channel triac output terminal
2744 KL2744 4-Channel output solid state relay
2751 KL2751 1-Channel universal dimmer terminal
33557183 KL2751-1200 1-Channel universal dimmer terminal
2761 KL2761 1-Channel universal dimmer terminal

Automation Interface Version: 1.3 137


API

Sub type Description


2784 KL2784 4-Channel output terminal
2791 KL2791 1-Channel speed controller terminal
33557223 KL2791-1200 1-Channel speed controller terminal
2794 KL2794 4-Channel output terminal
2808 KL2808 8-Channel output terminal
2809 KL2809 16-Channel output terminal
2872 KL2872 16-Channel output terminal
2889 KL2889 16-Channel output terminal

138 Version: 1.3 Automation Interface


API

5.3.3.5.3 ITcSmTreeItem Item Sub Types: Terminals: K-Bus analog input (KL3)

Automation Interface Version: 1.3 139


API

Sub type Description


3001 KL3001 1-Channel analog input terminal
3002 KL3002 3-Channel analog input terminal
3011 KL3011 1-Channel analog input terminal
3012 KL3012 2-Channel analog input terminal
3021 KL3021 1-Channel analog input terminal
3022 KL3022 2-Channel analog input terminal
3041 KL3041 1-Channel analog input terminal
3042 KL3042 2-Channel analog input terminal
3044 KL3044 4-Channel analog input terminal
3051 KL3051 1-Channel analog input terminal
3052 KL3052 2-Channel analog input terminal
3054 KL3054 4-Channel analog input terminal
3061 KL3061 1-Channel analog input terminal
3062 KL3062 2-Channel analog input terminal
3064 KL3064 4-Channel analog input terminal
3102 KL3102 2-Channel analog input terminal
3112 KL3112 2-Channel analog input terminal
3122 KL3122 2-Channel analog input terminal
3132 KL3132 2-Channel analog input terminal
3142 KL3142 2-Channel analog input terminal
3152 KL3152 2-Channel analog input terminal
3158 KL3158 8-Channel analog input terminal
3162 KL3162 2-Channel analog input terminal
3172 KL3172 2-Channel analog input terminal
33557604 KL3172-0500 2-Channel analog input terminal
67112036 KL3172-1000 2-Channel analog input terminal
3182 KL3182 2-Channel analog input terminal
3201 KL3201 1-Channel analog input terminal
3202 KL3202 2-Channel analog input terminal
3204 KL3204 4-Channel analog input terminal
33557640 KL3208-0010 8-Channel analog input terminal
3222 KL3222 2-Channel analog input terminal
3228 KL3228 8-Channel analog input terminal
3302 KL3302 2-Channel analog input terminal
3311 KL3311 1-Channel analog input terminal
3312 KL3312 2-Channel analog input terminal
3314 KL3314 4-Channel analog input terminal
3351 KL3351 1-Channel resistor bridge terminal
50334999 KL3351-0001 1-Channel resistor bridge terminal
3356 KL3356 1-Channel precise resistor bridge terminal
3361 KL3361 1-Channel oscilloscope terminal
3362 KL3362 2-Channel oscilloscope terminal
3403 KL3403 3-Phase power measuring terminal
3404 KL3404 4-Channel analog input terminal
3408 KL3408 8-Channel analog input terminal
3444 KL3444 4-Channel analog input terminal
3448 KL3448 8-Channel analog input terminal
3454 KL3454 4-Channel analog input terminal

140 Version: 1.3 Automation Interface


API

Sub type Description


3458 KL3458 8-Channel analog input terminal
3464 KL3464 4-Channel analog input terminal
3468 KL3468 8-Channel analog input terminal

5.3.3.5.4 ITcSmTreeItem Item Sub Types: Terminals: K-Bus analog output (KL4)
Sub type Description
4001 KL4001 1-Channel analog output terminal
4002 KL4002 2-Channel analog output terminal
4004 KL4004 4-Channel analog output terminal
4011 KL4011 1-Channel analog output terminal
4012 KL4012 2-Channel analog output terminal
4021 KL4021 1-Channel analog output terminal
4022 KL4022 2-Channel analog output terminal
4031 KL4031 1-Channel analog output terminal
4032 KL4032 2-Channel analog output terminal
4034 KL4034 4-Channel analog output terminal
4112 KL4112 2-Channel analog output terminal
4122 KL4122 2-Channel analog output terminal
4132 KL4132 2-Channel analog output terminal
4404 KL4404 4-Channel analog output terminal
4408 KL4408 8-Channel analog output terminal
4414 KL4414 4-Channel analog output terminal
4418 KL4418 8-Channel analog output terminal
4424 KL4424 4-Channel analog output terminal
4428 KL4428 8-Channel analog output terminal
4434 KL4434 4-Channel analog output terminal
4438 KL4438 8-Channel analog output terminal
4494 KL4494 2-Channel analog output terminal

5.3.3.5.5 ITcSmTreeItem Item Sub Types: Terminals: K-Bus measuring (KL5)


Sub type Description
5001 KL5001 1-Channel SSI encoder terminal
5051 KL5051 1-Channel Bi-SSI encoder terminal
16782267 KL5051-0010 1-Channel Bi-SSI encoder terminal
5101 KL5101 incremental encoder 5V terminal
5111 KL5111 incremental encoder 24V terminal
5121 KL5121 4-Channel line-motion-controller terminal
5151 KL5151 1-Channel incremental encoder terminal
33559583 KL5151-0021 1-Channel incremental encoder
terminal
16782367 KL5151-0050 2-Channel incremental encoder
terminal
5152 KL5152 2-Channel incremental encoder terminal

Automation Interface Version: 1.3 141


API

5.3.3.5.6 ITcSmTreeItem Item Sub Types: Terminals: K-Bus communication (KL6)


Sub type Description
16783217 KL6001 interface RS232C terminal
50337649 KL6001 interface RS232 terminal
16783227 KL6011 interface TTY terminal
50337659 KL6011 interface TTY terminal
16783237 KL6021 interface RS422/485 terminal
50337669 KL6021 interface RS485 terminal
100669317 KL6021 interface RS485 terminal
100669327 KL6031 interface RS232 terminal
50337679 KL6031 interface RS232 terminal
100669337 KL6041 interface RS485 terminal
50337689 KL6041 interface RS485 terminal
16783257 KL6041-0100 interface RS485 terminal
6051 KL6051 data exchange terminal
335550521 KL6201 ASI-Master terminal
369104953 KL6201 ASI-Master terminal
402659385 KL6201 ASI-Master terminal
335550531 KL6211 ASI-Master terminal
369104963 KL6211 ASI-Master terminal
402659395 KL6211 ASI-Master terminal
6224 KL6224 I/O-Link Master terminal
16783440 KL6224 I/O-Link Master terminal
33560656 KL6224 I/O-Link Master terminal
50337872 KL6224 I/O-Link Master terminal
33560733 KL6301 EIB terminal
33560833 KL6401 LON terminal
33561013 KL6581 EnOcean terminal
33561203 KL6771 MP-Bus Master terminal
6781 KL6781 M-Bus interface terminal
6811 KL6811 DALI-Master terminal
6821 KL6821 eDALI-Master terminal

142 Version: 1.3 Automation Interface


API

5.3.3.5.7 ITcSmTreeItem Item Sub Types: Terminals: K-Bus power (KL8)


Sub type Description
33562433 KL8001 1-Channel power terminal
8001 KL8001 3-Channel power terminal
8519 KL8519 16 digital input terminal
8524 KL8524 2x4 digital output terminal
8528 KL8528 8 digital output terminal
8548 KL8548 8-Channel analog output terminal
8610 KL8610 1-Channel adapter terminal KL8601
16785826 KL8610 2-Channel adapter terminal KL8601
33563042 KL8610 3-Channel adapter terminal KL8601
50340258 KL8610 4-Channel adapter terminal KL8601
67117474 KL8610 5-Channel adapter terminal KL8601
83894690 KL8610 6-Channel adapter terminal KL8601
100671906 KL8610 7-Channel adapter terminal KL8601
117449122 KL8610 8-Channel adapter terminal KL8601

Automation Interface Version: 1.3 143


API

5.3.3.5.8 ITcSmTreeItem Item Sub Types: Terminals: K-Bus system (KL9)


Sub type Description
9010 KL9010 end terminal
9020 KL9020 bus extension end terminal
9050 KL9050 bus extension coupler terminal
9060 KL9060 adapter terminal
9070 KL9070 shield terminal
9080 KL9080 separation terminal
9100 KL9100 power supplier terminal
9110 KL9110 power supplier terminal
9150 KL9150 power supplier terminal
9160 KL9160 power supplier terminal
9180 KL9180 potential connection terminal
9181 KL9181 potential connection terminal
9182 KL9182 potential connection terminal
9183 KL9183 potential connection terminal
9184 KL9184 potential connection terminal
9185 KL9185 potential connection terminal
9186 KL9186 potential connection terminal
9187 KL9187 potential connection terminal
9188 KL9188 potential connection terminal
9189 KL9189 potential connection terminal
9190 KL9190 power feed terminal
9195 KL9195 shield terminal
9200 KL9200 power supplier terminal
9210 KL9210 power supplier terminal
9250 KL9250 power supplier terminal
9260 KL9260 power supplier terminal
9290 KL9290 power supplier terminal
9300 KL9300 4-Channel diode array terminal
9301 KL9301 7-Channel diode array terminal
9302 KL9302 7-Channel diode array terminal
9309 KL9309 interface terminal for KL85xx
9400 KL9400 K-Bus power supplier terminal
9505 KL9505 power supplier terminal
167781665 KL9505-0010 power suppler terminal
9508 KL9508 power supplier terminal
167781668 KL9508-0010 power supplier terminal
9510 KL9510 power supplier terminal
167781670 KL9510-0010 power supplier terminal
9512 KL9512 power supplier terminal
167781672 KL9512-0010 power supplier terminal
9515 KL9515 power supplier terminal
167781675 KL9515-0010 power supplier terminal
9528 KL9528 power supplier terminal
9540 KL9540 surge filter field supply terminal
9550 KL9550 surge filter system and field supply terminal
9560 KL9560 power supplier terminal
9570 KL9570 buffer capacitor terminal

144 Version: 1.3 Automation Interface


API

5.3.3.5.9 ITcSmTreeItem Item Sub Types: Terminals: K-Bus safety (KLx90x)


Sub type Description
1904 KL1904 4-Channel safety input terminal
1908 KL1908 8-Channel safety input terminal
2904 KL2904 4-Channel safety output terminal
6904 KL6904 safety logic (7 TwinSAFE connections)
terminal
16784120 KL6904 safety logic (15 TwinSAFE connections)
terminal

5.3.3.6 Modules

5.3.3.6.1 ITcSmTreeItem Item Sub Types: Modules: K-Bus digital input (KM1)
Sub type Description
838861802 KM1002 16-Channel digital input module
838861804 KM1004 32-Channel digital input module
838861808 KM1008 64-Channel digital input module
838861812 KM1012 16-Channel digital input module
838861814 KM1014 32-Channel digital input module
838861818 KM1018 64-Channel digital input module
838862444 KM1644 4-Channel digital input module

5.3.3.6.2 ITcSmTreeItem Item Sub Types: Modules: K-Bus digital output (KM2)
Sub type Description
838862802 KM2002 16-Channel digital output module
838862804 KM2004 32-Channel digital output module
838862808 KM2008 64-Channel digital output module
838862822 KM2022 16-Channel digital output module
838862842 KM2042 16-Channel digital output module
838863404 KM2604 4-Channel digital output relay module
838863414 KM2614 4-Channel digital output relay module
838863442 KM2642 2-Channel digital power output relay module
838863452 KM2652 2-Channel digital power output relay module
16779990 KM2774 4-Channel blinds control terminal
2774 KM2774-1001 4-Channel blinds control terminal

5.3.3.6.3 ITcSmTreeItem Item Sub Types: Modules: K-Bus analog input (KM3)
Sub type Description
838864501 KM3701 1-Channel differential pressure measuring
872418933 KM3701-0340 1-Channel differential pressure
measuring
838864502 KM3702 2-Channel absolute pressure measuring
838864512 KM3712 2-Channel absolute pressure measuring

Automation Interface Version: 1.3 145


API

5.3.3.6.4 ITcSmTreeItem Item Sub Types: Modules: K-Bus analog output (KM4)
Sub type Description
838865402 KM4602 2-Channel analog output terminal

5.3.3.6.5 ITcSmTreeItem Item Sub Types: Modules: K-Bus communication (KM6)


Sub type Description
6551 KM6551 IEEE802.15.4 terminal
838867463 KM6663 Ethernet changeover switch terminal

5.3.4 ITcSmTreeItem::ProduceXml
The ProduceXml() method returns a XML string with item specific information and parameter.
HRESULT ProduceXml(VARIANT_BOOLbRecursive, BSTR* pXML);

Parameters

bRecursive [in, defaultvalue(0)] Optional parameter for future use.

pXML [out, retval] Contains the XML representation of the


item specific data and parameter.

Return Values

S_OK function returns successfully.


E_POINTER pXML pointer is invalid.

Comments

The following XML string is an incomplete example of the resulting information if the tree item is a I/O device
of the type SERCOS Master/Slave FC750x. This string can be used as input for the
IXMLDOMDocument::loadXML method to create a XML DOM document.

146 Version: 1.3 Automation Interface


API

<?xml version="1.0"?>
<TreeItem>
<ItemName>Device 1 (FC750x)</ItemName>
<PathName>TIID^Device 1 (FC750x)</PathName>
<ItemType>2</ItemType>
<ItemId>1</ItemId>
<ItemSubType>48</ItemSubType>
<ItemSubTypeName>SERCOS Master/Slave FC750x, PCI [Beckhoff FC7502 PCI]</ItemSubTypeName>
<ChildCount>0</ChildCount>
<Disabled>0</Disabled>
<DeviceDef>
<AmsPort>0</AmsPort>
<AddressInfo>
<Pci>
<BusNo>0</BusNo>
<SlotNo>16</SlotNo>
<IrqNo>9</IrqNo>
<FcChannel>0</FcChannel>
</Pci>
</AddressInfo>
<SercosMaster>
<Baudrate>0</Baudrate>
<OperationMode>0</OperationMode>
<SendPower>1</SendPower>
<AccessTime>200</AccessTime>
<ShiftTime>50</ShiftTime>
<StartupToPhase4>1</StartupToPhase4>
<CheckTiming>1</CheckTiming>
</SercosMaster>
</DeviceDef>
</TreeItem>

See also

ITcSmTreeItem::ConsumeXML [} 147]

5.3.5 ITcSmTreeItem::ConsumeXml
ITcSmTreeItem [} 113]

The ConsumeXml() method consumes a BSTR containing the XML representation with item specific data
and updates found parameters. This method is used to change item parameters not directly accessible by
the ITcSmTreeItem [} 113] interface.
HRESULT ConsumeXml(BSTRbstrXML);

Parameters

bstrXML [in] string with the XML representation of the item


specific parameter. The corresponding parameter will
be updated in the System Manager database

Return Values

S_OK function returns successfully.

E_FAIL the bstrXML string does not contain a valid xml


document.

Automation Interface Version: 1.3 147


API

Comments

The document can only contain the specific parameter that should be changed. The document structure has
to fit to the item specific XML tree, but parameter that should not be changed can be omitted. The following
document is a minimal example that can be used to change the specific parameter CheckNumberBoxes of
the item (in this case a C1220 fieldbus card). If the parameters in the document are not known by the item,
they will be ignored.

<TreeItem><DeviceDef><DevC1220Def><CheckNumberBoxes>0</CheckNumberBoxes></
DevC1220Def></DeviceDef></TreeItem>

The set of parameter of a specific tree item is defined in the xml schema document that comes with the
TwinCAT System Manager. The parameter of a specific item can also evaluated by calling the
ITcSmTreeItem::ProduceXML [} 146] method. The resulting xml string contains all parameters of that item, but
not all of them are changeable. The xml string can contain any number and hierarchical order of xml
elements that are valid in terms of the xml schema. It is allowed to change only one parameter at a time (like
in the example above), change a set of parameters at once or delivers the full parameter set that
ITcSmTreeItem::ProduceXML [} 146] returns (normally with same parameters changed).

There are some special xml elements that are not corresponding to parameters, they will "execute" a
function. An example is the <Rescan> element of a PLC project tree item. The string

<TreeItem><PlcDef><ReScan>1</ReScan></PlcDef></TreeItem>

as a parameter of ConsumeXml will cause the System Manager to rescan the PLC project (like a manually
rescan by pressing the "Rescan" button on a PLC project). The parameters and the functions that are
available are documented in the xml schema file.

See also

ITcSmTreeItem::ProduceXML [} 146]

5.3.6 ITcSmTreeItem::CreateChild
Creates a child itemon a parent node. The childis being specified by it'ssubtype [} 118].
HRESULT CreateChild(BSTRbstrName,long nSubType, BSTRbstrBefore, VARIANT vInfo,
ITcSmTreeItem**pipItem);

The following example demonstrates this behavior in better detail.

In this example, an EK1100 coupler is being added to an EtherCAT Master device (Device 1) in TwinCAT
XAE. In Automation Interface, this could be done with the CreateChild() method. The parent node (Device 1
EtherCAT) has the item type '2' (TREEITEMTYPE_DEVICE). The sub type specifies the child item and
therefore the EK1100, which is sub type '9099' (BOXTYPE_EXXXXX).

148 Version: 1.3 Automation Interface


API

Parameters

bstrName [in] Item name of the new child item.


nSubtype: [in]S [} 118]ub type [} 118] of the new child item. The
usable sub type depends on theitem type [} 114](the
category)of theparenttree item. For example, a PLC
Functionblock may only be added to the item type
PLCFOLDER and not to a DEVICE.
bstrBefore [in, defaultvalue("")] If set, the parameter contains the
name of another child item before that the new item
should be inserted.
vInfo [in, optional] An optional parameter with additional
creation information, whichdepends on the sub type
[} 118].The different dependencies are listed in the
table below.
pipItem [out, retval] Points to the location of a ITcSmTreeItem
[} 113] interface pointer that receives the result.

Return Values

S_OK function returns successfully.


E_POINTER the location of the returning pointer is invalid
TSM_E_INVALIDITEMSUBTYPE (0x98510003) the given sub type is invalid.
TSM_E_ITEMNOTFOUND (0x98510001) The item bstrBefore was not found.

Optional vInfo parameter

Depending on theitem subtypeof the new child item,someadditional informationmay berequiredto create the
child item. This information can be provided via the vInfo parameter.

Automation Interface Version: 1.3 149


API

Untergeordnetes Element: Element-Subtyp vInfo-Parameter


E-Bus Box / Klemme / Modul (Element-Subtyp 9099) Contains the Identity Object (CoE 1018h, VendorId,
ProductCode and optional RevisionNo and SerialNo)
of the EtherCAT box. The type of the variant must be
an array of LONG (VT_I4|VT_ARRAY, 2-4 elements).
Alternatively contains a BSTR of the following
formats (with %X = value in hex notation, e.g.
"V00000002_P044c2c52_R00000000"):
Especially for Beckhoff E-Bus terminals / modules,
please read the corresponding E-Bus article [} 119].
Interbus-Box. (Element-Subtyp 2002) Contains the IdentCode and LengthCode of the
Interbus box. The type of the variant must be an
unsigned short (VT_I2), the low byte contains the
IdentCode the high byte the LengthCode.
AX2000 (Element-Subtyp 5007) Optionally contains a bool value (VT_BOOL) and if
CANDrive (Element-Subtyp 5006) set an additional variable for the `Following Error`will
be created.
DeviceNET (Element-Subtyp 5203) Optionally contains the file path to an EDS file
TcDNSSlave (Element-Subtyp 5250) (VT_BSTR).
CX1500 (Element-Subtyp 1042)
FC520X Slave (Element-Subtyp 1043)
BK3000 und alle übrigen PROFIBUS-Box-Typen Optionally contains the file path to an GSD file
(VT_BSTR).
Variable Optionally contains the bit address of the new
variable. The type of the variant can be a SHORT or
a LONG (VT_I2 or VT_I4).
SPS-POU Funktionsblock (Element-Subtyp 604) Contains IEC language type as Integer, as defined by
IECLANGUAGETYPES [} 154].
SPS-POU Funktion (Element-Subtyp 603) Contains a string[2] array, which hols the following
values:
• array[0] = IEC language type as Integer, as
defined by IECLANGUAGETYPES [} 154].
• array[1] = return data type of function. May be any
PLC data type, for example DINT, BOOL, ...

Also see about this


2 ITcSmTreeItem [} 113]

5.3.7 ITcSmTreeItem::DeleteChild
Deletes a child item.
HRESULT DeleteChild(BSTRbstrName);

Parameters

bstrName [[in] Item name of the child item that should be


deleted.

Return Values

S_OK function returns successfully.


E_ACCESSDENIED it is not allowed to delete the child item.

150 Version: 1.3 Automation Interface


API

TSM_E_ITEMNOTFOUND (0x98510001) The item bstrBefore was not found.

Also see about this


2 ITcSmTreeItem [} 113]

5.3.8 ITcSmTreeItem::ImportChild
Imports a child item from the clipboard or a previously exported file.
HRESULT ImportChild(BSTRbstrFile, BSTRbstrBefore, VARIANT_BOOLbReconnect, BSTRbstrName,
ITcSmTreeItem**pipItem);

Parameters

bstrFile [in, defaultvalue(L"")] File name of the file from which


the new child will be imported. If no file name
specified (empty string) the child will be imported
from the clipboard.
bstrBefore [in, defaultvalue(L"")] If set, the parameter contains
the name of another child item in front of which the
new item should be inserted. If not set, the child will
be appended at the end.
bReconnect [in, defaultvalue(VARIANT_TRUE)] An optional flag
that instructs the System Manager to try to reconnect
the variables from the imported item to other
variables in the configuration (by name).
bstrName [in, defaultvalue(L"")] If set, overrides the child item
name with its name in the import file.
pipItem [out, retval] Points to the location of a ITcSmTreeItem
[} 113] interface pointer that receives the result.

Return Values

S_OK function returns successfully.


NTE_NOT_FOUND (0x80090011) the file can not be found/opened.
NTE_BAD_SIGNATURE (0x80090006) the file does not contain a valid tree item.
TSM_E_MISMATCHINGITEMS (0x98510004) the item in the file is not a valid child item.

Also see about this


2 ITcSmTreeItem [} 113]

5.3.9 ITcSmTreeItem::ExportChild
Exports a child item to the clipboard or a file.
HRESULT ExportChild(BSTRbstrName, BSTRbstrFile);

Parameters

bstrName [in] Name of the child being exported.

bstrFile [in, defaultvalue("")] File name of the file to which the


child will be exported. If no file name specified (empty
string) the child will be exported to the clipboard.

Automation Interface Version: 1.3 151


API

Return Values

S_OK function returns successfully.


TSM_E_ITEMNOTFOUND (0x98510001) The item bstrName was not found.

Also see about this


2 ITcSmTreeItem [} 113]

5.3.10 ITcSmTreeItem::LookupChild
Returns a ITcTreeItem pointer of a descendant child tree item given by it's relative path name.
HRESULT LookupChild(BSTRbstrName, ITcSmTreeItem**pipItem);

Parameters

bstrName [in] relative path of the tree item you are looking for.
The relative path name is required and each branch
must be separated by a circumflex accent '^' or a tab.
pipItem [out, retval] points to the location of a ITcSmTreeItem
[} 113] interface pointer on return. The interface
pointer gives access to specific methods belonging to
the tree item.

Return Values

S_OK function returns successfully.


TSM_E_ITEMNOTFOUND (0x98510001) the path name does not qualify an existing tree item.

Also see about this


2 ITcSmTreeItem [} 113]

5.3.11 ITcSmTreeItem::GetLastXmlError
Gets the Item path / Error message of the last erroneous ConsumeXml [} 147] call.
HRESULT GetLastXmlError(BSTR *pXML);

Parameters

pXML [out, retval] Error message.

Return Values

S_OK function returns successfully.

Also see about this


2 ITcSmTreeItem [} 113]

152 Version: 1.3 Automation Interface


API

5.4 ITcPlcProject

5.4.1 ITcPlcProject
The class ITcPlcProject enables developers to set properties for a PLC project. It usually targets the root
node of a PLC project, as shown in the picture below.

The following C# code snippet shows an example about how this class may be used in Automation Interface
code:
ITcSmTreeItem plcProjectRootItem = systemManager.LookupTreeItem("TIPC^PlcGenerated");
ITcPlcProject iecProjectRoot = (ITcPlcProject)plcProjectRootItem;
iecProjectRoot.BootProjectAutostart = true;
iecProjectRoot.GenerateBootProject (true);

Please note: If you would like tocompile a PLC project, please use the compiler functionalities of the Visual
Studio COM objectEnvDTE, as shown in many of our Samples [} 171] .

Methods

ITcPlcProject methods Description Available since


GenerateBootProject() Equals the entry "Activate Boot project" from the TwinCAT TwinCAT 3.1
[} 154] XAE context menu

Properties

ITcPlcProject properties Get/Set Description Available since


BootProjectAutoStart Yes / Yes Equals the checkbox "Autostart Boot Project" in TwinCAT 3.1
the dialog shown above
BootProjectEncryption Yes / Yes Equals the dropdown box "Encryption" in the TwinCAT 3.1
dialog shown above
TmcFileCopy Yes / Yes Equals the checkbox "Copy TMC File to Target" TwinCAT 3.1
in the dialog shown above

Version information

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

Automation Interface Version: 1.3 153


API

5.4.2 ITcPlcProject::GenerateBootProject
Activates or deactivates the PLC project as a boot project, depending on the bool parameter you specify.
HRESULT GenerateBootProject(VARIANT_BOOL bActivate);

Parameters

bActivate [in, optional, defaultvalue(-1)] Specifies if the boot


project should be activated

5.5 ITcPlcPou

5.5.1 ITcPlcPou
To handle POUs and their content within a TwinCAT 3 project, the interfaces ITcPlcPou, ITcPlcDeclaration
[} 155] and ITcPlcImplementation [} 156] may be used. For example, if you would like to create a new
function block for a PLC project and fill it with code, you can use these interfaces to do so. For more
information, please refer to our best practise article about "How to access and create PLC-Objects".

Properties

ITcPlcPou properties Get / Set Description Available since


DocumentXml Yes / Yes Gets/Sets PLC code of a TwinCAT 3.1
POU in XML format (not
PLCopen XML)
ReturnType Yes / No Return type of the POU, TwinCAT 3.1
for example the return
type of a function. May be
any data type known to
the PLC, for example
BOOL, DINT, ... . The
return type is being set
when creating the POU
via the CreateChild()
[} 148] method.

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.5.2 IECLanguageTypes
The enumeration IECLanguageTypes defines different programming languages according to IEC standard
and may be used when creating a new POU via the method ITcSmTreeItem [} 113]::CreateChild() [} 148].

154 Version: 1.3 Automation Interface


API

Entry Value Description


IECLANGUAGE_NONE 0 ---
IECLANGUAGE_ST 1 Structured Text
IECLANGUAGE_IL 2 Instruction List
IECLANGUAGE_SFC 3 Sequential Function Chart
IECLANGUAGE_FBD 4 Function Block Diagram
IECLANGUAGE_CFC 5 Continous Function Chart
IECLANGUAGE_LD 6 Ladder Diagram

5.6 ITcPlcDeclaration
The interface ITcPlcDeclaration provides access to the declaration area of PLC POUs and their sub-nodes
(like Actions, Methods, ...). Please also see the best practice article "Handling PLC-Objects" for more
information about how to use this interface.

Properties (in Vtable- Order)

ITcPlcDeclaration prop- Get / Set Description Available since


erties
DeclarationText Yes / Yes Represents the TwinCAT 3.1
declaration area of the
item and gets/sets its
content in cleartext

Version information

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

Automation Interface Version: 1.3 155


API

5.7 ITcPlcImplementation
The interface ITcPlcImplementation provides access to the implementation area of PLC POUs and their sub-
nodes (like Actions, Methods, ...). Please also see the best practice article about "Handling PLC-Objects" for
more information about how to use this interface.

Properties (in VTable Order

ITcPlcImplementation Get / Set Description Available since


properties
ImplementationText Yes / Yes Represents the TwinCAT 3.1
declaration area of the
item and gets/sets its
content in cleartext
ImplementationXml Yes / Yes Gets/Sets the content in TwinCAT 3.1
XML format (not
PLCopen XML)
Language Yes / No Gets the IEC language TwinCAT 3.1
used in the
implementation area

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

156 Version: 1.3 Automation Interface


API

5.8 ITcPlcIECProject

5.8.1 ITcPlcIECProject
The interface ITcPlcIECProject provides methods for importing and exporting PLC projects according to the
PlcOpen XML standard or saving PLC projects as a PLC library. Compared to the TwinCAT XAE GUI, this
interface represents the following four options:

Methods (in VTable Order)

ITcPlcIECProject methods Description Available since


PlcOpenExport() [} 158] Exports the specified tree nodes TwinCAT 3.1
and their content to a PlcOpen
conform XML file
PlcOpenImport() [} 158] Imports a PlcOpen conform XML TwinCAT 3.1
file and its content
SaveAsLibrary() [} 159] Saves the selected PLC project as TwinCAT 3.1
a PLC library and optionally also
installs it.

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

Automation Interface Version: 1.3 157


API

5.8.2 PlcImportOptions
This enum contains the following options and is being used when importing a PlcOpen conform XML file via
method ITcPlcIECProject [} 157]::PlcOpenImport() [} 158].

Element Description Supported By


PLCIMPORTOPTIONS_NONE --- TwinCAT 3.1
PLCIMPORTOPTIONS_RENAME In case the imported item already TwinCAT 3.1
exists in the PLC project, it is
automatically renamed
PLCIMPORTOPTIONS_REPLACE In case the imported item already TwinCAT 3.1
exists in the PLC project, the
existing project is being replaced
PLCIMPORTOPTIONS_SKIP In case the imported item already TwinCAT 3.1
exists in the PLC project, skip it

5.8.3 ITcPlcIECProject::PlcOpenExport
Exports the specified tree nodes and their content to a PlcOpen conform XML file. A path to the XML file and
the tree nodes will be specified in a parameter of this method.
HRESULT PlcOpenExport(BSTR bstrFile, BSTR bstrSelection);

Parameters

bStrFile

[in] : Path to the XML file

bstrSelection

[in] : Selection of tree items which should be exported. The items are separated by a semicolon, e.g. z.B.
"POUs.FBItem1;POUs.FBItem2"

Return Values

S_OK Items successfully exported into PlcOpen XML file.

5.8.4 ITcPlcIECProject::PlcOpenImport
Imports a PlcOpen conform XML file and its content. A path to the XML file will be passed to the method via
a parameter.
HRESULT PlcOpenImport(BSTR bstrFile, int options, BSTR bstrSelection, VARIANT_BOOL
bFolderStructure);

Parameters

bstrFile

[in] : Path to the XML file.

options

[in, optional, defaultvalue(0)] : Options for import, according to enum PLCIMPORTOPTIONS [} 158].

bstrSelection

[in, optional, defaultvalue("")] : Selects which items from the XML structure should be imported

158 Version: 1.3 Automation Interface


API

bFolderStructure

[in, optional, defaultvalue(-1)] : If set to true (-1), the folder structure of the imported objects remains the
same, if this information is available in the XML file

Return Values

S_OK PlcOpen XML file successfully imported.

Also see about this


2 ITcPlcIECProject [} 157]

5.8.5 ITcPlcIECProject::SaveAsLibrary
Saves the PLC project as a PLC library and optionally installs it.
HRESULT SaveAsLibrary(BSTR bstrLibraryPath, VARIANT_BOOL binstall);

Parameters

bStrLibraryPath

[in] : Path to the location where the PLC library should be saved to

binstall

[in] : set to "true" if PLC library should also be installed

Return Values

S_OK PLC project successfully saved as a PLC library.

Also see about this


2 ITcPlcIECProject [} 157]

5.9 ITcPlcLibraryManager

5.9.1 ITcPlcLibraryManager
The ITcPlcLibraryManager interface extends the Automation Interface by enabling access to PLC libraries of
a TwinCAT 3 PLC project or PLC repositories of a TwinCAT system.

Automation Interface Version: 1.3 159


API

Methods (in VTable Order)

ITcPlcLibraryManager methods Description Available since


AddLibrary() [} 161] Adds a library to a PLC project. TwinCAT 3.1
AddPlaceholder() [} 162] Adds a placeholder to a PLC TwinCAT 3.1
project
InsertRepository() [} 162] Creates a repository, which TwinCAT 3.1
represents a logical container for
several libraries.
InstallLibrary() [} 163] Installs a library into a repository. TwinCAT 3.1
MoveRepository() [} 163] Changes the position of the TwinCAT 3.1
repository in the repository location
list.
RemoveReference() [} 163] Removes library from the PLC TwinCAT 3.1
project.
RemoveRepository() [} 164] Removes a repository. TwinCAT 3.1
ScanLibraries() [} 164] Returns a list of all libraries found TwinCAT 3.1
in the system. The returned object
is of type ITcPlcLibraries [} 167],
which is a collection of ITcPlcLibrary
[} 166] objects.
SetEffectiveResolution() [} 165] Sets the Effective Resolution of a TwinCAT 3.1
placeholder
UninstallLibrary() [} 165] Uninstalls a library from a TwinCAT 3.1
repository.

160 Version: 1.3 Automation Interface


API

Properties (in VTable Order)

ITcPlcLibraryManager Get / Set Description Available since


properties
References Yes / No Gets an object of type TwinCAT 3.1
ITcPlcReferences [} 166],
which is a collection of
ITcPlcLibrary [} 166] or
ITcPlcPlaceholderRef
objects. Represents a list
of all references added to
the PLC project.
Repositories Yes / No Gets an object of type TwinCAT 3.1
ITcPlcLibRepositories
[} 169], which is a
collection of
ITcPlcLibRepository
[} 168] objects.
Represents a list of all
currently configured
repositories.

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.9.2 ITcPlcLibraryManager::AddLibrary
Adds a library to the PLC project. A library can either be added by its attributes (Name, Version, Company)
or by its display text.

HRESULT AddLibrary(
BSTR bstrLibName,
BSTR bstrVersion,
BSTR bstrCompany
);

HRESULT AddLibrary(BSTR bstrLibName, BSTR bstrVersion, BSTR bstrCompany);

Parameters

bstrLibName [in] Library name.


bstrVersion [in, optional, defaultvalue("")] Library version.
bstrCompany [in, optional, defaultvalue("")] Company which created
the library.

Return Values

S_OK Library successfully added..

Comments

Two common ways to add a PLC library are:

Automation Interface Version: 1.3 161


API

• libraryManager.AddLibrary("Tc2_MDP", "3.2.0.0", "Beckhoff Automation GmbH"); // Adding library via


its attributes
• libraryManager.AddLibrary("Tc2_MDP, 3.2.0.0 (Beckhoff Automation GmbH)"); // Adding library via its
display name

Where librayManager is an object of type ITcPlcLibraryManager.

5.9.3 ITcPlcLibraryManager::AddPlaceholder
Adds a placeholder to the PLC project. A placeholder can either be added by its attributes (Placeholder
name, library name, library version, library distributor) or by its name if the placeholder already exists.
HRESULT AddPlaceholder(BSTR bstrPlaceholderName, BSTR bstrDefaultLibName, BSTR bstrDefaultVersion,
BSTR bstrDefaultDistributor);

Parameters

bstrPlaceholderName [in] Placeholder name.


bstrDefaultLibName [in] Default library name which the placeholder points
to.
bstrVersion [in, optional, defaultvalue("")] Default library version.
bstrCompany [in, optional, defaultvalue("")] Company which created
the library.

Return Values

S_OK Placeholder successfully added..

Also see about this


2 ITcPlcLibraryManager [} 159]

5.9.4 ITcPlcLibraryManager::InsertRepository
Adds a new library repository at the specified position. The position represents the index at which the
repositories is located in the repository list in TwinCAT 3. In addition to the index, a repository is identified via
its name and path to a directory in the file system.
HRESULT InsertRepository(BSTR bstrName, BSTR rootFolder, int iIndex);

Parameters

bstrName [in] Repository name.


rootFolder [in] Path to repository (file system).
iIndex [in] Indicates on which position the repository is
located in the list of repositories.

Return Values

S_OK Repository successfully inserted

Also see about this


2 ITcPlcLibraryManager [} 159]

162 Version: 1.3 Automation Interface


API

5.9.5 ITcPlcLibraryManager::InstallLibrary
Installs a library into an existing library repository.
HRESULT InstallLibrary(BSTR bstrRepositoryName, BSTR bstrLibPath, VARIANT_BOOL bOverwrite);

Parameters

bstrRepositoryName [in] : Name of repository, where the library should be


inserted
bstrLibPath [in] : Path to the library
bOverwrite [in] : If another library already exists, set this
parameter to overwrite it

Return Values

S_OK Library installation successful.

Also see about this


2 ITcPlcLibraryManager [} 159]

5.9.6 ITcPlcLibraryManager::MoveRepository
Moves the repository to a new position in the list of repositories. The position is marked by its index, which
starts at 0.
HRESULT MoveRepository(BSTR bstrRepositoryName, int iNewIndex);

Parameters

bstrRepositoryName [in] : Name of the repository


iNewIndex [in] : Index of the repository

Also see about this


2 ITcPlcLibraryManager [} 159]

5.9.7 ITcPlcLibraryManager::RemoveReference
Removes a reference from the actual PLC project. A reference can either be a library or a placeholder.

Please note: In case of a library, this only removes the reference, not the actual library file from the
repository. For this, the method UninstallLibrary() [} 165] needs to be used.

Similar to the method AddLibrary(), a library can be removed either by specifying its attributes (Name,
Version, Company) or display text.
HRESULT RemoveReference(BSTR bstrLibName, BSTR bstrVersion, BSTR bstrCompany);

Parameters

bstrLibName [in] : Name of library


bstrVersion [in, optional, defaultvalue("")] :
bstrCompany [in, optional, defaultvalue("")]

Automation Interface Version: 1.3 163


API

Comments

Two common ways to remove a PLC library are:


• libraryManager.RemoveReference("Tc2_MDP", "3.2.0.0", "Beckhoff Automation GmbH"); // Removing
library via its attributes
• libraryManager.RemoveReference("Tc2_MDP, 3.2.0.0 (Beckhoff Automation GmbH)"); // Removing
library via its display name

Where librayManager is an object of type ITcPlcLibraryManager.

Also see about this


2 ITcPlcLibraryManager [} 159]

5.9.8 ITcPlcLibraryManager::RemoveRepository
Removes a library repository. A repository is specified by its unique name.
HRESULT RemoveRepository(BSTR bstrName);

Parameters

bstrName

[in] Name of repository.

Also see about this


2 ITcPlcLibraryManager [} 159]

5.9.9 ITcPlcLibraryManager::ScanLibraries
Returns a collection of all registered libraries in all repositories.
HRESULT ScanLibraries(ITcPlcLibraries** ppEnumLibraries);

Parameters

ppEnumLibraries [out, retval] Returns object of type ITcPlcLibraries


[} 167], which is a collection of ITcPlcLibrary [} 166]
objects.

Comments

This method provides the same functionality as importing the following XML structure via ConsumeXml()
[} 147] on the tree node "Library Manager":
<TreeItem>
<PlcLibDef>
    <ScanLibraries>
     <Active>true</Active>
    </ScanLibraries>
</PlcLibDef>
</TreeItem>

Also see about this


2 ITcPlcLibraryManager [} 159]

164 Version: 1.3 Automation Interface


API

5.9.10 ITcPlcLibraryManager::SetEffectiveResolution
Sets the Effective Resolution, meaning the effective library, of a placeholder.
HRESULT SetEffectiveResolution(BSTR bstrPlaceholderName, BSTR strLibName, BSTR bstrVersion, BSTR
bstrDistributor);

In TwinCAT XAE, the Effective Resolution can be set via the Placeholder configuration window.

Please note: The Default Resolution of a placeholder is set when the placeholder is added via
ITcPlcLibraryManager [} 159]::AddPlaceholder() [} 162].

Parameters

bstrPlaceholderName [in] Placeholder name for which the Effective


Resolution should be set.
bstrLibName [in] Library name for Effective Resolution.
bstrVersion [in, optional, defaultvalue("")] Library version.
bstrDistributor [in, optional, defaultvalue("")] Company which created
the library.

Return Values

S_OK Effective Resolution successfully set.

5.9.11 ITcPlcLibraryManager::UninstallLibrary
Uninstalls a library from a repository.
HRESULT UninstallLibrary(BSTR bstrRepositoryName, BSTR bstrLibraryName, BSTR bstrVersion, BSTR
bstrDistributor);

Automation Interface Version: 1.3 165


API

Parameters

bstrRepositoryName [in] : Name of repository


bstrLibraryName [in] : Name of library
bstrVersion [in, optional] : Version of library
bstrDistributor [in, optional] : Distributor of library

Also see about this


2 ITcPlcLibraryManager [} 159]

5.10 ITcPlcReferences
ITcPlcReferences represents a collection of ITcPlcLibRef [} 167] objects, which is returned for example when
using the property ITcPlcLibraryManager [} 159]::References.

Methods (in VTable Order)

Requirements

ITcPlcLibRepositories methods Description Available since


get_Item() [} 169] Returns an item of type TwinCAT 3.1
ITcPlcLibRef [} 167] which is
located on a specified position.

Properties (in VTable Order)

ITcPlcLibRepositories Get / Set Description Available since


properties
Count Yes / No Returns the amount of TwinCAT 3.1
ITcPlcLibRef [} 167]
objects in the collection

Version information

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.11 ITcPlcLibrary
Represents a single PLC library when used with collection ITcPlcLibraries [} 167] and method
ITcPlcLibraryManager [} 159]::ScanLibraries() [} 164] or property ITcPlcLibraryManager [} 159]::References.

Properties (in VTable Order)

ITcPlcLibrary properties Get / Set Description Available since


DisplayName Yes / No Display name to identify TwinCAT 3.1
library in library list
Distributor Yes / No Library creator TwinCAT 3.1
Name Yes / No Library name TwinCAT 3.1
Version Yes / No Library version TwinCAT 3.1

166 Version: 1.3 Automation Interface


API

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.12 ITcPlcLibraries

5.12.1 ITcPlcLibraries
ITcPlcLibraries represents a collection of ITcPlcLibrary [} 166] objects, for example when using method
ITcPlcLibraryManager [} 159]::ScanLibraries() [} 164] or property ITcPlcLibraryManager [} 159]::Libraries.

Methods (in VTable Order)

Requirements

ITcPlcLibraries methods Description Available since


get_Item() [} 167] Returns item of type ITcPlcLibrary TwinCAT 3.1
[} 166] which is located on a
specified position.

Properties (in VTable Order)

ITcPlcLibraries proper- Get / Set Description Available since


ties
Count Yes / No Returns the amount of TwinCAT 3.1
ITcPlcLibrary [} 166]
objects in the collection

Version information

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.12.2 ITcPlcLibraries::get_Item
Returns ITcPlcLibrary object on specified position.
HRESULT AddLibrary(long n, ITcPlcLibrary** pipType);

Parameters

n [in] Position of item in list.


pipType [out, retval] Returns object of type ITcPlcLibrary

5.13 ITcPlcLibRef
ITcPlcLibRef represents a base class for either ITcPlcLibrary [} 166] or ITcPlcPlaceholderRef [} 168] objects.

Automation Interface Version: 1.3 167


API

Properties (in VTable Order)

Requirements

ITcPlcLibRepositories Get / Set Description Available since


properties
Name Yes / No Returns the name of the TwinCAT 3.1
ITcPlcLibRef object

Version information

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.14 ITcPlcPlaceholderRef
Represents a single PLC placeholder when used with collection ITcPlcReferences [} 166] and method
ITcPlcLibraryManager [} 159]::ScanLibraries() [} 164] or property ITcPlcLibraryManager [} 159]::References.

Properties (in VTable Order)

ITcPlcLibrary properties Get / Set Description Available since


DisplayName Yes / No Display name to identify TwinCAT 3.1
library in library list
Distributor Yes / No Library creator TwinCAT 3.1
Name Yes / No Library name TwinCAT 3.1
Version Yes / No Library version TwinCAT 3.1

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.15 ITcPlcLibRepository
The ITcPlcLibRepository interface represents a single repository, for example when used with collection
ITcPlcLibRepositories [} 169] and property ITcPlcLibraryManager [} 159]::Repositories.

Properties

ITcPlcLibRepository Get / Set Description Available since


properties
Folder Yes / No Path to repository (file TwinCAT 3.1
system)
Name Yes / No Repository name. TwinCAT 3.1

168 Version: 1.3 Automation Interface


API

Version information

Requirements

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.16 ITcPlcLibRepositories

5.16.1 ITcPlcLibRepositories
ITcPlcLibraries represents a collection of ITcPlcLibRepository [} 168] objects, for example when using
property ITcPlcLibraryManager [} 159]::Repositories.

Methods (in VTable Order)

Requirements

ITcPlcLibRepositories methods Description Available since


get_Item() [} 169] Returns item of type TwinCAT 3.1
ITcPlcLibRepository [} 168] which is
located on a specified position.

Properties (in VTable Order)

ITcPlcLibRepositories Get / Set Description Available since


properties
Count Yes / No Returns the amount of TwinCAT 3.1
ITcPlcLibRepository
[} 168] objects in the
collection

Version information

Required TwinCAT version


This interface is supported in TwinCAT 3.1 and above

5.16.2 ITcPlcLibRepositories::get_Item
Returns ITcPlcLibRepository object on specified position.
HRESULT AddLibrary(long n, ITcPlcLibRepository** ppRepo);

Parameters

n [in] Position of item in list.


pipType [out, retval] Returns object of type
ITcPlcLibRepository

Automation Interface Version: 1.3 169


API

5.17 ITcPlcTaskReference
The ITcPlcTaskReference interface enables programmers to get or set the currently linked task of a PLC
project. This matches the following TwinCAT XAE entry:

Properties (in VTable Order)

Requirements

ITcPlcTaskReference Get / Set Description Available since


properties
LinkedTask Yes / Yes Gets or sets the linked TwinCAT 3.1
task of a PLC project.
When setting a new linked
task, the task will be
specified as a string which
represents the path to the
task in the TwinCAT XAE
tree.

170 Version: 1.3 Automation Interface


Samples

6 Samples

6.1 Sample downloads


Most of the samples and HowTo’s are available as code snippets in our “Best Practice” section to allow an
easy re-usability. However, this download section also provides ready-to-use samples as either binary or
source code.

Important notes:
• All C# samples are based on a Visual Studio project with at least .NET 4.0
• All C# samples include a reference to the "TwinCAT XAE Base" type library in version 2.1. Depending
on the installed TwinCAT version, the reference to this library may need to be updated, see Installation
article [} 16]
• Please note that all Visual Studio Plugin samples are only operable under Visual Studio 2010 and
2012. To develop Add-Ins for Visual Studio 2013, Microsoft recommends to use the VSPackage
Extension, as described on the corresponding MSDN website about Creating Add-ins and Wizards.
SampleNo. Description Programming / Minimum Download
Scripting lan- TwinCAT ver-
guage sion
1 Scripting C# Depends on ScriptingContainer Binaries only
Container script
ScriptingContainer Source
[} 171]
2 CodeGeneratio C# 3.1 Build CodeGenerationDemo Binaries only
nDemo [} 175] 4014.0
CodeGenerationDemo Source
3 Visual Studio C# 3.1 Build PluginSample_PlcVersionInfo.zip
Plugin 4016.6
PlcVersionInfo
[} 177]

Also see about this


2 Handling different Visual Studio versions [} 29]
2 Implementing a COM Message Filter [} 26]

6.2 Scripting Container

6.2.1 Scripting Container


The Scripting Contrainer (download here [} 171]) is a C# WPF application which represents a collection of all
available Automation Interface samples. Most of these samples are also available as a standalone sample
download - however, as new samples become available, they will be first published in the Scripting
Container before creating a separate sample. Threfore we recommend to become familiar with this
application and to check periodically for new samples.

This article describes the general structure of the Scripting Container application and consists of the
following topics:
• Basic structure
• First time setup

Automation Interface Version: 1.3 171


Samples

Basic structure

As mentioned above the ScriptingContainer consists of a collection of Automation Interface samples, which
are represented by different projects (each with an own UI) within the ScriptingContainer. The following table
gives an overview about all available projects and links to the corresponding documentation article.

Project name Description


CodeGenerationDemo [} 175] Implements AI code that reads three different
TwinCAT configurations from a XML file.
CopyProjectDemo Copies I/Os and Axis configuration from an existing
TwinCAT configuration to a new configuration.
ScriptingTestContainer [} 172] Provides a collection of available Automation
Interface samples, which can be executed from a
graphical user interface.

First time

When opening the ScriptingContainer for the first time, please set the StartUp Project to the desired user
interface, e.g. "ScriptingTestContainer" by right-clicking this project and selecting "Set as StartUp Project".
This ensures that the correct GUI will be loaded upon application start-up.

You can now start the application by going to the menu "Debug" and clicking on "Start Debugging". By
starting the application this way, you can set breakpoints or step through code execution to easily evaluate
the executed script.

6.2.2 Projects

6.2.2.1 Scripting Container: ScriptingTestContainer


This article describes the basic structure of the ScriptingTestContainer project and consists of the following
topics:
• The Graphical User Interface (GUI)

172 Version: 1.3 Automation Interface


Samples

• Early and late bound script samples


• Location of sample scripts ("Where's the Automation Interface code???" )
• Behind the scenes: Class structure
• Behind the scenes: Method structure
• Behind the scenes: Implementing own samples

The Graphical User Interface (GUI)

After you have started the Scripting Container application, its GUI will look as follows:

The dropdown box at the top of the window lets you choose the version of Visual Studio [} 29] that you would
like to use to create the TwinCAT configuration.

There are a variety of sample scripts available, which can be selected in the table at the center of the
window.

To execute a script, simply select it from the table and click on "Execute". During code execution, the script
displays status information in the message logging window below the script table.

To change the visibility behavior of Visual Studio, you can switch the checkboxes in the upper right corner of
the window. By default, Visual Studio is shown during script execution and not closed after the script
finishes.

Automation Interface Version: 1.3 173


Samples

Early and late bound script samples

This application contains both - early and late bound - script samples. Late bound samples make use of
the .NET data type "dynamic" and therefore determine an objects data type during runtime whereas early
bound scripts use the corresponding data type of an object during the creation of an object. Both ways have
their advantages and disadvantages and it depends on the developer and project which type handling is to
be prefered.

Location of sample scripts ("Where's the Automation Interface code???")

All script samples - early and late bound - are located in an own project container within the Visual Studio
solution: Scripting.CSharp.Scripts for early bound and Scripting.CSharp.ScriptsLateBound for late
bound sample code.

Each script file implements a method OnExecute() in which the TwinCAT Automation Interface script code is
implemented.

Behind the scenes: Class structure

Each code sample is represented by an own class which derives either from the abstract class
"ScriptEarlyBound" or "ScriptLateBound" - depending on the data type handling used in the sample. The
difference between these two classes is that the ScriptEarlyBound class uses static typing for the DTE and
Solution objects. The ScriptLateBound class uses dynamic typing instead. The following UML diagram
explains the class hierarchy in more detail. The grey classes represent the actual sample scripts, which
either derive from class ScriptEarlyBound (when static typing should be used) or from class ScriptLateBound
(when dynamic typing should be used).

174 Version: 1.3 Automation Interface


Samples

The abstract class "Script" defines methods and attributes which are common for both the ScriptEarlyBound
and ScriptLateBound classes.

Behind the scenes: Method structure

Each sample class contains three methods which are used in the Scripting Container to execute the
Automation Interface code. The following table shows their meaning.

Signature of derived method Description


OnInitialize (dynamic dte, dynamic solution, IWorker The OnInitialize() method is usually used for
worker) Automation Interface code which opens or prepares a
new TwinCAT XAE configuration.
OnCleanUp (IWorker worker) The OnCleanUp() method may be used to clean-up
the TwinCAT XAE configuration after code execution.
OnExecute (IWorker worker) This method is executing the actual Automation
Interface script code.

Please also compare the implementation of existing sample scripts to get a better understanding about how
each method works.

Behind the scenes: Implementing own samples

It is easily possible to implement own Automation Interface samples into the Scripting Container. To
implement own Automation Interface code, a developer only needs to decide which binding he would like to
use and then implement a new class which derives from one of the main classes (ScriptEarlyBound or
ScriptLateBound) and then implement the derived methods.

6.3 CodeGenerationDemo
The Scripting Contrainer (download here [} 171]) is a C# WPF application which represents a collection of all
available Automation Interface samples. Most of these samples are also available as a standalone sample
download - however, as new samples become available, they will be first published in the Scripting
Container before creating a separate sample. Threfore we recommend to become familiar with this
application and to check periodically for new samples.

This article describes the general structure of the Scripting Container application and consists of the
following topics:
• The Graphical User Interface (GUI)
• Location of sample scripts ("Where's the Automation Interface code???")
• Location of data ("Where does all the data come from?")

The Graphical User Interface (GUI)

After you have started the CodeGenerationDemo application, its GUI will look as follows:

Automation Interface Version: 1.3 175


Samples

On the left hand side you can select from three different TwinCAT configuration, each with its own I/O, Axis
and PLC configuration.

The dropdown box on the top right side lets you choose which Visual Studio version the script code should
use to create the configuration - in case you have different Visual Studio versions installed on your system.

To start the configuration creation, simply select a configuration and press "Generate".

Location of sample scripts ("Where's the Automation Interface code???" )

The actual Automation Interface code can be found within the following classes:
• CodeGenerationScript.cs
• ConfigurationScriptA.cs
• ConfigurationScriptB.cs
• ConfigurationScriptC.cs

Depending on the selected configuration, the CodeGenerationDemo application instantiates one of the three
ConfigurationScriptX.cs classes, which all derive from CodeGenerationScript.cs.

Each class provides corresponding methods for creating the PLC, Axis or I/O configuration.

Location of data ("Where does all the data come from?")

Each configuration has its own I/O, Axis and PLC settings. As you may have already noticed, this
configuration is not hard-coded into the Automation Interface code (like in other AI samples). In this demo,
these settings are stored in an XML file that can be found under "CodeGenerationDemo\Data\Orders.xml".
This XML file specifies two important XML sub-structures which are used to store TwinCAT settings.

Main description of a configuration:


<MachineOrders>
<Order id="1">
...
</Order>
</MachineOrders>

176 Version: 1.3 Automation Interface


Samples

This structure defines a configuration and sets its global descriptive properties, e.g. Name, Description, ... .
These properties will be shown on the GUI below the configuration selection.

Actual configuration with a reference to its description:


<AvailableConfigurations>
<Configuration id="..." name="...">
...
</Configuration>
</AvailableConfigurations>

This structure specifies the I/Os, Axis, PLC libraries and linking.

6.4 Visual Studio Plugin - PlcVersionInfo


The PlcVersionInfo sample demonstrates how to use the TwinCAT Automation Interface from within a Visual
Studio Plugin. Its main purpose is to show how to create a simple tool that extends the PLC engineering with
more functionalities. The small user interface allows to enter version and author information for PLC function
blocks. When executing the sample, this information is placed in a VAR_CONSTANT area in all
functionblocks within a PLC projeect. Although this might seem a pretty simple example, it clearly shows how
powerfull Visual Studio Plugins can be and how they might greatly enhance the users engineering
experience.

For more information about Visual Studio Plugins, please consult the MSDN webpage.

Basic concept

As previously noted, the tool starts an iteration over all PLC tree items of a PLC project. If the current tree
item is either a functionblock, function or program, then the declaration text of the tree item is determined
and extended with a VAR_CONSTANT block.

Notes about executing and debugging Visual Studio Plugins

Visual Studio Plugins may be located in different folders so that Visual Studio recognizes them. This
documentation assumes that the Plugin should only be made available for a specific user account which is
why the Plugin will be placed in a directory within the user profile. For more information, please consult the
MSDN webpage about Add-In Registration.

To execute the Plugin without debugging, please copy the compiled DLL and the .AddIn file to the directory
c:\Users\username\Documents\Visual Studio 201x\Addins\ and restart Visual Studio.

To execute the Plugin with debugging, simply execute the debugger from within the Plugin solution. If this
causes you issues, you may also copy the .AddIn file the Addins directory (mentioned above) and edit the
file with a text editor of your choice to change the <Assembly> node to the path of the compiled debug DLL.
Then start a Visual Studio instance and attach your debugger to this instance/process.

Automation Interface Version: 1.3 177


Samples

The Visual Studio Plugin will be made available in the TwinCAT menu in Visual Studio.

178 Version: 1.3 Automation Interface


Appendix

7 Appendix

7.1 Miscallaneous error codes


The following error codes represent the HRESULT values of Automation Interface methods, as explained in
the API reference [} 103].
typedefenum TCSYSMANAGERHRESULTS
{
    [helpstring("ITcSmTreeItem not found!" (ITcSmTreeItem nicht gefunden!))]
    TSM_E_ITEMNOTFOUND         = 0x98510001,
    [helpstring("Invalid Item Type!" (Ungültiger Elementtyp!))]                
    TSM_E_INVALIDITEMTYPE         = 0x98510002,
    [helpstring("Invalid SubItem Type!" (Ungültiger Unterelementtyp!))]        
    TSM_E_INVALIDITEMSUBTYPE        = 0x98510003,
    [helpstring("Mismatching Items!" (Nicht übereinstimmende Elemente!))]            
    TSM_E_MISMATCHINGITEMS         = 0x98510004,
    [helpstring("Corrupted Link" (Fehlerhafte Verknüpfung))]                
    TSM_E_CORRUPTEDLINK         = 0x98510005,
    [helpstring("Item still referenced!" (Element immer noch referenziert!))]        
    TSM_E_ITEMREFERENCED         = 0x98510006,
    [helpstring("Item already deleted!" (Element bereits gelöscht!))]        
    TSM_E_ITEMDELETED         = 0x98510007,
    [helpstring("XML Error" (XML-Fehler))]                    
    TSM_E_XMLERROR             = 0x98510008,
} TCSYSMANAGERHRESULTS;

Please note that the following list of COM error codes is just a snippet and not complete:

Error Description
RPC_E_CALL_REJECTED The COM-Server has rejected the call. Please read our article about
how to implement an own Message Filter [} 26] to circumvent this error.
Return value of method One cause of this error could be that the COM message filter has been
CoRegisterMessageFilter() <> 0 applied to a MTA apartment. Message filters can only be applied to
STA-Threads. Please view our Message Filter [} 26] article for more
information about message filters, including STA and MTA.
Error message "A reference to The type library is not correctly registered. Please re-register the type
Beckhoff TwinCAT XAE Base 2.0 library by executing the following command:
Type Library could not be added" C:\Windows\Microsoft .NET\Framework\v4.0.xxxxx\regtlibv12.exe C:
when referencing the type library in \TwinCAT3\Components\Base\TCatSysManager.tlb
Visual Studio. xxxxxx is the version of the currently installed version of the .NET
Framework 4.0.

Automation Interface Version: 1.3 179

You might also like