Automation Interface: Manual
Automation Interface: Manual
Automation Interface: 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
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
1 Foreword
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
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.
2 Overview
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.
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.
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
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.
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
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
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.
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?
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.
3 Installation
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.
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#.
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.
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.
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.
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.
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.
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
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.
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.
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.
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");
sysManager.ActivateConfiguration();
sysManager.StartRestartTwinCAT();
project.Save();
solution.SaveAs(@"C:\Temp\SolutionFolder\MySolution1\MySolution1.sln");
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"
$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)
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
Please note:
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].
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
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
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.
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)
...
Sample (PowerShell):
$systemItem = $systemManager.LookupTreeItem("TIRC")
foreach($child in $systemItem)
{
write-host$child.Name
}
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).
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.
Basics
* 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.
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]
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));
}
}
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
* ...
* ...
* ============================================================= */
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.
{
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
}
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
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.
This will suppress message box dialogs during usage of the TwinCAT Automation Interface.
The placeholder “pathToPlcProjFile” represents the full path to a *.plcproj file which represents a TwinCAT 3
PLC project.
The following TFS API DLLs are being used within this documentation:
• Microsoft.TeamFoundation.Client
• Microsoft.TeamFoundation.VersionControl.Client
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:
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:
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:
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:
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.
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:
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:
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.
You can also get a list of pending changes made to the item or a collection of items with following line of
code:
For collection of items, consider the overloaded variance with Item[] as argument.
Undo an operation
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.
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.
}
}
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();
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;
}
The DTE interface provides a property called "ActiveWindow", which returns the currently active window in
Visual Studio as an object of type EnvDTE.Window.
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".
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.
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.
$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
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;
sysMan.ActivateConfiguration();
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
The following code snippet demonstrates how to retrieve the TwinCAT project from a connected Target
Runtime.
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.
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.
Unlink variables
To delete all variable mappings in a TwinCAT project, the method ITcSysManager2.ClearMappingInfo() may
be used.
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).
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).
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.
By using SubType = -1, TwinCAT automatically attaches the new variable at the end of the variable list.
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, …).
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().
OR
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.
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.
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().
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.
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.
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().
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
}
// <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>
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();
}
The following code snippet demonstrates how to activate this setting if it is deactivated, e.g. on an EtherCAT
Master device.
General information
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.
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.
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.
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.
The "Scan Devices" functionality mentioned above can be triggered via Automation Interface by calling the
ITcSmTreeItem::ProduceXml() method on the I/O devices node.
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.
The last step only involves activating the configuration on the target device. Simply use the
ITcSysManager::ActivateConfiguration() method to do that.
4.3.3 ADS
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.
<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>
The following code snippet will use the hostname instead of the IP address.
Please note that the XML structure for regular and project routes may be used simultaneously.
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).
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.
This information might then be used to add a route to that ADS device, as described in a separate
documentation article.
To execute a broadcast search with a given hostname or IP address, the following XML structures can be
used in ConsumeXml().
4.3.4 PLC
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:
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.
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:
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.
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.
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 PLC project (to its plcproj file) that needs to be
added. As an alternative, you can also use a PLC project archive (tpzip file).
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.
Please note
A minimum of TwinCAT 3.1 Build 4018 is required to access the interface ITcProjectRoot.
To save a PLC project as a PLC library, you need to make use of the ITcPlcIECProject
[} 157]::SaveAsLibrary() [} 159] method.
The second parameter determines whether the library should be installed to the default repository after it has
been saved as a file.
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>
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.
The following code snippet demonstrates how to use the ITcPlcProject interface to set Boot project options
for a PLC project.
To save the whole TwinCAT solution in an ZIP compatible archive (*.tszip), the ITcSysManager9 interface
may be used.
To reload a previously saved TSZIP file, the DTE method AddFromTemplate() may be used.
To save a specific PLC project in an ZIP compatible archive (*.tpzip), the method
ITcSmTreeItem::ExportChild() may be used.
To reload a previously saved TPZIP file, the ITcSmTreeItem::CreateChild() method may be used.
Calling CheckAllObjects()
To call the CheckAllObjects() method on the PLC Nested Project, you can use the corresponding method
that is available in interface ITcPlcIECProject2.
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.
To be able to handle this object correctly, you need to type cast it to the ITcPlcLibraryManager interface.
ITcPlcLibraryManager libManager = (ITcPlcLibraryManager) 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).
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.
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().
The display name of a library can be determined in the properties window of a library or placeholder:
Adding libraries:
Adding placeholders:
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
Library references can be removed by either specifying their name, version and distributor or by specifying
their display name.
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).
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.
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.
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.
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.
To uninstall a library from the repository, use the ITcPlcLibraryManager [} 159]::UninstallLibrary() [} 165]
method.
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.
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.
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.
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.
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.
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.
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.
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";
}
}
}
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.
The following access modifiers are valid and may be used as a vInfo parameter, as shown in the table
above: PUBLIC, PRIVATE, PROTECTED, INTERNAL.
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:
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)
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.
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
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
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].
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).
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.
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:
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.
Please note: Should you have trouble using the bstrBefore parameter, please try to insert the terminal on a
"device-level", for example:
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:
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
The Previous Port of an EtherCAT terminal determines the position of the terminal inside the EtherCAT
topology.
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.
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.
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.
In TwinCAT Automation Interface, the same can be achieved by consuming the following XML structure on
the EtherCAT slave:
Please note:
• The <GroupMemberCnt> tag needs to specify the exact amount of terminals plus the device itself
EtherCAT SyncUnits can be set via ITcSmTreeItem::ConsumeXml() and by using the following XML
description.
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:
Please note that the Scripting Container [} 171] contains a detailed sample about how to create and
configure network variables with the Automation Interface.
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.
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.
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).
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).
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.
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).
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.
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".
Please see the Scripting Container [} 171] sample "EtherCAT Automation Protocol" for more information.
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.
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.
<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".
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".
Please see the Scripting Container [} 171] sample "EtherCAT Automation Protocol" for more information.
Please see the Scripting Container [} 171] sample "EtherCAT Automation Protocol" for more information.
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.
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.
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:
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.
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.
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.
2. Scan all the devices. (These actions can also be performed via Automation Interface.)
For other Profibus Masters, enter the correct ItemSubtype listed here. This will add the new device as shown
in the screenshot:
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:
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.
Similar to Profibus master, number of Profibus slaves can be published by following code:
$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:
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:
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
For other CANOpen master devices, enter the correct ItemSubtype listed here [} 121]. This will add the new
device as shown in the screenshot:
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:
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.
Similar to CANOpen Master, a list of CANOpen slaves can be published by following code:
The last line of code, claims the EL6751-0010 as the CANOpen slave, similar to the dialog box that appears
in TwinCAT user interface.
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 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.
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.
To add variables to a Devicenet box, simply use the following code snippet. The vInfo parameter specifies
the data type of the variable.
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.
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):
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
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:
The code above assumes that there is already a systemManager objects present in your AI code.
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.
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:
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.
To iterate through all added TcCOM module instances, you may use the ITcModuleManager2 interface. The
following code snippet demonstrates how to use this interface.
$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:
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”.
// 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";
$destModule = $targetDoc.TreeItem.TcModuleInstance.Module
$callByParameter = $destmodule.SelectSingleNode("Parameters/Parameter[Name='CallBy']")
$callByParameter.CreateSymbol = "true"
$targetXml = $targetDoc.OuterXml
$tempController.ConsumeXml($targetXml)
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.
// 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);
$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"
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:
You can determine the TaskObjectId via the XML description of the corresponding task, for example:
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++
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”.
The customer could define own templates, which is documented at the corresponding sub-section if C++
Section / Wizards.
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.
Within a C++ project usually a TwinCAT Module Wizard is used to let the wizard create a module by a
template.
As example for instantiating a Cyclic IO module project please use "TcModuleCyclicCallerWizard " as
pathToTemplateFile.
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.
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).
Please note that C++ projects can’t be renamed, thus the original project name needs to be specified. (cmp.
Renaming TwinCAT C++ projects)
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.).
TMC Code generator could be called to generate C++ code after changes at the TMC file of the C++ project.
</CppProjectDef>
</TreeItem>"
$cppProject.ConsumeXml($startTmcCodeGenerator)
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++.
C++ projects provide different options for the build and deployment process.
These are settable by the Automation Interface.
For the BootProjectEncryption the values “None” and “Target” are valid.
Both other settings are “false” and “true” values.
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
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\)
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
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".
[destination]: Path where the new configuration should be stored on hard disk.
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.
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".
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".
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.
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.
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:
Please use a DLL explorer (e.g. Visual Studio) for a more recent and up-to-date list.
To start/stop a configured Scope record, the corresponding methods from the IMeasurementScope interface
can be used:
((IMeasurementScope)scopeProject.ProjectItems.Item(1).Object).StartRecord()
((IMeasurementScope)scopeProject.ProjectItems.Item(1).Object).StopRecord();
4.3.9 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.
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.
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.
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.
4.3.10 Safety
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.
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).
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.
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).
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.
Methods
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].
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.
Version information
Requirements
5.2.2 ITcSysManager::NewConfiguration
The NewConfiguration() method generates a new TwinCAT configuration file.
HRESULT NewConfiguration();
Return Values
Comments
5.2.3 ITcSysManager::OpenConfiguration
The OpenConfiguration() method loads a previously created TwinCAT configuration file.
HRESULT OpenConfiguration(BSTRbstrFile);
Parameters
Return Values
Comments
5.2.4 ITcSysManager::SaveConfiguration
The SaveConfiguration() method saves a TwinCAT configuration in a file with the specified name.
HRESULT SaveConfiguration(BSTRbstrFile);
Parameters
Return Values
Comments
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
5.2.6 ITcSysManager::IsTwinCATStarted
The IsTwinCATStarted() method evaluates if the TwinCAT System is running.
HRESULT IsTwinCATStarted(VARIANT_BOOL*pStarted);
Parameters
Return Values
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
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
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_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.
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
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.
5.2.10 ITcSysManager2::GetTargetNetId
The GetTargetNetId() method returns the NetId of the current TwinCAT system.
HRESULT GetTargetNetId();
Parameters
None
Return Values
5.2.11 ITcSysManager2::SetTargetNetId
The SetTargetNetId() method sets the NetId of the current TwinCAT system.
HRESULT SetTargetNetId(STRING netId);
Parameters
Return Values
5.2.12 ITcSysManager2::GetLastErrorMessages
The GetLastErrorMessages() metod returns the last error messages.
HRESULT GetLastErrorMessages();
Parameters
None
Return Values
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.
Return Values
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;
ipItem->Release();
Comments
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
Return Values
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.
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].
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
Methods
Version information
Requirements
In the resulting XML file, the item type is represented by the node <ItemType>.
NC item types
Requirements
Notes
1
requires TwinCAT 3.1
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.
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)
There are a few exceptions to this rule, e.g. for RS232 terminals. The following table gives an overview
about these exceptions:
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:
5.3.3.3 Devices
Devices: Miscellaneous
Devices: Ethernet
Devices: USB
Devices: Hilscher
Devices: Indramat
Devices: Phoenix
5.3.3.4 Boxes
5.3.3.5 Terminals
5.3.3.5.1 ITcSmTreeItem Item Sub Types: Terminals: K-Bus digital input (KL1)
5.3.3.5.2 ITcSmTreeItem Item Sub Types: Terminals: K-Bus digital output (KL2)
5.3.3.5.3 ITcSmTreeItem Item Sub Types: Terminals: K-Bus analog input (KL3)
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.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
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.4 ITcSmTreeItem::ProduceXml
The ProduceXml() method returns a XML string with item specific information and parameter.
HRESULT ProduceXml(VARIANT_BOOLbRecursive, BSTR* pXML);
Parameters
Return Values
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.
<?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
Return Values
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);
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).
Parameters
Return Values
Depending on theitem subtypeof the new child item,someadditional informationmay berequiredto create the
child item. This information can be provided via the vInfo parameter.
5.3.7 ITcSmTreeItem::DeleteChild
Deletes a child item.
HRESULT DeleteChild(BSTRbstrName);
Parameters
Return Values
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
Return Values
5.3.9 ITcSmTreeItem::ExportChild
Exports a child item to the clipboard or a file.
HRESULT ExportChild(BSTRbstrName, BSTRbstrFile);
Parameters
Return Values
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
5.3.11 ITcSmTreeItem::GetLastXmlError
Gets the Item path / Error message of the last erroneous ConsumeXml [} 147] call.
HRESULT GetLastXmlError(BSTR *pXML);
Parameters
Return Values
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
Properties
Version information
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
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
Version information
Requirements
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].
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.
Version information
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.
Version information
Requirements
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:
Version information
Requirements
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].
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
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
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
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
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
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
Return Values
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.
Version information
Requirements
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
);
Parameters
Return Values
Comments
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
Return Values
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
Return Values
5.9.5 ITcPlcLibraryManager::InstallLibrary
Installs a library into an existing library repository.
HRESULT InstallLibrary(BSTR bstrRepositoryName, BSTR bstrLibPath, VARIANT_BOOL bOverwrite);
Parameters
Return Values
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
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
Comments
5.9.8 ITcPlcLibraryManager::RemoveRepository
Removes a library repository. A repository is specified by its unique name.
HRESULT RemoveRepository(BSTR bstrName);
Parameters
bstrName
5.9.9 ITcPlcLibraryManager::ScanLibraries
Returns a collection of all registered libraries in all repositories.
HRESULT ScanLibraries(ITcPlcLibraries** ppEnumLibraries);
Parameters
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>
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
Return Values
5.9.11 ITcPlcLibraryManager::UninstallLibrary
Uninstalls a library from a repository.
HRESULT UninstallLibrary(BSTR bstrRepositoryName, BSTR bstrLibraryName, BSTR bstrVersion, BSTR
bstrDistributor);
Parameters
5.10 ITcPlcReferences
ITcPlcReferences represents a collection of ITcPlcLibRef [} 167] objects, which is returned for example when
using the property ITcPlcLibraryManager [} 159]::References.
Requirements
Version information
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.
Version information
Requirements
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.
Requirements
Version information
5.12.2 ITcPlcLibraries::get_Item
Returns ITcPlcLibrary object on specified position.
HRESULT AddLibrary(long n, ITcPlcLibrary** pipType);
Parameters
5.13 ITcPlcLibRef
ITcPlcLibRef represents a base class for either ITcPlcLibrary [} 166] or ITcPlcPlaceholderRef [} 168] objects.
Requirements
Version information
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.
Version information
Requirements
5.15 ITcPlcLibRepository
The ITcPlcLibRepository interface represents a single repository, for example when used with collection
ITcPlcLibRepositories [} 169] and property ITcPlcLibraryManager [} 159]::Repositories.
Properties
Version information
Requirements
5.16 ITcPlcLibRepositories
5.16.1 ITcPlcLibRepositories
ITcPlcLibraries represents a collection of ITcPlcLibRepository [} 168] objects, for example when using
property ITcPlcLibraryManager [} 159]::Repositories.
Requirements
Version information
5.16.2 ITcPlcLibRepositories::get_Item
Returns ITcPlcLibRepository object on specified position.
HRESULT AddLibrary(long n, ITcPlcLibRepository** ppRepo);
Parameters
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:
Requirements
6 Samples
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]
This article describes the general structure of the Scripting Container application and consists of the
following topics:
• Basic structure
• First time setup
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.
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
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.
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.
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.
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).
The abstract class "Script" defines methods and attributes which are common for both the ScriptEarlyBound
and ScriptLateBound classes.
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.
Please also compare the implementation of existing sample scripts to get a better understanding about how
each method works.
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?")
After you have started the CodeGenerationDemo application, its GUI will look as follows:
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".
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.
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.
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.
This structure specifies the I/Os, Axis, PLC libraries and linking.
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.
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.
The Visual Studio Plugin will be made available in the TwinCAT menu in Visual Studio.
7 Appendix
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.