0% found this document useful (0 votes)
507 views1,292 pages

Simatic TIA Portal Openness: API For Automation of Engineering Workflows

Uploaded by

GUSTAVO PEREZ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
507 views1,292 pages

Simatic TIA Portal Openness: API For Automation of Engineering Workflows

Uploaded by

GUSTAVO PEREZ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1292

Security note 1

What's new in TIA Portal


Openness? 2
Readme TIA Portal
Openness 3
SIMATIC

Basics 4
TIA Portal
Openness: API for automation of
engineering workflows TIA Portal Openness API 5

Export/import 6
System Manual

Major Changes 7

Online documentation

05/2021
Online documentation
Legal information
Warning notice system
This manual contains notices you have to observe in order to ensure your personal safety, as well as to prevent damage
to property. The notices referring to your personal safety are highlighted in the manual by a safety alert symbol, notices
referring only to property damage have no safety alert symbol. These notices shown below are graded according to
the degree of danger.

DANGER
indicates that death or severe personal injury will result if proper precautions are not taken.

WARNING
indicates that death or severe personal injury may result if proper precautions are not taken.

CAUTION
indicates that minor personal injury can result if proper precautions are not taken.

NOTICE
indicates that property damage can result if proper precautions are not taken.
If more than one degree of danger is present, the warning notice representing the highest degree of danger will be
used. A notice warning of injury to persons with a safety alert symbol may also include a warning relating to property
damage.
Qualified Personnel
The product/system described in this documentation may be operated only by personnel qualified for the specific
task in accordance with the relevant documentation, in particular its warning notices and safety instructions.
Qualified personnel are those who, based on their training and experience, are capable of identifying risks and
avoiding potential hazards when working with these products/systems.
Proper use of Siemens products
Note the following:

WARNING
Siemens products may only be used for the applications described in the catalog and in the relevant technical
documentation. If products and components from other manufacturers are used, these must be recommended or
approved by Siemens. Proper transport, storage, installation, assembly, commissioning, operation and maintenance
are required to ensure that the products operate safely and without any problems. The permissible ambient
conditions must be complied with. The information in the relevant documentation must be observed.

Trademarks
All names identified by ® are registered trademarks of Siemens AG. The remaining trademarks in this publication may
be trademarks whose use by third parties for their own purposes could violate the rights of the owner.
Disclaimer of Liability
We have reviewed the contents of this publication to ensure consistency with the hardware and software described.
Since variance cannot be precluded entirely, we cannot guarantee full consistency. However, the information in this
publication is reviewed regularly and any necessary corrections are included in subsequent editions.

Siemens AG Document order number: Online documentation Copyright © Siemens AG 2021.


Digital Industries Ⓟ 05/2021 Subject to change All rights reserved
Postfach 48 48
90026 NÜRNBERG
GERMANY
Table of contents

1 Security note........................................................................................................................................ 19
2 What's new in TIA Portal Openness?.................................................................................................... 21
3 Readme TIA Portal Openness............................................................................................................... 25
3.1 Readme ............................................................................................................................. 25
3.2 Major changes for long-term stability in TIA Portal Openness V17 ....................................... 28
3.3 Hints for writing long-term stable code .............................................................................. 33
4 Basics ................................................................................................................................................... 35
4.1 Installation ........................................................................................................................ 35
4.1.1 Requirements for TIA Portal Openness ................................................................................ 35
4.1.2 Installing TIA Portal Openness ............................................................................................ 36
4.1.3 Adding users to the "Siemens TIA Openness" user group ..................................................... 37
4.1.4 Accessing the TIA Portal ..................................................................................................... 43
4.1.5 Configurations ................................................................................................................... 43
4.2 Openness tasks.................................................................................................................. 47
4.2.1 Introduction....................................................................................................................... 47
4.2.2 Applications....................................................................................................................... 48
4.2.3 Export/import .................................................................................................................... 49
5 TIA Portal Openness API ...................................................................................................................... 51
5.1 TIA Portal Openness object................................................................................................. 51
5.1.1 TIA Portal Openness object model ...................................................................................... 51
5.1.2 Blocks and types of the TIA Portal Openness object model .................................................. 57
5.1.3 Hierarchy of hardware objects of the object model ............................................................. 65
5.1.4 Object list .......................................................................................................................... 67
5.2 General functions .............................................................................................................. 71
5.2.1 Introduction....................................................................................................................... 71
5.2.2 Information about installed TIA Portal Openness versions ................................................... 71
5.2.3 TIA Portal Openness IntelliSense support ............................................................................ 72
5.2.4 Standard libraries............................................................................................................... 73
5.2.5 Use of the code examples .................................................................................................. 74
5.2.6 Example program............................................................................................................... 76
5.2.7 Programming steps ............................................................................................................ 80
5.2.8 Connecting to the TIA Portal............................................................................................... 81
5.2.9 TIA Portal Openness firewall ............................................................................................... 86
5.2.10 Event handlers................................................................................................................... 87
5.2.11 Program-controlled acknowledgement of dialogs with system events ................................. 89
5.2.12 Terminating the connection to the TIA Portal ...................................................................... 90
5.2.13 Diagnostic interfaces on TIA Portal ..................................................................................... 91
5.2.14 Exclusive access ................................................................................................................. 96
5.2.15 Dynamic behaviours .......................................................................................................... 98
5.2.16 Working with associations................................................................................................ 101
5.2.17 Working with compositions .............................................................................................. 101

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 3
Table of contents

5.2.18 Verifying object equality .................................................................................................. 102


5.2.19 Read operations for attributes .......................................................................................... 103
5.2.20 Transaction handling........................................................................................................ 105
5.2.21 Creating a DirectoryInfo/FileInfo object............................................................................. 107
5.2.22 Self-description support for attributes, navigators, actions, and services ........................... 108
5.2.23 Setting attributes of Blocks, DBs & UDTs ........................................................................... 111
5.2.24 Notes on performance of TIA Portal Openness .................................................................. 112
5.3 Functions for projects and project data ............................................................................. 113
5.3.1 Opening a project ............................................................................................................ 113
5.3.2 Creating a project ............................................................................................................ 118
5.3.3 Accessing general settings of the TIA Portal ...................................................................... 119
5.3.4 Archiving and Retrieving a project .................................................................................... 123
5.3.5 Accessing read-only TIA Portal project .............................................................................. 126
5.3.6 Accessing languages ........................................................................................................ 127
5.3.7 Determining the object structure and attributes................................................................ 129
5.3.8 Access software target .................................................................................................... 131
5.3.9 Accessing and enumerating multilingual texts .................................................................. 132
5.3.10 Updating project property simulation support .................................................................. 133
5.3.11 Read project related attributes.......................................................................................... 134
5.3.12 Deleting project graphics ................................................................................................. 137
5.3.13 Compiling a project.......................................................................................................... 137
5.3.14 Modifying project in UMAC .............................................................................................. 140
5.3.15 Saving a project ............................................................................................................... 141
5.3.16 Closing a project .............................................................................................................. 142
5.4 Functions for Connections................................................................................................ 143
5.4.1 Configurable attributes of a port-to-port connection ......................................................... 143
5.5 Functions on libraries....................................................................................................... 146
5.5.1 Functions for objects and instances .................................................................................. 146
5.5.2 Accessing global libraries ................................................................................................. 147
5.5.3 Accessing global library languages ................................................................................... 149
5.5.4 Opening libraries ............................................................................................................. 151
5.5.5 Enumerating open libraries .............................................................................................. 152
5.5.6 Saving and closing libraries .............................................................................................. 153
5.5.7 Archiving and retrieving a library...................................................................................... 155
5.5.8 Creating global libraries ................................................................................................... 157
5.5.9 Accessing folders in a library ............................................................................................ 158
5.5.10 Accessing types ............................................................................................................... 161
5.5.11 Accessing type versions.................................................................................................... 164
5.5.12 Accessing blocks located in library.................................................................................... 168
5.5.13 Accessing instances ......................................................................................................... 170
5.5.14 Accessing master copies................................................................................................... 172
5.5.15 Create master copy from a project in library...................................................................... 175
5.5.16 Create an object from a master copy ................................................................................ 176
5.5.17 Copying master copies ..................................................................................................... 178
5.5.18 Determining out-of-date type instances............................................................................ 179
5.5.19 Updating the project ........................................................................................................ 182
5.5.20 Updating a library ............................................................................................................ 184
5.5.21 Cleaning up library........................................................................................................... 185
5.5.22 Harmonize project from project library ............................................................................. 186
5.5.23 Updating Structure during Library Update......................................................................... 189
5.5.24 Deleting library content ................................................................................................... 196

Openness: API for automation of engineering workflows


4 System Manual, 05/2021, Online documentation
Table of contents

5.5.25 Setting default version of a type....................................................................................... 199


5.5.26 Getting default version of a type ...................................................................................... 200
5.5.27 Improved types consistency state ..................................................................................... 200
5.6 Functions for accessing devices, networks and connections .............................................. 204
5.6.1 Open the "Devices & networks" editor............................................................................... 204
5.6.2 Querying PLC and HMI targets.......................................................................................... 205
5.6.3 Accessing attributes of an address object.......................................................................... 206
5.6.4 Accessing the channels of a module ................................................................................. 209
5.7 Functions on networks..................................................................................................... 211
5.7.1 Creating a subnet............................................................................................................. 211
5.7.2 Accessing subnets............................................................................................................ 212
5.7.3 Accessing internal subnets ............................................................................................... 213
5.7.4 Get type identifier of subnets ........................................................................................... 214
5.7.5 Accessing attributes of a subnet ....................................................................................... 215
5.7.6 Deleting a global subnet .................................................................................................. 221
5.7.7 Enumerate all participants of a subnet.............................................................................. 221
5.7.8 Enumerate IO systems of a subnet.................................................................................... 222
5.7.9 Accessing nodes .............................................................................................................. 222
5.7.10 Accessing attributes of a node.......................................................................................... 223
5.7.11 Connecting a node to a subnet......................................................................................... 227
5.7.12 Disconnect a node from a subnet ..................................................................................... 228
5.7.13 Creating an IO system ...................................................................................................... 228
5.7.14 Accessing the attributes of an IO system........................................................................... 229
5.7.15 Connecting an IO connector to an IO system .................................................................... 230
5.7.16 Get master system or IO system of an interface ................................................................ 231
5.7.17 Get an IO Controller ......................................................................................................... 232
5.7.18 Get an IO Connector ........................................................................................................ 232
5.7.19 Disconnecting an IO connector from an IO system or a DP mastersystem .......................... 233
5.7.20 Accessing attributes of a DP mastersystem ....................................................................... 234
5.7.21 Accessing attributes of PN Driver ...................................................................................... 235
5.7.22 Accessing attributes of a profinet io system ...................................................................... 236
5.7.23 Deleting a DP master system ............................................................................................ 237
5.7.24 Deleting a profinet io system ............................................................................................ 238
5.7.25 Creating a DP master system ............................................................................................ 238
5.7.26 Accessing port interconnection information of port device item........................................ 239
5.7.27 Attributes of port inter-connection ................................................................................... 240
5.7.28 Accessing the attributes of a port ..................................................................................... 243
5.7.29 Enumerate DP master systems of a subnet........................................................................ 244
5.7.30 Enumerate assigned IO connectors................................................................................... 245
5.7.31 Connecting a DP IO connector to a DP master system ....................................................... 246
5.7.32 Accessing AS-i profile and parameter attributes for virtual slaves ....................................... 246
5.7.33 Accessing CM DP as DP slave and transfer area.................................................................. 249
5.7.34 Coupling 1516 isochron central and decentral Profinet .................................................... 250
5.7.35 Openness for CP 1604/CP 1616/CP 1626 .......................................................................... 253
5.7.36 Openness transfer areas for PnPn coupler ......................................................................... 256
5.7.37 Openness virtual modules/submodules for ET 200SP PN HF .............................................. 260
5.7.38 Accessing domain settings ............................................................................................... 262
5.8 Functions on devices........................................................................................................ 265
5.8.1 Mandatory attributes of devices ....................................................................................... 265
5.8.2 Get type identifier of devices and device items.................................................................. 266
5.8.3 Set App ID on device and device Items.............................................................................. 269

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 5
Table of contents

5.8.4 Get App ID on device and device Items ............................................................................. 270


5.8.5 Remove App ID on device and device items ...................................................................... 271
5.8.6 Creating a device ............................................................................................................. 272
5.8.7 Enumerating devices........................................................................................................ 273
5.8.8 Accessing devices ............................................................................................................ 276
5.8.9 Deleting a device ............................................................................................................. 278
5.9 Functions on device items ................................................................................................ 280
5.9.1 Mandatory attributes of device items ............................................................................... 280
5.9.2 Creating and plugging a device item ................................................................................ 282
5.9.3 Moving device items into another slot .............................................................................. 285
5.9.4 Copying a device item ...................................................................................................... 286
5.9.5 Deleting a device item...................................................................................................... 287
5.9.6 Enumerate device items .................................................................................................. 288
5.9.7 Accessing device items..................................................................................................... 289
5.9.8 Accessing device item as interface.................................................................................... 293
5.9.9 Accessing attributes of an I/O device interface .................................................................. 294
5.9.10 Accessing attributes of IoController .................................................................................. 296
5.9.11 Accessing attributes of IoConnector ................................................................................. 297
5.9.12 Accessing address controller............................................................................................. 299
5.9.13 Accessing addresses......................................................................................................... 300
5.9.14 Accessing hardware identifiers ......................................................................................... 302
5.9.15 Accessing hardware identifier controller ........................................................................... 303
5.9.16 Accessing channels of device items .................................................................................. 304
5.9.17 Creating and exporting psc file ......................................................................................... 305
5.9.18 Connection handling for extension racks .......................................................................... 306
5.10 Functions for accessing the data of an HMI device ............................................................ 308
5.10.1 Screens............................................................................................................................ 308
5.10.1.1 Creating user-defined screen folders................................................................................. 308
5.10.1.2 Deleting a screen from a folder......................................................................................... 308
5.10.1.3 Deleting a screen template from a folder .......................................................................... 309
5.10.1.4 Deleting all screens from a folder ..................................................................................... 310
5.10.2 Cycles .............................................................................................................................. 311
5.10.2.1 Deleting a cycle................................................................................................................ 311
5.10.3 Text lists .......................................................................................................................... 311
5.10.3.1 Deleting a text list ............................................................................................................ 311
5.10.4 Graphic lists..................................................................................................................... 312
5.10.4.1 Deleting a graphic list ...................................................................................................... 312
5.10.5 Connections .................................................................................................................... 313
5.10.5.1 Deleting a connection ...................................................................................................... 313
5.10.6 Tag table.......................................................................................................................... 313
5.10.6.1 Creating user-defined folders for HMI tags ........................................................................ 313
5.10.6.2 Enumerating tags of an HMI tag table .............................................................................. 314
5.10.6.3 Deleting an individual tag from an HMI tag table .............................................................. 314
5.10.6.4 Deleting a tag table from a folder ..................................................................................... 315
5.10.7 VB scripts......................................................................................................................... 316
5.10.7.1 Creating user-defined script folders .................................................................................. 316
5.10.7.2 Deleting a VB script from a folder ..................................................................................... 316
5.10.7.3 Deleting a user-defined folder of an HMI device ............................................................... 317
5.11 Functions for accessing the data of an HMI Unified device (RT Unified) .............................. 318
5.11.1 Object list (RT Unified)...................................................................................................... 318
5.11.2 Rename properties and data types (RT Unified) ................................................................. 318

Openness: API for automation of engineering workflows


6 System Manual, 05/2021, Online documentation
Table of contents

5.11.3 HMI Unified Software object (RT Unified) .......................................................................... 320


5.11.4 Querying errors (RT Unified) ............................................................................................. 322
5.11.5 Alarms (RT Unified) .......................................................................................................... 326
5.11.5.1 Working with analog alarms (RT Unified) .......................................................................... 326
5.11.5.2 Working with discrete alarms (RT Unified)......................................................................... 329
5.11.5.3 Working with alarm classes (RT Unified)............................................................................ 332
5.11.6 Logs (RT Unified).............................................................................................................. 334
5.11.6.1 Working with data logs (RT Unified).................................................................................. 334
5.11.6.2 Working with alarm logs (RT Unified) ................................................................................ 337
5.11.6.3 Working with logging tags (RT Unified)............................................................................. 341
5.11.6.4 Working with audit trail (RT Unified) ................................................................................. 344
5.11.7 Tags and tag tables (RT Unified)........................................................................................ 346
5.11.7.1 Working with tag tables (RT Unified)................................................................................. 346
5.11.7.2 Working with HMI tags (RT Unified) .................................................................................. 348
5.11.7.3 Working with system tags (RT Unified).............................................................................. 357
5.11.8 Connections (RT Unified).................................................................................................. 358
5.11.8.1 Working with connections (RT Unified) ............................................................................. 358
5.11.9 Runtime settings (RT Unified) ........................................................................................... 362
5.11.9.1 Working with runtime settings (RT Unified)....................................................................... 362
5.11.10 Screens and dynamizations (RT Unified) ........................................................................... 363
5.11.10.1 Working with screens (RT Unified) .................................................................................... 363
5.11.10.2 Basic screen items (RT Unified) ......................................................................................... 368
5.11.10.3 Element screen items (RT Unified) .................................................................................... 393
5.11.10.4 Control screen items (RT Unified)...................................................................................... 423
5.11.10.5 Faceplate instance screen items (RT Unified)..................................................................... 446
5.11.10.6 Working with events for screen/screen items & properties (RT Unified) .............................. 453
5.11.10.7 Working with dynamization & events for screen/screen items using scripts (RT Unified) ..... 456
5.11.10.8 Working with dynamization for screens/screen items (RT Unified)...................................... 459
5.11.10.9 Checking license for access Unified device (RT Unified)...................................................... 462
5.11.11 Accessing device name of HMI Panel (RT Unified).............................................................. 464
5.11.12 Accessing common plant model hierarchies (RT Unified)................................................... 465
5.11.12.1 Working with plant view (RT Unified) ................................................................................ 465
5.11.12.2 Working with plant view nodes (RT Unified)...................................................................... 466
5.11.12.3 Enumerating plant view (RT Unified) ................................................................................ 468
5.11.12.4 Working with plant view to device (RT Unified) ................................................................. 470
5.11.13 Accessing common plant model instance (RT Unified)....................................................... 471
5.11.13.1 Working with CPM object instance (RT Unified) ................................................................. 471
5.11.13.2 Working with plant view nodes of CPM object instance (RT Unified) .................................. 472
5.11.13.3 Enumerating interface tags of CPM object instance (RT Unified) ....................................... 474
5.11.14 Accessing properties for interface/logging tags of plant object instances (RT Unified) ........ 475
5.11.14.1 Accessing/Updating properties of interface tags of CPM plant object instances (RT Unified)... 475
5.11.14.2 Accessing/Updating properties of members tags of interface tags (RT Unified) .................. 477
5.11.14.3 Accessing/Updating properties of logging tags of member tags (RT Unified) ...................... 479
5.12 Functions for accessing the data of a PLC device ............................................................... 482
5.12.1 Functions for downloading data to PLC device .................................................................. 482
5.12.1.1 Downloading PC System .................................................................................................. 482
5.12.1.2 Downloading hardware and software components to PLC device ...................................... 485
5.12.1.3 Downloading Master Secret to PLC ................................................................................... 496
5.12.1.4 Managing PLC Master Secret in PLCs ................................................................................. 498
5.12.1.5 Setting / deleting a PLC Master Secret in a PLCs ................................................................ 500
5.12.1.6 Running and stopping PLC................................................................................................ 501
5.12.1.7 Supporting callbacks ........................................................................................................ 502

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 7
Table of contents

5.12.1.8 Protecting PLC through password ..................................................................................... 504


5.12.1.9 Handling PLC block binding passwords ............................................................................. 505
5.12.1.10 Uploading hardware, software and files to PLC device ....................................................... 506
5.12.1.11 Comparing PLC software .................................................................................................. 512
5.12.1.12 Comparing PLC hardware ................................................................................................. 515
5.12.2 Functions for accessing PLC service .................................................................................. 516
5.12.2.1 Access level setting .......................................................................................................... 516
5.12.2.2 Accessing OPC UA server interface ................................................................................... 518
5.12.2.3 Accessing Software Checksum ......................................................................................... 520
5.12.2.4 Assigning PC interface...................................................................................................... 521
5.12.2.5 Determining the status of a PLC........................................................................................ 523
5.12.2.6 Accessing parameters of an online connection ................................................................. 524
5.12.2.7 Accessing fingerprint for quick station compare ................................................................ 528
5.12.2.8 Setting PLC online of R/H system ...................................................................................... 536
5.12.2.9 Accessing software container from primary PLC of R/H system ......................................... 538
5.12.2.10 Downloading PLCs of R/H System ..................................................................................... 539
5.12.2.11 Establishing or disconnecting the online connection to the PLC ........................................ 546
5.12.2.12 Assigning project language to PLC .................................................................................... 547
5.12.2.13 Assigning watch & force tables for web server and PLC display .......................................... 548
5.12.2.14 Managing certificate ........................................................................................................ 551
5.12.2.15 Supporting secure S7 communication TLS ........................................................................ 554
5.12.2.16 Updating module description ........................................................................................... 559
5.12.2.17 Supporting IP Accessibility................................................................................................ 561
5.12.2.18 Setting a display password ............................................................................................... 561
5.12.2.19 Accessing web server and OPC UA user management ....................................................... 562
5.12.3 Blocks.............................................................................................................................. 566
5.12.3.1 Querying the "Program blocks" group ............................................................................... 566
5.12.3.2 Querying the system group for system blocks ................................................................... 566
5.12.3.3 Enumerating system subgroups ....................................................................................... 567
5.12.3.4 Enumerating user-defined block groups............................................................................ 568
5.12.3.5 Enumerating all blocks..................................................................................................... 569
5.12.3.6 Querying information of a block/user data type ................................................................ 570
5.12.3.7 Setting and removing protections from a block ................................................................. 572
5.12.3.8 Deleting block.................................................................................................................. 574
5.12.3.9 Creating group for blocks ................................................................................................. 575
5.12.3.10 Deleting group for blocks ................................................................................................. 576
5.12.3.11 Accessing attributes of all blocks ...................................................................................... 576
5.12.3.12 Creating a ProDiag-FB ...................................................................................................... 578
5.12.3.13 Accessing supervisions and properties of ProDiag-FB ........................................................ 579
5.12.3.14 Assigning ProDiag FB for DBs & Tag Table.......................................................................... 581
5.12.3.15 Reading ProDiag-FB blocks and attributes ......................................................................... 583
5.12.3.16 Accessing value of DB parameter without export .............................................................. 583
5.12.3.17 Adding an external file ..................................................................................................... 585
5.12.3.18 Generate source from block ............................................................................................. 586
5.12.3.19 Generating blocks from source......................................................................................... 587
5.12.3.20 Generating from source of known source format ............................................................. 588
5.12.3.21 Deleting user data type .................................................................................................... 591
5.12.3.22 Deleting an external file ................................................................................................... 591
5.12.3.23 Starting the block editor................................................................................................... 592
5.12.3.24 Changing blocks using fingerprints................................................................................... 593
5.12.3.25 Generating/deleting blocks for user defined pages ............................................................ 594
5.12.3.26 Writing access for OB block priority attribute..................................................................... 596

Openness: API for automation of engineering workflows


8 System Manual, 05/2021, Online documentation
Table of contents

5.12.3.27 Generating block/UDT from external source file in specific user group................................ 597
5.12.4 Technology objects .......................................................................................................... 598
5.12.4.1 Overview of functions for technology objects ................................................................... 598
5.12.4.2 Overview of technology objects and versions ................................................................... 599
5.12.4.3 Overview of data types .................................................................................................... 600
5.12.4.4 Querying the composition of technology objects .............................................................. 601
5.12.4.5 Creating technology object .............................................................................................. 602
5.12.4.6 Deleting technology object .............................................................................................. 603
5.12.4.7 Compiling technology object............................................................................................ 604
5.12.4.8 Enumerating technology object ....................................................................................... 605
5.12.4.9 Finding technology object................................................................................................ 606
5.12.4.10 Enumerating parameters of technology object ................................................................. 607
5.12.4.11 Finding parameters of technology object.......................................................................... 607
5.12.4.12 Reading parameters of technology object ......................................................................... 608
5.12.4.13 Writing parameters of technology object .......................................................................... 609
5.12.4.14 S7-1200 Motion Control................................................................................................... 610
5.12.4.15 S7-1500 Motion Control................................................................................................... 619
5.12.4.16 PID control....................................................................................................................... 640
5.12.4.17 Counting ......................................................................................................................... 641
5.12.4.18 Easy Motion Control......................................................................................................... 641
5.12.5 Tags and Tag tables .......................................................................................................... 642
5.12.5.1 Starting the "PLC Tags" editor ........................................................................................... 642
5.12.5.2 Querying system groups for PLC tags................................................................................ 643
5.12.5.3 Creating PLC tag table ...................................................................................................... 643
5.12.5.4 Enumerating user-defined groups for PLC tags .................................................................. 644
5.12.5.5 Creating user-defined groups for PLC tags ......................................................................... 645
5.12.5.6 Deleting user-defined groups for PLC tags ......................................................................... 646
5.12.5.7 Enumerating PLC tag tables in a folder ............................................................................. 646
5.12.5.8 Querying information from a PLC tag table ....................................................................... 647
5.12.5.9 Reading the time of the last changes of a PLC tag table..................................................... 649
5.12.5.10 Deleting a PLC tag table from a group............................................................................... 649
5.12.5.11 Enumerating PLC tags ...................................................................................................... 650
5.12.5.12 Accessing PLC tags ........................................................................................................... 650
5.12.5.13 Accessing PLC constants................................................................................................... 652
5.12.6 Functions for software units............................................................................................. 654
5.12.6.1 Working with software unit .............................................................................................. 654
5.12.6.2 Accessing software unit ................................................................................................... 657
5.12.6.3 Accessing software unit underlying objects ...................................................................... 658
5.12.6.4 Accessing to existing relations of a unit ............................................................................ 660
5.12.6.5 Updating software unit properties.................................................................................... 662
5.12.6.6 Publishing software unit object ........................................................................................ 664
5.12.6.7 Adding external sources in units....................................................................................... 666
5.12.6.8 Units as mastercopies ...................................................................................................... 668
5.12.6.9 Updating existing relations & create/delete relations......................................................... 670
5.13 Functions for Version Control Interface............................................................................. 676
5.13.1 Accessing VCI system group in project .............................................................................. 676
5.13.2 Enumerating user groups in VCI group ............................................................................. 676
5.13.3 Creating VCI user group in VCI group ................................................................................ 677
5.13.4 Updating VCI group properties ......................................................................................... 678
5.13.5 Deleting VCI user group.................................................................................................... 679
5.13.6 Enumerating VCI workspaces in VCI group........................................................................ 679
5.13.7 Creating VCI workspace in VCI group ................................................................................ 680

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 9
Table of contents

5.13.8 Updating VCI workspace properties .................................................................................. 681


5.13.9 Deleting VCI workspace.................................................................................................... 682
5.13.10 Enumerating VCI workspace mappings in VCI ................................................................... 683
5.13.11 Creating VCI workspace mapping in VCI workspace........................................................... 684
5.13.12 Updating VCI workspace mapping properties.................................................................... 685
5.13.13 Deleting VCI workspace mapping ..................................................................................... 685
5.13.14 Synchronizing a workspace mapping................................................................................ 686
5.14 Functions support for Multiuser ....................................................................................... 690
5.14.1 Creating project server connection ................................................................................... 690
5.14.2 Editing project server connection ..................................................................................... 691
5.14.3 Deleting project server connection ................................................................................... 692
5.14.4 Getting project server connection from TIA Portal Setting ................................................. 692
5.14.5 Adding a project to server ................................................................................................ 693
5.14.6 Getting server projects ..................................................................................................... 694
5.14.7 Getting available local sessions......................................................................................... 695
5.14.8 Creating a local session .................................................................................................... 696
5.14.9 Saving a local session....................................................................................................... 697
5.14.10 Deleting local session from server .................................................................................... 698
5.14.11 Opening local/exclusive session........................................................................................ 699
5.14.12 Opening server project..................................................................................................... 700
5.14.13 Checking marked objects ................................................................................................. 701
5.14.14 Closing local session ........................................................................................................ 703
5.14.15 Commiting server project changes ................................................................................... 704
5.14.16 Getting lockstate provider ................................................................................................ 705
5.14.17 Checking project locked ................................................................................................... 706
5.14.18 Getting lock owner .......................................................................................................... 707
5.14.19 Checking session UptoDate .............................................................................................. 708
5.14.20 Getting markings from local session ................................................................................. 709
5.15 Functions for accessing data of the user management ...................................................... 711
5.15.1 Functions for accessing user, roles and function rights...................................................... 711
5.15.1.1 Protecting Project............................................................................................................. 711
5.15.1.2 Engineering Function Rights............................................................................................. 712
5.15.1.3 Device Function Righhts................................................................................................... 713
5.15.1.4 System Roles.................................................................................................................... 714
5.15.1.5 Custom Roles ................................................................................................................... 715
5.15.1.6 Project Users.................................................................................................................... 718
5.15.2 Functions for UMAC Global Users and UMC Server ............................................................ 720
5.15.2.1 Authentication to connect to a UMC Server ...................................................................... 720
5.15.2.2 Retrieving an UMC User Group from a UMC Server............................................................ 721
5.15.2.3 Retrieving an UMC User from a UMC Server ...................................................................... 722
5.15.2.4 Adding an UMC User Group.............................................................................................. 723
5.15.2.5 Getting all UMC groups in TIA Portal ................................................................................. 723
5.15.2.6 Adding an UMC User to TIA Portal..................................................................................... 724
5.15.2.7 Getting all UMC Users in TIA Portal project........................................................................ 725
5.15.2.8 Finding an UMC User added in TIA Portal ......................................................................... 725
5.15.2.9 Finding an UMC User group added in TIA Portal project..................................................... 726
5.15.2.10 Assigning role to UMC User .............................................................................................. 727
5.15.2.11 Getting the list of assigned roles of UMC User and UMC User Group. ................................. 727
5.15.2.12 Assigning role to UMC User Group .................................................................................... 728
5.15.2.13 Removing role from UMC User and UMC User Group......................................................... 729
5.15.2.14 Activating/Deactivating UMC User and UMC User Group ................................................... 730

Openness: API for automation of engineering workflows


10 System Manual, 05/2021, Online documentation
Table of contents

5.15.2.15 Checking state for UMC User and UMC User Group ........................................................... 730
5.15.2.16 Deleting UMC User and UMC User Group .......................................................................... 731
5.15.2.17 Complete sample code..................................................................................................... 732
5.16 Functions on OPC............................................................................................................. 740
5.16.1 Configuring OPC UA server secure communication protocol .............................................. 740
5.16.2 Setting OPC UA security policy.......................................................................................... 742
5.17 SiVArc Openness .............................................................................................................. 744
5.17.1 Introduction..................................................................................................................... 744
5.17.2 SiVArc service properties ................................................................................................. 744
5.17.3 Copying rules or groups from library................................................................................. 746
5.17.4 Finding a screen rule and screen rule group...................................................................... 747
5.17.5 Deleting rules and rule groups.......................................................................................... 748
5.17.6 UMAC set up for openness ............................................................................................... 749
5.17.7 SiVArc generation ............................................................................................................ 749
5.18 Functions for SINUMERIK 840D sl ..................................................................................... 752
5.18.1 Introduction..................................................................................................................... 752
5.18.2 Type identifier - identifier of the components .................................................................... 752
5.18.3 Fundamentals.................................................................................................................. 753
5.18.4 Object model ................................................................................................................... 756
5.18.5 Code example.................................................................................................................. 758
5.18.5.1 General ........................................................................................................................... 758
5.18.5.2 Executing the first steps in SINUMERIK.............................................................................. 758
5.18.5.3 Creating an NCU .............................................................................................................. 758
5.18.5.4 Creating an NX module .................................................................................................... 759
5.18.5.5 Connecting an NX module with NCU ................................................................................ 759
5.18.5.6 Activating Safety Integrated ............................................................................................. 760
5.18.5.7 Accessing PLC software .................................................................................................... 761
5.19 Functions for SINUMERIK ONE .......................................................................................... 763
5.19.1 Introduction..................................................................................................................... 763
5.19.2 Type identifier designation of the components ................................................................. 763
5.19.3 Fundamentals.................................................................................................................. 764
5.19.4 Object model ................................................................................................................... 767
5.19.5 Reference ........................................................................................................................ 769
5.19.5.1 Namespace Siemens.Engineering.MC.DriveConfiguration ................................................. 769
5.19.5.2 Namespace Siemens.Engineering.MC.Drives .................................................................... 777
5.19.5.3 ArchiveProvider................................................................................................................ 785
5.19.6 Code example.................................................................................................................. 786
5.19.6.1 General ........................................................................................................................... 786
5.19.6.2 Executing the first steps in SINUMERIK.............................................................................. 786
5.19.6.3 Creating an NCU .............................................................................................................. 787
5.19.6.4 Creating an NX module .................................................................................................... 787
5.19.6.5 Connecting an NX module with NCU ................................................................................ 788
5.19.6.6 Accessing NCK events ...................................................................................................... 788
5.19.6.7 Creating archives ............................................................................................................. 789
5.19.6.8 Activating Safety Integrated ............................................................................................. 791
5.19.6.9 Accessing PLC software .................................................................................................... 792
5.19.6.10 Examples for Namespace Siemens.Engineering.MC.DriveConfiguration............................. 793
5.19.6.11 Examples for Namespace Siemens.Engineering.MC.Drives ................................................ 797
5.20 Functions for Startdrive.................................................................................................... 802
5.20.1 Introduction..................................................................................................................... 802

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 11
Table of contents

5.20.2 Security information ........................................................................................................ 802


5.20.2.1 Encrypted communication with SecureString passwords ................................................... 802
5.20.2.2 Passwords in TIA Openness .............................................................................................. 803
5.20.3 TypeIdentifier - identifier of the components..................................................................... 803
5.20.4 References....................................................................................................................... 805
5.20.4.1 AddressComposition ........................................................................................................ 805
5.20.4.2 AddressContext................................................................................................................ 805
5.20.4.3 AddressIoType.................................................................................................................. 806
5.20.4.4 Commissioning ................................................................................................................ 806
5.20.4.5 ConfigurationEntry .......................................................................................................... 807
5.20.4.6 DriveDomainFunctions..................................................................................................... 807
5.20.4.7 DriveObject...................................................................................................................... 808
5.20.4.8 DriveObjectActivation ...................................................................................................... 808
5.20.4.9 DriveObjectContainer....................................................................................................... 809
5.20.4.10 DriveObjectTypeHandler................................................................................................... 809
5.20.4.11 DriveParameter ................................................................................................................ 810
5.20.4.12 DriveParameterComposition............................................................................................. 811
5.20.4.13 EncoderConfiguration ...................................................................................................... 812
5.20.4.14 HardwareProjection ......................................................................................................... 813
5.20.4.15 MotorConfiguration ......................................................................................................... 814
5.20.4.16 OnlineDriveObject ........................................................................................................... 815
5.20.4.17 OnlineDriveObjectContainer............................................................................................. 815
5.20.4.18 StartDriveDownloadCheckConfiguration ........................................................................... 816
5.20.4.19 SafetyTelegram ................................................................................................................ 816
5.20.4.20 Telegram ......................................................................................................................... 817
5.20.4.21 TelegramComposition ...................................................................................................... 818
5.20.4.22 TelegramType .................................................................................................................. 819
5.20.4.23 TorqueTelegram ............................................................................................................... 819
5.20.5 Code examples ................................................................................................................ 820
5.20.5.1 Determining the activation status..................................................................................... 820
5.20.5.2 Executing drive functions ................................................................................................. 821
5.20.5.3 Creating a drive unit......................................................................................................... 821
5.20.5.4 Creating a drive component ............................................................................................. 822
5.20.5.5 Determining a drive object ............................................................................................... 823
5.20.5.6 Determining the drive object type .................................................................................... 823
5.20.5.7 Reading and writing BICO parameters............................................................................... 824
5.20.5.8 Download........................................................................................................................ 825
5.20.5.9 Editing DRIVE-CLiQ connections ....................................................................................... 827
5.20.5.10 Carrying out the first steps in Startdrive ............................................................................ 828
5.20.5.11 Defining the encoder type ................................................................................................ 829
5.20.5.12 Configuring devices.......................................................................................................... 836
5.20.5.13 Creating a component for a drive component (S120 only) ................................................ 837
5.20.5.14 Defining the motor type and motor configuration ............................................................. 838
5.20.5.15 Reading and writing parameters....................................................................................... 840
5.20.5.16 Reading and writing parameters online ............................................................................ 842
5.20.5.17 Saving the parameterization............................................................................................. 842
5.20.5.18 How to assign a SecureString password ............................................................................ 843
5.20.5.19 Using Safety Integrated telegrams .................................................................................... 844
5.20.5.20 Setting the SIMOGEAR article number for G115D drives.................................................... 845
5.20.5.21 Inserting and extending telegrams ................................................................................... 845
5.20.5.22 Using torque telegrams .................................................................................................... 846
5.20.5.23 Restoring factory settings................................................................................................. 847

Openness: API for automation of engineering workflows


12 System Manual, 05/2021, Online documentation
Table of contents

5.21 Functions for DCC ............................................................................................................ 848


5.21.1 Introduction..................................................................................................................... 848
5.21.2 DCC Openness ................................................................................................................. 848
5.21.3 DCC Openness object model ............................................................................................ 849
5.21.4 References....................................................................................................................... 850
5.21.4.1 DriveControlChartContainer ............................................................................................. 850
5.21.4.2 DriveControlChartComposition......................................................................................... 850
5.21.4.3 DccImportOptions............................................................................................................ 851
5.21.4.4 DccImportResultData ....................................................................................................... 851
5.21.4.5 DriveControlChart ............................................................................................................ 852
5.21.4.6 Importing DCB extension library....................................................................................... 852
5.21.5 Code examples ................................................................................................................ 853
5.21.5.1 General ........................................................................................................................... 853
5.21.5.2 Accessing a DriveControlChartContainer via DriveObject................................................... 853
5.21.5.3 Retrieving charts .............................................................................................................. 853
5.21.5.4 Accessing charts .............................................................................................................. 853
5.21.5.5 Importing charts .............................................................................................................. 854
5.21.5.6 Exporting charts .............................................................................................................. 854
5.21.5.7 Export all charts............................................................................................................... 854
5.21.5.8 Retrieving charts in the order in which they are executed.................................................. 855
5.21.5.9 Finding charts based on their names ................................................................................ 855
5.21.5.10 Displaying an import report.............................................................................................. 855
5.21.5.11 Deleting a chart ............................................................................................................... 856
5.21.5.12 Optimizing the execution sequence.................................................................................. 856
5.21.5.13 Importing a DCB Extension library .................................................................................... 857
5.21.6 DCC Openness exceptions ................................................................................................ 858
5.21.6.1 Exception handling .......................................................................................................... 858
5.21.6.2 DriveControlChart Exceptions........................................................................................... 859
5.21.6.3 DriveControlChartComposition exceptions........................................................................ 860
5.21.6.4 ImportDcbLibrary Exceptions............................................................................................ 861
5.22 Exceptions ....................................................................................................................... 862
5.22.1 Handling exceptions ........................................................................................................ 862
5.23 F-related Openness .......................................................................................................... 865
5.23.1 F-related Openness .......................................................................................................... 865
5.23.2 SafetyModificationsPossible.............................................................................................. 866
5.23.3 UsernameForFChangeHistory........................................................................................... 867
5.23.4 SafetySignatureProvider ................................................................................................... 867
5.23.5 SafetyAdministration ....................................................................................................... 868
5.23.5.1 SafetyAdministration ....................................................................................................... 868
5.23.5.2 IsSafetyOfflineProgramPasswordSet .................................................................................. 868
5.23.5.3 SetSafetyOfflineProgramPassword .................................................................................... 868
5.23.5.4 RevokeSafetyOfflineProgramPassword .............................................................................. 869
5.23.5.5 IsLoggedOnToSafetyOfflineProgram.................................................................................. 870
5.23.5.6 LoginToSafetyOfflineProgram............................................................................................ 870
5.23.5.7 LogoffFromSafetyOfflineProgram ...................................................................................... 870
5.23.5.8 Runtime Groups............................................................................................................... 871
5.23.5.9 Safety settings ................................................................................................................. 875
5.23.6 SafetyPrintout.................................................................................................................. 878
6 Export/import .................................................................................................................................... 879
6.1 Overview ......................................................................................................................... 879

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 13
Table of contents

6.1.1 Basic principles of importing/exporting............................................................................. 879


6.1.2 Field of application for Import/Export ............................................................................... 881
6.1.3 Version Specific Simatic ML Import ................................................................................... 882
6.1.4 Editing the XML file .......................................................................................................... 883
6.1.5 Exporting configuration data............................................................................................ 884
6.1.6 Importing configuration data ........................................................................................... 885
6.2 Import/export of project data ........................................................................................... 887
6.2.1 Project graphics ............................................................................................................... 887
6.2.1.1 Exporting/importing graphics........................................................................................... 887
6.2.1.2 Exporting all graphics of a project .................................................................................... 888
6.2.1.3 Importing graphics to a project ........................................................................................ 889
6.2.2 Project texts..................................................................................................................... 890
6.2.2.1 Export of project texts...................................................................................................... 890
6.2.2.2 Import of project texts ..................................................................................................... 891
6.3 Importing/exporting data of an HMI device....................................................................... 893
6.3.1 Data structure for import/export....................................................................................... 893
6.3.1.1 Structure of an XML file .................................................................................................... 893
6.3.1.2 Structure of the data for importing/exporting ................................................................... 895
6.3.1.3 Cycles .............................................................................................................................. 898
6.3.2 Tag tables ........................................................................................................................ 900
6.3.2.1 Exporting HMI tag tables.................................................................................................. 900
6.3.2.2 Importing HMI tag table................................................................................................... 903
6.3.2.3 Exporting an individual tag from an HMI tag table ............................................................ 904
6.3.2.4 Importing an individual tag into an HMI tag table ............................................................. 905
6.3.2.5 Special considerations for the export/import of HMI tags .................................................. 905
6.3.3 VB scripts......................................................................................................................... 907
6.3.3.1 Exporting VB scripts ......................................................................................................... 907
6.3.3.2 Exporting VB scripts from a folder..................................................................................... 908
6.3.3.3 Importing VB scripts......................................................................................................... 909
6.3.4 Text lists .......................................................................................................................... 910
6.3.4.1 Exporting text lists from an HMI device............................................................................. 910
6.3.4.2 Importing a text list into an HMI device ............................................................................ 910
6.3.4.3 Advanced XML formats for export/import of text lists........................................................ 911
6.3.5 Graphic lists..................................................................................................................... 913
6.3.5.1 Exporting graphic lists...................................................................................................... 913
6.3.5.2 Importing a graphic list .................................................................................................... 913
6.3.6 Connections .................................................................................................................... 914
6.3.6.1 Exporting connections ..................................................................................................... 914
6.3.6.2 Importing connections..................................................................................................... 915
6.3.7 Screens............................................................................................................................ 916
6.3.7.1 Overview of exportable screen objects ............................................................................. 916
6.3.7.2 Exporting all screens of an HMI device.............................................................................. 920
6.3.7.3 Exporting a screen from a screen folder............................................................................ 921
6.3.7.4 Importing screens to an HMI device.................................................................................. 923
6.3.7.5 Exporting permanent areas .............................................................................................. 925
6.3.7.6 Importing permanent areas.............................................................................................. 926
6.3.7.7 Exporting all screen templates of an HMI device ............................................................... 927
6.3.7.8 Exporting screen templates from a folder ......................................................................... 928
6.3.7.9 Importing screen templates.............................................................................................. 930
6.3.7.10 Exporting a pop-up screen ............................................................................................... 931
6.3.7.11 Importing a pop-up screen ............................................................................................... 932

Openness: API for automation of engineering workflows


14 System Manual, 05/2021, Online documentation
Table of contents

6.3.7.12 Exporting a slide-in screen ............................................................................................... 934


6.3.7.13 Importing a slide-in screen ............................................................................................... 935
6.3.7.14 Exporting a screen with a faceplate instance .................................................................... 936
6.3.7.15 Importing a screen with a faceplate instance .................................................................... 938
6.4 Importing/exporting data of a PLC device ......................................................................... 942
6.4.1 Blocks.............................................................................................................................. 942
6.4.1.1 XML structure of the block interface section .................................................................... 942
6.4.1.2 Changes of the object model and XML file format ............................................................. 952
6.4.1.3 Exporting DBs with snapshots .......................................................................................... 954
6.4.1.4 Exporting blocks with know-how protection ..................................................................... 956
6.4.1.5 Export/Import of SCL blocks ............................................................................................. 956
6.4.1.6 Export/Import of structured types of SCL blocks ................................................................ 970
6.4.1.7 Export/Import of SCL call blocks ....................................................................................... 976
6.4.1.8 Export/Import multilingual comments in SCL ................................................................... 993
6.4.1.9 Exporting failsafe blocks .................................................................................................. 994
6.4.1.10 Exporting system blocks................................................................................................... 994
6.4.1.11 Exporting GRAPH blocks with multi-language text ............................................................ 995
6.4.1.12 Importing block ............................................................................................................... 996
6.4.1.13 Exporting blocks ............................................................................................................. 998
6.4.1.14 Importing blocks/UDT with open reference ..................................................................... 1005
6.4.1.15 Importing blocks/UDT for structural change object.......................................................... 1006
6.4.1.16 Export/Import of unit specific publishing attribute of blocks and types ............................ 1008
6.4.1.17 Creating Instance DB...................................................................................................... 1012
6.4.1.18 Accessing DB value parameter without export ................................................................ 1013
6.4.1.19 Export/Import of Plc Alarm TextLists ............................................................................... 1014
6.4.1.20 Export/Import of Alarm classes ....................................................................................... 1020
6.4.1.21 Export/Import of global supervision for ProDiag-FB ......................................................... 1024
6.4.1.22 Export/import of ProDiag supervisions from Global overview editor ................................ 1025
6.4.1.23 Export/Import of settings for ProDiag supervisions.......................................................... 1027
6.4.1.24 Export/Import Watch & Force Table................................................................................. 1029
6.4.1.25 Exporting user data type ................................................................................................ 1031
6.4.1.26 Importing user data type................................................................................................ 1032
6.4.1.27 Export of data in OPC UA XML format ............................................................................. 1033
6.4.1.28 Export/Import of UDT & DB............................................................................................. 1033
6.4.1.29 Export/Import of Array & Instance DB ............................................................................. 1040
6.4.2 Technology objects ........................................................................................................ 1046
6.4.2.1 Overview of technology objects and versions ................................................................. 1046
6.4.2.2 XML structure of the block interface section ................................................................... 1047
6.4.2.3 Exporting technology objects ......................................................................................... 1049
6.4.2.4 Importing technology objects......................................................................................... 1051
6.4.2.5 S7-1200 Motion Control................................................................................................. 1052
6.4.2.6 S7-1500 Motion Control................................................................................................. 1055
6.4.2.7 PID control..................................................................................................................... 1065
6.4.2.8 Counting ....................................................................................................................... 1066
6.4.2.9 Easy Motion Control....................................................................................................... 1066
6.4.3 Tag tables ...................................................................................................................... 1067
6.4.3.1 Exporting PLC tag tables................................................................................................. 1067
6.4.3.2 Importing PLC tag table.................................................................................................. 1068
6.4.3.3 Exporting an individual tag or constant from a PLC tag table........................................... 1069
6.4.3.4 Importing an individual tag or constant into a PLC tag table............................................ 1070
6.5 Importing/exporting hardware data................................................................................ 1072

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 15
Table of contents

6.5.1 AML file format .............................................................................................................. 1072


6.5.2 Pruned AML ................................................................................................................... 1072
6.5.3 Overview of the objects and parameters of the CAx import/export .................................. 1074
6.5.4 Structure of the CAx data for importing/exporting .......................................................... 1076
6.5.5 AML type identifiers ....................................................................................................... 1080
6.5.6 Export/Import of base unit Information via AML.............................................................. 1083
6.5.7 Export/Import AML with extension rack connection ........................................................ 1086
6.5.8 Connection handling for extension racks ........................................................................ 1092
6.5.9 Export of CAx data ......................................................................................................... 1093
6.5.10 Import of CAx data......................................................................................................... 1097
6.5.11 Export/Import of sub modules ........................................................................................ 1099
6.5.12 Export/Import AML file in UMAC environment................................................................. 1113
6.5.13 Export/Import AML file with normalized type identifier.................................................... 1114
6.5.14 Export/import AML file with custom attributes in GSD/GSDML ......................................... 1114
6.5.15 Import CAx data without logical address......................................................................... 1121
6.5.16 Exceptions during import and export of CAx data ........................................................... 1128
6.5.17 Round trip exchange of devices and modules ................................................................. 1129
6.5.18 Import AML ignoring unknown artifacts ......................................................................... 1132
6.5.19 Export/Import topology.................................................................................................. 1140
6.5.20 Import of device with Library references......................................................................... 1141
6.5.21 Export of a device object ................................................................................................ 1165
6.5.22 Import of a device object................................................................................................ 1168
6.5.23 Export/Import of device with set address ........................................................................ 1171
6.5.24 Export/Import of device with channels ........................................................................... 1174
6.5.25 Export of device item objects ......................................................................................... 1176
6.5.26 Import of device item objects ......................................................................................... 1181
6.5.27 Export/Import of GSD/GSDML based devices and device items......................................... 1184
6.5.28 Export/Import device configuration with virtual interface................................................ 1190
6.5.29 Export/Import of subnets ............................................................................................... 1193
6.5.30 Export/Import of IO-systems........................................................................................... 1201
6.5.31 Export/Import of multilingual comments ........................................................................ 1203
6.5.32 Export/Import ET200 SP/ET200 AL devices with extension rack connections .................... 1205
6.5.33 Export/Import of ARE APC Drive 1.2.0 ............................................................................. 1217
6.5.34 Export/Import of PLC tags............................................................................................... 1219
6.5.35 Export/Import of RH/PLC................................................................................................. 1221
6.5.36 Export/Import AML with customized tag and deviceitems ............................................... 1223
6.5.37 Export/Import of FailSafe PLC ......................................................................................... 1226
6.5.38 Export/Import of Failsafe IO............................................................................................ 1233
6.5.39 Export/Import vendor specific attribute .......................................................................... 1235
6.5.40 AML attributes versus TIA Portal Openness attributes...................................................... 1236
7 Major Changes ................................................................................................................................. 1239
7.1 Major changes in TIA Portal Openness V16 ..................................................................... 1239
7.2 Major changes in TIA Portal Openness V15.1 .................................................................. 1241
7.3 Major changes in TIA Portal Openness V15 ..................................................................... 1244
7.4 Major changes in V14 SP1 .............................................................................................. 1246
7.4.1 Major changes in V14 SP1 .............................................................................................. 1246
7.4.2 Major changes in the object model................................................................................. 1249
7.4.3 Changes on pilot functionality........................................................................................ 1253
7.4.4 Changes for export and import....................................................................................... 1258
7.4.4.1 Changes for export and import....................................................................................... 1258

Openness: API for automation of engineering workflows


16 System Manual, 05/2021, Online documentation
Table of contents

7.4.4.2 Changes in API............................................................................................................... 1258


7.4.4.3 Schema extension.......................................................................................................... 1259
7.4.4.4 Schema changes............................................................................................................ 1262
7.4.4.5 Behaviour changes......................................................................................................... 1265
7.4.4.6 Block attribute changes.................................................................................................. 1276
7.5 Major changes in V14 .................................................................................................... 1278
7.5.1 Major changes of the object model ................................................................................ 1278
7.5.2 Before updating an application to TIA Portal Openness V14 ............................................ 1280
7.5.3 Major string changes...................................................................................................... 1280
7.5.4 Import of files generated with TIA Portal Openness V13 SP1 and previous ....................... 1284
Index ................................................................................................................................................ 1287

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 17
Table of contents

Openness: API for automation of engineering workflows


18 System Manual, 05/2021, Online documentation
Security note 1
Security information
Siemens provides products and solutions with industrial security functions that support the
secure operation of plants, systems, machines, equipment and/or networks.
In order to protect plants, systems, machines and networks against cyber threats, it is necessary
to implement – and continuously maintain – a holistic, state-of-the-art industrial security
concept. Siemens’ products and solutions only form one element of such a concept.
Customer is responsible to prevent unauthorized access to its plants, systems, machines and
networks. Systems, machines and components should only be connected to the enterprise
network or the internet if and to the extent necessary and with appropriate security measures
(e.g. use of firewalls and network segmentation) in place.
Additionally, Siemens’ guidance on appropriate security measures should be taken into account.
For more information about industrial security, please visit
http://www.siemens.com/industrialsecurity
Siemens’ products and solutions undergo continuous development to make them more secure.
Siemens strongly recommends to apply product updates as soon as available and to always use
the latest product versions. Use of product versions that are no longer supported, and failure to
apply latest updates may increase customer’s exposure to cyber threats.
To stay informed about product updates, subscribe to the Siemens Industrial Security RSS Feed
under
http://www.siemens.com/industrialsecurity

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 19
Security note

Openness: API for automation of engineering workflows


20 System Manual, 05/2021, Online documentation
What's new in TIA Portal Openness? 2
Compatibility and long term stability
• Siemens.Engineering.dll assemblies
Because the Siemens.Engineering.dll assemblies of V15, V15.1, V16 and V17 are included in
the scope of delivery, applications based on V15, V15.1 and V16 also run in V17 without
modification. To make use of the functions of V17, you must integrate the DLL of V17 and
recompile the application.
The Siemens.Engineering.dll assemblies can be found in the installation directory under
"PublicAPI\[version]\". For example, the V15 dll can be found as "C:\Program Files\Siemens
\Automation\Portal V*\PublicAPI\V15\Siemens.Engineering.dll".
Note
V14SP1 Siemens.Engineering.dll will not be available as part of TIA Portal Openness V17.

• Exporting Simatic ML files


The Siemens.Engineering.dll assemblies V15, V15.1, V16 and V17 will create Simatic ML
files of TIA Portal version V17.
• Importing Simatic ML files
Each Siemens.Engineering.dll assemblies is able to import Simatic ML files from that version
and any supported version from a previous release. For example, Simatic ML files of V16 can
be imported with Siemens.Engineering.dll assemblies V17. Simatic ML files of V17 can not be
imported with Siemens.Engineering.dll assemblies V16.
• Generate Siemens.engineering.dll with Net Framework 4.8 version
An Openness client application with .Net Framework 4.6.1 loaded with
Siemens.Engineering.dll runs successfully with .Net 4.8 version.
When there is a recompilation required on the Openness client applicaton, then the
application should be in .Net Framework 4.8 .

Note
V* refer to the installed version of the TIA Portal Openness API.

For changes to the object model see Major Changes in TIA Portal Openness V17 for further
information.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 21
What's new in TIA Portal Openness?

New features
The following new features and innovations are available in TIA Portal Openness V17. You can
find additional details on the various topics in the individual sections of the product
documentation.
• Extensions for project generation of PLC programs:
– Creation of instance DBs for FBs in the following additional languages: LAD, FBD, STL, SCL,
Graph, Cause Effect Matrix (CEM)
– Write access to the "PriorityNumber" OB attribute
– Modules or data types from "ExternalSourceGroup" can be generated directly into a
subgroup.
– Direct read access to DB tags and write access to their "StartValue" property
• Extension for devices with IP address not configured in the project when downloading to the
PLC
• Extensions for Safety engineering:
– Write access for most attributes of the Safety Administration Editor (SAE)
– Configuration of the Safety engineering password (set, reset, lock, unlock)
– Compiling the Safety hardware and Safety software
– Loading of changes in the standard software or standard hardware configuration to an F-
PLC with unchanged Safety program / Safety hardware configuration
– Documentation generation (Safety printout)
• Extended support for library processes:
– Structure applied when updating the library
– Clean up library
– Harmonize project
– Force update
– Reading and setting the default version of a type
– Reading the status information of library types
• Extension of CAx export and import:
– Support of the AML specification AR APC v1.2
– Support of Safety Base Units for ET200SP modules
– Exchange of manufacturer-specific hardware parameters for GSD/GSDML-based devices
– Option to export normalized order numbers (MLFB)
– Tolerant import of order numbers (MLFB)

Openness: API for automation of engineering workflows


22 System Manual, 05/2021, Online documentation
What's new in TIA Portal Openness?

• Support for protected projects (UMAC):


– Activation of project protection
– Method extension for opening a protected project
– Configuration of users and roles in the project
– Openness function right to prevent changes to a protected project via the Openness API
• Support of the Openness API in a multiuser session
• Support of multi-user processes
– Create, modify and delete server connections
– Read out the available projects, sessions on a project server
– Add projects to the project server
– Create, open, save and close multi-user sessions
– Information about changed objects
– Apply or discard changes (exclusive sessions / server project view)
• Extended export/import support for alarms and ProDiag
– Export/import of alarm classes
– Export/import of system diagnostics settings
– Export/import of ProDiag supervisions and supervision settings
– Export/import of global supervisions of a ProDiag FB
– Exporting/importing UDT supervisions
• Support of TIA Portal Test Suite Advanced
– Export/import of rule sets and test cases
– Execution of rule sets and test cases
– Provision of test results from application tests or style guide checks as .NET objects
• Enhancements for Startdrive
– Write access to MRP communication attributes for all drive devices that support this
function
– Support for G115D
• Openness API enhancement
– Load software changes into all CPU families

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 23
What's new in TIA Portal Openness?

Openness: API for automation of engineering workflows


24 System Manual, 05/2021, Online documentation
Readme TIA Portal Openness 3
3.1 Readme

Security measures for TIA Portal Openness applications


It is recommended
• to install a TIA Portal Openness application with admin rights to the programs folder.
• to avoid the dynamical loading of program parts like assemblies or dlls from the users area.
• to run the TIA Portal Openness application with user rights.

Hardware parameters
A description of hardware parameters is available in the installation folder of TIA Portal at
Siemens\Automation\Portal V*\PublicAPI\V*\HW Parameter Description
\Openness_hardware_parameter_description.pdf

Note
V* refers to adapted path according to the installed version of TIA Portal.

Copying a TIA Portal Openness application


When you copy an executable TIA Portal Openness application, it may occur under certain
circumstances that the directory path in which the TIA Portal Openness application was
originally created is read out by the TIA Portal Openness application.
Remedy:
If you have copied the TIA Portal Openness application to a new directory, open and close the
properties dialog to update the Windows cache.

Support of specific features in a TIA Portal project

Failsafe
When you are using TIA Portal Openness there are restrictions regarding failsafe. Please consider
the documentation "SIMATIC Safety - Configuring and Programming" for further information.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 25
Readme TIA Portal Openness
3.1 Readme

Improvement of the TIA Portal Openness performance


To achieve the maximum performance of TIA Portal Openness you can switch off the global
search feature of the TIA Portal. To switch off the global search use the GUI or the TIA Portal
Openness API call. When the TIA Portal Openness application is finished the global search could
be switched on again. Although this is improving the performance, all TIA Portal Openness
features work fine even with global search switched on.

Thread-safe program code


Take care that your code is thread-safe, an event appears in a different thread.

Export behaviour of screen items with style enabled


Export of a screen items with style enabled will not export the attributes of the style item, but
those of the screen item before activating the style. If a style is selected and
UseDesignColorSchema for the screen item is checked, the screen item fetches the attribute
values from the style in the user interface but the attribute values of the screen item that were
set before selecting the style are still stored in the database for this screen item. TIA Portal
Openness exports these actual values that are stored in the database.
After disabling and enabling the style and exporting the screen item again, the same attribute
values will be exported for the screen item like in the style item. If UseDesignColorSchema is
unchecked, the attribute values of the selected style item are saved to the database for that
screen item.
This problem can be solved by following the steps below:
1. Associate the screen item to the style item:
– The database contains the attribute values before activating the style.
– The user interfaces fetches attributes from the style item directly.
2. Export the screen item associated to the style item:
– The XML file contains the attribute values from the database which are those before
activating style.
3. Disable the UseDesignColorSchema:
– The attribute values of style item are written in the attributes of the screen item in the
database.
4. Enable the UseDesignColorSchema:
– The attribute values of the screen item in the database are not changed and are still the
ones from 3.
– The user interfaces fetches attributes from the style item directly.
5. Export the screen item associated to the style item:
– The XML file contains the attribute values from the database which were set at step 3,
which are the same as the values in the style item.

Openness: API for automation of engineering workflows


26 System Manual, 05/2021, Online documentation
Readme TIA Portal Openness
3.1 Readme

Importing ASi slaves via AML


If one of the following ASi slaves is imported via an aml-file the firmware version of the device
item will be set to V13.0 in all cases:
• ASIsafe FS400 RCV-B: 3SF7 844-*B***-***1
• ASIsafe FS400 RCV-M: 3SF7 844-*M***-***1
• ASIsafe FS400 TRX-M: 3SF7 844-*M***-**T0
• ASIsafe FS400 RCV-C: 3SF7 844-*T***-***1

Exporting and importing function keys


Function keys are synchronized during the import. If a function key is created in the global screen
and the key is empty in the screen, the corresponding function key will use the global definition
in all screens.
If you want to disable the global use of function keys after the import, define empty keys in the
screens and import the screen types in the following order: Global screen, templates, screens.
If you want to ensure when exporting the screens that the global definition of a function key is
not used by the template or by the global screen, create an empty function key in the screen.
Select the required function key in the screen, then enable the "Use global assignment" property
and disable it again.

Accessing a device while Online


Writing attributes of a device that is Online is not supported. Reading attributes is supported.
Disconnecting a subnet is not supported when the device is online.

Instance-specific attributes when importing blocks via TIA Portal Openness


In certain situations, the import rules can mean the loss of instance-specific attributes, such as
start values, for example.

Writing access for OB block priority attribute


The Priority attribute name for write access for OB block is changed to PriorityNumber.

Information on specific features


Please See FAQ entries in Siemens Industry Online Support for further information concerning
the following Openness functionalities:
• Archive/retrieve project
• Export/import watch tables

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 27
Readme TIA Portal Openness
3.2 Major changes for long-term stability in TIA Portal Openness V17

3.2 Major changes for long-term stability in TIA Portal Openness V17

Changes
If you have considered the hints concerning programming across versions and you do not
rebuild your Openness application to V17 your applications will run without any restrictions on
any computer even if only a TIA Portal V17 is installed.
If you rebuild your Openness application to V17 it is necessary to recompile your application
using the SiemensEngineering.dll of V17. In some cases it might be necessary to adapt the code
of your application.

Change in implementation of GetAttribute


Up to TIA Portal Openness V16, the visibility of the implementation of GetAttribute/SetAttribute/
GetAttributeInfos is dependent on the fact whether the type declares as "Supports dynamic
attribute". To access methods like GetAttribute/SetAttribute/GetAttributeInfos, Then the type
should support dynamic attributes. When the type does not support dynamic attributes, then
you have to explicitly cast to IEngineeringObject to get the methods GetAttribute/SetAttribute/
GetAttributeInfos.
The below code sample shows how the code is executed up to TIA Portal Openness V16:

var projectAttributeInfos = ((IEngineeringObject) project).GetAttributeInfos();

With TIA Portal Openness V17, all methods of IEngineeringObject is implicitly implemented on
all types that implement IEngineeringObject so that the explicit cast is not required, all methods
will be visible to you. The change will be available in all previous version engineering dll's i.e V15,
V15.1 & V16 supported in V17.
For following methods, typecast is not required:
• object GetAttribute(string name) - Gets an attribute with the given name.
• IList<EngineeringAttributeInfo> GetAttributeInfos() - Returns a collection of
EngineeringAttributeInfo objects describing the different attributes on this object.
• IList<object> GetAttributes(IEnumerable<string> names) - Gets a list of attributes for the
given names.
• void SetAttribute(string name, object value) - Sets an attribute with the given name to the
given value.
• void SetAttributes(IEnumerable<KeyValuePair<string, object>> attributes) - Sets the
attributes with the given names to the given values as indicated in attribute
By introducing this change, there will be a slight change-in behavior if you recompile the code
used under extension method. For example when you have used extension method and when
the code is compiled into the V17 engineering dll, call from the extension method doesn’t get
executed. In this case you would have to change code to stay with the behavior compatible.
There would also be no compiler error.

Openness: API for automation of engineering workflows


28 System Manual, 05/2021, Online documentation
Readme TIA Portal Openness
3.2 Major changes for long-term stability in TIA Portal Openness V17

The below example code explains where GetAttribute method doesn’t get executed:

static class CustomerExtension


{
public static object GetAttribute(this Project project, string name)
{
// Customer Logic
return ((IEngineeringObject)project);
}
}

Changes on AssignInterface API


Before TIA Portal Openness V17, the AssignInterface API cannot be not used inside a transaction
in TIA Portal Openness application. With TIA Portal Openness V17, this behaviour is changed and
AssignInterface API can be used in transaction.

Setting master system number


With TIA Portal Openness V17, it is possible to set the master system number during the import
of a API.

Removal of ExternalSourceCreate method


Before TIA Portal Openness V17, the Create action from ExternalSource is supported with "Not
Supported Exception" in TIA Portal Openness application. With TIA Portal Openness V17, the
Create action from external sources composition will be removed.

Removal of attribute SyncRole


Before TIA Portal Openness V17, the attribute "SyncRole" is read-only for IPC627D device. With
TIA Portal Openness V17, the attribute "SyncRole" will be removed from device where the
attribute serves no purpose.

Change in behaviour of Safety Compile


Before TIA Portal Openness V17, Failsafe with a set password and without a user being logged
in is not supported and throws compile error result. With TIA Portal Openness V17, this
behaviour is changed from compile error to an exception.

Removal of download configuration


With TIA Portal Openness V17, STEP7 specific download configurations are no longer available
in TIA Portal Openness without STEP7 installed.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 29
Readme TIA Portal Openness
3.2 Major changes for long-term stability in TIA Portal Openness V17

Restriction concerning attribute "SecondaryType" when importing OB MC-Transformation


With TIA Portal Openness V17, when importing the OB MC-Transformation, the attribute
"SecondaryType" needs to have the exact string value "Transformation" (which is also the value
that is exported).

Export ProDiag Information


With TIA Portal Openness V17, you can export ProDiag alarm messages within a ProDiag FB via
public Openness API in CSV format.
The output can be viewed in Microsoft Excel.

Changes in behavior of ExportInstanceTextsToXlsx and ExportToXlsx method in


PlcAlarmTextProvider
Before TIA Portal Openness V17, if the file (given as path parameter) already exists, the file will
be overwritten during the export. With TIA Portal Openness V17, this behaviour is changed and
if the file (given as path parameter) already exists, UserException will be thrown to the user.

Changes in behavior of Export API to accept specific path


Before TIA Portal Openness V17, In Export API, specific paths are not allowed.
EngineeringTargetInvocationDetailException.SpecificPathException exception will be thrown
when specific path is specified.
With TIA Portal Openness V17, this behavior is changed and the specific paths are allowed.
Below are the scenarios where TIA Portal Openness API allows specific path.

Input path TIA Poral Openness V17


D:SampleDirectory\Sample No exception is thrown
D:\SampleDirectory/Sample No exception is thrown
D:\SampleDirectory\Sample No exception is thrown
D:\\SampleDirectory\Sample No exception is thrown
D:\\\SampleDirectory\Sample No exception is thrown
D:\\SampleDirectory\\Sample No exception is thrown
D:\\\\\\SampleDirectory\\\Sample No exception is thrown
D:\\SampleDirectory\\\Sample No exception is thrown
\\SampleDirectory\Sample No exception is thrown
\\SampleDirectory\\Sample No exception is thrown
\\\\SampleDirectory\\\\Sample No exception is thrown
\\\\SampleDirectory\\\\Sample No exception is thrown
//SampleDirectory/Sample No exception is thrown
"SampleDirectory" EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.

Openness: API for automation of engineering workflows


30 System Manual, 05/2021, Online documentation
Readme TIA Portal Openness
3.2 Major changes for long-term stability in TIA Portal Openness V17

Input path TIA Poral Openness V17


"//SampleDirectory" EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.
"D:\SampleDirectory\Sample\..\otherSample" EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.
"SampleDirectory\Sample" EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.
"..\Sample", "SampleName" EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.
"D:\ SampleDirectory\Sample" EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.
D:\SampleDirectory\ \Sample EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.
D:\SampleDirectory\Sample EngineeringTargetInvocationDetailException.SpecificPathEx‐
ception is thrown from export Openness API.

Changes in data type of ScreenNumber attribute


With TIA Portal Openness V17 Siemens.Engineering.dll, the data type of ScreenNumber
attribute is changed from Byte to UInt16.

Changes in behavior of CAx Export/Import


With TIA Portal Openness V17, following changes are done for CAx export/import:
• Support for custom(user specific) attributes on GSD/GSDML devices.
• An user can exchange CAx data on multiuser projects and UMAC protected projects.
• Support for exchange of CAx data with normalized TypeIdentifier. This facility is controlled via
CAx user interface
• The structure of PN PN Coupler device inside AML file has changed. This is to avoid the internal
structural differences in the exchanging tools (TIAP and ECAD systems) and arrive at a
common structure for exchange.
• Export/Import of Plus PC Stations are supported. Remark: Exchange with EPLAN and other
Tools will not work, since the additional defined attributes are not defined in AR APC.
• During Import, user notification for start address/network address re-assignment in case it is
adjusted due to internal operations of TIAP. For ex: Any subnet/io system connection failures,
Address overlapping etc., . This facility is controlled via CAx user interface Settings.
• A warning user notification incase user imports an AML file with OMS and security enabled
PLC's.
• A new attribute ‘ProfinetDeviceName’ for all Ethernet nodes is introduced.
• The device with pluggable profinet/profibus interface deviceitem is always exported with
‘segregated’ roles. A pluggable interface deviceitem in TIA project shall be exported as a
pluggable device item with DeviceItem role (having a ‘new’ child device item with
CommunicationInterface role). However, Import of older AML files shall be supported always.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 31
Readme TIA Portal Openness
3.2 Major changes for long-term stability in TIA Portal Openness V17

• Supports more tolerant (independent of IoType order within deviceitem) start address
import.
• Import of compact module using ‘TemplateReference’ with some restrictions supported.

Support of blocks of new programming language CEM


With TIA Portal Openness V17, the new programming language CEM (Cause Effect Matrix) was
introduced. If you encounter an instance of such a block accessing the attribute Programming
Language in any Siemens.Engineering.dll < V17 will throw an exception. In Engineering.dll V17,
the correct programming language is returned. Blocks of programming language CEM do not
support the Export-method in any Siemens.Engineering.dll.

Support of new library types "Unified Faceplate" and "Unified Graphic"


With TIA Portal Openness V17, the new library types “Unified Faceplate” and “Unified Graphic”
was introduced. These types are not supported in Openness. If you encounter instances of these
types all versions of Siemens.Engineering.dll will thrown an exception.

Openness: API for automation of engineering workflows


32 System Manual, 05/2021, Online documentation
Readme TIA Portal Openness
3.3 Hints for writing long-term stable code

3.3 Hints for writing long-term stable code

Version change
If you consider some hints for writing long-term stable code you will be able to use your
application with other versions of the TIA Portal without modifying the code of your application.

Note
V* and *.ap* in document refer to the adapted path and extension according to the installed
version of the TIA Portal.

Registry path and appconfig file


Modifications are necessary to change registry path and application configuration file, for
instance:
“C:\Program Files\Siemens\Automation\Portal V14\PublicAPI\V14 SP1\Siemens.Engineering.dll”
has to be changed to
“C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Siemens.Engineering.dll”
To write long-term stable code, the registry path should be configurable and the application
configuration file must be updated.

Installation path
Modifications are necessary to change the installation path of TIA Portal, for instance:
“C:\Program Files\Siemens\Automation\Portal V14\PublicAPI\V14 SP1\Siemens.Engineering.dll”
has to be changed to
“C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Siemens.Engineering.dll”
To write long-term stable code, the installation path should be configurable.

Path of AmiHost
Modifications are necessary to change the path of AmiHost, for instance:
“C:\Program Files\Siemens\Automation\Portal V14\bin\Siemens.Automation.Cax.AmiHost.exe”
has to be changed to “C:\Program Files\Siemens\Automation\Portal V*\bin
\Siemens.Automation.Cax.AmiHost.exe”
To write long-term stable code, the path of AmiHost should be configurable.

Extensions of TIA Portal project files and libraries


Modifications are necessary to change the extensions of TIA Portal project file and of libraries, for
instance:
*.ap14
has to be changed to
*.ap*
To write long-term stable code, the extensions of TIA Portal project files and libraries should be
configurable.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 33
Readme TIA Portal Openness
3.3 Hints for writing long-term stable code

Opening a project
To write long-term stable code, the Projects.OpenWithUpgrade method should be used
instead of the Projects.Open method.

Hierarchy of compare, compile or download results


The hierarchy and/or the order of compare, compile or download results might change across
versions.
To write long-term stable code, you should avoid making assumptions about the depth and order
of specific results.
The class layout is actually considered long term stable, mention explicit type names
CompilerResult, CompareResult, DownloadResult, UploadResult. There is also a new results
class: UploadResult. Content, hierarchy and order follow what is presented on the TIA Portal user
interface of the currently executed or installed TIA Portal.

Openness: API for automation of engineering workflows


34 System Manual, 05/2021, Online documentation
Basics 4
4.1 Installation

4.1.1 Requirements for TIA Portal Openness

Requirements for using TIA Openness applications


• A product based on the TIA Portal is installed on the PC, for example, "STEP 7 Professional" or
"WinCC Professional".
• The "TIA Portal Openness" is installed on the PC.
See Installing TIA Portal Openness (Page 36)

Supported Windows operating systems


The following table shows which combinations of Windows operating system, TIA Portal and
user application are mutually compatible:

Windows operating system TIA Portal User application


64-bit 64-bit 32-bit, 64-bit and "Any CPU"

Requirements for programming TIA Portal Openness applications


• Microsoft Visual Studio 2017 or later with .Net Framework SDK 4.8 and the Windows Classic
Desktop package

Necessary user knowledge


• Knowledge as a system engineer
• Advanced knowledge of Microsoft Visual Studio 2017 or later with .Net Framework SDK 4.8
• Advanced knowledge of C# / VB.net and .Net Framework
• User knowledge of the TIA Portal

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 35
Basics
4.1 Installation

TIA Portal Openness remoting channels


The TIA Portal Openness remoting channels are registered as type IpcChannel with the
“ensureSecurity” parameter set to "false".

Note
You should avoid registering another IpcChannel using a “ensureSecurity” parameter value other
than "false" with a priority higher than or equal to “1”.

The IpcChannel is defined with the following attributes:

Attribute Settings
"name" and "portName" Set to $”{Process.Name}_{Process.Id}” or $”{Proc‐
ess.Name}_{Process.Id}_{AppDomain.Id}” when registered in
an AppDomain other than the application’s default.
“priority” Set with the default value of “1”.
“typeFilterLevel” Set to “Full”.
“authorizedGroup” Set to the NTAccount value string for the built-in user account
(i.e. everyone).

See also
Adding users to the "Siemens TIA Openness" user group (Page 37)

4.1.2 Installing TIA Portal Openness

Introduction
The "TIA Portal Openness" is installed via TIA Portal setup program by selecting the TIA Portal
Openness checkbox (under Options) during TIA Portal installation.

Requirements
• Hardware and software of the programming device or PC meet the system requirements.
• You have administrator rights.
• Running programs are closed.
• Autorun is disabled.
• WinCC and/or STEP 7 are installed.
• The version number of the "TIA Portal Openness" matches the version numbers of WinCC and
STEP 7.

Openness: API for automation of engineering workflows


36 System Manual, 05/2021, Online documentation
Basics
4.1 Installation

Note
If a previous version of TIA Portal Openness is already installed, the current version will be
installed side by side.

Procedure
To install the TIA Portal Openness, ensure the TIA Portal Openness checkbox is selected during
the installation of TIA Portal. Follow the below steps to check the TIA Openness installation.
1. Under Configuration menu, select the folder Options.
2. Check the TIA Portal Openness checkbox.
3. Click "Next" and select the required option.

Follow the installation procedure of TIA Portal to complete the TIA Portal Openness installation.

Result
"TIA Portal Openness" is installed on the PC. Moreover, the local user group "Siemens TIA
Openness" is generated.

Note
You still do not have access to the TIA Portal with the "TIA Portal Openness" add-on package. You
need to be a member of the "Siemens TIA Openness" user group (see Adding users to the
"Siemens TIA Openness" user group (Page 37)).

4.1.3 Adding users to the "Siemens TIA Openness" user group

Introduction
When you install TIA Portal Openness on the PC, the "Siemens TIA Openness" user group is
automatically created.
Whenever you access the TIA Portal with your TIA Portal Openness application, the TIA Portal
verifies that you are a member of the "Siemens TIA Openness" user group, either directly or
indirectly by way of another user group. If you are a member of the "Siemens TIA Openness" user
group, the TIA Portal Openness application starts and establishes a connection to the TIA Portal.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 37
Basics
4.1 Installation

Procedure
You add a user to the "Siemens TIA Openness" user group with applications from your operating
system. The TIA Portal does not support this operation.

Note
Depending on the configuration of your domain or computer, you may need to log on with
administrator rights to expand the user group.

In a Windows 7 operating system (English language setting), for example, you can add a user to
the user group as follows:
1. Select "Start" > "Control Panel".
2. Double-click "Administrative Tools" in the Control Panel.

Openness: API for automation of engineering workflows


38 System Manual, 05/2021, Online documentation
Basics
4.1 Installation

3. Click "Computer Management" to open the configuration dialog of the same name.

4. Select "Local Users and Groups > Groups", in order to display all created user groups.
5. Select the "Siemens TIA Openness" entry from the list of user groups in the right pane.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 39
Basics
4.1 Installation

6. Select the "Action > Add to Group..." menu command.

The attributes dialog of the user group opens:

Openness: API for automation of engineering workflows


40 System Manual, 05/2021, Online documentation
Basics
4.1 Installation

7. Click "Add".
The selection dialog that opens displays the users that can be selected:

8. Enter a valid user name in the input field.


Note
Click "Check Names" to verify that the user entered has a valid user account for this domain
or computer.
The "From this location" field displays the domain or computer name for the user name
entered. For more information, contact your system administrator.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 41
Basics
4.1 Installation

9. Confirm your selection with "OK".


The new user is now displayed in the attributes dialog of the user group.

You register additional users by clicking the "Add" button.


10.Click "OK" to end this operation.
11.Log on to the PC again for the changes to take effect.

Openness: API for automation of engineering workflows


42 System Manual, 05/2021, Online documentation
Basics
4.1 Installation

4.1.4 Accessing the TIA Portal

Overview

&RQILJXUDWLRQ3&

<RXU 6LHPHQV
SURJUDP (QJLQHHULQJGOO

7,$3RUWDO 3URMHFWIRU
3URFHVV 0DFKLQH

Procedure
1. Set up the development environment to access and start the TIA Portal.
2. Instantiate the object of the portal application in your program to start the portal.
3. Find the desired project and open it.
4. Access the project data.
5. Close the project and exit the TIA Portal.

See also
Connecting to the TIA Portal (Page 81)
Terminating the connection to the TIA Portal (Page 90)

4.1.5 Configurations
You can work with two variants of the TIA Portal Openness:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 43
Basics
4.1 Installation

Application and the TIA Portal are on different computers

$SSOLFDWLRQFRPSXWHU 7,$3RUWDOSURMHFWFRPSXWHU

3& 3&

'DWDH[FKDQJH

<RXU ;0/ <RXU


SURJUDP SURJUDP

'DWD
SURFHVVLQJ

7,$3RUWDO
3URFHVV

• Data exchange takes place by XML files. The XML files can be exported or imported by your
programs.
• The data exported from the TIA Portal project to PC2 can be modified on PC1 and re-imported.
Note
You have to develop an executable program "Your Program 2" for PC2, such as
"program2.exe". The TIA Portal runs with this program in the background.
Import and export of XML files takes place exclusively via the TIA Portal Openness API.

• You can archive exchanged files for verification purposes.


• Exchanged data can be processed at different locations and times.

Openness: API for automation of engineering workflows


44 System Manual, 05/2021, Online documentation
Basics
4.1 Installation

Application and the TIA Portal are on the same computer

&RQILJXUDWLRQ3&

3URMHFWGDWD
7,$3RUWDO
0DFKLQH

<RXU 3XEOLF$3,
SURJUDP

• Your program launches the TIA Portal either with or without the user interface. Your program
opens, saves and/or closes a project. The program can also connect to a running TIA Portal.
• You can then use the TIA Portal functionality to request, generate and modify project data or
to initiate import or export processes.
• The data is created under control of the TIA Portal processing and stored in the project data.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 45
Basics
4.1 Installation

Typical application in modular mechanical engineering

&RQILJXUDWLRQFRPSXWHU

3DUDPHWHUVIRU
PDFKLQH *HQHUDWRU
3DUDPHWHUVIRU 7RRO
PDFKLQH

3URMHFWIRU
PDFKLQH
7,$3RUWDO
3URFHVV
3URMHFWIRU
PDFKLQH

• An efficient automation system is to be applied to similar machines.


• A project is available in the TIA Portal, which contains the components of all machine variants.
• The Generator tool controls the creation of the project for a specific machine variant.
• The Generator tool obtains the defaults by reading in the parameters for the requested
machine variant.
• The Generator tool filters out the relevant elements from the overall TIA Portal project,
modifies them if necessary and generates the requested machine project.

Openness: API for automation of engineering workflows


46 System Manual, 05/2021, Online documentation
Basics
4.2 Openness tasks

4.2 Openness tasks

4.2.1 Introduction

Introduction
TIA Portal Openness describes open interfaces for engineering with the TIA Portal. You will find
further information about "TIA Portal Openness - Efficient generation of program code using
code generators" in the SIEMENS YouTube channel (www.youtube.com/watch?v=Ki12pLbEcxs).
You automate the engineering with TIA Portal Openness by controlling the TIA Portal externally
from a program you have created.
You can perform the following actions with TIA Portal Openness:
• Create project data
• Modify projects and project data
• Delete project data
• Read in project data
• Make projects and project data available for other applications.

Note
Siemens is not liable for and does not guarantee the compatibility of the data and information
transported via these interfaces with third-party software.
We expressly point out that improper use of the interfaces can result in data loss or production
downtimes.

Note
The code snippets contained in this documentation are written in C# syntax.
Due to the shortness of the used code snippets the error handling description has been
shortened as well.

Application
The TIA Portal Openness interface is used to do the following:
• Provide project data.
• Access the TIA Portal process.
• Use project data.

Using defaults from the field of automation engineering


• By importing externally generated data
• By remote control of the TIA Portal for generating projects

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 47
Basics
4.2 Openness tasks

Providing project data of the TIA Portal for external applications


• By exporting project data

Ensuring competitive advantages through efficient engineering


• You do not have to configure existing engineering data in the TIA Portal.
• Automated engineering processes replace manual engineering.
• Low engineering costs strengthen the bidding position as compared to the competition.

Working together on project data


• Test routines and bulk data processing can take place in parallel to the ongoing configuration.

See also
Configurations (Page 43)

4.2.2 Applications

Introduction
TIA Portal Openness provides you with various ways to access the TIA Portal and offers a selection
of functions for defined tasks.
You access the following areas of the TIA Portal by using the TIA Portal Openness API interface :
• Portal data
• Project data
• PLC data
• HMI data
• Drive data

Note
You must not use the TIA Portal Openness API to execute checks or generate data for the
acceptance/approval of a fail-safe system. Acceptance/approval may only be carried out with a
safety printout using the STEP 7 Safety add-on package or with the function test. The TIA Portal
Openness API is no substitute.

Accessing the TIA Portal


TIA Portal Openness offers various ways to access the TIA Portal. You create an external TIA Portal
instance in the process either with or without UI. You can also access ongoing TIA Portal
processes at the same time.

Openness: API for automation of engineering workflows


48 System Manual, 05/2021, Online documentation
Basics
4.2 Openness tasks

Accessing projects and project data


When accessing projects and project data, you mainly use TIA Portal Openness for the following
tasks:
• Close, open and save the project
• Enumerate and query objects
• Create objects
• Delete objects

4.2.3 Export/import

Introduction
TIA Portal Openness supports the import and export of project data by means of XML files. The
import/export function supports external configuration of existing engineering data. You use
this function to make the engineering process effective and free of error.

Application
You use the import/export function for the following purposes:
• Data exchange
• Copying parts of a project
• External processing of configuration data, for example, for bulk data operations using find
and replace
• External processing of configuration data for new projects based on existing configurations
• Importing externally-created configuration data, for example, text lists and tags
• Providing project data for external applications

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 49
Basics
4.2 Openness tasks

Openness: API for automation of engineering workflows


50 System Manual, 05/2021, Online documentation
TIA Portal Openness API 5
5.1 TIA Portal Openness object

5.1.1 TIA Portal Openness object model

Overview
The following diagram describes the highest level of the TIA Portal Openness object model:

7LD3RUWDO6HWWLQJ
'HYLFHV Q

6HWWLQJV Q 8QJURXSHG'HYLFHV*URXS  'HYLFH6\VWHP*URXS 'HYLFH,WHPV Q


)ROGHUV Q

'HYLFH*URXS
'HYLFHV Q 'HYLFH 'HYLFH,WHPV Q 'HYLFH,WHP
7LD3RUWDO6HWWLQJV)ROGHU $EVWUDFW!!

'HYLFH*URXSV Q 'HYLFH8VHU*URXS *URXSV 6RIWZDUH&RQWDLQHU


6HWWLQJV)ROGHUV Q 6HUYLFH!!

*UDSKLFV Q 0XOWL/LQJXDO*UDSKLF


6RIWZDUH&RQWDLQHU

7LD3RUWDO 3URMHFWV  3URMHFW +Z8WLOLWLHV Q +DUGZDUH8WLOLW\


6RIWZDUH 

+LVWRU\(QWULHV Q +LVWRU\(QWU\ 6RIWZDUH


$EVWUDFW!!
*OREDO/LEUDULHV Q 3URMHFW/LEUDU\ 
/DQJXDJHV Q /DQJXDJH

3OF6RIWZDUH +PL6RIWZDUH +PL7DUJHW
*OREDO/LEUDU\ 3URMHFW/LEUDU\ /DQJXDJH6HWWLQJV Q /DQJXDJH6HWWLQJ

6XEQHWV Q 6XEQHW

8VHG3URGXFWV Q 8VHG3URGXFW

8VHU*OREDO/LEUDU\ &RUSRUDWH*OREDO/LEUDU\ 6\VWHP*OREDO/LEUDU\

The following diagram describes the objects which are located under GlobalLibrary.

0DVWHU&RS\6\VWHP)ROGHU 0DVWHU&RS\8VHU)ROGHU

0DVWHU&RS\)ROGHU  0DVWHU&RS\)ROGHU )ROGHUV Q


$EVWUDFW!! 0DVWHU&RSLHV Q 0DVWHU&RS\

*OREDO/LEUDU\
/LEUDU\7\SH)ROGHU 7\SHV Q /LEUDU\7\SH 9HUVLRQV Q /LEUDU\7\SH9HUVLRQ
7\SH)ROGHU  $EVWUDFW!! )ROGHUV Q

/LEUDU\7\SH6\VWHP)ROGHU /LEUDU\7\SH8VHU)ROGHU

The following diagram describes the objects which are located under ProjectLibrary.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 51
TIA Portal Openness API
5.1 TIA Portal Openness object

0DVWHU&RS\6\VWHP)ROGHU 0DVWHU&RS\8VHU)ROGHU

0DVWHU&RS\)ROGHU  0DVWHU&RS\)ROGHU )ROGHUV Q


$EVWUDFW!! 0DVWHU&RSLHV Q 0DVWHU&RS\

3URMHFW/LEUDU\
/LEUDU\7\SH)ROGHU 7\SHV Q /LEUDU\7\SH 9HUVLRQV Q /LEUDU\7\SH9HUVLRQ
7\SH)ROGHU  $EVWUDFW!! )ROGHUV Q

/LEUDU\7\SH6\VWHP)ROGHU /LEUDU\7\SH8VHU)ROGHU

The following diagram describes the objects which are located under HmiTarget.

&RQQHFWLRQV Q &RQQHFWLRQ

&\FOHV Q &\FOH

*UDSKLF/LVWV Q *UDSKLF/LVW

6FUHHQ)ROGHU )ROGHUV Q 6FUHHQ8VHU)ROGHU


6FUHHQ)ROGHU  6FUHHQ6\VWHP)ROGHU
$EVWUDFW!! 6FUHHQV Q 6FUHHQ

6FUHHQ*OREDO(OHPHQWV  6FUHHQ*OREDO(OHPHQWV

6FUHHQ2YHUYLHZ  6FUHHQ2YHUYLHZ

+PL7DUJHW 6FUHHQ3RSXS)ROGHU )ROGHUV Q 6FUHHQ3RSXS8VHU)ROGHU


$EVWUDFW!! 6FUHHQ3RSXSV Q 6FUHHQ3RSXS
6FUHHQ3RSXS)ROGHU  6FUHHQ3RSXS6\VWHP)ROGHU

6FUHHQ6OLGHLQ)ROGHU  6FUHHQ6OLGHLQ6\VWHP)ROGHU 6FUHHQ6OLGHLQV  6FUHHQ6OLGHLQ

6FUHHQ7HPSODWH)ROGHU )ROGHUV Q 6FUHHQ7HPSODWH8VHU)ROGHU


$EVWUDFW!! 6FUHHQ7HPSODWHV Q 6FUHHQ7HPSODWH
6FUHHQ7HPSODWH)ROGHU  6FUHHQ7HPSODWH6\VWHP)ROGHU

7DJ)ROGHU )ROGHUV Q 7DJ8VHU)ROGHU


$EVWUDFW!! 7DJ7DEOHV Q
7DJ)ROGHU  7DJ6\VWHP)ROGHU 7DJ7DEOH 7DJV Q 7DJ
'HIDXOW7DJ7DEOH 

7H[W/LVWV Q 7H[W/LVW

9%6FULSW)ROGHU )ROGHUV Q 9%6FULSW8VHU)ROGHU


9%6FULSW)ROGHU  9%6FULSW6\VWHP)ROGHU
$EVWUDFW!! 9%6FULSWV Q 9%6FULSW

The following diagram describes the object which are located under HmiSoftware.

Openness: API for automation of engineering workflows


52 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

$ODUP&ODVVHV Q $ODUP&ODVV

$ODUP/RJV Q $ODUP/RJ

$QDORJ$ODUPV Q $QDORJ$ODUP

'DWD/RJV Q 'DWD/RJ

'LVFUHWH$ODUPV Q 'LVFUHWH$ODUP

+PL6RIWZDUH

+PL&RQQHFWLRQV Q +PL&RQQHFWLRQ

+PL7DJ7DEOHV Q +PL7DJ7DEOH

+PL7DJV Q +PL7DJV

5XQWLPH6HWWLQJV

6FUHHQDQG 6FUHHQVDQG6FUHHQ,WHPV
6FUHHQ,WHP Q

The following diagram describes the objects which are located under PlcSoftware.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 53
TIA Portal Openness API
5.1 TIA Portal Openness object

Openness: API for automation of engineering workflows


54 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

Note
*The Force Table must be in PlcWatch and ForceTableSystemGroup

Access to objects in lists


You have the following options for addressing an object in a list:
• Address via the index. The counting within the lists starts with 0.
• Use Find method.
Use this method to address an object via its name. You can use this method for an
composition or list. The Find method is not recursive.
Example:
ScreenComposition screens = folder.Screens;
Screen screen = screens.Find("myScreen");
• Use symbolic names.

Relationship between TIA Portal and TIA Portal Openness object model
The figure below shows the relationship between the object model and a project in the TIA
Portal:

1
5

5 5

Project DeviceItem

2 PlcSoftware

HmiTarget
3

HmiUnified
4 Software

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 55
TIA Portal Openness API
5.1 TIA Portal Openness object

See also
Blocks and types of the TIA Portal Openness object model (Page 57)
Hierarchy of hardware objects of the object model (Page 65)

Openness: API for automation of engineering workflows


56 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

5.1.2 Blocks and types of the TIA Portal Openness object model

Introduction
The following diagram describes the domain model of the PLCs to give an overview of the
current modeling in TIA Portal Openness.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 57
TIA Portal Openness API
5.1 TIA Portal Openness object

Openness: API for automation of engineering workflows


58 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

Note
* The Force Table must be in PlcWatch and ForceTableSystemGroup

Representation of blocks and types in the TIA Portal Openness API


The simplified model part of blocks and for the structure is based on the attributes in the TIA
Portal Openness API. These classes provide the export function and for blocks also the compile
function.

Class diagrams
In the TIA Portal Openness object model all classes are defined as abstract which aren't directly
instantiated.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 59
TIA Portal Openness API
5.1 TIA Portal Openness object

Data

Openness: API for automation of engineering workflows


60 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

3OF%ORFN

*HQHUDODWWULEXWHV
$XWR1XPEHU%RROHDQ
&RGH0RGLILHG'DWH'DWH7LPH
&RPSLOH'DWH'DWH7LPH
&UHDWLRQ'DWH'DWH7LPH
+HDGHU$XWKRU6WULQJ
+HDGHU)DPLO\6WULQJ
+HDGHU1DPH6WULQJ
+HDGHU9HUVLRQ6WULQJ
,QWHUIDFH0RGLILHG'DWH'DWH7LPH
,V&RQVLVWHQW%RROHDQ
,V.QRZ+RZ3URWHFWHG%RROHDQ
0HPRU\/D\RXW0HPRU\/D\RXW
0RGLILHG'DWH'DWH7LPH
1DPH6WULQJ
1XPEHU,QW
3DUDPHWHU0RGLILHG'DWH7LPH
3URJUDPPLQJ/DQJXDJH3URJUDPPLQJ/DQJXDJH
6WUXFWXUH0RGLILHG'DWH7LPH
6HUYLFHV
,&RPSLODEOH

([SRUW
6KRZ,Q(GLWRU
'HOHWH

'DWD%ORFN
6SHFLILFDWWULEXWHV
,V2QO\6WRUHG,Q/RDG0HPRU\%RROHDQ
,V:ULWH3URWHFWHG,Q$6%RROHDQ

$UUD\'% *OREDO'% ,QVWDQFH'%

6SHFLILFDWWULEXWHV 6SHFLILFDWWULEXWHV 1RWH7KHGLIIHUHQFHVEHWZHHQWKHVSHFLILFDWWULE


RI,'%RI)%DQG,'%RIO8'7ZLOOEHKDQGOHGE\FR
'RZQORDG:LWKRXW5HLQLW%RROHDQ
$UUD\'DWD7\SH6WULQJ
,V3/&'%%RROHDQ *HQHUDODWWULEXWHV
$UUD\/LPLW8SSHU%RXQG,QW
,V5HWDLQ0HP5HV(QDEOHG%RROHDQ ,QVWDQFH2I1DPH6WULQJ
5HWDLQ0HPRU\5HVHUYH8,QWSOXV 2I6\VWHP/LE(OHPHQW6WULQJ
2I6\VWHP/LE9HUVLRQ6WULQJ

6SHFLILFDWWULEXWHV
'RZQORDG:LWKRXW5HLQLW%RROHDQ
,QVWDQFH2I1XPEHU,QW
,QVWDQFH2I7\SH%ORFN7\SH
,V5HWDLQ0HP5HV(QDEOHG%RROHDQ
0HPRU\5HVHUYH8,QWSOXV
5HWDLQ0HPRU\5HVHUYH8,QWSOXV
8'$(QDEOH7DJ5HDGEDFN%RROHDQ
8'$%ORFN3URSHUWLHV6WULQJ

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 61
TIA Portal Openness API
5.1 TIA Portal Openness object

Code and Type

3OF%ORFN

1RWH$
WKHIROOR

&RGH%ORFN /LEUDU\7\SH,QVWDQFH,QIR &UHDWL


,QWHUID
6SHFLILFDWWULEXWHV ,V&RQV
+DQGOH(UURUV:LWKLQ%ORFN%RROHDQSOXV /LEUDU\7\SH9HUVLRQ/LEUDU\7\SH9HUVLRQ 0RGLIL
,V,(&&KHFN(QDEOHG%RROHDQ /LEUDU\7\SH,QVWDQFH,(QJLQHHULQJ2EMHFW 1DPH

,&RPS

([SRU
6KRZ,
'HOHWH

2%
*HQHUDODWWULEXWHV
6HFRQGDU\7\SH6WULQJ
6SHFLILFDWWULEXWHV
&RQVWDQW1DPH6WULQJ
3URFHVV,PDJH3DUW1XPEHU8,QW
(YHQW&ODVV6WULQJ
3ULRULW\1XPEHU,QW )%
(YHQWV7R%H4XHXHG,QW
5HSRUW(YHQWV%RRO 6SHFLILFDWWULEXWHV
(QDEOH7LPH(UURU%RRO $FNQRZOHGJH(UURUV5HTXLUHG%RROHDQ
(YHQW7KUHVKROG)RU7LPH(UURU,QW &UHDWH0LQLPL]HG'%%RROHDQFODVVLF
&\FOLF7LPH,QW 'RZQORDG:LWKRXW5HLQLW%RROHDQ
3KDVH2IIVHW,QW *UDSK9HUVLRQ6WULQJSOXV
$SSOLFDWLRQ&\FOH6LQJOH ,V0XOWL,QVWDQFH&DSDEOH%RROHDQ
$XWRPDWLF0LQLPXP%RRO
,V5HWDLQ0HP5HV(QDEOHG%RROHDQ
)&
'HOD\7LPH'RXEOH

'LVWULEXWLRQ,21DPH,QW /DQJXDJH,Q1HWZRUNV6WULQJ 6SHFLILFDWWULEXWHV
'LVWULEXWLRQ,21XPEHU,QW /RFN2SHUDWLQJ0RGH%RROHDQ
3DUDPHWHU3DVVLQJ%RROHD
([HFXWLRQ2%([HFXWLRQ 0HPRU\5HVHUYH8,QWSOXV
8'$(QDEOH7DJ5HDGEDFN
6WDUW'DWH'DWH7LPH 3DUDPHWHU3DVVLQJ%RROHDQSOXV
8'$%ORFN3URSHUWLHV6WULQ
7LPH2I'D\'DWH7LPH 3HUPDQHQW,/3URFHVVLQJ,Q0$10RGH%RROHDQ
/LEUDU\&RQIRUPDQFH6WDWXV
7LPH0RGH2%7LPH0RGH 5HWDLQ0HPRU\5HVHUYH8,QWSOXV
'DWD([FKDQJH0RGH2%'DWD([FKDQJH0RGH 6HW(12$XWRPDWLFDOO\%RROHDQSOXV
&\FOLF7LPH'LVWULEXWHG,26LQJOH 6NLS6WHSV%RROHDQ
)DFWRU6LQJOH 8'$(QDEOH7DJ5HDGEDFN%RROHDQ
6\QFKURQRXV$SSOLFDWLRQ&\FOH7LPH6LQJOH 8'$%ORFN3URSHUWLHV6WULQJ
&\FOLF$SSOLFDWLRQ&\FOH7LPH6LQJOH :LWK$ODUP+DQGOLQJ%RROHDQ
/LEUDU\&RQIRUPDQFH6WDWXV6WULQJ
7UDQVIRUPDWLRQ'%1XPEHU8,QW

Openness: API for automation of engineering workflows


62 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

Representation of groups for blocks and types in the TIA Portal Openness API
The two high level groups "PlcBlocks" ("Program blocks" in the GUI of TIA Portal) and "PlcTypes"
("Plc data types" in the GUI of TIA Portal) contain blocks and type definitions. These groups
provide the import and the compile functions for blocks. Due to the fact that most of the
methods of functionalities of the groups are only achievable via collections, there is an
"embedded" or "compacted" representation of the collections and their methods at the "host"
classes.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 63
TIA Portal Openness API
5.1 TIA Portal Openness object

Blocks and Types

3OF%ORFN*URXS
3OF6RIWZDUH
&RPSRVLWLRQV
%ORFNV3OF%ORFN&RPSRVLWLRQ 7\SHV3OF7
*URXSV3OF%ORFN8VHU*URXS&RPSRVLWLRQ *URXSV3O

6HUYLFHV
,&RPSLODEOH ,&RPSLODEOH
1DPH6WULQJ JHW 1DPH6WUL

0HWKRGVRQ3OF%ORFN&RPSRVLWLRQ
,PSRUW ,PSRUW
0HWKRGVRQ3OF%ORFN8VHU*URXS&RPSRVLWLRQ 0HWK
&UHDWH &UHDWH

 

3OF%ORFN8VHU*URXS 3OF%ORFN6\VWHP*URXS 3OF7\SH6\VWHP*URXS


&RPSRVLWLRQV
6\VWHP%ORFN*URXSV3OF6\VWHP%ORFN*URXS&RPSRVLWLRQ



3OF6\VWHP%ORFN*URXS
&RPSRVLWLRQV
%ORFNV3OF%ORFN&RPSRVLWLRQ
*URXSV3OF6\VWHP%ORFN*URXS&RPSRVLWLRQ

1DPH6WULQJ JHW

0HWKRGVRQ3OF%ORFN&RPSRVLWLRQ
,PSRUW


3OF%ORFN

Openness: API for automation of engineering workflows


64 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

External Sources

3OF([WHUQDO6RXUFH*URXS
&RPSRVLWLRQV
*URXSV3OF([WHUQDO6RXUFH8VHU*URXS&RPSRVLWLRQ
([WHUQDO6RXUFHV3OF([WHUQDO6RXUFH&RPSRVLWLRQ
3OF6RIWZDUH
1DPH6WULQJ JHW

0HWKRGVRQ3OF([WHUQDO6RXUFH&RPSRVLWLRQ
&UHDWH)URP)LOH
0HWKRGVRQ3OF([WHUQDO6RXUFH8VHU*URXS&RPSRVLWLRQ
&UHDWH


3OF([WHUQDO6RXUFH6\VWHP*URXS 3OF([WHUQDO6RXUFH8VHU*URXS 3OF([

1DPH6WULQJ

'HOHWH
*HQHUDWH%ORFN

See also
TIA Portal Openness object model (Page 51)
Hierarchy of hardware objects of the object model (Page 65)

5.1.3 Hierarchy of hardware objects of the object model

Relation between the visible elements in the TIA Portal and the modeled elements in the object
model

Hardware object Explanation


Device The container object for a central or distributed configuration.
(Device)
Device item Each device item object has a container object.
(DeviceItem) The logical relation is "Items".

The container relation is comparable to the relation of the modules for the device item objects.
Example: A device includes one or more slots. A slot includes modules. A module includes
submodules.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 65
TIA Portal Openness API
5.1 TIA Portal Openness object

This is the relation similar to the representation in the network view and device view of the TIA
Portal. The "PositionNumber" attribute of a device item is unique in the items area, within a
container.
The parent-child relation between device item objects is a purely logical relation in the object
model. A child cannot exist without its parents.
• If a submodule is modeled as part of a module (child), the submodule cannot be removed
without the module.
• If you add and then remove a submodule from the module, this child has the same parents
as the module.
The diagrams below show the hierarchy relationship between devices, and device items of PLC
and HMI devices.

Hierarchy relationships of PLC devices

Hierarchy when iterating via .Items Hierarchy when iterating via .DeviceItems

'HYLFH 'HYLFH

'HYLFH,WHP 5DFN 'HYLFH,WHP 5DFN

'HYLFH,WHP 3/& 'HYLFH,WHP 3/&

6RIWZDUH&RQWDLQHU 6RIWZDUH&RQWDLQHU

3OF6RIWZDUH 3OF6RIWZDUH

'HYLFH,WHP '3 'HYLFH,WHP '3

'HYLFH,WHP 352),1(7 'HYLFH,WHP 352),1(7

'HYLFH,WHP ,2&3 'HYLFH,WHP ,2&3

Hierarchy relationships of HMI devices

Hierarchy when iterating via .Items Hierarchy when iterating via .DeviceItems

'HYLFH 'HYLFH

'HYLFH,WHP +0, 'HYLFH,WHP +0,

'HYLFH,WHP 352),1(7 'HYLFH,WHP 352),1(7

'HYLFH,WHP 03,'3 'HYLFH,WHP 03,'3

'HYLFH,WHP +0,57 'HYLFH,WHP +0,57

6RIWZDUH&RQWDLQHU 6RIWZDUH&RQWDLQHU

+PL7DUJHW +PL7DUJHW

Openness: API for automation of engineering workflows


66 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

See also
TIA Portal Openness object model (Page 51)
Blocks and types of the TIA Portal Openness object model (Page 57)

5.1.4 Object list

Introduction
The following tables show the available objects up to and including Runtime Advanced, and
indicate whether these objects are supported by TIA Portal Openness.
Neither Runtime Professional nor device proxy files are supported by TIA Portal Openness in
WinCC.

Objects
You can control the following project data depending on which HMI device you are using:

Table 5-1 Screens

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Screen Yes Yes Yes Yes
Global screen Yes Yes Yes Yes
Templates Yes Yes Yes Yes
Permanent area No Yes Yes Yes
Pop-up screen No Yes Yes Yes
Slide-in screen No Yes Yes Yes

Table 5-2 Screen objects

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Line Yes Yes Yes Yes
Polyline No Yes Yes Yes
Polygon No Yes Yes Yes
Ellipse Yes Yes Yes Yes
Ellipse segment No No No No
Circle segment No No No No
Elliptical arc No No No No
Camera view No No No No
Circular arc No No No No
Circle Yes Yes Yes Yes
PDF view No No No No
Rectangle Yes Yes Yes Yes

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 67
TIA Portal Openness API
5.1 TIA Portal Openness object

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Connector No No No No
Text field Yes Yes Yes Yes
Graphic view Yes Yes Yes Yes
Pipe No No No No
Double T-piece No No No No
T-piece No No No No
Pipe bends No No No No
I/O field Yes Yes Yes Yes
Date/time field Yes Yes Yes Yes
Graphic I/O field Yes Yes Yes Yes
Editable text field No No No No
List box No No No No
Combo box No No No No
Button Yes Yes Yes Yes
Round button No No No No
Illuminated button No No Yes No
Switch Yes Yes Yes Yes
Symbolic I/O field Yes Yes Yes Yes
Key-operated switch No No Yes No
Bar Yes Yes Yes Yes
Symbol library No Yes Yes Yes
Slider No Yes Yes Yes
Scroll bar No No No No
Check box No No No No
Option buttons No No No No
Gauge No Yes Yes Yes
Clock No Yes Yes Yes
Memory space view No No No No
Function keys Yes Yes Yes Yes
Faceplate instances No Yes Yes Yes
Screen window No No No No
User view Yes Yes Yes Yes
HTML Browser No No No No
Print job/script diagnos‐ No No No No
tics
Recipe view No No No No
Alarm view No No No No
Alarm indicator No No No No
Alarm window No No No No
Criteria analysis view No Yes 1)
Yes Yes
ProDiag overview No Yes 1)
Yes Yes

Openness: API for automation of engineering workflows


68 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.1 TIA Portal Openness object

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


GRAPH overview No Yes 1) Yes Yes
PLC code view No Yes 1) Yes Yes
f(x) trend view No No No No
f(t) trend view No No No No
Table view No No No No
Value table No No No No
Media Player No No No No
Channel diagnostics No No No No
WLAN reception No No No No
Zone name No No No No
Zone signal No No No No
Effective range name No No No No
Effective range name No No No No
(RFID)
Effective range signal No No No No
Charge condition No No No No
Handwheel No No Yes No
Help indicator No No No No
Sm@rtClient view No No No No
Status/Force No No No No
System diagnostic view No No No No
System diagnostic win‐ No No No No
dow

1) Only Mobile Panels with the device version greater than 12.0.0.0 support this screen object

Table 5-3 Dynamic

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Display Yes Yes Yes Yes
Operability No Yes Yes Yes
Visibility Yes Yes Yes Yes
Movements Yes Yes Yes Yes

Table 5-4 Additional objects

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Groups Yes Yes Yes Yes
Soft keys Yes Yes Yes Yes
Cycles Yes Yes Yes Yes
VB scripts No Yes Yes Yes
Function lists Yes Yes Yes Yes
Project graphics Yes Yes Yes Yes

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 69
TIA Portal Openness API
5.1 TIA Portal Openness object

Table 5-5 Tags

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Multiplex tags Yes Yes Yes Yes
Arrays Yes Yes Yes Yes
User data types Yes Yes Yes Yes
Internal No Yes Yes Yes
Points of use of elemen‐ Yes Yes Yes Yes
tary data types
Points of use of user da‐ Yes Yes Yes Yes
ta types
Points of use of arrays Yes Yes Yes Yes

TIA Portal Openness also supports all value ranges which are supported by the communication
drivers.
Connections
TIA Portal Openness supports non-integrated connections that are also supported by the
respective HMI devices. You can find additional information in the online help for the TIA Portal
under "Process visualization > Controller communication > Device-dependent".

Table 5-6 Lists

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Text lists Yes Yes Yes Yes
Graphic lists Yes Yes Yes Yes

Table 5-7 Texts

Object Basic Panels Comfort Panels Mobile Panels RT Advanced


Multilingual texts Yes Yes Yes Yes
Formatted texts and No Yes Yes Yes
their instances

Openness: API for automation of engineering workflows


70 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

5.2 General functions

5.2.1 Introduction

Overview
TIA Portal Openness supports a selection of functions for defined tasks that you can call outside
the TIA Portal by means of the TIA Portal Openness API.

Note
If a previous version of TIA Portal Openness is already installed, the current version will be
installed side by side.

You are provided with an overview of the typical programming steps in the sections below. You
can learn how the individual code sections interact and how to integrate the respective
functions into a complete program. You also get an overview of the code components that have
to be adapted for each task.

Example program
The individual programming steps are explained using the "Creating API access in a console
application" function as an example. You integrate the provided functions in this program code
and adapt the respective code components for this task.

Functions
The section below lists the functions for defined tasks that you can call with TIA Portal Openness
outside the TIA Portal.

See also
Applications (Page 48)
Object list (Page 67)

5.2.2 Information about installed TIA Portal Openness versions

Requirement
• TIA Portal Openness and TIA Portal are installed

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 71
TIA Portal Openness API
5.2 General functions

Application
Starting from TIA Portal Openness V14 each installed version has a registry key that contains
information about the version. This enables an automatic generation of app.config files for each
installed version of TIA Portal Openness.
The registry keys can be located under the following path:
HKEY_LOCAL_MACHINE\Software\Siemens\Automation\Openness\xx.x
\PublicAPI

Note
The version number in this path, is always the number of the currently installed version of TIA
Portal. If there are multiple side-by-side installations there are multiple sets of entries for TIA
Portal Openness in the registry.

There is a single key for each version of TIA Portal Openness. The names of the Versions will be
the same as in the assembly described, for example, the registry entries for TIA Portal Openness:

[HKEY_LOCAL_MACHINE\SOFTWARE\Siemens\Automation\Openness\xx.x\PublicAPI
\xx.x.x.x]"PublicKeyToken"="d29ec89bac048f84"
"Siemens.Engineering"="C:\Program Files\Siemens\Automation\Portal Vxx\PublicAPI\Vxx
\Siemens.Engineering.dll"
"Siemens.Engineering.Hmi"="C:\Program Files\Siemens\Automation\Portal Vxx\PublicAPI\Vxx
\Siemens.Engineering.Hmi.dll"
"EngineeringVersion"="xx"
"AssemblyVersion"="xx.x.x.x"

Note
If you want to generate an app.config file (Page 81) you can get the path of the
Siemens.Engineering.dll, the Siemens.Engineering.Hmi.dll and the public key token from the
registry key.

5.2.3 TIA Portal Openness IntelliSense support

Application
The Intellisense support of TIA Portal Openness helps you at available attributes or methods via
tooltip information. It could contain information about the number, names and types of the
required parameters. At the following example the bold parameter in the first line indicates the
next parameter that is required as you type the function.

Openness: API for automation of engineering workflows


72 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

You can manually invoke Parameter Info by clicking Edit IntelliSense/Parameter Info, typing CTRL
+SHIFT+SPACE, or clicking the Parameter Info button on the editor toolbar.

5.2.4 Standard libraries


Insert the following namespace statements at the beginning of the relevant code example to
ensure that the code examples work:

using System;
using System.Collections.Generic;
using System.IO;
using Siemens.Engineering;
using Siemens.Engineering.Cax;
using Siemens.Engineering.Compiler;
using Siemens.Engineering.Compare;
using Siemens.Engineering.Download;
using Siemens.Engineering.Hmi;
using Siemens.Engineering.Hmi.Cycle;
using Siemens.Engineering.Hmi.Communication;
using Siemens.Engineering.Hmi.Globalization;
using Siemens.Engineering.Hmi.RuntimeScripting;
using Siemens.Engineering.Hmi.Screen;
using Siemens.Engineering.Hmi.Tag;
using Siemens.Engineering.Hmi.TextGraphicList;
using Siemens.Engineering.HW;
using Siemens.Engineering.HW.Extensions;
using Siemens.Engineering.HW.Features;
using Siemens.Engineering.HW.Utilities;
using Siemens.Engineering.Library;
using Siemens.Engineering.Library.MasterCopies;
using Siemens.Engineering.Library.Types;
using Siemens.Engineering.SW;
using Siemens.Engineering.SW.Blocks;
using Siemens.Engineering.SW.ExternalSources;
using Siemens.Engineering.SW.Tags;
using Siemens.Engineering.SW.TechnologicalObjects;
using Siemens.Engineering.SW.TechnologicalObjects.Motion;
using Siemens.Engineering.SW.Types;
using Siemens.Engineering.Upload;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 73
TIA Portal Openness API
5.2 General functions

5.2.5 Use of the code examples

Structure of the code-snippets


Each code-snippet in this documentation is implemented as a function without return value with
an object reference as transfer parameter. Disposing of objects is omitted for the sake of
readability. Objects of the TIA Portal are addressed by their name using the Find method.

//Deletes a single screen from a user folder or a system folder


private static void DeleteScreenFromFolder(HmiTarget hmiTarget)
{
//The screen "MyScreen" will be deleted if it is existing in the folder
"myScreenFolder".
//If "myScreen" is stored in a subfolder of "myScreenFolder" it will not be deleted.
string screenName = "MyScreen";
ScreenUserFolder folder = hmiTarget.ScreenFolder.Folders.Find("myScreenFolder");
ScreenComposition screens = folder.Screens;
Screen screen = screens.Find(screenName);
if (screen != null)
{
screen.Delete();
}
}

You need the following to execute this code-snippet:


• A WinCC project with an HMI device that includes a group with at least one screen.
• A function that instantiates the HMI device.

Note
When you specify directory paths, use the absolute directory path, for example, "C:/path/file.txt".
Relative directory paths are only allowed in the XML files for import and export, for example,
"file.txt" or "C:/path01/.../path02/file.txt".

Openness: API for automation of engineering workflows


74 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Example for execution of the code-snippet


Use the following example to execute the code-snippet "DeleteScreenFromFolder" as part of the
"Hello TIA" example program:

//In the sample program "Hello TIA" replace the function call
//"IterateThroughDevices(project)" by the following functions calls:
HmiTarget hmiTarget = GetTheFirstHmiTarget(project);
DeleteScreenFromFolder(hmiTarget);

//Put the following function definitions before or after the


//function definition of "private static void IterateThroughDevices(Project project)":
private static HmiTarget GetTheFirstHmiTarget(Project project)
{
if (project == null)
{
Console.WriteLine("Project cannot be null");
throw new ArgumentNullException("project");
}
foreach (Device device in project.Devices)
//This example looks for devices located directly in the project.
//Devices which are stored in a subfolder of the project will not be affected by this
example.
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
DeviceItem deviceItemToGetService = deviceItem as DeviceItem;
SoftwareContainer container =
deviceItemToGetService.GetService<SoftwareContainer>();
if (container != null)
{
HmiTarget hmi = container.Software as HmiTarget;
if (hmi != null)
{
return hmi;
}
}
}
}
return null;
}

//Deletes a single screen from a user folder or a system folder


private static void DeleteScreenFromFolder(HmiTarget hmiTarget)
{
string screenName = "MyScreen";
ScreenUserFolder folder = hmiTarget.ScreenFolder.Folders.Find("myScreenFolder");
ScreenComposition screens = folder.Screens;
Screen screen = screens.Find(screenName);
if (screen != null)
{
screen.Delete();
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 75
TIA Portal Openness API
5.2 General functions

5.2.6 Example program

Application example: Creating API access in an application


The complete program code of the application example is shown below. The typical
programming steps are explained next based on this example.

Note
The application example requires an application configuration file (Page 81).

Openness: API for automation of engineering workflows


76 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

using System;
using Siemens.Engineering;
using Siemens.Engineering.HW;
using Siemens.Engineering.HW.Features;
using Siemens.Engineering.SW;
using Siemens.Engineering.SW.Blocks;
using Siemens.Engineering.SW.ExternalSources;
using Siemens.Engineering.SW.Tags;
using Siemens.Engineering.SW.Types;
using Siemens.Engineering.Hmi;
using HmiTarget = Siemens.Engineering.Hmi.HmiTarget;
using Siemens.Engineering.Hmi.Tag;
using Siemens.Engineering.Hmi.Screen;
using Siemens.Engineering.Hmi.Cycle;
using Siemens.Engineering.Hmi.Communication;
using Siemens.Engineering.Hmi.Globalization;
using Siemens.Engineering.Hmi.TextGraphicList;
using Siemens.Engineering.Hmi.RuntimeScripting;
using System.Collections.Generic;
using Siemens.Engineering.Compiler;
using Siemens.Engineering.Library;
using System.IO;
namespace HelloTIA
{
internal class Program
{
private static void Main(string[] args)
{
RunTiaPortal();
}

private static void RunTiaPortal()


{
Console.WriteLine("Starting TIA Portal");
using (TiaPortal tiaPortal = new TiaPortal(TiaPortalMode.WithUserInterface))
{
Console.WriteLine("TIA Portal has started");
ProjectComposition projects = tiaPortal.Projects;

Console.WriteLine("Opening Project...");
// please adapt the path and the extension apx to the installed version of
TIA Portal
FileInfo projectPath = new FileInfo("C:\Demo\AnyCompanyProject.apx"); //edit
the path according to your project
Project project = null;
try
{
project = projects.OpenWithUpgrade(projectPath);
}
catch (Exception)
{
Console.WriteLine(String.Format("Could not open project {0}",
projectPath.FullName));
Console.WriteLine("Demo complete hit enter to exit");
Console.ReadLine();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 77
TIA Portal Openness API
5.2 General functions

return;
}

Console.WriteLine(String.Format("Project {0} is open",


project.Path.FullName));

IterateThroughDevices(project);

project.Close();

Console.WriteLine("Demo complete hit enter to exit");


Console.ReadLine();
}
}

private static void IterateThroughDevices(Project project)


{
if (project == null)
{
Console.WriteLine("Project cannot be null");
return;
}

Console.WriteLine(String.Format("Iterate through {0} device(s)",


project.Devices.Count));

foreach (Device device in project.Devices)


{
Console.WriteLine(String.Format("Device: \"{0}\".", device.Name));
}

Console.WriteLine();
}
}
}

Procedure in steps

1. Make the TIA Portal known in the development environment


In your development environment, create a reference to all "dll files" in the "C:\Program Files
\Siemens\Automation\PortalV..\PublicAPI\V.." directory.
The following provides a description of this process using the "Siemens.Engineering.dll" file as
an example.
The "Siemens.Engineering.dll" file is available in the directory "C:\Program Files\Siemens
\Automation\PortalV..\PublicAPI\V..". Create a reference to the "Siemens.Engineering.dll" file in
your development environment.

Note
Ensure that parameter "CopyLocal" is assigned the value "False" in the reference attributes.

Openness: API for automation of engineering workflows


78 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

2. Publish the name space for the TIA Portal


Add the following code:

using Siemens.Engineering;

3. Publish and start the TIA Portal


In order to publish and start the TIA Portal, insert the following code:

using (TiaPortal tiaPortal = new TiaPortal())


{
// Add your code here
}

4. Open project
You can use the following code, for example, to open a project:

ProjectComposition projects = tiaPortal.Projects;


Console.WriteLine("Opening Project...");
//please adapt the path and the extension apx to the installed version of TIA Portal
FileInfo projectPath = new FileInfo("C:\Demo\AnyCompanyProject.apx");
Project project = null;
try
{
project = projects.Open(projectPath);
}
catch (Exception)
{
Console.WriteLine(String.Format("Could not open project {0}", projectPath.FullName));
Console.WriteLine("Demo complete hit enter to exit");
Console.ReadLine();
return;
}
Console.WriteLine(String.Format("Project {0} is open", project.Path.FullName));

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 79
TIA Portal Openness API
5.2 General functions

5. Enumerate devices of a project


Insert the following code to enumerate all devices of the project:

static private void IterateThroughDevices(Project project)


{
if (project == null)
{
Console.WriteLine("Project cannot be null");
return;
}

Console.WriteLine();
Console.WriteLine(String.Format("Iterate through {0} device(s)",
project.Devices.Count));
foreach (Device device in project.Devices)
{
Console.WriteLine(String.Format("Device: \"{0}\".", device.Name));
}
Console.WriteLine();
}

6. Save and close the project


Insert the following code to save and close the project:

project.Save();
project.Close();

5.2.7 Programming steps

Overview
TIA Portal Openness requires the following programming steps for access by means of the TIA
Portal Openness API:
1. Make the TIA Portal known in the development environment
2. Set up program access to the TIA Portal
3. Activate program access to the TIA Portal
4. Publish and start the TIA Portal
5. Open project
6. Execute commands
7. Save and close the project
8. Terminate the connection to the TIA Portal

Openness: API for automation of engineering workflows


80 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Note
Permitted strings
Only certain characters are allowed in strings in the TIA Portal. All strings passed to the TIA Portal
via the TIA Portal Openness application are subject to these rules. If you pass an invalid character
in a parameter, an exception is thrown.

See also
Example program (Page 76)
Use of the code examples (Page 74)

5.2.8 Connecting to the TIA Portal

Introduction
You start the TIA Portal with TIA Portal Openness or connect to a TIA Portal already running.
When using a TIA Portal Openness application to start the TIA Portal, you specify if the TIA Portal
should be started with or without graphical user interface. When you operate the TIA Portal
without user interface, the TIA Portal is only started as a process by the operating system. You
create several instances of the TIA Portal with a TIA Portal Openness application, if necessary.

Note
If you use TIA Portal Openness with the TIA Portal interface, you cannot use an HMI editor. You
can open the "Devices & Networks" editors or the programming editor manually or with TIA
Portal Openness API.

You have the following options to start the TIA Portal with a TIA Portal Openness application:
• Use an application configuration file (recommended in most use cases).
• Use the "AssemblyResolve" method (recommended when you use copy deploy etc.).
• Copy the Siemens.Engineering.dll in the TIA Portal Openness application directory.

Note
It is recommended to load the Siemens.Engineering.dll by using the app.config file. By using this
method the strong names are considered and malicious modifications to the engineering.dll will
result in a loading error. By using the AssemblyResolve method this can't be detected.

Starting the TIA Portal with an application configuration file


Reference all required program libraries in the application configuration file. You distribute the
application configuration file together with the TIA Portal Openness application.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 81
TIA Portal Openness API
5.2 General functions

Store the application configuration file "app.config" in the same directory as the TIA Portal
Openness application and likewise incorporate this in your application. Check whether the file
path in each code matches the TIA Portal installation path.
You can use the following code snippet for the application configuration file:

<?xml version="1.0"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Siemens.Engineering" culture="neutral"
publicKeyToken="d29ec89bac048f84"/>
<!-- Edit the following path according to your installed version of TIA Portal
-->
<codeBase version="Vxx.x.x.x" href="FILE://C:\Program Files\Siemens
\Automation\Portal Vxx\PublicAPI\Vxx\Siemens.Engineering.dll"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Siemens.Engineering.Hmi" culture="neutral"
publicKeyToken="d29ec89bac048f84"/>
<!-- Edit the following path according to your installed version of TIA Portal
-->
<codeBase version="Vxx.x.x.x" href="FILE://C:\Program Files\Siemens
\Automation\Portal Vxx\PublicAPI\Vxx\Siemens.Engineering.Hmi.dll"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Openness: API for automation of engineering workflows


82 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Use the following program code to open a new TIA Portal Instance by means of the application
configuration file:

//Connect a TIA Portal Openness application via API using


using System;
using System.IO;
using Siemens.Engineering;

namespace UserProgram
{
internal class MyProgram
{
public static void Main(string[] args)
{
// To start TIA Portal with user interface:
// using (TiaPortal tiaPortal = new TiaPortal(TiaPortalMode.WithUserInterface))
//
// To start TIA Portal without user interface:
// using (TiaPortal tiaPortal = new
TiaPortal(TiaPortalMode.WithoutUserInterface))
using (TiaPortal tiaPortal = new TiaPortal(TiaPortalMode.WithUserInterface))
{
//begin of code for further implementation
//...
//end of code
}
}
}
}

Starting the TIA Portal using the "AssemblyResolve" method


Design the program code of the TIA Portal Openness application in such a way that you register
on the event "AssemblyResolve" as early as possible. Encapsulate the access to the TIA Portal in
an additional object or method.
Caution must be taken when resolving the engineering assembly using an assembly resolver
method. If any types from the engineering assembly are used before the assembly resolver has
had run, the program will crash. The reason for this is that the Just-in-time compiler (JIT
compiler) doesn't compile methods until it needs to execute them. If engineering assembly
types are used in Main, for example, the JIT compiler will attempt to compile Main when the
program runs and fail because it doesn't know where to find the engineering assembly. The
registration of the assembly resolver in Main doesn't change this. The method needs to run
before the assembly resolver is registered, and it needs to be compiled before it can be run. The
solution for this problem, is to place the business logic that uses types from the engineering
assembly into a separate method that uses only types that the JIT compiler already understands.
In the example, a method that returns void and has no parameters and place all business logic
inside it is used. When the JIT compiler compiles Main, it will succeed because it knows all the
types in Main. At runtime, when we call RunTiaPortal, the assembly resolver will already be
registered, so when the JIT compiler tries to find our business logic types, it will know where to
find the engineering assembly.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 83
TIA Portal Openness API
5.2 General functions

Use the following program code to open a new TIA Portal Instance.

using System;
using System.IO;
using System.Reflection;
using Siemens.Engineering;

namespace UserProgram
{
static class MyProgram
{
public static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += MyResolver;
RunTiaPortal();
}
private static void RunTiaPortal()
{
// To start TIA Portal with user interface:
// using (TiaPortal tiaPortal = new TiaPortal(TiaPortalMode.WithUserInterface))
//
// To start TIA Portal without user interface:
// using (TiaPortal tiaPortal = new
TiaPortal(TiaPortalMode.WithoutUserInterface))
using (TiaPortal tiaPortal = new TiaPortal(TiaPortalMode.WithUserInterface))
{
//begin of code for further implementation
//...
//end of code
}
}
private static Assembly MyResolver(object sender, ResolveEventArgs args)
{
int index = args.Name.IndexOf(',');
if (index == -1)
{
return null;
}
string name = args.Name.Substring(0, index) + ".dll";
// Edit the following path according to your installed version of TIA Portal
string path = Path.Combine(@"C:\Program Files\Siemens\Automation\Portal Vxx
\PublicAPI\Vxx\", name);
string fullPath = Path.GetFullPath(path);
if (File.Exists(fullPath))
{
return Assembly.LoadFrom(fullPath);
}
return null;
}
}
}

Openness: API for automation of engineering workflows


84 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Accessing running instances of the TIA Portal


In order to connect to a running instance of the TIA Portal with a TIA Portal Openness application,
start by enumerating the instances of the TIA Portal. You can connect to multiple instances
within a Windows session. The running instance can be TIA Portal with or without a started user
interface:

foreach (TiaPortalProcess tiaPortalProcess in TiaPortal.GetProcesses())


{
//...
}

If you know the process ID of the instance of the TIA Portal, use this process ID to access the
object. TIA Portal requires a certain amount of time to start up before you can connect the TIA
Portal Openness application to the TIA Portal.
When you connect to a running instance of the TIA Portal, a connection prompt of the TIA Portal
Openness firewall appears. The connection prompt offers the following options:
• Allow connection once
• Do not allow connection
• Always allow connections from this application
See TIA Portal Openness firewall (Page 86) for further information.
Note
If the registry prompt is rejected three times, the system throws an exception of the
type EngineeringSecurityException.

Once you have connected to the process, you can use the following attributes to retrieve
information on the instances of the TIA Portal:

Attribute Information
InstalledSoftware as Returns information about the installed products.
IList<TiaPortalProduct>
Mode as TiaPortalMode Returns the mode in which the TIA Portal was started (WithoutUserInterface/WithUserIn‐
terface).
AttachedSessions as Returns a list of applications connected to the TIA Portal.
IList<TiaPortalSession>
ProjectPath as FileInfo Returns the file name of the project opened in the TIA Portal, including the folder, for ex‐
ample,
"D:\WinCCProjects\ColorMixing\ColorMixing.ap*"
If no project is open, a null string is returned.
ID as int Returns the process ID of the TIA Portal instance
Path as FileInfo Returns the path to the TIA Portal executable

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 85
TIA Portal Openness API
5.2 General functions

5.2.9 TIA Portal Openness firewall

TIA Portal Openness firewall prompt


When you try to connect to a running TIA Portal via TIA Portal Openness, the TIA Portal will
prompt you to accept or reject the connection like the following screenshot is showing.

Allow connection to the TIA Portal once


If you just want to connect your TIA Portal Openness application to the TIA Portal once, click "Yes"
at the prompt. The next time your TIA Portal Openness application tries to connect the TIA Portal,
the prompt will be shown again.

Addition of a whitelist entry by connecting the TIA Portal


To create a whitlist entry for your TIA Portal Openness application follow these steps:
1. Click "Yes to all" at the prompt to display an User Account Control Dialog.
2. Click "Yes" at the User Account Control Dialog to add your application to the whitelist in the
windows registry and to attach the application to the TIA Portal.

Openness: API for automation of engineering workflows


86 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Addition of a whitelist entry without using the TIA Portal


If you want to add an entry to the whitelist without using TIA Portal you can create a reg file like
this:

Windows Registry Editor Version 5.00


[HKEY_LOCAL_MACHINE\SOFTWARE\Siemens\Automation\Openness\xx.x\Whitelist
\CustomerApplication.exe]
[HKEY_LOCAL_MACHINE\SOFTWARE\Siemens\Automation\Openness\xx.x\Whitelist
\CustomerApplication.exe\Entry]
"Path"="E:\\Work\\Openness\\CustomerApplication\\bin\\Release\\CustomerApplication.exe"
"DateModified"="2014/06/10 15:09:44.406"
"FileHash"="0rXRKUCNzMWHOMFrT52OwXzqJef10ran4UykTeBraaY="

The following example shows how you can calculate the file hash and last modified date:

string applicationPath = @"E:\\Work\\Openness\\CustomerApplication\\bin\\Release\


\CustomerApplication.exe";
string lastWriteTimeUtcFormatted = String.Empty;
DateTime lastWriteTimeUtc;
HashAlgorithm hashAlgorithm = SHA256.Create();
FileStream stream = File.OpenRead(applicationPath);
byte[] hash = hashAlgorithm.ComputeHash(stream);
// this is how the hash should appear in the .reg file
string convertedHash = Convert.ToBase64String(hash);
lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
// this is how the last write time should be formatted
lastWriteTimeUtcFormatted = lastWriteTimeUtc.ToString(@"yyyy/MM/dd HH:mm:ss.fff");

5.2.10 Event handlers

Event handlers in TIA Portal Openness application


An instance of the TIA Portal provides the following events to which you can react with an event
handler in a TIA Portal Openness application. You can access the attributes of notifications and
define the responses accordingly.

Event Response
Disposed Use this event to respond to the closing of the TIA Portal with a TIA Portal Openness appli‐
cation.
Notification Use this event to respond to notifications of the TIA Portal with a TIA Portal Openness
application. Notifications require only an acknowledgment, e.g. "OK".
Confirmation Use this event to respond to confirmations of the TIA Portal with a TIA Portal Openness
application. Confirmations always require a decision, e.g. "Do you want to save the project?".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 87
TIA Portal Openness API
5.2 General functions

Program code
Modify the following program code to register event handlers in a TIA Portal Openness
application:

//Register event handler for Disposed-Event


....
tiaPortal.Disposed +=TiaPortal_Disposed;
....

private static void TiaPortal_Disposed(object sender, EventArgs e)


{
....
}

//Register event handler for Notification-Event


....
tiaPortal.Notification += TiaPortal_Notification;
....

private static void TiaPortal_Notification(object sender, NotificationEventArgs e)

{
....
}

//Register event handler for Confirmation-Event


....
tiaPortal.Confirmation += TiaPortal_Confirmation;
....

private static void TiaPortal_Confirmation(object sender, ConfirmationEventArgs e)


{
....
}

Attributes of TIA Portal notifications


TIA Portal notifications have the following attributes:

Attribute Description
Caption Returns the name of the confirmation.
DetailText Returns the detail text of the confirmation.
Icon Returns the icon of the confirmation.
IsHandled Returns the confirmation or specifies if it is still pending.
Text Returns the text of the confirmation.

Openness: API for automation of engineering workflows


88 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Attributes of confirmations
Confirmations have the following attributes:

Attribute Description
Caption Returns the name of the confirmation.
Choices Returns the option to acknowledge the confirmation.
DetailText Returns the detail text of the confirmation.
Icon Returns the icon of the confirmation.
IsHandled Returns the confirmation or specifies if it is still pending.
Result Returns the result of the acknowledgment or specifies it.
Text Returns the text of the confirmation.

See also
Program-controlled acknowledgement of dialogs with system events (Page 89)

5.2.11 Program-controlled acknowledgement of dialogs with system events

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• Event handlers are registered.
See Connecting to the TIA Portal (Page 81)

Application
When you operate the TIA Portal with the user interface, dialogs with system events are
displayed for some program sequences. You decide how you want to proceed based on these
system events.
When the TIA Portal is accessed with a TIA Portal Openness application, these system events
must be acknowledged by means of corresponding ".NET" events.
The permitted confirmations are contained in the Choices list:
• Abort
• Cancel
• Ignore
• No
• NoToAll
• None

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 89
TIA Portal Openness API
5.2 General functions

• OK
• Retry
• Yes
• YesToAll
The value of ConfirmationEventArgs.Result must be one of the above-mentioned
entries. Otherwise, an exception is thrown.

Program code
Modify the following program code to respond to a confirmation event:

...
tiaPortal.Confirmation += TiaPortalConfirmation;
...
private void TiaPortalConfirmation(object sender, ConfirmationEventArgs e)
{
...
}

Modify the following program code to notify the project engineer about executed actions of a
TIA Portal Openness application:

//Handles notifications
using (TiaPortal tiaPortal = new TiaPortal())
{
tiaPortal.Notification += Notification;
try
{
//perform actions that will result in a notification event
}
finally
{
tiaPortal.Notification -= Notification;
}
}

5.2.12 Terminating the connection to the TIA Portal

Introduction
If you started the TIA Portal instance without a user interface and if your application is the only
TIA Portal Openness client attached to the TIA Portal, you can close the TIA Portal instance with
the TIA Portal Openness application. Otherwise, you disconnect the TIA Portal Openness
application from the TIA Portal instance.
Use the IDisposable.Dispose() method to separate or close the active instance of the TIA
Portal.

Openness: API for automation of engineering workflows


90 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

You can use the IDisposable.Dispose() method as follows:


• With a using statement.
• Surround the object description with a try-finally block and call the IDispose.Dispose()
method within the finally block.
You can no longer access the TIA Portal when you close the active instance of the TIA Portal.

Note
When a configuration engineer closes the TIA Portal instance despite ongoing access of a TIA
Portal Openness application, an exception of the class "NonRecoverableException" is thrown in
the TIA Portal Openness application on the next API access. You can subscribe to the dispose
event to get a call when the TIA Portal is closed.

Program code
Modify the following program code to separate or close the connection to the TIA Portal:

// Add code to dispose the application if the application is still instantiated


if (tiaPortal != null)
{
tiaPortal.Dispose();
}

See also
Event handlers (Page 87)

5.2.13 Diagnostic interfaces on TIA Portal

Application
You can retrieve certain diagnostic information from running instances of TIA Portal via a static
method. The diagnostic interface is implemented on the TiaPortalProcess object, which can be
retrieved for any currently running instance of the TIA Portal.
The diagnostic interface is not blocking, so you can retrieve the TiaPortalProcess object and
access it's members, regardless of if the TIA Portal is busy or not. The diagnostic interface
includes the following Members:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 91
TIA Portal Openness API
5.2 General functions

Class TiaPortalProcess

Member Type Function


AcquisitionTime DateTime The time when the TiaPortalPro‐
cess object was acquired. Since
the TiaPortalProcess object repre‐
sents a completely static snap‐
shot of the state of the TIA Portal
at a given point in time, the infor‐
mation it contains may become
outdated.
Attach TiaPortal Attaches to the given TiaPortal‐
Process, it returns a TiaPortal in‐
stance.
AttachedSessions IList<TiaPortalSession> A collection of all other sessions
currently attached to the same
TIA Portal. This collection can be
empty. Each session is represen‐
ted by a TiaPortalSession object.
Attaching EventHandler<AttachingEven‐ This event enables an application
tArgs> to approve any attempts to at‐
tach to the TIA Portal. When an‐
other application attempts to at‐
tach to the TIA Portal, the sub‐
scribers of this event are notified
and given 10 seconds to approve
the attachment. If any subscriber
ignores this event or does not re‐
spond in time, it is understood to
be denying the other application
permission to attach. Crashed ap‐
plications, being unable to re‐
spond to this event and cannot
cause an application to be denied
permission to attach.
Dispose void Closes the associated TIA Portal
instance.
Id int The Process ID of the TIA Portal.
InstalledSoftware IList<TiaPortalProduct> A collection of all the products
currently installed as part of the
TIA Portal. Each product is repre‐
sented by a TiaPortalProduct ob‐
ject, which is described below.
Mode TiaPortalMode The mode in which the TIA Portal
was started. The current values
are WithUserInterface and With‐
outUserInterface.
Path FileInfo The path to the executable of the
TIA Portal.
ProjectPath FileInfo The path to the project which is
currently open in the TIA Portal. If
no project is open, this attribute
will be null.

Openness: API for automation of engineering workflows


92 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Class TiaPortalSession

Member Type Function


AccessLevel TiaPortalAccessLevel The level access of the session. It
is represented as a flags enum,
where multiple levels of access
are possible. TiaPortalAccessLe‐
vel is described in detail below.
AttachTime DateTime The time when the connection to
the TIA Portal was established.
Id int The Id of the current session.
IsActive bool Returns "true" if the TIA Portal is
currently processing a call from
the running session.
Dispose void Severs the process's connection
to the TIA Portal. This method
does not kill the process itself in
the way that System.Diagnos‐
tics.Process.Kill would do. The ap‐
plication whose connection is ter‐
minated will still get a disposed
event, but there is no other indi‐
cation of why the connection
was terminated.
ProcessId int The process ID of the attached
process.
ProcessPath FileInfo The path to the executable of the
attached process.
TrustAuthority TiaPortalTrustAuthority Indicates if the current session
was started by a process that was
signed, and if it is a TIA Portal
Openness certificate or not. Trust‐
Authority is a flags enum and is
described below.
UtilizationTime TimeSpan The period of time the process
has spent actively using the TIA
Portal.Combined with the Attach‐
Time attribute, this could be used
to determine usage percentages
or similar data.
Version string The version of the Siemens.Engi‐
neering.dll to which the session
is attached to.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 93
TIA Portal Openness API
5.2 General functions

Enum TiaPortalAccessLevel

Enum Value Function


None This is not a valid value. It is included because Tia‐
PortalAccessLevel is a flags enum which needs an
appropriate "zero value" to represent no flags being
set, but it will never appear in actual use because
no session can be started that has no access.
Published The session has access to published functionality.
Modify The session has modify access.

Enum TiaPortalTrustAuthority

Enum Value Function


None The main module of the attached process is not
signed with a certificate.
Signed The main module is signed with a certificate, which
is not a TIA Portal Openness certificate.
Certified The main module is signed with a TIA Portal Open‐
ness certificate.
CertifiedWithExpiration The main module is signed with a TIA Portal Open‐
ness certificate that will become invalid at the end
of its lifetime.

Class TiaPortalProduct

Member Type Function


Name string The name of the product (e.g.
STEP 7 Professional).
Options IList<TiaPortalProduct> A collection of all optional pack‐
ages that belong to the connec‐
ted TIA Portal, represented as Tia‐
PortalProduct objects. If an op‐
tion package itself has option
packages, this nesting could con‐
tinue.
Version string The version string of the product.

Openness: API for automation of engineering workflows


94 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

The following code snippet provides an example of how to use the diagnostic Interface to query
information and of how to use them in your application.

public void TiaPortalDiagnostics()


{
IList<TiaPortalProcess> tiaPortalProcesses = TiaPortal.GetProcesses();
foreach (TiaPortalProcess tiaPortalProcess in tiaPortalProcesses)
{
Console.WriteLine("Process ID: {0}", tiaPortalProcess.Id);
Console.WriteLine("Path: {0}", tiaPortalProcess.Path);
Console.WriteLine("Project: {0}", tiaPortalProcess.ProjectPath);
Console.WriteLine("Timestamp: {0}", tiaPortalProcess.AcquisitionTime);
Console.WriteLine("UI Mode: {0}", tiaPortalProcess.Mode);
//See method body below.
Console.WriteLine("Installed Software:");
EnumerateInstalledProducts(tiaPortalProcess.InstalledSoftware);
Console.WriteLine("Attached Openness Applications:");
foreach (TiaPortalSession session in tiaPortalProcess.AttachedSessions)
{
Console.WriteLine("Process: {0}", session.ProcessPath);
Console.WriteLine("Process ID: {0}", session.ProcessId);
DateTime attachTime = session.AttachTime;
TimeSpan timeSpentAttached = DateTime.Now - attachTime;
TimeSpan utilizationTime = session.UtilizationTime;
long percentageTimeUsed = (utilizationTime.Ticks / timeSpentAttached.Ticks) *
100;
Console.WriteLine("AttachTime: {0}", attachTime);
Console.WriteLine("Utilization Time: {0}", utilizationTime);
Console.WriteLine("Time spent attached: {0}", timeSpentAttached);
Console.WriteLine("Percentage of attached time spent using TIA Portal: {0}",
percentageTimeUsed);
Console.WriteLine("AccessLevel: {0}", session.AccessLevel);
Console.WriteLine("TrustAuthority: {0}", session.TrustAuthority);
if ((session.TrustAuthority & TiaPortalTrustAuthority.Certified) !=
TiaPortalTrustAuthority.Certified)
{
Console.WriteLine("TrustAuthority doesn't match required level, attempting
to terminate connection to TIA Portal.");
session.Dispose();
}
}
}
}
public void EnumerateInstalledProducts(IEnumerable<TiaPortalProduct> products)
{
foreach (TiaPortalProduct product in products)
{
Console.WriteLine("Name: {0}", product.Name);
Console.WriteLine("Version: {0}", product.Version);
//recursively enumerate all option packages
Console.WriteLine("Option Packages \n:");
EnumerateInstalledProducts(product.Options);
}
}

Security Relevant Information

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 95
TIA Portal Openness API
5.2 General functions

Because of the fact that no connection to the TIA Portal is needed to use the diagnostics
interface, it's possible to write a Windows service that uses the attaching event to check any
application attempting to attach to a TIA Portal, e.g. only applications that begin with your
company's name are allowed to attach. Another option might be to always grant access, but
write information about attaching processes to a log. The following program code is an example
event handler to check incoming connections:

public void OnAttaching(object sender, AttachingEventArgs e)


{
string name = Path.GetFileNameWithoutExtension(e.ProcessPath);
TiaPortalAccessLevel requestedAccessLevel = e.AccessLevel &
TiaPortalAccessLevel.Published;
TiaPortalTrustAuthority certificateStatus = e.TrustAuthority
&TiaPortalTrustAuthority.Certified;
if (requestedAccessLevel == TiaPortalAccessLevel.Published &&
certificateStatus == TiaPortalTrustAuthority.Certified &&
name.StartsWith("SampleCustomerName"))
{
e.GrantAccess();
}
}

5.2.14 Exclusive access

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The "TIA Portal" class provides the method "ExclusiveAccess(String text)" to establish an
exclusive access to an attached TIA Portal process. The usage of an exclusive access is highly
recommended even if it is not mandatory.
Use "ExclusiveAccess" in an "using" statement to ensure it is disposed attribute even when
exceptions occur or the application is shutdown.

Note
Any attempt to create a second exclusive access within the scope of an open exclusive access will
result in an recoverable exception being raised.

Openness: API for automation of engineering workflows


96 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Modify the following example to get "ExclusiveAccess" to an instance:

...
[assembly: AssemblyTitle("MyApplication")]
// This will be used for the exclusive access dialog when present....
TiaPortal tiaPortal = ...;
using (ExclusiveAccess exclusiveAccess = tiaPortal.ExclusiveAccess("My Activity"))
{
...
}

After acquiring an "ExclusiveAccess" instance for a given TIA Portal process a dialog will be
displayed. This dialog will display the message provided during instantiation. In addition the
following information of the client application will be displayed:
• the assembly title of the manifest data if available; otherwise, the process name
• the process ID
• the SID (Openness Session ID of the client application's TiaPortal instance)

Note
There can be multiple sessions active for a given TIA Portal Openness client application because
there can be multiple instances of TiaPortal each associated with the same TIA Portal process.

The client application can also update the displayed content of the exclusive access dialog by
setting the "Text" attribute with new values. Modify the following program code to invoke this
behavior:

exclusiveAccess = ...;
...
exclusiveAccess.Text = "My Activity Phase 1";
...
exclusiveAccess.Text = "My Activity Phase 2";
...
exclusiveAccess.Text = String.Empty; // or null;
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 97
TIA Portal Openness API
5.2 General functions

You can request that the exclusive access could be cancelled by selecting the "Cancel" button.
Modify the following program code to invoke this behavior:

exclusiveAccess = ...;
...
if (exclusiveAccess.IsCancellationRequested)
{
// stop your activity
...
}
else
{
// continue your activity
...
}
...

5.2.15 Dynamic behaviours

Dynamic behaviors in Openness


The Openness users can determine objects and their attributes during the run time. They also
are able to invoke actions and navigate to related objects bidirectionally in the hierarchy. In order
to support dynamic behaviors the following interfaces are provided and implemented by
Openness objects:

IEngineeringInstance
The interface that allows up navigation in the Object Model.
Properties:
• IEngineeringObject Parent - Parent object of an instance instance.

IEngineeringCompositionOrObject
The interface is implemented by both engineering objects and compositions.

IEngineeringObject
The interface is implemented by the majority of objects that are available for the Openness
users. IEngineeringObject interface is derived from IEngineeringCompositionOrObject and
IEngineeringInstance:

Openness: API for automation of engineering workflows


98 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Methods:
• IList<EngineeringCreationInfo> GetCreationInfos(string compositionName) - Gets the list of
composition infos available for the object.
• IEngineeringObject Create(string compositionName, Type type,
IEnumerable<KeyValuePair<string, object>> parameters) - Creates an IEngineeringObject of
indicated type initialized with values as indicated compositionName within the parameters
• object GetAttribute(string name) - Gets an attribute with the given name.
• IList<EngineeringAttributeInfo> GetAttributeInfos() - Returns a collection of
EngineeringAttributeInfo objects describing the different attributes on this object.
• IList<object> GetAttributes(IEnumerable<string> names) - Gets a list of attributes for the
given names
• IEngineeringCompositionOrObject GetComposition(string name) - Gets an
IEngineeringCompositionOrObject with the given name.
• IList<EngineeringInvocationInfo> GetInvocationInfos() - Returns a collection of
EngineeringInvocationInfo objects describing the different actions on this object.
• object Invoke(string name, IEnumerable<KeyValuePair<Type, object>> parameters) -
Invokes the method represented by the current instance, using the specified parameters.
• void SetAttribute(string name, object value) - Sets an attribute with the given name to the
given value
• void SetAttributes(IEnumerable<KeyValuePair<string, object>> attributes) - Sets the
attributes with the given names to the given values as indicated in attributes.
• EngineeringObjectHandle GetHandle() - Gets the object's unique handle.

IEngineeringRoot
This interface is implemented by TiaPortal objects and indicates that the user is at the top object
in the hierarchy. IEngineeringRoot is derived from IEngineeringObject,
IEngineeringCompositionOrObject and IEngineeringInstance.
Methods:
• IEngineeringObject GetObject(EngineeringObjectHandle objectHandle) - Gets the object
from a handle

IEngineeringComposition
The interface is implemented by the majority of objects that are available for the Openness
users. IEngineeringObject interface is derived from IEngineeringCompositionOrObject and
IEngineeringInstance. In addition to the properties and methods described in Working with
compositions (Page 101), the following methods are supported.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 99
TIA Portal Openness API
5.2 General functions

Methods:
• IEngineeringObject Create(Type type, IEnumerable<KeyValuePair<string, object>>
parameters) - Creates an IEngineeringObject of indicated type initialized with values as
indicated in parameters..
• IList<EngineeringCreationInfo> GetCreationInfos() - Gets the collection of
EngineeringCreateInfo objects describing the different CreateInfos on this object.
• IList<EngineeringInvocationInfo> GetInvocationInfos() - Returns a collection of
EngineeringInvocationInfo objects describing the different actions on this object.
• object Invoke(string name, IEnumerable<KeyValuePair<Type, object>> parameters) -
Invokes the method represented by the current instance, using the specified parameters.

IEngineeringObjectAssociation
This interface is implemented by the collection of associated engineering objects. This interface
is derived from IEngineeringAssociation and IEngineeringInstance. See Working with
associations (Page 101)

IEngineeringServiceProvider
The interface is implemented by engineering objects that can provide service(s).
Methods:
• T GetService<T>() where T : class, IEngineeringService - Gets an instance of type T.
• IList<EngineeringServiceInfo> GetServiceInfos() - Returns a collection of
EngineeringServiceInfo objects describing the different services on this object.

IEngineeringService
The interface representing an engineering service that is provided by
IEngineeringServiceProvider.

EngineeringObjectHandle
The structure that provides a unique object handle.

See also
Working with compositions (Page 101)
Working with associations (Page 101)

Openness: API for automation of engineering workflows


100 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

5.2.16 Working with associations

Accessing associations
An association describes the relationship between two or more objects at type level.
TIA Portal Openness supports access to associations via index and via "foreach" loops. Direct
access, for example via string name, is not supported.

Attributes
The following attributes are available:
• int Count
• bool IsReadonly
• IEngineeringObject Parent
• retType this [ int index ] { get; }

Methods
TIA Portal Openness supports the following methods:
• int IndexOf ( type ): Returns the index in the association for a transferred instance.
• bool Contains ( type ): Determines whether the transferred instance is contained in
the association.
• IEnumerator GetEnumerator <retType>(): Employed within "foreach" loops to
access an object.
• void Add ( type )1: Adds the transferred instance to the association.
• void Remove ( type )1: Removes the transferred instance from the association.
1
: Not supported by all associations.

5.2.17 Working with compositions

Accessing compositions
A composition is the special case of an association. A composition expresses a semantic
relationship of two objects, of which one is part of the other.

Attributes
The following attributes are available:
• int Count
• bool IsReadonly

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 101
TIA Portal Openness API
5.2 General functions

• IEngineeringObject Parent
• retType this [int index] {get;}: Indexed access to an object of the composition.
This type of access should only be used in a targeted manner, as each indexed access
operation exceeds process boundaries.

Methods
TIA Portal Openness supports the following methods:
• retType Create (id, …): Creates a new instance and adds this instance to the
composition.
The signature of the method depends on the way in which the instance is created. This
method is not supported by all compositions.
• type Find (id, …): Scans a composition for the instance with the transferred ID.
The search is not recursive. The signature of the method depends on the way in which the
instance is searched for. This method is not supported by all compositions.
• IEnumerator GetEnumerator<retType> (): Employed within "foreach" loops to
access an object.
• Delete (type)1: Deletes the instance specified by the current object reference.
• int IndexOf (type): Returns the index in the composition for a transferred instance.
• bool Contains (type): Determines whether the transferred instance is contained in the
composition.
• void Import(string path, ImportOptions importOptions)1: Used for each
composition that contains importable types.
Each import signature includes a configuration parameter of the type "ImportOptions
(Page 885)" ("None", "Overwrite") by which the user controls the import behavior.
1
: Not supported by all compositions.

5.2.18 Verifying object equality

Application
As user of a TIA Portal Openness API, you can check that objects are the same with program code:
• You check whether two object references are the same with the operator "==".
• Use the System.Object.Equals() method to check if both objects are really identical
with regard to the TIA Portal.

Openness: API for automation of engineering workflows


102 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Program code
Modify the following program code to check for object reference types:

...
//Composition
DeviceComposition sameCompA = project.Devices;
DeviceComposition sameCompB = project.Devices;
if (sameCompA.Equals(sameCompB))
{
Console.WriteLine("sameCompA is equal to sameCompB");
}
if (!(sameCompA == sameCompB))
{
Console.WriteLine("sameCompA is not reference equal to sameCompB");
}
DeviceComposition sameCompAsA = sameCompA;
if (sameCompAsA.Equals(sameCompA))
{
Console.WriteLine("sameCompAsA is equal to sameCompA");
}
if (sameCompAsA == sameCompA)
{
Console.WriteLine("sameCompAsA is reference equal to sameCompA");
}
MultiLingualGraphicComposition notSameComp = project.Graphics;
if (!sameCompA.Equals(notSameComp))
{
Console.WriteLine("sameCompA is not equal to notSameComp");
}

5.2.19 Read operations for attributes

Group operations and standard read operations for attributes


TIA Portal Openness supports access to attributes via the following methods which are available
at the object level:
• Group operation for read access
• Standard read operations

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 103
TIA Portal Openness API
5.2 General functions

Program code for group operations

//Exercise GetAttributes and GetAttributeNames


//get all available attributes for a device,
//then get the names for those attributes, then display the results.
private static void DynamicTest(Project project)
{
Device device = project.Devices[0];
IList<string> attributeNames = new List<string>();
IList<EngineeringAttributeInfo> attributes =
((IEngineeringObject)device).GetAttributeInfos();
foreach (EngineeringAttributeInfo engineeringAttributeInfo in attributes)
{
string name = engineeringAttributeInfo.Name;
attributeNames.Add(name);
}
IList<object> values = ((IEngineeringObject)device).GetAttributes(attributeNames);
for (int i = 0; i < attributes.Count; i++)
{
Console.WriteLine("attribute name: " + attributeNames[i] + " value: " + values[i]);
}
}

Group operation for read access


This method is available for any object:
public abstract IList<object> GetAttributes(IEnumerable<string>
names);

Standard read operations


The following operations are available:
• Retrieve the names of available attributes:
Use the method GetAttributeInfos() (Page 108) on an IEngineeringObject.
• Generic method for reading an attribute
public abstract object GetAttribute(string name);

Note
Dynamic attributes are not shown in IntelliSense because their availability depends on the status
of the object instance.

Openness: API for automation of engineering workflows


104 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

5.2.20 Transaction handling

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Operation
A persistence (project, library, etc.) opened within an associated TIA Portal process can be
modified by a TIA Portal Openness client application. You can produce this modification from a
single operation or by a series of operations. Depending on the activity, it is reasonable to group
these operations into a single undo unit for more logical workflows. Additionally there are
performance advantages provided by grouping operations into a single undo unit. To support
this, the "ExclusiveAccess" class provides the method "Transaction(ITransactionSupport
persistence, string undoDescription)". The invocation of this method results in the instantiation
of a new disposable object of type "Transaction". You have to provide a description of the
transaction's contents (the text attribute cannot be null or Empty). While this instance has not
been disposed, all client application operations will be grouped into a in a single undo unit
within the associated TIA Portal process.
Modify the following program code to acquire a "Transaction" instance:

ExclusiveAccess exclusiveAccess = ...;


Project project = ...;
using (Transaction transaction = exclusiveAccess.Transaction(project, "My Operation"))
{
...
}

Note
Use a "using" statement to instatiate a "Transaction" to ensure it is disposed properly even when
exceptions occur, thus rolling back the transaction.

Consistent commit or rollback


The use of a "Transaction" within a client application helps you to ensure that there is a
predictable way to commit or rollback a set of modifications. Your client application must decide
whether or not to commit their modifications to a persistence. To do this your application must
request that the modifications within the scope of an open transaction be committed when the
transaction is disposed by invoking the 'Transaction.CommitOnDispose()' method. If this
method is never invoked in the code flow, the modifications within the scope of the open
transaction will automatically be rolled back when it is disposed.
If an exception occur after making the request, all modifications within the scope of an open
transaction will still be rolled back on its disposal.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 105
TIA Portal Openness API
5.2 General functions

Modify the following program code to create a single undo unit in the attached TIA Portal
containing two "Create" modifications:

ExclusiveAccess exclusiveAccess = ...;


Project project = ...;
using (Transaction transaction = exclusiveAccess.Transaction(project, "My Operation")
{
project.DeviceGroups.Create("My Group 1");
project.DeviceGroups.Create("My Group 2");
transaction.CommitOnDispose();
}

Restrictions
The following actions are not allowed inside of a transaction. Calling these will result in a
recoverable exception:
• Compile
• Go Online
• Go Offline
• ProjectText Import
• ProjectText Export
• Open Global Library
• Close Global Library
• Project Create
• Project Open
• Project OpenWithUpgrade
• Project Save
• Project SaveAs
• Project Close

Undo behavior
Actions performed by a TIA Portal Openness client application can result in undo units within the
attached TIA Portal process. Each of these undo entries will be grouped under a location entry.
This location entry will compose the following information from the client application:
• the assembly title from the manifest data if available; otherwise, the process name
• the process ID
• the SID (Openness Session ID of the client application's TiaPortal instance)
• optionally an indication that the client process is still running

Openness: API for automation of engineering workflows


106 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

These entries will be one of the following two kinds:


1. The operations that are gathered into one undo transaction as a result of using a
"Transaction" have the description as provided by the client application when the
"Transaction" was instantiated.
– Undo entry for a running client application:

– Undo entry for a stopped client application:

2. The operations that are executed individually have individual undo entries describing the
operation as defined in the respective command meta data.
– Undo entry for a running client application:

– Undo entry for a stopped client application:

5.2.21 Creating a DirectoryInfo/FileInfo object

Application
The instances of DirectoryInfo and FileInfo classes have to contain an absolute path.
Otherwise the methods using the DirectoryInfo or FileInfo objects.will lead to an
exception.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 107
TIA Portal Openness API
5.2 General functions

Program code
Modify the following program code to create a DirectoryInfo or a FileInfo object.

..
//Create a DirectoryInfo object
string directoryPath = @"D:\Test\Project 1";
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
   

//Create a FileInfo object


//please adapt the path and the extension apx to the installed version of TIA Portal
string fileName = @"D:\Test\Project 1\Project 1.apx");
FileInfo fileInfo = new FileInfo(fileName);
...

5.2.22 Self-description support for attributes, navigators, actions, and services

Application
In TIA Portal Openness each IEngineeringServiceProvider of the TIA Portal Openness API
describes its capabilities to potential calls.
Self-description Support on IEngineeringObject

Method Name Return values


GetCompositionInfos Returns a collection of EngineeringCompositionIn‐
fo objects describing the different compositions of
these objects. EngineeringCompositionInfo is de‐
scribed below.
GetAttributeInfos Returns a collection of EngineeringAttributeInfo
objects describing the different attributes of these
objects. EngineeringAttributeInfo is described be‐
low.
GetInvocationInfos Returns a collection of EngineeringInvocationInfo
objects describing the different actions of these ob‐
jects. EngineeringInvocationInfo is described be‐
low.

Self-description Support on IEngineeringServiceProvider

Method Name Return values


GetServiceInfos Returns a collection of EngineeringServiceInfo ob‐
jects describing the different services of these ob‐
jects. EngineeringServiceInfo is described below.

Openness: API for automation of engineering workflows


108 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Self-description Support on IEngineeringComposition

Method Name Return values


GetCreationInfos Returns a collection of EngineeringCreationInfo ob‐
jects describing the different actions of these ob‐
jects.
EngineeringcreationInfo is described below.

Class EngineeringCompositionInfo

Attribute Name Return values


Name The name of the composition

Class EngineeringAttributeInfo

Attribute Name Return values


AccessMode The level of access supported by the attribute. This
attribute is combinable and is described in detail
below.
Name The name of the attribute.

Class EngineeringInvocationInfo

Attribute Name Return values


Name The name of the action.
ParameterInfos A collection of EngineeringInvocationParameterIn‐
fo objects describing any parameters that the ac‐
tion might require. EngineeringInvocationParame‐
terInfo is described below.

Class EngineeringServiceInfo

Attribute Name Return values


Type The type of the service as a System.Type object.

Enum AccessMode

Enum Value Return values


None This is not a valid option.
Read The attribute can be read.
Write The attribute can be written.

Class EngineeringInvocationParameterInfo

Attribute Name Return values


Name The name of the parameter.
Type The type of the parameter as a System.Type object

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 109
TIA Portal Openness API
5.2 General functions

Class EngineeringCreationInfo

Attribute Name Return values


Type The Type property returns a System.Type object
ParameterInfos The ParameterInfos property returns a collection of
EngineeringCreationParameterInfo objects

Class EngineeringCreationParameterInfo

Attribute Name Return values


Name The name of the parameter in question

Program code
AccessMode is a flags enum and its values can be combined like the following program code:

EngineeringAttributeAccessMode value = EngineeringAttributeAccessMode.Read|


EngineeringAttributeAccessMode.Write;

Modify the following program code to find all attributes of an IEngineeringObject and to do
changes on the access mode of those attributes.

...
IEngineeringObject engineeringObject = ...;
IList<EngineeringAttributeInfo> attributeInfos = engineeringObject.GetAttributeInfos();
foreach(EngineeringAttributeInfo attributeInfo in attributeInfos)
{
switch (attributeInfo.AccessMode)
{
case EngineeringAttributeAccessMode.Read:
...
break;
case EngineeringAttributeAccessMode.Write:
...
break;
case EngineeringAttributeAccessMode.Read|EngineeringAttributeAccessMode.Write:
...
break;
}
}
...

Openness: API for automation of engineering workflows


110 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.2 General functions

Modify the following program code of how Create and GetCreationInfos are intended to be used
together.

...
Project project = tiaPortal.Projects.Open(projectPath);
IEngineeringComposition deviceGroupComposition = project.DeviceGroups;
EngineeringCreationInfo deviceGroupCreationInfo = deviceGroupComposition.GetCreationInfos()
[0];
EngineeringCreationParameterInfo deviceGroupCreationParameterInfo =
deviceGroupCreationInfo.ParameterInfos[0];
string deviceGroupCreationParameterName = deviceGroupCreationParameterInfo.Name;
string groupName = "Example";
IDictionary<string, object> createParameters = new Dictionary<string, object>
{
{deviceGroupCreationParameterName, groupName }
};
IEngineeringObject group = deviceGroupComposition.Create(deviceGroupCreationInfo.Type,
createParameters);
...

5.2.23 Setting attributes of Blocks, DBs & UDTs

Introduction
It is possible to write and read (general) attributes of the Blocks (written in any programming
language), DBs and UDTs via the Openness API.
TechnologicalObjects are internally DBs, so this feature is also valid for TOs.
The same checking rules are to be applied on Name by using SetAttribute of the Openness API
on block, DB (TO) or UDT which are applied in the GUI.
In case of rule violation an appropriate user exception will be thrown and the attribute value
won't be changed.
This extension of the API doesn't affect the XML export / import.

General Attributes
Legend
• X: The attribute is relevant, write to xml, accessible with API
• -: The attribute is not accessible, the attribute does not exist

Attributes Datatype Availability via the API


CodeBlock DB UDT
AutoNumber Boolean X (xml); RW (API) X (xml); RW (API) -
CodeModifiedDate DateTime X (xml); R (API) X (xml); R (API) -

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 111
TIA Portal Openness API
5.2 General functions

Attributes Datatype Availability via the API


CodeBlock DB UDT
CompileDate DateTime X (xml); R (API) X (xml); R (API) -
CreationDate DateTime X (xml); R (API) X (xml); R (API) X (xml); R (API)
HeaderAuthor String X (xml); R (API) X (xml); R (API) -
HeaderFamily String X (xml); R (API) X (xml); R (API) -
HeaderName String X (xml); R (API) X (xml); R (API) -
HeaderVersion System.Version X (xml); R (API) X (xml); R (API) -
InstanceOfName String - X (xml); R (API) -
Interface String X (xml); - (API) X (xml); - (API) X (xml); - (API)
InterfaceModifiedDate DateTime X (xml); R (API) X (xml); R (API) X (xml); R (API)
IsConsistent Boolean X (xml); R (API) X (xml); R (API) X (xml); R (API)
IsKnowHowProtected Boolean X (xml); R (API) X (xml); R (API) X (xml); R (API)
MemoryLayout (sofar: MemoryLayout X (xml); R (API) X (xml); R (API) -
Optimization)
ModifiedDate DateTime X (xml); R (API) X (xml); R (API) X (xml); R (API)
Name String X (xml); RW (API) X (xml); RW (API) X (xml); RW (API)
Number Int32 X (xml); RW (API) X (xml); RW (API) -
ParameterModified DateTime X (xml); R (API) X (xml); R (API) -
ProgrammingLanguage ProgrammingLan‐ X (xml); R (API) X (xml); R (API) -
guage
SecondaryType String X (xml); R (API) - -
StructureModified DateTime X (xml); R (API) X (xml); R (API) -

5.2.24 Notes on performance of TIA Portal Openness

Root objects
You can specify several root objects in import files.
Example: You can create several text lists in an XML file instead of one text list for each XML file.

TIA Portal Openness functions


The first call of a TIA Portal Openness function can take longer than any subsequent calls of the
TIA Portal Openness function.
Example: If you perform multiple configuration data exports one after the other, the first export
can take longer than the subsequent exports.

Openness: API for automation of engineering workflows


112 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

5.3 Functions for projects and project data

5.3.1 Opening a project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• The project to be opened is not open in any other instance of the TIA Portal.

Note
Undo of project upgrade
If you undo an upgrade of a project to V14SP1 after you have connected it to TIA Portal
Openness, conflicts will occur.

Application
Use the Projects.Open method to open a project. Enter a path to the desired project in
the Projects.Open method.
The Projects.Open method only accesses projects that were created with the current
version of TIA Portal or which have been upgraded to the current version. If you access a project
of a previous version with the Projects.Open method, an exception will be returned. Use the
OpenWithUpgrade method, to open projects which have been made with previous versions of
TIA Portal.

Note
No access to read-only projects
TIA Portal Openness can only access projects with read and write privileges.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 113
TIA Portal Openness API
5.3 Functions for projects and project data

Program code
Modify the following program code to open a project:

Project project =tiaPortal.Projects.Open(new FileInfo(@"D:\Project_1\Project_1.apXX"));


if (project != null)
{
try
{
...
}
finally
{
project.Close();
}
}

Opening a UMAC protected project


You can also open a UMAC protected project. The overload of Open function takes an additional
parameter of type UmacDelegate. This additional parameter allows the caller to specify a
handler to be used during UMAC authentication. The new UmacDelegate is implemented with
a method containing one parameter of type UmacCredentials. The UmacCredentials has two
properties, 'Name' of type string, and 'Type' of type UmacUserType; and one method
SetPassword with one parameter of type SecureString. The use of UmacUserType.Project
indicates a UMAC scope of project whereas the use of UmacUserType.Global indicates a UMAC
scope of application (i.e. controlled by a UMAC server).

Openness: API for automation of engineering workflows


114 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Program code

...
Siemens.Engineering.Project project = tiaPortal.Projects.Open(new
FileInfo(@"D:\Project_3\Project_2.apXX"), MyUmacDelegate);
if (project != null)
{
try
{
...
}
finally
{
project.Close();
}
}
...
private static void MyUmacDelegate(UmacCredentials umacCredentials)
{
SecureString password = ...; // Get password from a secure location
umacCredentials.Type = UmacUserType.Project;
umacCredentials.Name = "SomeUser";
umacCredentials.SetPassword(password);
}
...
}

Opening a UMAC protected project using new authentication


Before TIA Portal Openness V17, You can open the protected project by passing the user name
and password through Umac delegate in Open Project API.
With TIA Portal Openness V17, UMAC have introduced new authentication mechanism by which
you will able to open a protected project. The following new authentication mechanisms are
Desktop Single Sign-On (SSO) and Anonymous User.
TIA Potal Openness V17 will support below Authentication Mechanisms. . Also Openness
implementation is independent of settings in TIA Portal.
• Desktop Single Sign-On (SSO)
• Anonymous User
• Interactive log on
• Credential (Existing From TIA Portal V15.1)
In order to accommodate the additional authentication methods, Openness have introduced a
new event name "Authentication" in TIA Portal object. The changes are introduced as a part of
V17 Engineering.dll. The Event "Authentication" when registered by the user in the Openness

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 115
TIA Portal Openness API
5.3 Functions for projects and project data

script, will be executed when open project is called. The Event "Authentication" will be executed
only for Open Protected Project.

var tiaPortal = new TiaPortal();


tiaPortal.Authentication += OnAuthentication;
private static void OnAuthentication(object sender, AuthenticationEventArgs e)
{
e.AuthenticationTypeProvider = AuthenticationTypeProvider.Credentials;
}

You would be able to use the Additional Authentication Methods using the
AuthenticationEventArgs event args. Using AuthenticationTypeProvider ,the mode of
authentication is provided. From the above example , the crediantial mode is set.
Below are the values for AuthenticationTypeProvider.
• AuthenticationTypeProvider.DesktopSso : Open project with Single sign on user , no
password asked
• AuthenticationTypeProvider.Anonymous : Open project with anonymous user , no password
asked
• AuthenticationTypeProvider.Interactive : Open project with Interactive logon, User name and
password to be given in user interface
• AuthenticationTypeProvider.Credentials : Open Project with User name and password given.
The event is applicable for opening the project in Multiuser user environment.The above
authentication methods is applicable when a protected project is opened in Local session or
Server View.
If there are exceptions for example, a single sign-on session or a user name / password invalid
scenarios are handled by Openness exception EngineeringTargetInvocationException.

Opening multiple projects


You can open one primary project and multiple secondary projects at time in an instance of the
TIA Portal. In this case you have to decide to open a project as a primary or a secondary project.
If a project is opened as primary, then this project is represented in the project navigation if the
Openness application is attached to a TIA Portal. If a project is opened as secondary, the project
will not be reflected in the user interface. Secondary projects are always opened as read-only.
Therefore, a user with read and write priviliges to UMAC projected project will only have read-
only priviliges when project is opened as secondary. A primary project does not need to be open
in order to open a secondary project.
Any opened projects can be enumerated by using the ProjectComposition available on the
TiaPortal instance. The order of the projects in the composition will be determined by the order
in which the projects were opened. If a project is closed, the index of all projects will be
recalculated.

Openness: API for automation of engineering workflows


116 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Program code

TiaPortal tiaPortal = ...;


Project project1 = tiaPortal.Projects.Open(new
FileInfo(@"D:\Project_1\Project_1.apXX"), null, ProjectOpenMode.Primary);
Project project3 = tiaPortal.Projects.Open(new
FileInfo(@"D:\Project_3\Project_3.apXX"), null, ProjectOpenMode.Secondary);
bool isPrimary = project3.IsPrimary

Opening projects created with previous versions


Use the OpenWithUpgrade method to open a project which was created with the previous
version of TIA Portal. The method will create a new, upgraded project and open it.
If you access a project created with an elder version than the previous, an exception will be
returned.

Note
If you access a project created with the current version the project will just be opened.

Program code
Modify the following program code to open a project via the OpenWithUpgrade method:

Project project = tiaPortal.Projects.OpenWithUpgrade(new FileInfo(@"D:\Some


\Path\Here\Project.apXX"));
if (project != null)
{
try
{
...
}
finally
{
project.Close();
}
}

Program code for UMAC protected project


You can also open a UMAC protected which has been created with a previous version of TIA
Portal. An overload function of OpenWithUpgrade takes an additional parameter of type
UmacDelegate. OpenWithUpgrade is also supported for secondary projects.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 117
TIA Portal Openness API
5.3 Functions for projects and project data

...
Siemens.Engineering.Project project = tiaPortal.Projects.OpenWithUpgrade(new
FileInfo(@"D:\Project_1\Project.apXX"), MyUmacDelegate);
...

5.3.2 Creating a project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)

Application
Projects can be created via TIA Portal Openness API
• by calling the Create method on ProjectComposition
• by calling the Create method on IEngineeringComposition

ProjectComposition.Create
Modify the following program code:

TiaPortal tiaPortal = ...;


ProjectComposition projectComposition = tiaPortal.Projects;
DirectoryInfo targetDirectory = new DirectoryInfo(@"D:\TiaProjects");

// Create a project with name MyProject


Project project = projectComposition.Create(targetDirectory, "MyProject");

According to this example


• a folder "D:\TiaProjects\MyProject" will be created.
• a project file "D:\TiaProjects\MyProject\MyProject.aPXX" will be created.

Note
About parameter targetDirectory
The parameter targetDirectory can also represent an UNC (Universal Naming Convention) path,
therefore a project can also be created on a network shared drive.

Openness: API for automation of engineering workflows


118 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

IEngineeringComposition.Create
Modify the following program code:

TiaPortal tiaPortal = ...;


ProjectComposition projectComposition = tiaPortal.Projects;

//allows the user to give optional create parameters like author, comment in addition to
mandatory create parameters (targetdirectory, projectname)

IEnumerable<KeyValuePair<string, object>> createParameters = new [] {


new KeyValuePair<string, object>("TargetDirectory", new
DirectoryInfo(@"D:\TiaProjects")), // Mandatory
new KeyValuePair<string, object>("Name", "MyProject"), // Mandatory
new KeyValuePair<string, object>("Author", "Bob"), // Optional
new KeyValuePair<string, object>("Comment", "This project was created with
Openness") // Optional };

// Create a project with both mandatory and optional parameters


((IEngineeringComposition)projectComposition).Create(typeof (Project), createParameters);

According to this example


• a folder "D:\TiaProjects\MyProject" will be created.
• a project file "D:\TiaProjects\MyProject\MyProject.aPXX" will be created with project
attributes Author as "Bob" and Comment as "This project was created with openness".

Parameters for creating project with optional project attributes

Parameter Data Type Is Manda‐ Description


tory
Author String No Author of a project.
Comment String No Comment for the project.
Name String Yes Name of a project,
TargetDirecto‐ DirectoryInfo Yes Directory that will contain the created proeject fold‐
ry er.

5.3.3 Accessing general settings of the TIA Portal

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 119
TIA Portal Openness API
5.3 Functions for projects and project data

Application
Via TIA Portal Openness you can access general settings of the TIA Portal:
• Current user interface language
• "Search in project" option to create the search index needed for searching within a project.
The following table shows the details of the accessible settings in the "General" section of the TIA
Portal settings. The TiaPortalSettingsFolder instance will have the name "General".

Setting name Data type Writeable Description


"SearchInProj System.Boolean r/w Enables or disables the creation of the
ect" search index needed for searching with‐
in a project.
"UserInterfac System.CultureInfo r/w Indicates the active user interface lan‐
eLanguage" guage of the TIA Portal or the specifica‐
tion of the active user interface lan‐
guage.

The access to these settings is provided via the TiaPortalSettingsFolder class. The
TiaPortalSettingsFolder class will be accessible via the Settings attribute on the
TiaPortal class.
The following figure shows the specific settings in TIA Portal Openness:

Openness: API for automation of engineering workflows


120 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

7LD3RUWDO


6HWWLQJV)ROGHUV7LD3RUWDO6HWWLQJV)ROGHU&RPSRVLWLRQ


6HWWLQJV)ROGHUV

7LD3RUWDO6HWWLQJV)ROGHU&RPSRVLWLRQ

)LQG 6WULQJQDPH 7LD3RUWDO6HWWLQJV)ROGHU

)ROGHUV

7LD3RUWDO6HWWLQJV)ROGHU

1DPH 6WULQJ
6HWWLQJV 7LD3RUWDO6HWWLQJ&RPSRVLWLRQ
)ROGHUV 7LD3RUWDO6HWWLQJV)ROGHU&RPSRVLWLRQ

6HWWLQJV

7LD3RUWDO6HWWLQJ&RPSRVLWLRQ

)LQG 6WULQJQDPH 7LD3RUWDO6HWWLQJ

7LD3RUWDO6HWWLQJ

1DPH6WULQJ
9DOXH2EMHFW

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 121
TIA Portal Openness API
5.3 Functions for projects and project data

Program code: Search in project


Modify the following program code to activate/deactivate the "Search in project" option.

private static void SetSearchInPoject(Project project)


{
TiaPortalSettingsFolder generalSettingsFolder =
tiaPortal.SettingsFolders.Find("General");
TiaPortalSetting searchSetting =
generalSettingsFolder.Settings.Find("SearchInProject");

if (((bool)searchSetting.Value))
{
searchSetting.Value = false;
}
}

Program code: User interface language


Modify the following program code to access the current user interface language.

private static void SetUILanguage(Project project)


{

TiaPortalSettingsFolder generalSettingsFolder =
tiaPortal.SettingsFolders.Find("General");

TiaPortalSetting UILanguageSetting =
generalSettingsFolder.Settings.Find("UserInterfaceLanguage");

if (((CultureInfo)UILanguageSetting.Value) != CultureInfo.GetCultureInfo("de-DE"))
{
UILanguageSetting .Value = CultureInfo.GetCultureInfo("de-DE");
}

See also
Opening a project (Page 113)

Openness: API for automation of engineering workflows


122 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

5.3.4 Archiving and Retrieving a project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)
• A project is save
See Saving a Project (Page 141)

Application
You can use the TIA Portal Openness to archive the opened and saved project state prior to
further any changes and then later you can retrieve the archived project.

Archiving a project
You can archive a TIA Portal project using TIA Openness API available on
Siemens.Engineering.Project object.

public void Archive(System.IO.DirectoryInfo targetDirectory, string targetName,


Siemens.Engineering.ProjectArchivationMode archivationMode)

'targetName' is the name of the file created may it be archived or non archived. This file may or
may not contain any file extensions. For ProjectArchivationMode value as Compressed and
DiscardRestorableDataAndCompressed, the archived file name is as it is provided by you. If you
don't provide any extension or extension apart from "zap15_1" or "zap14" etc., then this archived
project could not be retrieved from TIA Portal outside the Openness API. If you don't not choose
Compressed or DiscardRestorableDataAndCompressed the result will be the default file
structure of a project of the current version.

Note
You must have saved the project before calling Archiving API. In case the project contains any
unsaved changes, archive would throw an EngineeringTargetInvocationException.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 123
TIA Portal Openness API
5.3 Functions for projects and project data

Project ArchivationMode
The ProjectArchivationMode enumeration have four values.

ProjectArchivationMode Description
None • No special action are taken with the orginial files. Mode is
similiar to a "save as" operation.
• No compressed zip file is created in this mode.
• The difference with SaveAs in this case is that the Archive
will not change the persistence location to the new Ar‐
chived folder whereas SaveAs does that
DiscardRestorableData • The file storage stores the project in an internal data file
and this file grows whenever a project data modification
happens. In the case of DiscardRestorableData mode this
data file is reorganized (only latest version of the objects
are stored and history is removed from the file) and Inter‐
mediate data, the files of the IM directory and tmp direc‐
tory are not copied to the archive location.
• No compressed zip file is created in this mode.
Compressed • The tmp project folder structure, created by Archiving, is
compressed into a zip compatible archive. The tmp folder
structure is removed after creation of the zip file.
DiscardRestorableDataAndCompressed • In the tmp project folder structure, created by Archiving,
the restorable data is discarded and then compressed into
a zip compatible archive. The tmp folder structure is re‐
moved after creation of the zip file.

Program code: Archiving a poject


Modify the following program code to access the archive project without an extension:

var tiaPortal = new TiaPortal(TiaPortalMode.WithoutUserInterface);


var projectFilePath = @"E:\Sample1\Sample1.ap15_1";
var project = tiaPortal.Projects.Open(new FileInfo(projectFilePath));
var archiveDirectory = @"E:\Archive";
project.Archive(new DirectoryInfo(archiveDirectory), "ArchiveProjectNameWithoutExtension",
ProjectArchivationMode.Compressed);

Modify the following program code to access the archive project with an extension as '.archive':

var tiaPortal = new TiaPortal(TiaPortalMode.WithoutUserInterface);


var projectFilePath = @"E:\Sample1\Sample1.ap15_1";
var project = tiaPortal.Projects.Open(new FileInfo(projectFilePath));
var archiveDirectory = @"E:\Archive";
project.Archive(new DirectoryInfo (archiveDirectory), "ArchiveProjectName.archive",
ProjectArchivationMode.Compressed);

Openness: API for automation of engineering workflows


124 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Note
You are free to use any extension. The behavior of Archive would be same with/without
extension.

Retrieving a project
You can use the Openness API to retrieve an archived TIA Portal project. You can only retrieve a
compressed archive. For Archived project with 'ProjectArchivationMode.None' or
'ProjectArchivationMode.DiscardRestorableData' enumeration value cannot be retrieved by this
API. This API is available on the "Siemens.Engineering.ProjectComposition" object.

public Siemens.Engineering.Project Retrieve(System.IO.FileInfo sourcePath,


System.IO.DirectoryInfo targetDirectory)

For retrieving a UMAC protected project an overloaded API with the UmacDelegate is provided
for getting the credentials, then the following API definition is used

public Siemens.Engineering.Project Retrieve(System.IO.FileInfo sourcePath,


System.IO.DirectoryInfo targetDirectory, Siemens.Engineering.UmacDelegate umacDelegate)

Retrieve also supports ProjectOpenMode that can be specified as "Primary" or "Secondary", then
the following API definition is used

public Siemens.Engineering.Project Retrieve(System.IO.FileInfo sourcePath,


System.IO.DirectoryInfo targetDirectory,Siemens.Engineering.UmacDelegate umacDelegate,
Siemens.Engineering.ProjectOpenMode projectOpenMode)

Note
umacDelegate could be passed as null if the project is not protected

If the archived project is of a previous TIA Portal version then you have to call the
RetrieveWithUpgrade API, then the following API definition is used

public Siemens.Engineering.Project RetrieveWithUpgrade(System.IO.FileInfo sourcePath,


System.IO.DirectoryInfo targetDirectory);

If the archived project is of a previous TIA Portal version and UMAC protected then another
overloaded API with UmacDelegate is available, then the following API definition is used.

public Siemens.Engineering.Project RetrieveWithUpgrade(System.IO.FileInfo sourcePath,


System.IO.DirectoryInfo targetDirectory, Siemens.Engineering.UmacDelegate umacDelegate)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 125
TIA Portal Openness API
5.3 Functions for projects and project data

If the archived project is of a previous TIA portal version and project open mode also needs to be
specified, then the following API definition is used.

public Siemens.Engineering.Project RetrieveWithUpgrade(System.IO.FileInfo sourcePath,


System.IO.DirectoryInfo targetDirectory,Siemens.Engineering.UmacDelegate umacDelegate,
Siemens.Engineering.ProjectOpenMode projectOpenMode)

Note
umacDelegate could be passed as null if the project is not protected. If the project is protected
then the user credentials of an admin user is required to perform the RetrieveWithUpgrade
action

Program code: Retrieving a project


Modify the following program code to access the retrieve project:

var archivePath = @"E:\Archive\Sample1.zap15_1";


var retrievedProjectsDirectory = @"E:\RetrievedProjects";
var tiaPortal = new TiaPortal(TiaPortalMode.WithoutUserInterface);
tiaPortal.Projects.Retrieve(new FileInfo(archivePath), new
DirectoryInfo(retrievedProjectsDirectory));

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Saving a project (Page 141)

5.3.5 Accessing read-only TIA Portal project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


126 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Application
Using TIA Portal Openness, you can perform select operations while working with a read-only
TIA Portal project. You can have access to read-only project, but you will not be able to use full
set of features that are available to a user with read-write access. For example, a user with read-
only credentials can use Openness to open a UMAC protected project as described in Opening
a project (Page 113). This functionality does not include Reference projects.
The list of Openness features that are available to you while accessing a read-only project can be
categorized into two sets of features - Inherent and Enabled non-modifying actions:
Inherent functionality
• GetAttribute(s) or using the getter for any attribute on any accessible object
• GetComposition on any accessible object
• GetService on any accessible object
• Find actions on any accessible object
• Navigation on any accessible object
• Determining the existence of accessible objects and accessing those objects in compositions
and associations
• System.Object methods on any accessible object
Enabled non-modifying actions
• Project.Close (...)
• PlcBlock.ShowInEditor ()
• CaxProvider.Export (Device,...)
• CaxProvider.Export (Project,...)

See also
Opening a project (Page 113)

5.3.6 Accessing languages

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 127
TIA Portal Openness API
5.3 Functions for projects and project data

Application
In the TIA Portal you can set and manage the project language in the Editor "Project languages".
TIA Portal Openness supports the following access to the project languages:
• Iterating through supported languages.
• Searching through the collection of supported languages
by System.Globalization.CultureInfo.
• Accessing individual languages. Each Language object will contain a single read-only
attribute Culture of type System.Globalization.CultureInfo.
• Accessing a collection of active languages.
• Searchring through the collection of active languages
by System.Globalization.CultureInfo.
• Adding a language to a collection of active languages.
• Removing a language from a collection of active languages.
• Setting an editing language.
• Setting a reference language.
The functionalities are provided by the LanguageSettings object. The following figure shows
model, which is provided by TIA Portal Openness:

3URMHFW


/DQJXDJH6HWWLQJV/DQJXDJH6HWWLQJV


/DQJXDJH6HWWLQJV

/DQJXDJH6HWWLQJV

(GLWLQJ/DQJXDJH/DQJXDJH
5HIHUHQFH/DQJXDJH/DQJXDJH
$FWLYH/DQJXDJHV/DQJXDJH$VVRFLDWLRQ $FWLYH/DQJXDJHV /DQJXDJHV
/DQJXDJHV/DQJXDJH&RPSRVLWLRQ
/DQJXDJH$VVRFLDWLRQ /DQJXDJH&RPSRVLWLRQ

$GG LWHP/DQJXDJH YRLG )LQG FXOWXUH&XOWXUH,QIR /DQJXDJH


)LQG FXOWXUH&XOWXUH,QIR YRLG
(GLWLQJ/DQJXDJH 5HIHUHQFH/DQJXDJH 5HPRYH LWHP/DQJXDJH ERRO

/DQJXDJH

&XOWXUH,QIR&XOWXUHLQIR

Openness: API for automation of engineering workflows


128 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Program code: Setting languages


Modify the following program code to set a language. If you set an inactive language via TIA
Portal Openness, the language will be added to the active languages collection.

Project project = ...;

LanguageSettings languageSettings = project.LanguageSettings;

LanguageComposition supportedLanguages = languageSettings.Languages;


LanguageAssociation activeLanguages = languageSettings.ActiveLanguages;

Language supportedGermanLanguage =
supportedLanguages.Find(CultureInfo.GetCultureInfo("de-DE"));
activeLanguages.Add(supportedGermanLanguage);

languageSettings.EditingLanguage = supportedGermanLanguage;
languageSettings.ReferenceLanguage = supportedGermanLanguage;

Program code: Deactivating an active language


Modify the following program code to deactivate an active language. If you deactivate a
language which is used as reference or editing language the language selected will be
consistent with the behavior in the user interface.

Project project = ...;

LanguageSettings languageSettings = project.LanguageSettings;


LanguageAssociation activeLanguages = languageSettings.ActiveLanguages;
Language activeGermanLanguage = activeLanguages.Find(CultureInfo.GetCultureInfo("de-
DE"));
activeLanguages.Remove(activeGermanLanguage);

See also
Hierarchy of hardware objects of the object model (Page 65)

5.3.7 Determining the object structure and attributes

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 129
TIA Portal Openness API
5.3 Functions for projects and project data

Application
You can determine the navigation structure through the object hierarchy with
the IEngineeringObject interface. The result is returned as a list:
• Child objects
• Child compositions
• All attributes

Signature
Use the GetAttributeInfos method to determine attributes.
IList<EngineeringAttributeInfo>
IEngineeringObject.GetAttributeInfos();

Program code: Determining objects or compositions


Use the following program code to display alll composition names:

public static void DisplayCompositionInfos(IEngineeringObject obj)


{
IList<EngineeringCompositionInfo> compositionInfos = obj.GetCompositionInfos();
foreach (EngineeringCompositionInfo compositionInfo in compositionInfos)
{
Console.WriteLine(compositionInfo.Name);
}
}

Modify the following program code if you know the return value:

public static DeviceItemComposition GetDeviceItemComposition(Device device)


{
IEngineeringCompositionOrObject composition = ((IEngineeringObject)
device).GetComposition("DeviceItems");
DeviceItemComposition deviceItemComposition = (DeviceItemComposition)composition;
return deviceItemComposition;
}

Openness: API for automation of engineering workflows


130 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Program code: Determining attributes


Modify the following program code to return attributes of an object with specific access rights
in a list:

public static void DisplayAttributenInfos(IEngineeringObject obj)


{
IList<EngineeringAttributeInfo> attributeInfos = obj.GetAttributeInfos();
foreach (EngineeringAttributeInfo attributeInfo in attributeInfos)
{
Console.WriteLine("Attribute: {0} - AccessMode {1} ",
attributeInfo.Name, attributeInfo.AccessMode);
switch (attributeInfo.AccessMode)
{
case EngineeringAttributeAccessMode.Read: Console.WriteLine("Attribute: {0} -
Read Access", attributeInfo.Name);
break;
case EngineeringAttributeAccessMode.Write: Console.WriteLine("Attribute: {0} -
Write Access", attributeInfo.Name);
break;
case EngineeringAttributeAccessMode.Read | EngineeringAttributeAccessMode.Write:
Console.WriteLine("Attribute: {0} - Read and Write Access", attributeInfo.Name);
break;
}
}
}
public static string GetNameAttribute(IEngineeringObject obj)
{
Object nameAttribute = obj.GetAttribute("Name");
return (string)nameAttribute;
}

5.3.8 Access software target

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 131
TIA Portal Openness API
5.3 Functions for projects and project data

Programm code
Modify the following programm code to make a software target available:

SoftwareContainer softwareContainer =
((IEngineeringServiceProvider)deviceItem).GetService<SoftwareContainer>();
if (softwareContainer != null)
{
Software software = softwareContainer.Software;
}

Modify the following programm code to access the software attributes:

SoftwareContainer softwareContainer =
((IEngineeringServiceProvider)deviceItem).GetService<SoftwareContainer>();
if (softwareContainer != null)
{
PlcSoftware software = softwareContainer.Software as PlcSoftware;
string name = software.Name;
}

5.3.9 Accessing and enumerating multilingual texts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Multilingual texts in the TIA Portal are e. g. Project.Comment, PlcTag.Comment etc. In TIA Portal
Openness, the multilingual texts are represented by the MultilingualText object.
A MultilingualText object is composed of MultilingualTextItemComposition.
MultilingualTextItemComposition supports the following Find method:
• Find(<language:
Siemens.Engineering.Language>):MultilingualTextItem
Each MultilingualTextItem provides the following attributes:

Attribute name Data type Writable Description


Language Siemens.Engineering.Language r/o Language of this item.
Text System.String r/w Text provided for this language.

Openness: API for automation of engineering workflows


132 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Program code: Set multilingual text

...
Language englishLanguage = project.LanguageSettings.Languages.Find(new CultureInfo("en-
US"));
MultilingualText comment = project.Comment;
MultilingualTextItemComposition mltItemComposition = comment.Items;
MultilingualTextItem englishComment = mltItemComposition.Find(englishLanguage);
englishComment.Text = "English comment";
...

Program code: Set multilingual text for devices


Modify the following program code to set the multilingual text for devices and device items:

...
var mltObject = device.GetAttribute("CommentML");
MultilingualText multilingualText = mltObject as MultilingualText;
if (multilingualText != null)
{
Language englishLanguage = project.LanguageSettings.Languages.Find(new
CultureInfo("en-US"));
MultilingualTextItem multilingualTextItem =
multilingualText.Items.Find(englishLanguage);
if (multilingualTextItem != null)
{
multilingualTextItem.Text = comment;
}
}
...

5.3.10 Updating project property simulation support

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to update the project property "simulation support" so that
you can create plc programs that are also used in a virtual SINUMERIK controller.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 133
TIA Portal Openness API
5.3 Functions for projects and project data

The following attributes are supported by Openness to read/write the property "simulation
support" of a TIA Portal project. The API is available on the "Siemens.Engineering.Project" object.

Attribute name Data type Write Description


IsSimulationDuringBlockCompi‐ System.Boo‐ yes To indicate whether Support for Simulation during block
lationEnabled lean compilation is enabled for the project

Program code
Modify and use the following program code to read/write the attribute value:

Project project = ...;


// Read the attribute value
var attributeValue = project.IsSimulationDuringBlockCompilationEnabled;
//Write the attribute value to false
project.IsSimulationDuringBlockCompilationEnabled = false;

See also
Opening a project (Page 113)

5.3.11 Read project related attributes

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
By using this function you can get project related attributes from the TIA Portal Openness API.
The provided information contains project attributes, project history and products utilized by the
project.

Project attributes
The project attributes provide the following information:

Attribute name Data type Writeable Description


Author System.String r/o The author of the project
Comment Siemens.Engineering.MultilingualText r/o The comment of the project
Copyright System.String r/o The copyright statement of the project
CreationTime System.DateTime r/o The time when project has been created

Openness: API for automation of engineering workflows


134 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Attribute name Data type Writeable Description


Family System.String r/o The family of the project
IsModified System.Boolean r/o Returns true if the project has been modified
LanguageSettings Siemens.Engineering.LanguageSettings r/o Handles proct languages
LastModified System.DateTime r/o The time when project was last modified
LastModifiedBy System.String r/o Who made the last modification
Name System.String r/o The name of the project
Path System.IO.FileInfo r/o The absolute path of the project
Size System.Int64 r/o The size of the project in KB
Version System.String r/o The version of the project

Modify the following program code to access project related attributes:

Project project = ...;


string author = project.Author;
string name = project.Name;
string path = project.Path;
DateTime creationTime = project.CreationTime;
DateTime modificationTime = project.LastModified;
string lastModifiedBy = project.LastModifiedBy;
string version = project.Version;
MultilingualText comment = project.Comment;
string copyright = project.Copyright;
string family = project.Family;
Int64 size = project.Size;
LanguageSettings languageSettings = project.LanguageSettings;

Modify the following programm code to enumerate the project languages:

Project project = ...;


LanguageComposition languages = project.LanguageSettings.Languages;
foreach (Language language in languages)
{
CultureInfo lang = language.Culture;
}

Modify the following program code to get comment text:

Project project = ...;


Language english =
project.LanguageSettings.ActiveLanguages.Find(CultureInfo.GetCultureInfo("en-US"));

MultilingualText projectComment = project.Comment;


MultilingualTextItem textItem = project.Comment.Items.Find(english);
string text = textItem.Text;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 135
TIA Portal Openness API
5.3 Functions for projects and project data

Project history
The project history is a composition of HistoryEntry objects, which contain the following
information:

Attribute name Data type Writeable Description


Text System.String r/o The event description
DateTime System.DateTime r/o The time when the
event was occured

Modify the following program code to enumerate through HistoryEntries and access their
attributes:

Project project = ...;


HistoryEntryComposition historyEntryComposition = project.HistoryEntries;
foreach (HistoryEntry historyEntry in historyEntryComposition)
{
string entryText = historyEntry.Text;
DateTime entryTime = historyEntry.DateTime;
}

Note
The text attribute of HistoryEntry contains a string in the same language as UI. If a TIA Portal
Openness application is attached to a TIA Portal with no UI, the string is always in English

Used Products
The object UsedProduct includes the following information:

Attribute name Data type Writeable Description


Name System.String r/o The name of the prod‐
uct used
Version System.String r/o The version of the prod‐
uct

Modify the following program code to enumerate through UsedProduct and access the
attributes.

Project project = ...;


UsedProductComposition usedProductComposition = project.UsedProducts;
foreach (UsedProduct usedProduct in usedProductComposition)
{
string productName = usedProduct.Name;
string productVersion = usedProduct.Version;
}

Openness: API for automation of engineering workflows


136 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

5.3.12 Deleting project graphics

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to delete a project graphics:

//Deletes a single project graphic entry


public static void DeletesSingleProjectGraphicEntry(Project project)
{
MultiLingualGraphicComposition graphicsAggregation = project.Graphics;
MultiLingualGraphic graphic = graphicsAggregation.Find("Graphic XYZ");
graphic.Delete();
}

5.3.13 Compiling a project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• All devices are "Offline".

Application
The API interface supports the compilation of devices and program blocks. The compilation
result is returned as an object. Depending on type of the object HW or SW or HW/SW compilation
will be provided. The following object types are supported:
• Device - HW & SW
• Device with failsafe CPU - SW with switched-off F-activation property
• DeviceItem - HW
• CodeBlock - SW
• DataBlock - SW
• HmiTarget - SW

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 137
TIA Portal Openness API
5.3 Functions for projects and project data

• PlcSoftware - SW
• PlcType - SW
• PlcBlockSystemGroup - SW
• PlcBlockUserGroup - SW
• PlcTypeSystemGroup - SW
• PlcTypeUserGroup - SW

Note
Time stamp format
All time stamps are in UTC. If you want to see the local time you can use DateTime.ToLocalTime().

Note
If a password has been assigned (Page 868) to the safety program, you are required to a log on
to the safety program (Page 870) to compile software changes. Otherwise, the process is
canceled and an exception is triggered.

Signature
Use the ICompilable method for compilation.
ICompilable compileService =
iEngineeringServiceProvider.GetService<ICompilable>();
CompilerResult result = compileService.Compile();

Note
All devices must be "Offline" before you start compiling.

Program code
Modify the following program code to compile the software changes of an object of the
type HmiTarget:

public static void CompileHmiTarget(HmiTarget hmiTarget)


{
ICompilable compileService = hmiTarget.GetService<ICompilable>();
CompilerResult result = compileService.Compile();
}

Openness: API for automation of engineering workflows


138 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

Modify the following program code to compile the software changes of an object of the type
PlcSoftware:

public static void CompilePlcSoftware(PlcSoftware plcSoftware)


{
ICompilable compileService = plcSoftware.GetService<ICompilable>();
CompilerResult result = compileService.Compile();
}

Modify the following program code to compile the software changes of an object of the type
CodeBlock:

public static void CompileCodeBlock(PlcSoftware plcSoftware)


{
CodeBlock block = plcSoftware.BlockGroup.Blocks.Find("MyCodeBlock") as CodeBlock;
if (block != null)
{
ICompilable compileService = block.GetService<ICompilable>();
CompilerResult result = compileService.Compile();
}
}

Modify the following program code to evaluate the compilation result:

private void WriteCompilerResults(CompilerResult result)


{
Console.WriteLine("State:" + result.State);
Console.WriteLine("Warning Count:" + result.WarningCount);
Console.WriteLine("Error Count:" + result.ErrorCount);
RecursivelyWriteMessages(result.Messages);
}
private void RecursivelyWriteMessages(CompilerResultMessageComposition messages, string
indent = "")
{
indent += "\t";
foreach (CompilerResultMessage message in messages)
{
Console.WriteLine(indent + "Path: " + message.Path);
Console.WriteLine(indent + "DateTime: " + message.DateTime);
Console.WriteLine(indent + "State: " + message.State);
Console.WriteLine(indent + "Description: " + message.Description);
Console.WriteLine(indent + "Warning Count: " + message.WarningCount);
Console.WriteLine(indent + "Error Count: " + message.ErrorCount);
RecursivelyWriteMessages(message.Messages, indent);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 139
TIA Portal Openness API
5.3 Functions for projects and project data

5.3.14 Modifying project in UMAC

Introduction
You can use the TIA Portal Openness to modify project in user management and access right.
With this Function Right , When a project is protected, "Modify Project via Openness API" can be
assigned to a role which in turn can be assigned to user.
There are certain behavior changes in TIA Portal Openness when you are having / without
having this function right in a protected project and affected when a protect project is opened
with a particular user credentials. The changes for Openness API is applicable only on protected
project and on project which is opened with ProjectOpenMode as primary.The
ProjectOpenMode as secondary is not considered.

Changes in behaviors with function right


The below described behaviors with Openness function right is applicable for all the versions of
Siemens.Engineering.dll (V15, V15.1, V16 and V17) if it is running against TIA Portal V17.
• When you are having "Modify project via Openness API" function right along with Project
Read Write rights , you are given with full access to Openness API i.e you can perform any
operation using Openness API.
• When you are not having "Modify project via Openness API" function right along with Project
Read Write rights / Project Read rights, you are entitled to Read only operations in Openness
API. The examples of read only operations are export, navigation to a device etc. In this
scenario, if you want to do an operation like import which is a data oriented operation
( Change of project data in TIA portal) , then you would get an exception depending on the
function rights assigned to you.
• When there are user interface related Openness API's example (ShowInEditor), the user
interface related function rights does not depend on "Modify project via Openness API" , it
depends on GUI function right which should be handled by the respective GUI function right.
Below API's are the exceptions from point 1 and 2 . Openness API will bypass the Function
Right "Modify project via Openness API" and the API's are allowed irrespective of Function
Right "Modify project via Openness API" set / not set.
– project.ShowHwEditor(View.Network)
– project.ShowHwEditor(View.Topology)
– device.ShowInEditor(View.Device)
– plcBlock.ShowInEditor()
– plcType.ShowInEditor()
– plcTagTable.ShowInEditor()
– plcForceTable.ShowInEditor()
– plcWatchTable.ShowInEditor()

Openness: API for automation of engineering workflows


140 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.3 Functions for projects and project data

5.3.15 Saving a project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
To save a project
• Use the Save() method to save a project
• Use the SaveAs() method to save a project with a different name or in a different directory

Program code
Modify the following program code open and save a project:

public static void SaveProject(TiaPortal tiaPortal)


{
Project project = null;
//Use the code in the try block to open and save a project
try
{
//please adapt the path and the extension apx to the installed version of TIA Portal
project = tiaPortal.Projects.Open(new FileInfo(@"Some\Path\MyProject.apx"));
//begin of code for further implementation
//...
//end of code
project.Save();
}
//Use the code in the final block to close a project
finally
{
if (project != null)
project.Close();
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 141
TIA Portal Openness API
5.3 Functions for projects and project data

Modify the following program code save a project with a different name or in a different location:

...
TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
FileInfo fileInfoExistingProject = new FileInfo(@"D:\SampleProjects
\SampleProject.apXX");
DirectoryInfo dirInfoSaveAsProject = new DirectoryInfo(@"D:\SampleProjects
\SampleProjectSaveAs");
Project sampleProject = portal.Projects.Open(fileInfoExistingProject );
sampleProject.SaveAs(dirInfoSaveAsProject);
...

5.3.16 Closing a project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Program code
Modify the following program code to close a project:

public static void CloseProject(Project project)


{
project.Close();
}

Openness: API for automation of engineering workflows


142 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.4 Functions for Connections

5.4 Functions for Connections

5.4.1 Configurable attributes of a port-to-port connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Opening a project (Page 113)
• A project is open.
See Opening a project (Page 113)

Application
The attributes of a port interconnection are located at the port device item. The read and write
access of attributes via TIA Portal Openness is the same as at the UI.

Port interface settings


The following attributes are provided for port interface settings:

Attribute name Data type Writeable Access Description


MediumAttachmentType MediumAttachment‐ r/o Dynamic at‐ -
Type tribute
CableName CableName r/w Dynamic at‐ -
tribute
AlternativePartnerPorts Boolean r/w Dynamic at‐ Only available if toolchanger
tribute functionality is supported, e.g. at
CPU1516.
SignalDelaySelection SignalDelaySelection r/w Dynamic at‐ -
tribute
CableLength CableLength r/w Dynamic at‐ -
tribute
SignalDelayTime Double r/w Dynamic at‐ -
tribute

The following ENUM values are provided for the attribute MediumAttachmentType:

Value Description
MediumAttachmentType.None Attachment type cannot be determined.
MediumAttachmentType.Copper Attachment type is copper.
MediumAttachmentType.FibreOp Attachment type is fiber optic.
tic

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 143
TIA Portal Openness API
5.4 Functions for Connections

The following ENUM values are provided for the attribute CableName:

Value Description
CableName.None No cable name is specified
CableName.FO_Standard_Cable_9 FO standard cable GP (9 µm)
CableName.Flexible_FO_Cable_9 Flexible FO cable (9 µm)
CableName.FO_Standard_Cable_GP_50 FO standard cable GP (50 µm)
CableName.FO_Trailing_Cable_GP FO trailing cable / GP
CableName.FO_Ground_Cable FO ground cable
CableName.FO_Standard_Cable_62_5 FO standard cable (62.5 µm)
CableName.Flexible_FO_Cable_62_5 Flexible FO cable (62.5 µm)
CableName.POF_Standard_Cable_GP POF standard cable GP
CableName.POF_Trailing_Cable POF trailing cable
CableName.PCF_Standard_Cable_GP PCF standard cable GP
CableName.PCF_Trailing_Cable_GP PCF trailing cable / GP
CableName.GI_POF_Standard_Cable GI-POF standard cable
CableName.GI_POF_Trailing_Cable GI-POF trailing cable
CableName.GI_PCF_Standard_Cable GI-PCF standard cable
CableName.GI_PCF_Trailing_Cable GI-PCF trailing cable

The following ENUM values are provided for the attribute SignalDelaySelection:

Value Description
SignalDelaySelection.None -
SignalDelaySelection.CableLength CableLength is used to define the signal delay.
SignalDelaySelection.SignalDelayTime SignalDelayTime is used to define the signal delay.

The following ENUM values are provided for the attribute CableLength:

Value Description
CableLength.None Cable length is not specified.
CableLength.Length20m Cable length is 20m.
CableLength.Length50m Cable length is 50m.
CableLength.Length100m Cable length is 100m.
CableLength.Length1000m Cable length is 1000m.
CableLength.Length3000m Cable length is 3000m.

Port options
The following attributes are provided for port options:

Attribute name Data type Writea‐ Access


ble
PortActivation bool r/w Dynamic attribute
TransmissionRateAndDuplex TransmissionRateAndDuplex r/w Dynamic attribute
PortMonitoring bool r/w Dynamic attribute

Openness: API for automation of engineering workflows


144 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.4 Functions for Connections

Attribute name Data type Writea‐ Access


ble
TransmissionRateAutoNegoti bool r/w Dynamic attribute
ation
EndOfDetectionOfAccessible bool r/w Dynamic attribute
Devices
EndOfTopologyDiscovery bool r/w Dynamic attribute
EndOfSyncDomain bool r/w Dynamic attribute

The following ENUM values are provided for the attribute TransmissionRateAndDuplex:

Value Description
TransmissionRateAndDuplex.None  -
TransmissionRateAndDuplex.Automatic Automatic
TransmissionRateAndDuplex.AUI10Mbps 10 Mbps AUI
TransmissionRateAndDuplex.TP10MbpsHa TP 10 Mbps half duplex
lfDuplex
TransmissionRateAndDuplex.TP10MbpsFu TP 10 Mbps full duplex
llDuplex
TransmissionRateAndDuplex.AsyncFiber async fiber 10Mbit/s half duplex mode
10MbpsHalfDuplex
TransmissionRateAndDuplex.AsyncFiber async fiber 10Mbit/s full duplex mode
10MbpsFullDuplex
TransmissionRateAndDuplex.TP100MbpsH TP 100 Mbps half duplex
alfDuplex
TransmissionRateAndDuplex.TP100MbpsF TP 100 Mbps full duplex
ullDuplex
TransmissionRateAndDuplex.FO100MbpsF FO 100 Mbps full duplex
ullDuplex
TransmissionRateAndDuplex.X1000MbpsF X1000 Mbps full Duplex
ullDuplex
TransmissionRateAndDuplex.FO1000Mbps FO 1000 Mbps full duplex LD
FullDuplexLD
TransmissionRateAndDuplex.FO1000Mbps FO 1000 Mbps full Duplex
FullDuplex
TransmissionRateAndDuplex.TP1000Mbps TP 1000 Mbps full duplex
FullDuplex
TransmissionRateAndDuplex.FO10000Mbp FO 10000 Mbps full Duplex
sFullDuplex
TransmissionRateAndDuplex.FO100MbpsF FO 100 Mbps full duplex LD
ullDuplexLD
TransmissionRateAndDuplex.POFPCF100M POF/PCF 100 Mbps full duplex
bpsFullDuplex

See also
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 145
TIA Portal Openness API
5.5 Functions on libraries

5.5 Functions on libraries

5.5.1 Functions for objects and instances

Accessing types and instances


You can use the TIA Portal Openness API interface to access types, type versions and master
copies in the project library or global libraries. You can determine connections between type
versions and instances. You can also update instances in the project and synchronize changes
between a global library and the project library. The TIA Portal Openness API interface also
supports the comparison of types versions and instances.

Openness: API for automation of engineering workflows


146 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Functions for objects and instances


You have access to the following functions for types, type versions, master copies and instances
with the TIA Portal Openness API interface:

① Display attributes of types, type versions, master copies and instances


② The following functions are available in the project library:
• Update instances of types
• Instantiating type versions in the project
• Navigate within the library group
• Delete groups, types, type versions and master copies
③ The following functions are available in the global library:
• Update instances of types
• Instantiate type version in the project
• Navigate within the library group

5.5.2 Accessing global libraries

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 147
TIA Portal Openness API
5.5 Functions on libraries

Application
Three types of Global Libraries are existing.
• System global library (Siemens.Engineering.Library.SystemGlobalLibrary): These global
libraries are included as part of a TIA Portal installation and use the .asx file extension. All
system global libraries are read only.
• Corporate global library (Siemens.Engineering.Library.CorporateGlobalLibrary): These
global libraries have been chosen by an administrator to be preloaded when TIA Portal is
started. All corporate global libraries are read only.
• User global library (Siemens.Engineering.Library.UserGlobalLibrary): These global libraries
have been created by users of TIA Portal. User global libraries can be opened either as read
only mode or readwrite mode.
If an user global library is already openned in a certain mode then the same user global library
cannot be openned with another mode.
User global libraries from previous versions can be opened only in read only mode.

Global Libraries opened using TIA Portal Openness will also be added to the TIA Portal UI's global
library collection, and seen in the TIA Portal UI if the UI is present.

Program code: Available global libraries


Modify the following program code to get informations about all available global libraries:

TiaPortal tia = ...;


var availableLibraries = tia.GlobalLibraries.GetGlobalLibraryInfos();
foreach (GlobalLibraryInfo info in availableLibraries)
{
Console.WriteLine(" Library Name: {0}", info.Name);
Console.WriteLine(" Library Path: {0}", info.Path);
Console.WriteLine(" Library Type: {0}", info.LibraryType);
Console.WriteLine(" Library IsOpen: {0}", info.IsOpen);
}

Attributes of GlobalLibrary

Value Data type Description


Author String Author of the global library.
Comment MultilingualText Comment of the global library.
IsReadOnly Boolean True if the global library is read only.
IsModified Boolean True if the contents of the global library has been
modified.
Name String Name of the global library.
Path FileInfo Path of the global library.

Openness: API for automation of engineering workflows


148 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Attributes of GlobalLibraryInfo

Value Return Type Description


IsReadOnly Boolean True if the global library is read only.
IsOpen Boolean True if the global library is already open.
LibraryType GlobalLibraryType Type of the global library:
• System: System global library
• Corporate: Corporate global library
• User: User global library
Name String Name of the global library.
Path FileInfo Path of the global library.

See also
Accessing folders in a library (Page 158)

5.5.3 Accessing global library languages

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A library is open
See Opening libraries (Page 151)

Application
You can use language setting navigator to access and manage the Global Library languages.
TIA Portal Openness supports the following access to the global library languages:
• Iterating through supported languages.
• Searching through the collection of supported languages
by System.Globalization.CultureInfo.
• Accessing individual languages. Each Language object will contain a single read-only
attribute Culture of type System.Globalization.CultureInfo.
• Accessing a collection of active languages.
• Searching through the collection of active languages
by System.Globalization.CultureInfo.
• Adding a language to a collection of active languages.
• Removing a language from a collection of active languages.
• Setting an editing language.
• Setting a reference language.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 149
TIA Portal Openness API
5.5 Functions on libraries

Attribute of global library languages


Global library languages provides the following attribute:

Attribute name Data type Writea‐ Description


ble
LanguageSet‐ Siemens.Engineering.Lan‐ r/o Handles global library languages
tings guageSettings

Program code: Enumerating global library language


Modify the following program code to enumerate the global library language:

FileInfo m_GlobalLibrarypath = new FileInfo("bla");


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
var globalLibrary = portal.GlobalLibraries.Open(m_GlobalLibrarypath, OpenMode.ReadOnly);
LanguageSettings languageSettings = globalLibrary.LanguageSettings;

Program code: Accessing language setting


Modify the following program code to access the language setting on global library:

FileInfo m_GlobalLibrarypath = new FileInfo("bla");


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
var globalLibrary = portal.GlobalLibraries.Open(m_GlobalLibrarypath, OpenMode.ReadOnly);
LanguageComposition languages = globalLibrary.LanguageSettings.Languages;
foreach (Language language in languages)
{
// Work with this language
}

Program code: Setting global library languages


Modify the following program code to set global library languages. If you set a new supported
language through TIA Portal Openness, the language will be added to the active languages
collection.

FileInfo m_GlobalLibrarypath = new FileInfo("bla");


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
var globalLibrary = portal.GlobalLibraries.Open(m_GlobalLibrarypath, OpenMode.ReadOnly);
LanguageSettings languageSettings = globalLibrary.LanguageSettings;
LanguageComposition supportedLanguages = languageSettings.Languages;
LanguageAssociation activeLanguages = languageSettings.ActiveLanguages;
Language supportedGermanLanguage = supportedLanguages.Find(CultureInfo.GetCultureInfo("de-
DE"));
activeLanguages.Add(supportedGermanLanguage);
languageSettings.EditingLanguage = supportedGermanLanguage;
languageSettings.ReferenceLanguage = supportedGermanLanguage;

Openness: API for automation of engineering workflows


150 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Note
Adding and modifying languages in global library language setting does not modify languages
of released versions in the global library. This behaviour holds true for updating global library
languages through UI (language editor) or LanguageSettings navigator.

5.5.4 Opening libraries

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application. This requirement is
only for accessing project libraries.
See Opening a project (Page 113)

Application
A global library can be opened using System.IO.FileInfo with a path to the library file on a local
storage medium or a network storage. Only user global libraries ca be opened by path. A path
obtained from a system global library or a corporate global library can not be used to open it.
As of V14 SP1 global libraries can be opened using the GlobalLibraryInfo. The OpenMode is
specified in the GlobalLibraryInfo.
A user global library from a previous version of TIA Portal can be upgraded and opened with the
current version of TIA Portal. A global library from V13 or a previous version cannot be opened
with upgrade. These libraries have to be upgraded to V13 SP1 first.
Libraries opened using TIA Portal Openness will also be added to the global library collection in
the TIA Portal, and will be visible in the user interface of TIA Portal.

Program code: Opening a library using System.IO.FileInfo


Modify the following program code:

TiaPortal tia = ...


FileInfo fileInfo = ....

UserGlobalLibrary userLib = tia.GlobalLibraries.Open(fileInfo, OpenMode.ReadWrite);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 151
TIA Portal Openness API
5.5 Functions on libraries

Program code: Opening a library using GlobalLibraryInfo


Modify the following program code:

TiaPortal tia = ...


IList<GlobalLibraryInfo> libraryInfos = tia.GlobalLibraries.GetGlobalLibraryInfos();
GlobalLibraryInfo libInfo = ...; //check for the info you need from the list, e.g.
GlobalLibrary libraryOpenedWithInfo;
if (libInfo.Name == "myLibrary")
libraryOpenedWithInfo = tia.GlobalLibraries.Open(libInfo);

Program code: Upgrading a library


Modify the following program code:

TiaPortal tia = ...


FileInfo fileInfo = .... //library from previous TIA Portal version

UserGlobalLibrary userLib = tia.GlobalLibraries.OpenWithUpgrade(fileInfo);

OpenMode

Value Description
ReadOnly Read access to the library.
ReadWrite Read and write access to the library.

5.5.5 Enumerating open libraries

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)

Application
All opened global libraries in the TIA Portal, regardless if they have been opened via API or via
user interface can be enumerated.
Global Libraries from previous versions of TIA Portal will not be enumerated if they are opened
with write access.

Openness: API for automation of engineering workflows


152 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to enumerate open global libraries.

TiaPortal tia = ...


foreach (GlobalLibrary globLib in tia.GlobalLibraries)
{
////work with the global library
}

See also
Opening a project (Page 113)

5.5.6 Saving and closing libraries

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A library is open.
See Opening libraries (Page 151)

Application
User global libraries can be closed or saved. Any changes made to the global library will not be
saved automatically. All unsaved changes will be discarded without prompting by closing a
global library.
System global libraries and corporate global library cannot be closed or saved.
To save and close a global library:
• Use the Save ( ) method to save a user global library
• Use the SaveAs ( ) method to save a user global library in a different directory
• Use the Close ( ) method to close a user global library
Feature tokens included for SaveAs ( ) are:
• PublicAPI : Necessary for any Published feature
• DenyIfTransaction : Necessary since SaveAs should not be allowed within a transaction as it
cannot be undone.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 153
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to save a user global library:

UserGlobalLibrary userLib = ...


// save changes and close library
userLib.Save();
userLib.Close();

Modify the following program code to save a user global library in a different location:

TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);


GlobalLibraryComposition globalLibraryComposition = portal.GlobalLibraries;
//please adapt the path and the extension alx to the installed version of TIA Portal
FileInfo existingLibraryfileInfo = new FileInfo(@"D:\GlobalLibraries\MyGlobalLibrary
\MyGlobalLibrary.alx");
DirectoryInfo targetDirectoryInfo = new DirectoryInfo(@"D:\GlobalLibraries
\GlobalLibrarySaveAs");
UserGlobalLibrary userGlobalLibary =
globalLibraryComposition.Open(existingLibraryfileInfo, OpenMode.ReadWrite);
userGlobalLibary.SaveAs(targetDirectoryInfo);

Note
The persistence of the library is changed after SaveAs operation. Thus, after the SaveAs is
performed, the newly saved library is available in libraries card. However, the original library on
which SaveAs operation was performed, would not be available. The newly saved library would
have the same mode as the original library on which SaveAs was performed. This means if the
existing library was opened in ReadOnly mode, then the newly saved library in the target path
would also open in the ReadOnly mode. Similar is the case for ReadWrite mode.

Modify the following program code to close a user global library:

UserGlobalLibrary userLib = ...


// close and discard changes
userLib.Close();

Openness: API for automation of engineering workflows


154 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

5.5.7 Archiving and retrieving a library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connectng to the TIA Portal (Page 81)
• A library is open.
See Opening libraries (Page 151)
• A library is save
See Saving and closing libraries (Page 153)

Application
A opened and saved global libraries can be archived prior to any further modification to prevent
from unintended result so that you can later retrieve the archived library. You can also share the
archived file across the network easily.

Archiving a library
You can use the TIA Portal Openness API interface to archive a user global library. The API is
available on the "Siemens.Engineering.UserGlobalLibrary" object.

public void Archive(System.IO.DirectoryInfo targetDirectory, string targetName,


Siemens.Engineering.LibraryArchivationMode archivationMode)

'targetName' is the name of the file created for archived or non archived. This file may or may not
contain any file extensions. If you do not provide any extension or provide an extension apart
from "zalx" or "zal14" etc., then the archived file could not be retrieved from TIA Portal outside
the Openness API.
For LibraryArchivationMode value as Compressed and DiscardRestorableDataAndCompressed,
the archived file name is same as it is provided by you. For LibraryArchivationMode value as
None and DiscardRestorableData, the Library file extension is automatically decided by TIA
Portal Project Manager component, based on the current version of TIA Portal.

Note
You must have saved the library before calling Archive API. In case the library contains any
unsaved changes, archive would throw an EngineeringTargetInvocationException.

Library Archivation Mode

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 155
TIA Portal Openness API
5.5 Functions on libraries

The LibraryArchivationMode enumeration have four values:

LibraryArchivation‐ Description
Mode
None • No special action are taken with the orginial files. Mode is similiar to a "save as" operation.
• No compressed zip file is created in this mode.
• The difference with SaveAs in this case is that the Archive will not change the persistence location
to the new Archived folder whereas SaveAs does that.
DiscardRestorableDa‐ • The file storage stores the library in an internal data file and this file grows whenever a library data
ta modification happens. In the case of DiscardRestorableData mode this data file is reorganized (only
latest version of the objects are stored and history is removed from the file) and Intermediate data,
the files of the IM directory and tmp directory (see Library Directory structure) are not copied to the
archive location.
• No compressed zip file is created in this mode.
Compressed The tmp library folder structure, created by Archiving, is compressed into a zip compatible archive. The
tmp folder structure is removed after creation of the zip file.
DiscardRestorableDa‐ The tmp library folder structure, created by Archiving, discards the restorable data and then com‐
taAndCompressed pressed into a zip compatible archive. The tmp folder structure is removed after creation of the zip file.

Program code: Archiving a library


Modify the following program code to archive a user global library:

var tiaPortal = new TiaPortal(TiaPortalMode.WithoutUserInterface);


//Please adapt the path and the extension alx to the installed version of TIA Portal
var libraryFilePath = @"E:\Sample1\Sample1.alx";
var userGlobalLibrary = tiaPortal.GlobalLibraries.Open(new FileInfo(LibraryFilePath),
OpenMode.ReadWrite);
var archivePath = @"E:\Archive";
var archiveFileName = "SampleArchive";
userGlobalLibrary.Archive(new DirectoryInfo(archivePath), archiveFileName,
LibraryArchivationMode.Compressed);

Retrieving a library
You can use the TIA Portal Openness API interface to retrieve an archived TIA Portal library. You
can only retrieve a compressed archive. The API is available on the
"Siemens.Engineering.GlobalLibraryComposition" object.

public Siemens.Engineering.Library.UserGlobalLibrary Retrieve(System.IO.FileInfo


sourcePath, System.IO.DirectoryInfo targetDirectory, Siemens.Engineering.OpenMode openMode)

Note
You cannot retrieve an archived library with 'LibraryArchivationMode.None' or
'LibraryArchivationMode.DiscardRestorableData' enumeration value.

Openness: API for automation of engineering workflows


156 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

You can call RetrieveWithUpgrade API for the archived library of a previous TIA Portal version. The
API definition looks like the following:

public Siemens.Engineering.Library.UserGlobalLibrary
RetrieveWithUpgrade(System.IO.FileInfo sourcePath, System.IO.DirectoryInfo
targetDirectory, Siemens.Engineering.OpenMode openMode)

Open Mode
The OpenMode enumeration have two values:

OpenMode Description
ReadMode • Read access to the library. Data can be read from the library.
ReadWrite • Write access to the library. Data can be written to the library.

Program code: Retrieving a library


Modify the following program code to access to retrieve a library:

//Please adapt the path and the extension zalx to the installed version of TIA Portal
var archivePath = @"E:\Archive\Sample1.zalx";
var retrievedLibraryDirectory = @"E:\RetrievedLibraries";
var tiaPortal = new TiaPortal(TiaPortalMode.WithoutUserInterface);
tiaPortal.GlobalLibraries.Retrieve(new FileInfo(archivePath), new
DirectoryInfo(retrievedLibraryDirectory), OpenMode.ReadWrite));

See also
Opening libraries (Page 151)
Saving and closing libraries (Page 153)

5.5.8 Creating global libraries

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)

Application
Global libraries can be created via TIA Portal Openness API by calling the Create method on the
GlobalLibraryComposition. A UserGlobalLibrary will be returned

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 157
TIA Portal Openness API
5.5 Functions on libraries

GlobalLibraryComposition.Create
Modify the following program code:

TiaPortal tia= ...;


DirectoryInfo targetDirectory = new DirectoryInfo(@"D:\GlobalLibraries");
UserGlobalLibrary globalLibrary =
tia.GlobalLibraries.Create<UserGlobalLibrary>(targetDirectory, "Library1")

According to this example


• a folder "D:\GlobalLibraries\Library1" will be created
• a global library file "D:\GlobalLibraries\Library1\Library1.alXX" will be created

Parameters for creating global libraries

Parameter Data Type Type Description


Author String Mandatory Author of a global library.
Comment String Optional Comment of a global library.
Name String Optional Name of a global library
TargetDirectory DirectoryInfo Mandatory Directory that will contain global library folder.

See also
Opening a project (Page 113)

5.5.9 Accessing folders in a library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147).

Application
You can use the TIA Portal Openness API interface to access the system folders for types and
master copies in a library. You can access types, type versions, master copies and user-defined
folders within the system folder.
You can access a user-defined folder at any time using the Find method, for example
libTypeUserFolder.Folders.Find("SomeUserFolder");.

Openness: API for automation of engineering workflows


158 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Program code: Accessing system folders


Modify the following program code to access the system folder for types in a library:

public static void AccessTypeSystemFolder(ILibrary library)


{
LibraryTypeSystemFolder libTypeSystemFolder = library.TypeFolder;
}

Modify the following program code to access the system folder for master copies in a library:

public static void AccessMasterCopySystemFolder(ILibrary library)


{
MasterCopySystemFolder libMasterCopySystemFolder = library.MasterCopyFolder;
}

Program code: Accessing user-defined folders via Find() method


Modify the following program code:

...
LibraryTypeUserFolderComposition userFolderComposition = ...
LibraryTypeUserFolder userFolder = userFolderComposition.Find("Name of user folder");
...

Program code: Enumerating user defined folders


Modify the following program code to enumerate user-defined subfolders in a system folder for
types:

public static void EnumerateUserFoldersInTypeSystemFolder(ILibrary library)


{
// Enumerating user folders in type system folder:
LibraryTypeSystemFolder libTypeSystemFolder = library.TypeFolder;
foreach (LibraryTypeUserFolder libTypeUserFolder in libTypeSystemFolder.Folders)
{
//...
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 159
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to enumerate user-defined subfolders in a system folder for
master copies:

public static void EnumerateUserFoldersInMasterCopySystemFolder(ILibrary library)


{
// Enumerating user folders in master copy system folder:
MasterCopySystemFolder libMasterCopySystemFolder = library.MasterCopyFolder;
foreach (MasterCopyUserFolder libMasterCopyUserFolder in
libMasterCopySystemFolder.Folders)
{
//..
}
}

Modify the following program code to enumerate user-defined subfolders in a user-defined


folder for types:

public static void EnumerateAllUserFolders(LibraryTypeUserFolder libUserFolder)


{
foreach (LibraryTypeUserFolder libSubUserFolder in libUserFolder.Folders)
{
EnumerateAllUserFolders(libSubUserFolder);
}
}

Modify the following program code to enumerate user-defined subfolders in a user-defined


folder for master copies:

public static void EnumerateAllUserFolders(MasterCopyUserFolder libUserFolder)


{
foreach (MasterCopyUserFolder libSubUserFolder in libUserFolder.Folders)
{
EnumerateAllUserFolders(libSubUserFolder);
}
}

Program code: Creating user-defined folders


Modify the following program code to create a user-defined folder for types:

var typeFolderComposition = ProjectLibrary.TypeFolder.Folders;


var newTypeUserFolder = typeFolderComposition.Create("NewTypeUserFolder");

Modify the following program code to create a user-defined folder for master copies:

var masterCopyFolderComposition = projectProjectLibrary.MasterCopyFolder.Folders;


MasterCopyUserFolder newMasterCopyUserFolder =
masterCopyFolderComposition.Create("NewMasterCopyUserFolder);

Openness: API for automation of engineering workflows


160 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Program code: Renaming user-defined folders


Modify the following program code to create a user-defined folder for types:

var typeUserFolder =
project.ProjectLibrary.TypeFolder.Folders.Find("SampleTypeUserFolderName");
typeUserFolder.Name = "NewTypeUserFolderName";

var typeUserFolder = ProjectLibrary.TypeFolder.Folders.Find("SampleTypeUserFolderName");


typeUserFolder.SetAttributes(new[] {new KeyValuePair<string,object>("Name",
"NewTypeUserFolderName")});

Modify the following program code to create a user-defined folder for master copies:

var masterCopyUserFolder =
project.ProjectLibrary.MasterCopyFolder.Folders.Find("SampleMasterCopyUserFolderName");
masterCopyUserFolder.Name = "NewMasterCopyUserFolderName";

var masterCopyUserFolder =
ProjectLibrary.MasterCopyFolder.Folders.Find("SampleMasterCopyUserFolderName");
masterCopyUserFolder.SetAttributes(new[] {new KeyValuePair<string,object>("Name",
"NewMasterCopyUserFolderName")});

See also
Accessing master copies (Page 172)

5.5.10 Accessing types

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147).
• You have access to a group for types.
See Accessing folders in a library (Page 158).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 161
TIA Portal Openness API
5.5 Functions on libraries

Application
You can access the types contained in a library via the TIA Portal Openness API interface.
• You can enumerate the types.
• You can rename types.
• You can access the following attributes for every type:

Attribute Data type Description


Author String Returns the name of the author.
Comment MultilingualText Returns the comment.
Guid Guid Returns the GUID of the type.1
Name String Returns the name of the type. 2
1
You can find an individual type in a library using this attribute. The search is recursive.
2
You can find an individual type in a folder using this attribute. Subfolders are not included in the
search. A type name is not unique. There can be several types with the same name in different
groups. However, the type Guid is unique.

Subclasses for library type objects


With TIA Portal Openness API you can access library type objects via sub-classes. The following
subclasses are existing:
• Siemens.Engineering.Hmi.Faceplate.FaceplateLibraryType
• Siemens.Engineering.Hmi.Faceplate.FaceplateLibraryTypeVersion
• Siemens.Engineering.Hmi.RuntimeScripting.VBScriptLibraryType
• Siemens.Engineering.Hmi.RuntimeScripting.VBScriptLibraryTypeVersion
• Siemens.Engineering.Hmi.RuntimeScripting.CScriptLibraryType
• Siemens.Engineering.Hmi.RuntimeScripting.CScriptLibraryTypeVersion
• Siemens.Engineering.Hmi.Screen.ScreenLibraryType
• Siemens.Engineering.Hmi.Screen.ScreenLibraryTypeVersion
• Siemens.Engineering.Hmi.Screen.StyleLibraryType
• Siemens.Engineering.Hmi.Screen.StyleLibraryTypeVersion
• Siemens.Engineering.Hmi.Screen.StyleSheetLibraryTypeVersion
• Siemens.Engineering.Hmi.Tag.HmiUdtLibraryType
• Siemens.Engineering.Hmi.Tag.HmiUdtLibraryTypeVersion
• Siemens.Engineering.SW.Blocks.CodeBlockLibraryType
• Siemens.Engineering.SW.Blocks.CodeBlockLibraryTypeVersion
• Siemens.Engineering.SW.Types.PlcTypeLibraryType
• Siemens.Engineering.SW.Types.PlcTypeLibraryTypeVersion

Openness: API for automation of engineering workflows


162 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

The following code is an example of how to use the library type sub-classes

ProjectLibrary library = project.ProjectLibrary;


VBScriptLibraryType vbScriptType = ...;
VBScriptLibraryType libraryTypeAsVbScript = libraryType as VBScriptLibraryType;
VBScriptLibraryTypeVersion libraryTypeVersionAsVbScript = libraryTypeVersion as
VBScriptLibraryTypeVersion

Program code
Modify the following program code to enumerate all types in the system folder of a library:

public static void EnumerateTypesInTypesSystemFolder(LibraryTypeSystemFolder


libraryTypeSystemFolder)
{
foreach (LibraryType libraryType in libraryTypeSystemFolder.Types)
{
//...
}
}

Modify the following program code to enumerate all types in a user-defined folder of a library:

public static void EnumerateTypesInTypesUserFolder (LibraryTypeUserFolder


libraryTypeUserGroup)
{
foreach (LibraryType libraryType in libraryTypeUserGroup.Types)
{
//...
}
}

Modify the following program code to access the attributes of a type:

public static void InspectPropertiesOfType (LibraryType libTypeObject)


{
string typeAuthor = libTypeObject.Author;
MultilingualText typeComment = libTypeObject.Comment;
string typeName = libTypeObject.Name;
Guid typeGUID = libTypeObject.Guid;
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 163
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to find an individual type by its name or GUID:

public static void FindTypeObjectInLibrary(ILibrary library)


{
// Find type object by its GUID in a given library:
System.Guid targetGuid = ...;
LibraryType libTypeByGUID = library.FindType(targetGuid);
// Find type object by its name in a given group:
LibraryTypeFolder libTypeSystemFolder = library.TypeFolder;
LibraryType libTypeByName = libTypeSystemFolder.Types.Find("myTypeObject");
}

Modify the following program code to rename a type:

// Setting the name attribute


var type = project.ProjectLibrary.TypeFolder.Types.Find("SampleTypeName");
type.Name = "NewTypeName";

//Setting the name attribute dynamically


var type = project.ProjectLibrary.TypeFolder.Types.Find("SampleTypeName");
type.SetAttributes(new[] {new KeyValuePair<string,object>("Name", "NewTypeName")});

5.5.11 Accessing type versions

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147).
• You have access to a group for types.
See Accessing folders in a library (Page 158).

Application
You can access type versions via the TIA Portal Openness API interface.
• You can enumerate the type versions of a type.
• You can determine the type to which a type version belongs.
• You can enumerate the instances of a type version.
• You can create a new instance of a type version.
• Vou can navigate from an instance to its connected version object.
• You can access the following attributes for every type version:

Openness: API for automation of engineering workflows


164 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Attribute Data type Description


Author String Returns the name of the author.
Comment MultilingualText Returns the comment.
Guid Guid Returns the GUID of the type version.1
ModifiedDate DateTime Returns the date and time at which the type version was set
to the "Committed" status.
State LibraryTypeVersion‐ Returns the status of the version:
State • InWork: Corresponds to the status "In progress" or "In
testing" depending on the associated type.
• Committed: Corresponds to the status "Released".
TypeObject LibraryType Returns the type to which this type version belongs.
VersionNumber Version Returns the version number as a three digit version identi‐
fication, for example, "1.0.0".2
1
You can find an individual type version in a library using this attribute.
2
You can find an individual type version in a "LibraryTypeVersion" composition using this attribute.

Enumerate all type versions of a type


Modify the following program code:

//Enumerate the type versions of a type


public static void EnumerateVersionsInType(LibraryType libraryType)
{
foreach (LibraryTypeVersion libraryTypeVersion in libraryType.Versions)
{
//...
}
}

Accessing the attributes of a type version


Modify the following program code:

//Acessing the attributes of a type version


public static void InspectPropertiesOfVersion(LibraryTypeVersion libTypeVersion)
{
string versionAuthor = libTypeVersion.Author;
MultilingualText versionComment = libTypeVersion.Comment;
Guid versionGUID = libTypeVersion.Guid; DateTime versionModifiedDate =
libTypeVersion.ModifiedDate;
LibraryTypeVersionState versionStateLibrary = libTypeVersion.State;
LibraryType versionParentObject = libTypeVersion.TypeObject;
Version versionNumber = libTypeVersion.VersionNumber;
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 165
TIA Portal Openness API
5.5 Functions on libraries

Creating an instance of a type version


You can create a new instance of a type version. The following objects are supported:
• Blocks (FB/FC)
• PLC user data types
• Screens
• VB scripts
An instance can be created of a type version from global library and project library. When you
create the instance of a type version from a global library, the type version is first synchronized
with the project library.
A recoverable Exception will be thrown if an instance cannot be created in the target, then .
Possible reasons are:
• The library type version is in-work
• An instance of the library type version already exists in the target device
Modify the following program code:

VBScriptLibraryTypeVersion scriptVersion = ...;


VBScriptComposition vbscripts = ...;

//Using the CreateFrom method to create an instance of the version in the VBScripts
composition
VBScript newScript = vbscripts.CreateFrom(scriptVersion);

Modify the following program code:

ScreenLibraryTypeVersion screenVersion = ...;


ScreenComposition screens = ...;

//Using the CreateFrom method to create an instance of the version in the screens
composition
Screen newScreen = screens.CreateFrom(screenVersion);

Modify the following program code:

CodeBlockLibraryTypeVersion blockVersion = ...;


PlcBlockComposition blocks = ...;

//Using the CreateFrom method to create an instance of the version in the blocks composition
PlcBlock newBlock = blocks.CreateFrom(blockVersion);

Openness: API for automation of engineering workflows


166 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code:

PlcTypeLibraryTypeVersion plcTypVersione=...;
PlcTypeComposition types=...;

//Using the CreateFrom method to create an instance of the version in the types composition
PlcType newType = types.CreateFrom(plcTypeVersion);

Determining uses of a type version


The following uses are distinguished for type versions:
• The type version uses other type versions from the library.
Example: A user data type is used in a program block. The program block must have access
to the user data type. This means the program block depends on the user data type.
When you access the Dependencies attribute of CodeBlockLibraryVersion
through GetDependencies() method, a list of LibraryTypeVersions are returned.
• The type is being used by another type version in the library.
Example: A user data type is used in a program block. The program block must have access
to the user data type. The user data type has the associated program block. The program
block depends on the user data type.
When you access the Dependents attribute of PlcTypeLibraryTypeVersion
through GetDependents() method, a list of LibraryTypeVersions are returned.
Both attributes return a list that contains objects of the LibraryTypeVersion type. If there
are no uses, an empty list is returned.

Note
If you use these attributes on type versions with the "InWork" status, an exception can be
thrown.

Modify the following program code:

//Determine the uses of a type version in a library


public static void GetDependenciesAndDependentsOfAVersion(LibraryTypeVersion
libTypeVersion)
{
IList<LibraryTypeVersion> versionDependents = libTypeVersion.Dependents();
IList<LibraryTypeVersion> versionDependencies = libTypeVersion.Dependencies();
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 167
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to determine the type to which a type version belongs:

public static void GetParentTypeOfVersion(LibraryTypeVersion libTypeVersion)


{
LibraryType parentType = libTypeVersion.TypeObject;
}

Modify the following program code to determine the master copies that contain instances of a
type version:

public static void GetMasterCopiesContainingInstances(LibraryTypeVersion libTypeVersion)


{
MasterCopyAssociation masterCopies = libTypeVersion.MasterCopiesContainingInstances;
}

Modify the following program code to find an individual type version by its version number:

public static void FindVersionInLibrary(ILibrary library, Guid versionGUID)


{
LibraryTypeVersion libTypeVersionByVersionNumber = library.FindVersion(versionGUID);
}

5.5.12 Accessing blocks located in library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• Opening a project
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get version information from a library object without
instantiating and compiling the object.
The following new Export Action will be provided on the LibraryTypeVersion engineering object
to export the version content.
The action will create the Exported xml file at given exportFileInfo.

void Export('''FileInfo''' exportFileInfo, '''ExportOptions''' exportOptions)

Openness: API for automation of engineering workflows


168 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Exception will occur:


• In case of the user exceptions stating "The version data cannot be exported as it in in-work
state" and the version to be exported is in "in test" state
• In case of the General user DataExchange for example "FileAlreadyExists" exception stating
"The export cannot be made because the file 'D:\\*.xml' already exists".

Library Type Version enginnering Object


The following additions are made to the Library TypeVersion engineering Object:
1. Export action is provided on LibraryTypeVersion
2. Navigator to navigate to the version content browsable:
– Navigator name : ContentObject
– ReadPublicationLevel : System
– Relation name: Engineering.Library.DefaultVersionContentObject
– Base navigator will provide a default implementation to provide empty browsable
collection as version content. Client can override this navigator and provide
versioncontent.
3. "LibraryTypeName" and "LibraryTypeGuid" on LibraryTypeVersion object

Attributes ReadPublicationLevel
LibraryTypeName System
LibraryTypeGuid System

Note
This is necessary because without this info you would not be able to understand that exported
version info (in the exported xml file) belongs to which type.

Exported Content
Following content are available in the exported file:
• Library Version Info exported

Attributes SimaticMLAAccess
Author ReadWrite
Guid ReadOnly
Modified Data ReadOnly
VersionNumber ReadWrite
LibraryTypeName ReadOnly
Library TypeGuid ReadOnly

Navigators Exported:
• Comment

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 169
TIA Portal Openness API
5.5 Functions on libraries

Note
Attributes with SimaticMLAccess readonly get exported only if you choose the exportoption as
"ExportOptions.WithReadOnly".

Program code
Modify the following program code to export version content information:

Guid g = new Guid("35ad9996-d6d7-40c9-989f-0f0c7e21a7b2");


//Block1
var version = m_Project.ProjectLibrary.FindType(g).Versions[0];
version.Export(new FileInfo(@"D:\ExportCodeBlock.xml"),ExportOptions.WithReadOnly);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.5.13 Accessing instances

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147).
• You have access to a group for types.
See Accessing folders in a library (Page 158).

Application
You can access instances of type versions via the TIA Portal Openness API interface.
Use the FindInstances(IInstanceSearchScope searchScope) method to find all
instances of a type version.

Openness: API for automation of engineering workflows


170 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

You can use the searchScope parameter to specify the area of the project to be searched. The
following classes implement the IInstanceSearchScope interface and can be used to
search for instances:
• PlcSoftware
• HmiTarget
The method returns a list that contains objects of the LibraryTypeInstanceInfo type. If
there are no instances, an empty list is returned.

Note
Instances of faceplates and HMI user data types are always linked to the associated type version.
Instances of all other objects, such as program blocks or screens, can be linked to a type version.

Enumerate the instances of a type version


Modify the following program code:

//Enumerate the instances of a type version in the project


LibraryTypeVersion version = ...;
PlcSoftware plcSoftware = ...;

IInstanceSearchScope searchScope = plcSoftware as IInstanceSearchScope;

if(searchScope==null)
{
//No search possible
}

IList<LibraryTypeInstanceInfo> instanceInfos = version.FindInstances(searchScope);


IEnumerable<IEngineeringObject> instances = instanceInfos.Select(instanceInfo =>
instanceInfo.LibraryTypeInstance);

Navigate from an instance to its connected version object


Use the LibraryTypeVersion attribute of LibraryTypeInstanceInfo service to navigate from an
instance to its connected version object.
The following objects provide the LibraryTypeInstanceInfo service:
• Blocks FB
• Blocks FC
• PLC user data types
• Screens
• VB scripts

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 171
TIA Portal Openness API
5.5 Functions on libraries

If an instance object is not connected to a version object, then it will not provide the
"LibraryTypeInstanceInfo" service.

FC fc = ...;
//Using LibraryTypeInstanceInfo service

LibraryTypeInstanceInfo instanceInfo = fc.GetService<LibraryTypeInstanceInfo>();


if(instanceInfo != null)
{
LibraryTypeVersion connectedVersion = instanceInfo.LibraryTypeVersion;
FC parentFc = instanceInfo.LibraryTypeInstance as FC; //parentFc == fc
}

5.5.14 Accessing master copies

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147)
• You have access to a group for master copies.
See Accessing folders in a library (Page 158)

Application
The TIA Portal Openness API interface supports access to master copies in a global library and the
project library:
• Creating master copies
• Enumerating master copies in system folders and user-defined folders
• Renaming master copies
• Querying information from master copies
• Querying information from objects in a master copy

Attribute Data type Description


Author String Returns the name of the author.
ContentDescriptions MasterCopyContentDescrip‐ Returns a description for the content of the MasterCopy.
tionComposition
CreationDate DateTime Returns the creation date.
Name String Returns the name of the master copy.

Openness: API for automation of engineering workflows


172 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to enumerate all master copies in the system folder of a
library:

public static void EnumerateMasterCopiesInSystemFolder


(MasterCopySystemFolder masterCopySystemFolder)
{
foreach (MasterCopy masterCopy in masterCopySystemFolder.MasterCopies)
{
//...
}
}

Modify the following program code to access an individual mastercopy by using the find method:

...
MasterCopySystemFolder systemFolder = projectLibrary.MasterCopyFolder;
MasterCopyComposition mastercopies = systemFolder.MasterCopies;
MasterCopy masterCopy = mastercopies.Find("Copy of ...");
...

Modify the following program code to enumerate master copy groups and subgroups:

private static void EnumerateFolder(MasterCopyFolder folder)


{
EnumerateMasterCopies(folder.MasterCopies);
foreach (MasterCopyUserFolder subFolder in folder.Folders)
{
EnumerateFolder(subFolder); // recursion
}
}
private static void EnumerateMasterCopies(MasterCopyComposition masterCopies)
{
foreach (MasterCopy masterCopy in masterCopies)
{
...
}
}

Modify the following program code to access a MasterCopyUserFolder by using the find method:

...
MasterCopyUserFolderComposition userFolderComposition = ...
MasterCopyUserFolder userFolder = userFolderComposition.Find("Name of user folder");
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 173
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to rename a master copy:

//Setting the name attribute


var masterCopy = projectLibrary.MasterCopyFolder.MasterCopies.Find("SampleMasterCopyName");
masterCopy.Name = "NewMasterCopyName";

//Setting the name attribute dynamically


var masterCopy = projectLibrary.MasterCopyFolder.MasterCopies.Find("SampleMasterCopyName");
masterCopy.SetAttributes(new[] {new KeyValuePair<string,object>("Name",
"NewMasterCopyName")});

Querying information from master copies


Modify the following program code to get information of a master copy:

public static void GetMasterCopyInformation(MasterCopy masterCopy)


{
string author = masterCopy.Author;
DateTime creationDate = masterCopy.CreationDate;
string name = masterCopy.Name;
}

Querying information from objects in a master copy


The MasterCopy object contains a navigator called ContentDescriptions, which is a composition
of MasterCopyContentDescriptions.
A master copy may contain multiple objects. The MasterCopy object contains
ContentDescriptions for each object directly contained in the MasterCopy. If the master copy
contains a folder which also contains some items, the MasterCopy object only contains one
ContentDescription of the folder.

MasterCopy multiObjectMasterCopy = ...;

//Using ContentDescriptions
MasterCopyContentDescriptionComposition masterCopyContentDescriptions =
multiObjectMasterCopy.ContentDescriptions;
MasterCopyContentDescription contentDescription= masterCopyContentDescriptions.First();

string name = contentDescription.ContentName;


Type type = contentDescription.ContentType;

Openness: API for automation of engineering workflows


174 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

5.5.15 Create master copy from a project in library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
If the library is a read-write library, you can create a MasterCopy of an IMasterCopySource at
target location.

MasterCopy
MasterCopyComposition.Create(Siemens.Engineering.Library.MasterCopies.IMasterCopySource
sourceObject);

An EngineeringException will be thrown if:


• The target location is read-only
• Creation of the MasterCopy from the source is rejected by the system
The following items are defined as IMasterCopySources:
• Device - HW
• DeviceItem - HW
• DeviceUserGroup - HW
• CodeBlock - SW
• DataBlock - SW
• PlcBlockUserGroup - SW
• PlcTag - SW
• PlcTagTable - SW
• PlcTagTableUserGroup - SW
• PlcType - SW
• PlcTypeUserGroup - SW
• VBScript - HMI
• VBScriptUserFolder - HMI
• Screen - HMI
• ScreenTemplate - HMI
• ScreenTemplateUserFolder - HMI
• ScreenUserFolder - HMI

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 175
TIA Portal Openness API
5.5 Functions on libraries

• Tag - HMI
• TagTable - HMI
• TagUserFolder - HMI

Program code
Use the following program code:

// create a master copy from a code block in the project library


public static void Create(Project project, PlcSoftware plcSoftware)
{
MasterCopySystemFolder masterCopyFolder = project.ProjectLibrary.MasterCopyFolder;
CodeBlock block = plcSoftware.BlockGroup.Groups[0].Blocks.Find("Block_1") as CodeBlock;
MasterCopy masterCopy = masterCopyFolder.MasterCopies.Create(block);
}

5.5.16 Create an object from a master copy

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Application
The TIA Portal Openness API interface supports the use of master copies in the project. You can
create an object in the object's composition from a master copy in a project library or a global
library using the CreateFrom method.
The return type will correspond to the respective composition's return type.
The CreateFrom method only supports master copies containing single objects. If the
composition where the action is called and the source master copy are incompatible (e.g. source
master copy contains a plc tag table and the composition is a plc block composition), a
recoverable exception will be thrown.
The following compositions are supported:
• Siemens.Engineering.HW.DeviceComposition
• Siemens.Engineering.HW.DeviceItemComposition
• Siemens.Engineering.SW.Blocks.PlcBlockComposition
• Siemens.Engineering.SW.Tags.PlcTagTableComposition
• Siemens.Engineering.SW.Tags.PlcTagComposition

Openness: API for automation of engineering workflows


176 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

• Siemens.Engineering.SW.Types.PlcTypeComposition
• Siemens.Engineering.SW.TechnologicalObjects.TechnologicalInstanceDBComposition
• Siemens.Engineering.SW.Tags.PlcUserConstantComposition
• Siemens.Engineering.Hmi.Tag.TagTableComposition
• Siemens.Engineering.Hmi.Tag.TagComposition
• Siemens.Engineering.Hmi.Screen.ScreenComposition
• Siemens.Engineering.Hmi.Screen.ScreenTemplateComposition
• Siemens.Engineering.Hmi.RuntimeScripting.VBScriptComposition
• Siemens.Engineering.HW.SubnetComposition
• Siemens.Engineering.HW.DeviceUserGroupComposition
• Siemens.Engineering.SW.Blocks.PlcBlockUserGroupComposition
• Siemens.Engineering.SW.ExternalSources.PlcExternalSourceUserGroupComposition
• Siemens.Engineering.SW.Tags.PlcTagTableUserGroupComposition
• Siemens.Engineering.SW.Types.PlcTypeUserGroupComposition

Program code: Create a PLC block from a mastercopy


Modify the following program code to create an PLC block from a master copy in a library:

var plcSoftware = ...;


MasterCopy copyOfPlcBlock = ...;
PlcBlock plcSoftware.BlockGroup.Blocks.CreateFrom(copyOfPlcBlock);

Program code: Create a device from a mastercopy


Modify the following program code to create a device from a master copy in a library:

Project project = ...;


MasterCopy copyOfDevice = ...;
Device newDevice = project.Devices.CreateFrom(copyOfDevice);

Program code: Create a device item from a mastercopy


Modify the following program code to create a device item from a master copy in a library:

Device device = ...;


MasterCopy copyOfDeviceItem = ...;
DeviceItem newDeviceItem = device.DeviceItems.CreateFrom(copyOfDeviceItem);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 177
TIA Portal Openness API
5.5 Functions on libraries

Program code: Create a subnet from a mastercopy


Modify the following program code to create a subnet from a master copy in a library:

Project project = ...;


MasterCopy copyOfSubnet = ...;
Subnet newSubnet = project.Subnets.CreateFrom(copyOfSubnet);

Program code: Create a device folder from a mastercopy


Modify the following program code to create a device folder from a master copy in a library:

Project project = ...;


MasterCopy copyOfDeviceGroup = ...;
DeviceGroup newDeviceGroup= project.DeviceGroups.CreateFrom(copyOfDeviceGroup);

See also
Accessing master copies (Page 172)

5.5.17 Copying master copies

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The TIA Portal Openness API interface supports copying of master copies within a library and
between libraries using the CreateFrom action. The action will create a new object based on the
source master copy and place it in the composition where the action was called. The action will
try to create the new master copy with the same name as the source master copy. If such name
is not available, the system will give the new master copy a new name. Then, it will return the
new master copy.
If the composition where the "CreateFrom" action is called is in a read-only global library, a
recoverable exception will be thrown.

Openness: API for automation of engineering workflows


178 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code:

ProjectLibrary projectLibrary = ...;

MasterCopy copiedMasterCopy =
projectLibrary.MasterCopyFolder.MasterCopies.CreateFrom(sampleMasterCopy)

See also
Accessing master copies (Page 172)

5.5.18 Determining out-of-date type instances

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147)
• You have access to a folder for types.
See Accessing folders in a library (Page 158).

Application
The TIA Portal Openness API interface allows you to determine type versions which belong to the
instances in the open project. The TIA Portal Openness API returns one of the following two
states per instance:
• The instance refers to an out-of-date type version.
• The instance refers to the latest type version.
The following rules apply when determining the version:
• You determine the version based on a library and the project that you want to open via the
TIA Portal Openness API interface.
• Instances are not updated when you determine the version.

Signature
Use the UpdateCheck method to determine the instances of a type version:
UpdateCheck(Project project, UpdateCheckMode updateCheckMode)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 179
TIA Portal Openness API
5.5 Functions on libraries

Parameter Function
Project Specifies the project in which the type versions of instances are determined.
UpdateCheckMode Specifies the versions that are determined:
• ReportOutOfDateOnly: Returns only status of the "out of date" type.
• ReportOutOfDateAndUpToDate:
Returns status of the type "out of date" and "up to date".

Result
The devices of the project are scanned from top to bottom when determining the version. Each
device is checked to determine whether its configuration data contain an instance of a type
version from the specified library. The UpdateCheck method returns the result of the version
check in hierarchical order.
The table below shows a result of a version check with the parameter
UpdateCheck.ReportOutOfDateAndUpToDate:

Update check for: HMI_1


Update check for library element Screen_1 0.0.3
Out-of-date
\HMI_1\Screens Screen_4 0.0.1
\HMI_1\Screens Screen_2 0.0.2
Up-to-date
\HMI_1\Screens Screen_1 0.0.3
\HMI_1\Screens Screen_10 0.0.3
Update check for: HMI_2
Update check of library element Screen_4 0.0.3
Out-of-date
\Screens folder1 Screen_02 0.0.1
\Screens folder1 Screen_07 0.0.2
Up-to-date
\Screens folder1 Screen_05 0.0.3
\Screens folder1 Screen_08 0.0.3

Program code
There is no difference between project and global libraries in handling the update check.

Openness: API for automation of engineering workflows


180 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to determine the type versions from a global or project
library for instances in the project:

public static void UpdateCheckOfGlobalLibrary(Project project, ILibrary library)


{
// check for out of date instances and report only out of date instances in the returned
feedback
UpdateCheckResult result = library.UpdateCheck(project,
UpdateCheckMode.ReportOutOfDateOnly);

//Alternatively, check for out of date instances and report both out of date and up to
date instances in the returned feedback
UpdateCheckResult alternateResult = library.UpdateCheck(project,
UpdateCheckMode.ReportOutOfDateAndUpToDate);

//Show result
RecursivelyWriteMessages(result.Messages);

// Alternatively, show result and access single message parts


RecursivelyWriteMessageParts(result.Messages);
}

Modify the following program code to output the result of the version check and process the
messages individually:

private static void RecursivelyWriteMessages (UpdateCheckResultMessageComposition


messages, string indent = "")
{
indent += "\t";
foreach (UpdateCheckResultMessage message in messages)
{
Console.WriteLine(indent + message.Description);
RecursivelyWriteMessages(message.Messages, indent);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 181
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to access individual message parts in the result of the
version check:

private static void RecursivelyWriteMessageParts (UpdateCheckResultMessageComposition


messages, string indent= "")
{
indent += "\t";
foreach (UpdateCheckResultMessage message in messages)
{
Console.WriteLine(indent + "Full description: " + message.Description);
foreach (KeyValuePair<string, string> messagePart in message.MessageParts)
{
// first level
// part 1: device name
// second level:
// part 1: Name of the type in the global library
// part 2: version of the type in the global library
// third level:
// part 1: title (either "Out-of-date" or "Up-to-date");
// fourth level:
// part 1: Path hierarchy to instance
// part 2: Instance name in project
// part 3: Version of the instance in the project
Console.WriteLine(indent + "*Key: {0} Value:{1}", messagePart.Key,
messagePart.Value);
}
RecursivelyWriteMessageParts(message.Messages,indent);
}
}

5.5.19 Updating the project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147).
• You have access to a folder for types.
See Accessing folders in a library (Page 158).

Application
The TIA Portal Openness API interface allows you to update instances of a selected type within
a type folder in a project.

Openness: API for automation of engineering workflows


182 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

When updating, the instances used in the project are updated based on the last released type
version. If you start updating the instances from a global library, synchronization is performed
beforehand.

Signature
Use the UpdateProject method to update instances.
Use the following call for classes which implement the LibraryTypes interface:
void UpdateProject(IUpdateProjectScope updateProjectScope)
Use the following call for classes which implement the ILibrary interface:
void UpdateProject(IEnumerable<ILibraryTypeOrFolderSelection>
selectedTypesOrFolders, IEnumerable <IUpdateProjectScope>
updateProjectScope)
Each call is entered in the log file in the project directory.

Parameter Function
IEnumerable<ILibraryTypeOrFolderSele Specifies the folder or types to be synchronized or
ction> selectedTypesOrFolders their instances in the project to be updated.
IUpdateProjectScope Specifies the object(s) in the project in which the
updateProjectScope uses of instances are to be updated. The following
IEnumerable <IUpdateProjectScope> objects are supported:
updateProjectScope • PlcSoftware
• HmiTarget

Program code
Modify the following program code to update instances of selected types within a type folder:

private static void UpdateInstances(ILibrary myLibrary, LibraryTypeFolder


singleFolderContainingTypes, LibraryType singleType, PlcSoftware plcSoftware, HmiTarget
hmiTarget)
{
//Update Instances of multiple types (subset of types and folders)
IUpdateProjectScope[] updateProjectScopes =
{
plcSoftware as IUpdateProjectScope, hmiTarget as IUpdateProjectScope
};
myLibrary.UpdateProject(new ILibraryTypeOrFolderSelection[] {singleType,
singleFolderContainingTypes}, updateProjectScopes);
//Update Instances of multiple types (all types in library)
myLibrary.UpdateProject(new[] {myLibrary.TypeFolder}, updateProjectScopes);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 183
TIA Portal Openness API
5.5 Functions on libraries

5.5.20 Updating a library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)
• You have access to the required library.
See Accessing global libraries (Page 147).
• You have access to a folder for types.
See Accessing folders in a library (Page 158).

Application
The TIA Portal Openness API interface supports the following updates in the project library:
• Synchronize selected types between libraries.
The folder structure is not adapted when you perform synchronization. The types to be updated
are identified by their GUID and updated:
• If a type in a library includes a type version that is missing in the library to be updated, the
type version is copied.
• If a type in a library includes a type version with the different GUID, the process is aborted and
an Exception is thrown.

Signature
Use the UpdateLibrary method to synchronize type versions.
Use the following call for classes which implement the LibraryTypes interface:
void UpdateLibrary(ILibrary targetLibrary)
Use the following call for classes which implement the ILibrary interface:
void UpdateLibrary(IEnumerable<LibraryTypeOrFolderSelection>
selectedTypesOrFolders, ILibrary targetLibrary)

Parameter Function
IEnumerable<ILibraryTypeOrFolderSele Specifies the folder or types to be synchronized or
ction> selectedTypesOrFolders their instances in the project to be updated.
ILibrary targetLibrary Specifies the library whose contents will be
synchronized with a library.
If source library and destination library are identi‐
cal, an exception is thrown.

Openness: API for automation of engineering workflows


184 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to synchronize a type from the project library with a global
library:

sourceType.UpdateLibrary(projectLibrary);

Modify the following program code to synchronize selected types within a type folder between
a global library and the project library:

globalLibrary.UpdateLibrary(new[]{globalLibrary.TypeFolder}, projectLibrary);

5.5.21 Cleaning up library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness application to delete the unused versions of the specified
types in a library and/ or all the types in a specified folder in a library.
The Cleanup API is available for both project and global libraries (libraries must be read-write).
It is analogous to the Clean up Library feature present in TIA Portal user interface.
The Cleanup is handled according to the specified CleanupLibraryMode flag.
A version is cleaned up based on the specified behavior of the two CleanupLibraryModes:

CleanupLibraryMode Description
CleanupLibraryMode.AllowTypeDeletion Allow deletion of all the versions on a type to be cleaned up. If
all versions on a type have been cleaned up, the type too will
be cleaned up.
CleanupLibraryMode.PreserveHighestVersion Preserve the highest version on a type

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 185
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to invoke cleanup action for a subset of types and folders:

...
ILibrary myLibrary = ...;
CleanupLibraryMode cleanupLibraryMode = ...;
ILibraryType typeA = ...;//from myLibrary
ILibraryType typeB = ...; //from myLibrary
LibraryTypeFolder singleFolderContainingTypes = ...;//from myLibrary
myLibrary.Cleanup(new[]{typeA, singleFolderContainingTypes}, cleanupLibraryMode);
...

Modify the following program code to invoke cleanup action for all types in a library:

...
ILibrary myLibrary = ...;
CleanupLibraryMode cleanupLibraryMode = ...;
myLibrary.Cleanup(new [] {myLibrary.TypeFolder}, cleanupLibraryMode);
...

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.5.22 Harmonize project from project library

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to harmonize the names and / or paths of type instances
with the types in a specified library.
The HarmonizeProject API is available for both project and global libraries. This feature is
analogous to the Harmonize feature present in TIA Portal user interface.
You can specifiy which devices in the project to harmonize along with the choosing whether to
harmonize names, paths, or both.
If the HarmonizeProject feature is called on a global library, the project library will be first
harmonized and then the project.

Openness: API for automation of engineering workflows


186 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

The Harmonize is handled according to the chosen HarmonizeProjectOptions:

HarmonizeProjectOptions Description
HarmonizePaths Harmonize paths of the specified types or the types under the
specified folders. The instances in the project are renamed to
the type names of the library
HarmonizeProjectOptions.HarmonizeNames Harmonize names of the specified types or the types under the
specified folders. The folder structure of the library types are
applied to the project instances
HarmonizeProjectOptions.HarmonizeNames | HarmonizePro‐ Harmonize names and paths of types selected or the types
jectOptions.HarmonizePaths under a selected folder
HarmonizeProjectOptions.None This is not to be used and exception is thrown on usage

Program code
Modify the following program code to perform Harmonize names for a subset of types and
folders:

...
ILibrary myLibrary = ...;
HarmonizeProjectOptions harmonizeProjectOptions = ...;
ILibraryType typeA = ...; //from myLibrary
ILibraryType typeB = ...; //from myLibrary
LibraryTypeFolder singleFolderContainingTypes = ...; //from myLibrary
IUpdateProjectScope harmonizeProjectScope = ....... //scope of device in project to be
harmonized
myLibrary.HarmonizeProject(new[]{typeA, singleFolderContainingTypes}, new[]
{harmonizeProjectScope}, HarmonizeProjectOptions.HarmonizeNames);
...

Modify the following program code to perform Harmonize paths for a subset of types and
folders:

...
ILibrary myLibrary = ...;
HarmonizeProjectOptions harmonizeProjectOptions = ...;
ILibraryType typeA = ...; //from myLibrary
ILibraryType typeB = ...; //from myLibrary
LibraryTypeFolder singleFolderContainingTypes = ...; //from myLibrary
IUpdateProjectScope harmonizeProjectScope = ....... //scope of device in project to be
harmonized
myLibrary.HarmonizeProject(new[]{typeA, singleFolderContainingTypes}, new[]
{harmonizeProjectScope}, HarmonizeProjectOptions.HarmonizePaths);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 187
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to perform Harmonize names and paths for a subset of types
and folders:\

...
ILibrary myLibrary = ...;
HarmonizeProjectOptions harmonizeProjectOptions = ...;
ILibraryType typeA = ...; //from myLibrary
ILibraryType typeB = ...; //from myLibrary
LibraryTypeFolder singleFolderContainingTypes = ...; //from myLibrary
IUpdateProjectScope harmonizeProjectScope = ....... //scope of device in project to be
harmonized
myLibrary.HarmonizeProject(new[]{typeA, singleFolderContainingTypes}, new[]
{harmonizeProjectScope}, HarmonizeProjectOptions.HarmonizeNames |
HarmonizeProjectOptions.HarmonizePaths);
...

Exception Handling
The exception scenarios are stated below:
NULL in sourceTypesAndFolder collection:

var projectLibrary = Project.ProjectLibrary;


var type1 = projectLibrary.Types.FindType("Type1"); // if this statement yields NULL
projectLibrary.HarmonizeProject(new[]{type1}, new[] {harmonizeProjectScope},
HarmonizeProjectOptions.HarmonizeNames); // throws EngineeringTargetInvocationException

NULL sourceTypesAndFolder collection:

projectLibrary.HarmonizeProject(null, new[] { harmonizeProjectScope },


HarmonizeProjectOptions.HarmonizeNames); // throws EngineeringTargetInvocationException

Empty sourceTypesAndFolder collection

projectLibrary.HarmonizeProject(new[]{}, new[] {harmonizeProjectScope},


HarmonizeProjectOptions.HarmonizeNames); // throws EngineeringTargetInvocationException

NULL in harmonizeProjectScope collection

var projectLibrary = Project.ProjectLibrary;


var type1 = projectLibrary.Types.FindType("Type1");
projectLibrary.HarmonizeProject(new[]{type1}, new[] { null },
HarmonizeProjectOptions.HarmonizeNames); // throws EngineeringTargetInvocationException

Openness: API for automation of engineering workflows


188 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

HarmonizeProjectOptions is None

var projectLibrary = Project.ProjectLibrary;


var type1 = projectLibrary.Types.FindType("Type1");// if this statement yields NULL
projectLibrary.HarmonizeProject(new[]{type1}, new[] { harmonizeProjectScope },
HarmonizeProjectOptions.None); // throws EngineeringTargetInvocationException

sourceTypesAndFolder from different library

var type1 = projectLibrary.Types.FindType("Type1");


var type2 = globalLibrary.Types.FindType("Type2");
projectLibrary.HarmonizeProject(new[]{type1, type2}, new[] { harmonizeProjectScope },
HarmonizeProjectOptions.None); // throws EngineeringTargetInvocationException

Other cases of EngineeringTargetInvocationException are as below:


• The project is in ReadOnly state
• The Library is in ReadOnly state
• The harmonizeScope are from different Projects
• The harmonizeScope Collection is in ReadOnly state

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.5.23 Updating Structure during Library Update

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to update/retain the structure if there are conflicts and also
retain/delete unused versions from target library.
With TIA Portal Openness 17, UpdateLibrary API is introduced with the following signature on
Project Library and Global Library:
• public void UpdateLibrary(IEnumerable<ILibraryTypeOrFolderSelection>
sourceTypesAndFolders, ILibrary targetLibrary, ForceUpdateMode forceUpdateMode,
DeleteUnusedVersionsMode updateMode, StructureConflictResolutionMode
structureConflictResolutionMode);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 189
TIA Portal Openness API
5.5 Functions on libraries

Another UpdateLibrary api is introduced on Single Types with the following signature :
• public void UpdateLibrary(ILibrary targetLibrary, DeleteUnusedVersionsMode updateMode,
StructureConflictResolutionMode structureConflictResolutionMode,ForceUpdateMode
forceUpdateMode);
With this new API, You can now pass delete unused version mode, structure conflict resolution
mode and forceUpdate mode
• DeleteUnusedVersionsMode - Options used to control whether to delete/retain unused
versions from the Target library.
• StructureConflictResolutionMode - Options used to control whether to update the target
library structure, retain the existing structure or to cancel the operation if there is a structural
conflict.
• ForceUpdateMode - Options used to control whether to set the updated version on the
target library as default/latest.
UpdateLibrary is processed based on the ENUM values provided as input :
• DeleteUnusedVersionsMode.AutomaticallyDelete : Unused versions will be deleted in the
Target Library <if there are unused version in target libraries>
• DeleteUnusedVersionsMode.DoNotDelete : Unused versions will not be deleted in the
Target Library <if there are unused version in target libraries>
• StructureConflictResolutionMode.UpdateStructure : Source Library structure will be
updated in the Target Library <if there are structural differnces between source and target
libraries>
• StructureConflictResolutionMode.RetainStructure : Source Library structure will be same
in the Target Library <if there are structural differnces between source and target libraries>
• StructureConflictResolutionMode.CancelIfStructureConflicts : If a structure conflict
occurs, it throws the EngineeringTargetInvocationException and cancel the operation.
• ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault : Default version in source
library is updated to target and the updated version is marked as default version in target only
if source version number is higher than target version number
• ForceUpdateMode.ForceSetAnyUpdatedVersionAsDefault : Default version in source
library is updated to target as default/latest version, irrespective of version number.
• ForceUpdateMode.NoDefaultVersionChange : This enum value should be used during
update from project library to project where force update option is not applicable.

Program code: Single Type Update Library


The UpdateLibrary API is part of Siemens.Engineering.Library.Types.LibraryType interface and
will accept a "singleselection" of types.

Openness: API for automation of engineering workflows


190 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Modify the program code to perform update libraryUpdateLibrary for a single type from Project
Library to Global Library(delete unused version , update existing target library structure and
force update target version as default irrespective of version number):

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeUserFolder singleFolderContainingTypes =
myProjectLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1");
// block1 has lower version.
DeleteUnusedVersionsMode deleteUnusedVersionsMode =
DeleteUnusedVersionsMode.AutomaticallyDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.UpdateStructure;
ForceUpdateMode forceUpdateMode = ForceUpdateMode.ForceSetAnyUpdatedVersionAsDefault;
ILibrary globalLibrary = ...;
typeA.UpdateLibrary(globalLibrary, deleteUnusedVersionsMode,
structureConflictResolutionMode, forceUpdateMode);
...

Modify the following program code to perform UpdateLibrary for a single type from Project
Library to Global Library(do not delete unused version, retain existing target library structure
and do not perform force update):

...
ILibrary globalLibrary = ...;
LibraryTypeUserFolder singleFolderContainingTypes =
globalLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1");// block1 has lower
version.
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.RetainStructure;
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
ILibrary myProjectLibrary = Project.ProjectLibrary;
typeA.UpdateLibrary(myProjectLibrary, deleteUnusedVersionsMode,
structureConflictResolutionMode, forceUpdateMode);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 191
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to perform UpdateLibrary for a single type from Global
Library to Project Library(do not delete unused version, retain existing target library structure
and do not perform force update):

...
ILibrary globalLibrary = ...;
LibraryTypeUserFolder singleFolderContainingTypes =
globalLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1"); // block1 has lower
version.
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.RetainStructure;
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
ILibrary myProjectLibrary = Project.ProjectLibrary;
typeA.UpdateLibrary(myProjectLibrary, deleteUnusedVersionsMode,
structureConflictResolutionMode, forceUpdateMode);
...

Modify the following program code to perform UpdateLibrary for a single type from Global
Library to Project Library(delete unused version, update existing target library structure and do
not perform force update):

...
ILibrary globalLibrary = ...;
LibraryTypeUserFolder singleFolderContainingTypes =
globalLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1"); // block1 has lower
version.
DeleteUnusedVersionsMode deleteUnusedVersionsMode =
DeleteUnusedVersionsMode.AutomaticallyDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.UpdateStructure;
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
ILibrary myProjectLibrary = Project.ProjectLibrary;
typeA.UpdateLibrary(myProjectLibrary, deleteUnusedVersionsMode,
structureConflictResolutionMode);
...

Program code: Multiple Types Update Library


The UpdateLibrary API is part of Siemens.Engineering.Library.ILibrary interface and will accept
a "multiselection" of types and type folders.

Openness: API for automation of engineering workflows


192 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to perform UpdateLibrary for a single type from Project
Library to Global Library:

...ILibrary myProjectLibrary = Project.ProjectLibrary;


LibraryTypeUserFolder singleFolderContainingTypes =
myProjectLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1"); // block1 has lower
version.
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.UpdateStructure;
ILibrary globalLibrary;
myProjectLibrary.UpdateLibrary(new[] { typeA }, globalLibrary, forceUpdateMode,
deleteUnusedVersionsMode, structureConflictResolutionMode);
...

Modify the following program code to perform UpdateLibrary for multiple types from Project
Library to Global Library:

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeUserFolder singleFolderContainingTypes =
myProjectLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1"); // block1 has lower
version.
ILibraryType typeB = ...;
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode=
StructureConflictResolutionMode.UpdateStructure;
ILibrary globalLibrary;myProjectLibrary.UpdateLibrary(new[] { typeA, typeB },
globalLibrary, forceUpdateMode, deleteUnusedVersionsMode, structureConflictResolutionMode);
...

Modify the following program code to perform UpdateLibrary for a user folder containing type
from Project Library to Global Library:

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeUserFolder singleFolderContainingTypes =
myProjectLibrary.TypeFolder.Folders.Find("folder1");
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.UpdateStructure;
ILibrary globalLibrary;
myProjectLibrary.UpdateLibrary(new[]
{ (ILibraryTypeOrFolderSelection)singleFolderContainingTypes }, globalLibrary,
forceUpdateMode, deleteUnusedVersionsMode, structureConflictResolutionMode);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 193
TIA Portal Openness API
5.5 Functions on libraries

Modify the following program code to perform UpdateLibrary on "Types" system folder from
Project Library to Global Library:

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeSystemFolder typeFolder = myProjectLibrary.TypeFolder;
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.RetainStructure;
ILibrary globalLibrary;
myProjectLibrary.UpdateLibrary(new[] { (ILibraryTypeOrFolderSelection)typeFolder },
globalLibrary, forceUpdateMode, deleteUnusedVersionsMode, structureConflictResolutionMode);
...

Modify the following program code to perform UpdateLibrary for a single type from Global
Library to Project Library:

...
ILibrary globalLibrary = ...;
LibraryTypeUserFolder singleFolderContainingTypes =
globalLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1"); // block1 has lower
version.
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.UpdateStructure;
ILibrary myProjectLibrary = Project.ProjectLibrary;
globalLibrary.UpdateLibrary(new[] { typeA }, myProjectLibrary, forceUpdateMode,
deleteUnusedVersionsMode, structureConflictResolutionMode);
...

Modify the following program code to perform UpdateLibrary for a single type from Global
Library to Global Library:

...
ILibrary globalLibrarySource = ...;
LibraryTypeUserFolder singleFolderContainingTypes =
globalLibrarySource.TypeFolder.Folders.Find("folder1");
ILibraryType typeA = singleFolderContainingTypes.Types.Find("block1"); // block1 has lower
version.
ForceUpdateMode forceUpdateMode = ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault;
DeleteUnusedVersionsMode deleteUnusedVersionsMode = DeleteUnusedVersionsMode.DoNotDelete;
StructureConflictResolutionMode structureConflictResolutionMode =
StructureConflictResolutionMode.UpdateStructure;
ILibrary globalLibraryTarget = ...;
globalLibrarySource.UpdateLibrary(new[] { typeA }, globalLibraryTarget, forceUpdateMode,
deleteUnusedVersionsMode, structureConflictResolutionMode);
...

Openness: API for automation of engineering workflows


194 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Exception handling for Single Type Exception Handling


Some of the exception scenarios are stated below:
StructureConflictResolutionMode is CancelIfStructureConflicts

var myProjectLibrary = Project.ProjectLibrary;


LibraryTypeSystemFolder typeFolder =
myProjectLibrary.TypeFolder.Folders.Find("folder1"); //from myProjectLibrary
var type1 = typeFolder.Types.FindType("Type1"); // if this structure is not available in
Global Library
type1.UpdateLibrary(globalLibrary, DeleteUnusedVersionsMode.DoNotDeleteUnusedVersions,
StructureConflictResolutionMode.CancelIfStructureConflicts,
ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault); // throws
EngineeringTargetInvocationException

Target Library is NULL.

var myProjectLibrary = Project.ProjectLibrary;


var type1 = projectLibrary.Types.FindType("Type1");
ILibrary globalLibrary = Null;
type1.UpdateLibrary(globalLibrary, DeleteUnusedVersionsMode.DoNotDeleteUnusedVersions,
StructureConflictResolutionMode.RetainStructure,
ForceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault); // throws
EngineeringTargetInvocationException

Bad Enum values throws EngineeringTargetInvocationException

var myProjectLibrary = Project.ProjectLibrary;


LibraryTypeSystemFolder typeFolder = myProjectLibrary.TypeFolder.Folders.Find("folder1");//
from myProjectLibrary
var type1 = typeFolder.Types.FindType("Type1"); // if this structure is not available in
Global Library
type1 .UpdateLibrary(globalLibrary, (DeleteUnusedVersionsMode)42,
StructureConflictResolutionMode.RetainStructure, (ForceUpdateMode)22); // throws
EngineeringTargetInvocationException

Exception handling for Multiple Type Exception Handling


Some of the exception scenarios are stated below:
NULL in sourceTypesAndFolder collection

var myProjectLibrary = Project.ProjectLibrary;


var type1 = projectLibrary.Types.FindType("Type1"); // if this statement yields NULL
myProjectLibrary.UpdateLibrary(new[] { type1 }, globalLibrary,
forceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault,
DeleteUnusedVersionsMode.DoNotDeleteUnusedVersions,
StructureConflictResolutionMode.RetainStructure); // throws
EngineeringTargetInvocationException

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 195
TIA Portal Openness API
5.5 Functions on libraries

StructureConflictResolutionMode is CancelIfStructureConflicts

var myProjectLibrary = Project.ProjectLibrary;


LibraryTypeSystemFolder typeFolder =
myProjectLibrary.TypeFolder.Folders.Find("folder1"); //from myProjectLibrary
var type1 = typeFolder.Types.FindType("Type1"); // if this structure is not available in
Global Library
myProjectLibrary.UpdateLibrary(new[] { type1 }, globalLibrary,
forceUpdateMode.SetOnlyHigherUpdatedVersionAsDefault,
DeleteUnusedVersionsMode.DoNotDeleteUnusedVersions,
StructureConflictResolutionMode.CancelIfStructureConflicts); // throws
EngineeringTargetInvocationException

Bad Enum values throws EngineeringTargetInvocationException

var myProjectLibrary = Project.ProjectLibrary;


LibraryTypeSystemFolder typeFolder =
myProjectLibrary.TypeFolder.Folders.Find("folder1"); //from myProjectLibrary
var type1 = typeFolder.Types.FindType("Type1"); // if this structure is not available in
Global Library
myProjectLibrary.UpdateLibrary(new[] { type1 }, globalLibrary, (ForceUpdateMode)22,
(DeleteUnusedVersionsMode)42, StructureConflictResolutionMode.RetainStructure); // throws
EngineeringTargetInvocationException

Note
Other cases in which EngineeringTargetInvocationException is thrown are as below:
• Any Update Library operations targeting a read-only global library will result in an exception
being thrown.
• An exception will be thrown if any of the selected types or folders are null or not part of the
source library.

See also
Opening a project (Page 113)
Connecting to the TIA Portal (Page 81)

5.5.24 Deleting library content

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


196 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

• You have access to the required library.


See Accessing global libraries (Page 147).
• You have access to a folder for types.
See Accessing folders in a library (Page 158).

Application
You can delete the following project library content using the TIA Portal Openness API interface:
• Types
• Type version
• User-defined folders for types
• Master copies
• User-defined folders for master copies

Note
Deleting of types and user-defined type folders
If you want to delete a type or user-defined folder type, the "Rules for deleting versions" must be
met. You can always delete an empty type folder.

Note
Rules for deleting versions
You can only delete versions with "Committed" status. The following rules also apply when
deleting versions:
• If a new version with the "InWork" status has just been created from a version with
"Committed" status , you can only delete the version with "Committed" status when the
new version is discarded or it obtains the "Committed" status.
• If a type only has one version, the type is deleted as well.
• If Version A is dependent on Version B of another type, first delete Version A and then Version
B.
• If there are instances of Version A, you can only delete Version A if the instances are deleted
as well. If an instance is also contained in a master copy, the master copy is deleted as well.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 197
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to delete types or user-defined type folders:

public static void DeleteMultipleTypesOrTypeUserFolders(ILibrary library)


{
LibraryType t1 = library.TypeFolder.Types.Find("type1");
LibraryType t2 = library.TypeFolder.Types.Find("type2");
LibraryTypeUserFolder f1 = library.TypeFolder.Folders.Find("folder1");
t1.Delete();
t2.Delete();
f1.Delete();
}

Modify the following program code to delete an individual type or user-defined type folder:

public static void DeleteSingleTypeOrTypeUserFolder(ILibrary library)


{
//Delete a single type
LibraryType t1 = library.TypeFolder.Types.Find("type1");
t1.Delete();

//Delete a single folder


LibraryTypeFolder parentFolder = library.TypeFolder;
LibraryTypeUserFolder f1 = parentFolder.Folders.Find("folder1");
f1.Delete();
}

Modify the following program code to delete a version:

public static void DeleteVersion(ILibrary library)


{
LibraryType singleType = library.TypeFolder.Types.Find("type1");
LibraryTypeVersion version1 = singleType.Versions.Find(new System.Version(1, 0, 0));
version1.Delete();
}

Modify the following program code to delete a master copy or a user-defined master copy folder:

public static void DeleteMasterCopies(ILibrary library)


{
// Delete master copy
MasterCopy masterCopy = library.MasterCopyFolder.MasterCopies.Find("myMasterCopy");
masterCopy.Delete();

// Delete master copy user folder


MasterCopyUserFolder masterUserFolder =
library.MasterCopyFolder.Folders.Find("myFolder");
masterUserFolder.Delete();
}

Openness: API for automation of engineering workflows


198 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

See also
Accessing master copies (Page 172)

5.5.25 Setting default version of a type

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connectng to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 81)

Application
You can use the TIA Portal Openness to set any released version as default version of that type
for project library and user global library.
Default version is considered as preferred version of a type.

Program code

ILibrary myLibrary = ....;


LibraryType typeA = ...;// from myLibrary
LibraryTypeVersion versionA = ...;//from typeA
versionA.setAsDefault();/set the version as a default version of te type.

Exception Handling
An exception "EngineeringTargetInvocationException" will be thrown to you if a failure
happened during the invocation of SetAsDefault API.
You can encounter exception in the following scenarios:
• In project library, when SetAsDefault() is called on in-test/in-work version
• When Global Library is read-only

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 199
TIA Portal Openness API
5.5 Functions on libraries

5.5.26 Getting default version of a type

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connectng to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get default version of a type for project library and global
library. You can also use the TIA Portal Openness application to check if a version is default or not.
Default version is considered as preferred version of a type.

Program code

...
ILibrary myLibrary = ...;
LibraryType typeA = ...;// from myLibrary
var typeADefaultVersion = typeA.Versions.First((version) => version.IsDefault);
//from default version , user can get details related to version like Author, Guid, etc.
var nameofType = typeADefaultVersion.LibraryTypeName;
var guid = typeADefaultVersion.Guid;
var versionNumber = typeADefaultVersion.VersionNumber;
var authoroftheVersion = typeADefaultVersion.Author;
var status = typeADefaultVersion.State;
...

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.5.27 Improved types consistency state

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connectng to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


200 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Application
You can use the TIA Portal Openness to check types for a inconsistencies. Types can have
different consistency status. It is Consistent, if Dependent Type is using default version of
Dependency.Type and is Inconsistent if Dependent Type is not using the default version of
Dependency Type.
The folder level consistency Status shows if any type under the structure is Consistent or
Inconsistent.
The Status API is part of Siemens.Engineering.Library.Types.LibraryType and
Siemens.Engineering.Library.Types.LibraryTypeFolder class and will be of
ConsistencyStatustype.
To allow TIA Portal Openness user to check the consistency status of type/folders a "Status"
attribute will be introduced for the following:
• SystemFolder
• UserFolder
• Type
Using this, you can prepare the list of inconsistent types to perform special operations on them:

var listOfInconsistentTypes = Folder.Types.Where(x => x.Status ==


ConsistencyStatus.DefaultVersionInconsistent);

ConsistencyStatus enum supports below mentioned values:

Value Description
DefaultVersionInConsistent Dependent Types are not using the default version of Depend‐
ency Types
Consistent Dependent Types are using the defautt version of Dependency
Types

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 201
TIA Portal Openness API
5.5 Functions on libraries

Program code
Modify the following program code to read status attribute support on "Types" system folder
from Project Library:

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeSystemFolder typeFolder = myProjectLibrary.TypeFolder;
var systemTypeFolderConsistencyStatus = typeFolder.Status;
if(systemTypeFolderConsistencyStatus == ConsistencyStatus.DefaultVersionInConsistent)
{
//Do something.
}
// List of InConsistentType
var listOfInCosistentTypes = typeFolder.Types.Where(x => x.Status ==
ConsistencyStatus.InConsistent);
foreach(var type in listOfInCosistentTypes)
{// From type, user can get details like Author, Guid etc
var nameOfType = type.LibraryTypeName;
var guid = type.Guid;
var authorOfTheVersion = type.Author;
var status = type.State;
}
...

Modify the following program code to read Status Attribute on "User Folder" from Project Library:

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeUserFolder userFolder = myProjectLibrary.TypeFolder.Folders.Find("folder1");
var userTypeFolderConsistencyStatus = userFolder.Status;
if(userTypeFolderConsistencyStatus == ConsistencyStatus.DefaultVersionInConsistent)
{
//Do something.
}
...

Modify the following program code to read Status Attribute on "Individual Type" from Project
Library:

...
ILibrary myProjectLibrary = Project.ProjectLibrary;
LibraryTypeUserFolder userFolder = myProjectLibrary.TypeFolder.Folders.Find("folder1");
ILibraryType blockType = userFolder.Types.Find("block1");
var blockTypeConsistencyStatus = blockType.Status;
if(blockTypeConsistencyStatus == ConsistencyStatus.DefaultVersionInConsistent)
{
//Do something.
}
...

Openness: API for automation of engineering workflows


202 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.5 Functions on libraries

Note
This attribute can also be used in similar way in Global Library.

Exception Handling
An ArgumentNullException exception will be thrown to you if any of the selected types or folders
are null or not part of the source library.

var projectLibrary = Project.ProjectLibrary;


var type1 = projectLibrary.Types.FindType("Type1");
var status = typeFolder.Status; // throws ArgumentNullException

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 203
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

5.6 Functions for accessing devices, networks and connections

5.6.1 Open the "Devices & networks" editor

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can open the "Devices & networks" editor via the API interface by using one of two methods:
• ShowHwEditor(View.Topology or View.Network or View.Device): Open the
"Devices & networks" editor from the project.
• ShowInEditor(View.Topology or View.Network or View.Device) : Displays
the specified device in the "Devices & networks" editor.
Use the View parameter to define the view that is displayed when you open the editor:
• View.Topology
• View.Network
• View.Device

Program code
Modify the following program code to open the "Devices & networks" editor:

// Open topology view from project


private static void OpenEditorDevicesAndNetworksFromProject(Project project)
{
project.ShowHwEditor(Siemens.Engineering.HW.View.Topology);
}

Modify the following program code to open the "Devices & networks" editor for a device:

// Open topology view for given device


private static void OpenEditorDevicesAndNetworksFromDevice(Device device)
{
device.ShowInEditor(Siemens.Engineering.HW.View.Topology);
}

Openness: API for automation of engineering workflows


204 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

See also
Importing configuration data (Page 885)

5.6.2 Querying PLC and HMI targets

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can determine whether a software base can be used as PLC target (PlcSoftware) or HMI
target in the TIA Portal Openness API.

Program code: PLC target


Modify the following program code to determine if a device item can be used as PLC target:

// Returns PlcSoftware
private PlcSoftware GetPlcSoftware(Device device)
{
DeviceItemComposition deviceItemComposition = device.DeviceItems;
foreach (DeviceItem deviceItem in deviceItemComposition)
{
SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
if (softwareContainer != null)
{
Software softwareBase = softwareContainer.Software;
PlcSoftware plcSoftware = softwareBase as PlcSoftware;
return plcSoftware;
}
}
return null;
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 205
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

Program code: HMI target


Modify the following program code to determine if a device item can be used as HMI target:

//Checks whether a device is of type hmitarget


private HmiTarget GetHmiTarget(Device device)
{
DeviceItemComposition deviceItemComposition = device.DeviceItems;
foreach (DeviceItem deviceItem in deviceItemComposition)
{
SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
if (softwareContainer != null)
{
Software softwareBase = softwareContainer.Software;
HmiTarget hmiTarget = softwareBase as HmiTarget;
return hmiTarget;
}
}
return null;
}

See also
Enumerating devices (Page 273)

5.6.3 Accessing attributes of an address object

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• For writing access, the PLC is offline.

Application
You can use the TIA Portal Openness API interface to get or set attributes of the address object.
Further you can assign the current process image to an OB.
The following attributes can be accessed:

Attribute name Data type Writeable Access Description


IsochronousMode BOOL r/w Dynamic attribute Activate/Deactivate isochro‐
nousMode
ProcessImage Int32 r/w Dynamic attribute Set/Get process image parti‐
tion number.

Openness: API for automation of engineering workflows


206 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

Attribute name Data type Writeable Access Description


InterruptObNumber Int64 r/w Dynamic attribute Set/Get interrupt organization
block number. (classic control‐
ler only)
StartAddress Int32 r/w Modelled attribute Set/Get new StartAddress val‐
ue.

Restrictions
• Attribute StartAddress
– Setting StartAddress may implicit change the StartAddress of the opposite I0
Type at the name module. Changing of input address changes the output address.
– Writing access is not supported for all devices.
– Packed addresses are not supported in TIA Portal Openness
– Changing an address via TIA Portal Openness will not rewire the assigned tags.
• Attribute InterruptObNumber
– Only accessible in settings with S7-300 or S7-400 controllers. Writing access is supported
for S7-400 controllers.

Program code: Get or set attributes of an address object


Modify the following program code to access isochronous mode of an address object:

Address address= ...;

// read attribute
bool attributeValue = (bool)address.GetAttribute("IsochronousMode");

// write attribute
address.SetAttribute("IsochronousMode", true);

Modify the following program code to access the ProcessImage attribute of an address object:

Address address= ...;

// read attribute
int attributeValue = (int)address.GetAttribute("ProcessImage");

// write attribute
address.SetAttribute("ProcessImage", 7);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 207
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

Modify the following program code to access the InterruptObNumber attribute of an address
object:

Address address= ...;

// read attribute
long attributeValue = (long)address.GetAttribute("InterrruptObNumber");

// write attribute
address.SetAttribute("InterrruptObNumber", 42L);

//default value = 40

Modify the following program code to access the StartAddress attribute of an address object:

Address address= ...;

// read attribute
int attributeValue = (int)address.GetAttribute("StartAddress");

// write attribute
address.StartAddress = IntValueStartAddress;

Program code: Assign the current process image to an OB


Modify the following program code to assign the current process image to an OB:

OB obX =…
Address address= ...;

// assign PIP 5 to obX

address.SetAttribute("ProcessImage", 5);

try
{
address.AssignProcessImageToOrganizationBlock(obX);
} catch(RecoverableException e) {
Console.WriteLine(e.Message);
}

// remove this PIP-OB assignment

try
{
address.AssignProcessImageToOrganizationBlock(null);
} catch(RecoverableException e) {
Console.WriteLine(e.Message);
}

Openness: API for automation of engineering workflows


208 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

5.6.4 Accessing the channels of a module

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Signal Modules like analog input modules usually have multiple channels within a single
module. Usually, channels provide similar functionality multiple times, e.g. an analog input
module with four channels can measure four voltage values at the same time.
To access all channels of a module, the Channels attribute of an device item is used.

Program code: Attributes of channels


Modify the following program code to access attributes of a channel:

DeviceItem aiModule = ...


ChannelComposition channels = aiModule.Channels;
foreach (Channel channel in channels)
{
... // Work with the channel
}

Program code: Identifying attributes


Modify the following program code to get the identifying attribute for each channel:

Channel channel = ...


int channelNumber = channel.Number;
ChannelType type = channel.Type;
ChannelIoType ioType = channel.IoType;

Program code: Accessing a single channel


Modify the following program code to use the identifying attributes to access a channel directly:

DeviceItem aiModule = ...


Channel channel = aiModule.Channels.Find(ChannelType.Analog, ChannelIoType.Input, 0);
... // Work with the channel

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 209
TIA Portal Openness API
5.6 Functions for accessing devices, networks and connections

Channel types

Value Description
ChannelType.None The channel type invalid.
ChannelType.Analog The channel type is analog.
ChannelType.Digital The channel type is digital.
ChannelType.Technology The channel type is technology.

Channel IO types

Value Description
ChannelIOType.None The channel IO type invalid.
ChannelIOType.Input An input channel.
ChannelIOType.Output An output channel.
ChannelIOType.Complex Complex IO types, e.g. for technological channels.

Openness: API for automation of engineering workflows


210 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

5.7 Functions on networks

5.7.1 Creating a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Subnets can be created in two different ways:
• Create a subnet that is connected to an interface: The type of the interface, where the subnet
is created, determines the type of the subnet
• Create a subnet not connected to an interface.

Program code: Create a subnet connected to a node


Modify the following program code to create a subnet:

Node node = ...;


Subnet subnet = node.CreateAndConnectToSubnet("NameOfSubnet");

The following type identifiers are used:


• System:Subnet.Ethernet
• System:Subnet.Profibus
• System:Subnet.Mpi
• System:Subnet.Asi

Program code: Create a subnet not connected to an interface


Modify the following program code to create a subnet:

Project project = ...;


SubnetComposition subnets = project.Subnets;

Subnet newSubnet = subnets.Create("System:Subnet.Ethernet", "NewSubnet");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 211
TIA Portal Openness API
5.7 Functions on networks

The following type identifiers can be used:


• System:Subnet.Ethernet
• System:Subnet.Profibus
• System:Subnet.Mpi
• System:Subnet.Asi

5.7.2 Accessing subnets

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
For several network related features, e.g. assigning interfaces to a subnet, you have to access
subnets in the project. Typically, subnets are aggregated directly on project level.

Program code: Access all subnets of a project


Modify the following program code to access all subnets excluding internal subnets of a project:

Project project = ...


foreach (Subnet net in project.Subnets)
{
... // Work with the subnet
}

Program code: Access a specific subnet


Modify the following program code to access a specific subnet by it's name:

Project project = ...


Subnet net = project.Subnets.Find("PROFIBUS_1");
{
... // Work with the subnet
}

Openness: API for automation of engineering workflows


212 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attributes of a subnet
A subnet has the following attributes:

Subnet net = ...;


string name = net.Name;
NetType type = net.NetType;

Network types

Value Description
NetType.Unknown The type of the network is unknown.
NetType.Ethernet The type of the network is Ethernet.
NetType.Profibus The type of the network is Profibus.
NetType.Mpi The type of the network is MPI.
NetType.ProfibusIntegrated The type of the network is integrated Profibus.
NetType.Asi The type of the network is ASi.
NetType.PcInternal The type of the network is PC internal.
NetType.Ptp The type of the network is PtP.
NetType.Link The type of the network is Link.
NetType.Wan The type of the network is Wide Area Network

5.7.3 Accessing internal subnets

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
If a device item is able to compose a subnet, it provides the additional functionality "subnet
owner". To access this additional functionality, a specific service of the device item must be used.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 213
TIA Portal Openness API
5.7 Functions on networks

Program code: Get the subnet owner role


Modify the following program code to get the subnet owner role:

SubnetOwner subnetOwner =
((IEngineeringServiceProvider)deviceItem).GetService<SubnetOwner>();
if (subnetOwner != null)
{
// work with the role
}

Program code: Attributes of a subnet owner


Modify the following program code to access the subnets of a subnet owner:

foreach(Subnet subnet in subnetOwner.Subnets)


{
Subnet interalSubnet = subnet;
}

5.7.4 Get type identifier of subnets

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The attribute TypeIdentifier is used to identify a subnet. The TypeIdentifier is a string
consisting of several parts: <TypeIdentifierType>:<SystemIdentifier>
Possible values for TypeIdentifierType are:
• System

SystemIdentifier

Subnet type SystemIdentifier


PROFIBUS Subnet.Profibus
MPI Subnet.Mpi
Industrial Ethernet Subnet.Ethernet
ASI Subnet.Asi
Ptp Subnet.Ptp

Openness: API for automation of engineering workflows


214 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Subnet type SystemIdentifier


PROFIBUS-Integrated null
PC-Internal null

Program code
Modify the following program code to get the type identifier for user manageable and separately
creatable objects for GSD:

Subnet subnet = ...;


string typeIdentifier = subnet.TypeIdentifier;

5.7.5 Accessing attributes of a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A subnet provides certain mandatory attributes that can be read and/or written. The attributes
are only available, if they are available at the UI. Writing is generally only allowed if an attribute
can also be changed by the user at the UI. This might vary depending on the type of the subnet.
For example, the user can only set the DpCycleTime, if the IsochronousMode is true and the
DpCycleMinTimeAutoCalculation is false

Attributes of subnets of type ASI

Attribute Data type Writa‐ Access Description


ble
Name string r/w mod‐ Name of the subnet.
eled
NetType NetType r mod‐ Type of the subnet
eled
SubnetId string r dynam‐ Unique identification of the subnet. The S7 subnet ID is
ic made up of two numbers separated by a hyphen. One
number for the project and one for the subnet. e.g.
4493-1.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 215
TIA Portal Openness API
5.7 Functions on networks

Attributes of subnets of type Ethernet

Attribute Data type Writa‐ Access Description


ble
Name string r/w mod‐ Name of the subnet.
eled
NetType NetType r mod‐ Type of the subnet
eled
SubnetId string r/w dynam‐ Unique identification of the subnet. The S7 subnet ID is
ic made up of two numbers separated by a hyphen. One
number for the project and one for the subnet. e.g.
4493-1.
DefaultSubnet bool r/w dynam‐ true if the subnet is a default subnet. There is at most one
ic default subnet in a project.

Attributes of subnets of type MPI

Attribute Data type Writa‐ Access Description


ble
Name string r/w mod‐ Name of the subnet.
eled
NetType NetType r mod‐ Type of the subnet
eled
SubnetId string r/w dynam‐ Unique identification of the subnet. The S7 subnet ID is
ic made up of two numbers separated by a hyphen. One
number for the project and one for the subnet. e.g.
4493-1.
HighestAddress int r/w dynam‐ Highest MPI address at subnet.
ic
TransmissionSpeed BaudRate r/w dynam‐ True if the subnet is a default subnet. There is at most
ic one default subnet in a project.

Attributes of subnets of type PC internal

Attribute Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the subnet.
eled
NetType NetType r mod‐ Type of the subnet
eled
SubnetId string r dynam‐ Unique identification of the subnet. The S7 subnet ID is
ic made up of two numbers separated by a hyphen. One
number for the project and one for the subnet. e.g.
4493-1.

Openness: API for automation of engineering workflows


216 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attributes of subnets of type PROFIBUS

Attribute Data type Writa‐ Access Description


ble
Name string r/w mod‐ Name of the subnet.
eled
NetType NetType r model‐ Type of the subnet
led
SubnetId string r/w dynam‐ Unique identification of the subnet. The S7 sub‐
ic net ID is made up of two numbers separated by a
hyphen. One number for the project and one for
the subnet. e.g. 4493-1.
HighestAddress int r/w dynam‐ Highest PROFIBUS address at subnet.
ic
TransmissionSpeed BaudRate r/w dynam‐ True if the subnet is a default subnet. There is at
ic most one default subnet in a project.
BusProfile BusProfile r/w dynam‐ The PROFIBUS profile.
ic
PbCableConfiguration bool r/w dynam‐ True to enable additional PROFIBUS network set‐
ic tings
PbRepeaterCount int r/w dynam‐ Number of repeaters for copper cable
ic
PbCopperCableLength double r/w dynam‐ The length of the copper cable
ic
PbOpticalComponentCount int r/w dynam‐ Number of OLMs and OBTs of fiber-optical cable.
ic
PbOpticalCableLength double r/w dynam‐ The length of the fiber-optical cable for the PRO‐
ic FIBUS network in km.
PbOpticalRing bool r/w dynam‐ True if bus parameter are adapted for an optical
ic ring
PbOlmP12 bool r/w dynam‐ True if OLM/P12 is enabled for bus parameter cal‐
ic culation
PbOlmG12 bool r/w dynam‐ True if OLM/G12 is enabled for bus parameter
ic calculation
PbOlmG12Eec bool r/w dynam‐ True if OLM/G12-EEC is enabled for bus parame‐
ic ter calculation
PbOlmG121300 bool r/w dynam‐ True if OLM/G12-1300 is enabled for bus param‐
ic eter calculation
PbAdditionalNetworkDevices bool r/w dynam‐ True if additional bus devices that don't exist in
ic project will be taken in to account when calculat‐
ing bus times.
PbAdditionalDpMaster int r/w dynam‐ Number of unconfigured DP masters.
ic
PbTotalDpMaster int r dynam‐ Number of total DP masters
ic
PbAdditionalPassiveDevice int r/w dynam‐ Number of unconfigured DP slaves or passive de‐
ic vices.
PbTotalPassiveDevice int r dynam‐ Number of total DP slaves or passive devices.
ic

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 217
TIA Portal Openness API
5.7 Functions on networks

Attribute Data type Writa‐ Access Description


ble
PbAdditionalActiveDevice int r/w dynam‐ Number of unconfigured active devices with FDL/
ic FMS/S/ communication load.
PbTotalActiveDevice int r dynam‐ Number of total active devices with FDL/FMS/S/
ic communication load.
PbAdditionalCommunicationLoad Communica‐ r/w dynam‐ Rough quantification of the communication load
tionLoad ic
PbDirectDateExchange bool r/w dynam‐ Optimization for direct data exchange.
ic
PbMinimizeTslotForSlaveFailure bool r/w dynam‐ Minimization for time allocation for slave failure.
ic
PbOptimizeCableConfiguration bool r/w dynam‐ Optimiazation of the cable configuration.
ic
PbCyclicDistribution bool r/w dynam‐ True if enable cyclic distribution of bus parameter.
ic
PbTslotInit int r/w dynam‐ Default value of Tslot.
ic
PbTslot int r dynam‐ Waiting to receive time (slot time)
ic
PbMinTsdr int r/w dynam‐ Minimum protocol processing time
ic
PbMaxTsdr int r/w dynam‐ Maximum protocol processing time
ic
PbTid1 int r dynam‐ Idle time 1
ic
PbTid2 int r dynam‐ Idle time 2
ic
PbTrdy int r dynam‐ Ready time
ic
PbTset int r/w dynam‐ Setup time
ic
PbTqui int r/w dynam‐ Quiet time for modulator
ic
PbTtr int64 r/w dynam‐ The Ttr value in t_Bit
ic
PbTtrTypical int64 r dynam‐ Average response time on bus
ic
PbWatchdog int64 r/w dynam‐ Watchdog
ic
PbGapFactor int r/w dynam‐ Gab update factor
ic
PbRetryLimit int r/w dynam‐ Maximum number of retries
ic
IsochronousMode bool r/w dynam‐ True if constant bus cycle time is enabled.
ic
PbAdditionalPassivDeviceForIsochro‐ int r/w dynam‐ Number of additional OPs/PGs/TDs etc. that are
nousMode ic not configured in this network view.

Openness: API for automation of engineering workflows


218 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attribute Data type Writa‐ Access Description


ble
PbTotalPassivDeviceForIsochronous‐ int r dynam‐ Sum of configured and unconfigured devices,
Mode ic such as OPs/PGs/TDs etc.
DpCycleMinTimeAutoCalculation bool r/w dynam‐ True if automatic calculation and setting of short‐
ic est DP cycle time is enabled.
DpCycleTime double r/w dynam‐ The DP cycle time.
ic
IsochronousTiToAutoCalculation bool r/w dynam‐ True if automatic calculation and setting of val‐
ic ues of IsochronousTi and IsochronousTo.
IsochronousTi double r/w dynam‐ Time Ti (read in process values)
ic
IsochronousTo double r/w dynam‐ Time To (output process values)
ic

Attributes of subnets of type PROFIBUS Integrated

Attribute Data type Writa‐ Access Description


ble
Name string r/w mod‐ Name of the subnet.
eled
NetType NetType r mod‐ Type of the subnet
eled
SubnetId string r/w dynam‐ Unique identification of the subnet. The S7 subnet ID is
ic made up of two numbers separated by a hyphen. One
number for the project and one for the subnet. e.g.
4493-1.
IsochronousMode bool r dynam‐ Enabled constant bus cycle time.
ic
DpCycleMinTimeAutoCalcu‐ bool r/w dynam‐ True if automatic calculation and setting of shortest DP
lation ic cycle time is enabled.
DpCycleTime double r/w dynam‐ The DP cycle time.
ic
IsochronousTiToAutoCalcu‐ bool r/w dynam‐ True if automatic calculation and setting of values of
lation ic IsochronousTi and IsochronousTo.
IsochronousTi double r/w dynam‐ Time Ti (read in process values)
ic
IsochronousTo double r/w dynam‐ Time To (output process values)
ic

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 219
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code to get or set the attributes of a subnet:

Subnet subnet = ...;

string nameValue = subnet.Name;


NetType nodeType = (NetType)subnet.NetType;
string subnetId = ((IEngineeringObject)subnet).GetAttribute("SubnetId");

subnet.Name = "NewName";
subnet.SetAttribute("Name", "NewName");

bool isDefaultSubnet = ((IEngineeringObject)subnet).GetAttribute("DefaultSubnet");

Baud rates

Value Description
BaudRate.None The baud rate is unknown.
BaudRate.Baud9600 9.6 kBaud
BaudRate.Baud19200 19.2 kBaud
BaudRate.Baud45450 45.45 kBaud
BaudRate.Baud93700 93.75 kBaud
BaudRate.Baud187500 187.5 kBaud
BaudRate.Baud500000 500 kBaud
BaudRate.Baud1500000 1.5 MBaud
BaudRate.Baud3000000 3 MBaud
BaudRate.Baud6000000 6 MBaud
BaudRate.Baud12000000 12 MBaud

Bus profiles

Value Description
BusProfile.None The bus profile is unknown.
BusProfile.DP The type of the network is DP.
BusProfile.Standard The type of the network is Standard.
BusProfile.Universal The type of the network is Universal.
BusProfile.UserDefined The type of the network is user defined.

Communication load

Value Description
CommunicationLoad.None No valid communication load.
CommunicationLoad.Low Typically used for DP, no great data communication apart from
DP.

Openness: API for automation of engineering workflows


220 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Value Description
CommunicationLoad.Medium Typically used for mixed operations featuring DP and other
communication services, such as for S7 communication, when
DP has strict time requirements and for average acyclic volumes
of communication.
CommunicationLoad.High For mixed operations featuring DP and other communication
services, such as for S7 communication, when DP has loose
time requirements and for high acyclic volumes of communi‐
cation.

5.7.6 Deleting a global subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to delete a a global subnet within a project.:

Project project = ...;


SubnetComposition subnets = projects.Subnets;

// delete subnet
Subnet subnetToDelete = ...;
subnetToDelete.Delete();

5.7.7 Enumerate all participants of a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Enumeration of all participants on a subnet.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 221
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code to enumerate dp master systems from subnet:

Subnet subnet = ...;


foreach (Node node in subnet.Nodes)
{
// work with the node
}

5.7.8 Enumerate IO systems of a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Enumeration of IoSystem provides all io systems that are present on a subnet. The class IoSystem
represents the master systems and the io systems.

Program code
Modify the following program code to enumerate dp master systems from subnet:

Subnet subnet = ...;


foreach (IoSystem ioSystem in subnet.IoSystems)
{
// work with the io system
}

5.7.9 Accessing nodes

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


222 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Application
The role interface aggregates nodes to access attributes that are related to the address and
subnet assignment of an interface.
The name of a node can be seen in the attributes of an interface in TIA Portal . The NodeId is a
unique identifier for every node aggregated at an interface, its value can only be seen via TIA
Portal Openness.

Program code
Modify the following program code to access all nodes of an interface:

NetworkInterface itf = ...


foreach (Node node in itf.Nodes)
{
... // Work with the node
}

Most interfaces provide only a single node, therefore, usually the first node is used:

NetworkInterface itf = ...


Node node = itf.Nodes.First();
{
... // Work with the node
}

Nodes provide their names and types and NodeIds as attributes:

Node node = ...


string name = node.Name;
NetType type = node.NodeType;
string id = node.NodeId;

5.7.10 Accessing attributes of a node

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 223
TIA Portal Openness API
5.7 Functions on networks

Application
A device item provides certain mandatory attributes that can be read and/or written. The
attributes are only available if they are available at the UI. Writing is generally only allowed if an
attribute can also be changed by the user at the UI. This might vary depending on the type of the
device item. For example, the user can only set the RouterAddress if the RouterUsed is true. If the
user changes the SubnetMask at IO controller, Subentmask on all IO devices will be also changed
to the same value.

Attributes of a node of type ASI

Attributes Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the node.
eled
NodeId string r mod‐ ID of the node.
eled
NodeType NetType r mod‐ A node gets his type from the subnet.
eled
Address string r/w dynam‐ Additional attribute for AS-i slaves.
ic

Attributes of a node of type Ethernet

Attributes Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the node.
eled
NodeId string r mod‐ ID of the node.
eled
NodeType NetType r/w mod‐ A node gets his type from the subnet.
some‐ eled
times
r/o
UseIsoProtocol bool r/w dynam‐ True, if ISO protocol should be used
ic
MacAddress string r/w dynam‐ e.g. 01-80-C2-00-00-00
ic
UseIpProtocol bool r/w dynam‐ This value can be read even if it noct visible at the cor‐
ic responding TIA UI control.
IpProtocolSelection enum r/w dynam‐ -
ic
Address string r/w dynam‐ only IPv4 and no IPv6 is supported
ic
SubnetMask string r/w dynam‐ -
ic
UseRouter bool r/w dynam‐ -
ic

Openness: API for automation of engineering workflows


224 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attributes Data type Writa‐ Access Description


ble
RouterAddress string r/w dynam‐ -
ic
DhcpClientId string r/w dynam‐ -
ic
PnDeviceNameSetDirectly bool r/w dynam‐ PROFINET device name is set directly at the device. Not
ic available for every device.
PnDeviceNameAutoGenera‐ bool r/w dynam‐ PROFINET device name is created automatically.
tion ic
PnDeviceName string r/w dynam‐ Unique device name in subnet.
ic
PnDeviceNameConverted string r dynam‐ Device name converted for system internal using.
ic

Attributs of a node of type MPI

Attribut Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the node.
eled
NodeId string r mod‐ ID of the node.
eled
NodeType NetType r mod‐ A node gets his type from the subnet.
eled
Address string r/w dynam‐ -
ic

Attributs of a node of type PC internal

Attribut Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the node.
eled
NodeId string r mod‐ ID of the node.
eled
NodeType NetType r mod‐ A node gets his type from the subnet.
eled

Attributs of a node of type PROFIBUS

Attribut Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the node.
eled
NodeId string r mod‐ ID of the node.
eled

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 225
TIA Portal Openness API
5.7 Functions on networks

Attribut Data type Writa‐ Access Description


ble
NodeType NetType r mod‐ A node gets his type from the subnet.
eled
Address string r/w dynam‐ The network address of the node. The type of address
ic depends on the node type (e.g. IP address for PROFINET
nodes, PROFIBUS address for PROFIBUS nodes)

Attributs of a node of type PROFIBUS integrated

Attribut Data type Writa‐ Access Description


ble
Name string r mod‐ Name of the node.
eled
NodeId string r mod‐ ID of the node.
eled
NodeType NetType r mod‐ A node gets his type from the subnet.
eled
Address string r dynam‐ -
ic

Program code: Attributes of a node


Modify the following program code to get or set the attributes of a node:

Node node = ...;


string nameValue = node.Name;
NetType nodeType = (NetType)node.NodeType;
node.NodeType = NetType.Mpi;

Program code: Dynamic attributes


Modify the following program code to get or set dynamic node attributes:

Node node = ...;


var attributeNames = new[]
{
"Address", "SubnetMask", "RouterAddress", "UseRouter", "DhcpClientId",
"IpProtocolSelection"
};
foreach (var attributeName in attributeNames)
{
object attributeValue = ((IEngineeringObject)node).GetAttribute(attributeName);
}

Openness: API for automation of engineering workflows


226 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Protocol selection

Value Description
IpProtocolSelection.None Error value
IpProtocolSelection.Project IP suite configured within project.
IpProtocolSelection.Dhcp IP suite managed via DHCP protocol. DHCP Client ID necessary.
IpProtocolSelection.UserProgram IP suite set via FB (function block).
IpProtocolSelection.OtherPath IP suite set via other methods, for example PST tool.
IpProtocolSelection.ViaIoController IP suite set via IO Controller in runtime.

Net type

Value Description
NetType.Asi Net type is ASI.
NetType.Ethernet Net type is Ethernet.
NetType.Link Net type is Link.
NetType.Mpi Net type is MPI.
NetType.PcInternal Net type is PC internal.
NetType.Profibus Net type is PROFIBUS.
NetType.ProfibusIntegrated Net type is PROFIBUS integrated.
NetType.Ptp Net type is PTP.
NetType.Wan Net type is Wide Area Network (WAN).
NetType.Unknown Net type is Unknow.

5.7.11 Connecting a node to a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to assign a node (device, interface) to a network:

Node node = ...;


Subnet subnet = ...;
node.ConnectToSubnet(subnet);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 227
TIA Portal Openness API
5.7 Functions on networks

5.7.12 Disconnect a node from a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to disconnect a node (device, interface) from a network:

Node node = ...;


node.DisconnectFromSubnet();

5.7.13 Creating an IO system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
An io system is created by calling the action IoController.CreateIoSystem("name") on an object
of the type IoController. In case name is null or String.Empty the default name will be used. The
io controller is aquired by accessing the attribute IoControllers object on the NetworkInterface.
The IoControllers navigator returns one IoController object.
Prerequisites for creating an io system:
• The interface of the io controller is connected to a subnet.
• The io controller has no io system.

Openness: API for automation of engineering workflows


228 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code to create an io system:

using System.Linq;
...

NetworkInterface interface = ...;


IoSystem ioSystem = null;

// Interface is configured as io controller


if((interface.InterfaceOperatingMode & InterfaceOperatingModes.IoController) != 0)
{
IoControllerComposition ioControllers = interface.IoControllers;
IoController ioController = ioControllers.First();
if(ioController != null)
{
ioSystem = ioController.CreateIoSystem("io system");
}
}

5.7.14 Accessing the attributes of an IO system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The master system and the io system will both be represented by the class IoSystem.

Program code: Attributes of an io system


Modify the following program code to get the attributes of the IoSystem:

NetworkInterface itf = ...


foreach (IIoController ioController in itf.IoControllers)
{
IoSystem ioSystem = ioController.IoSystem;
int ioSystemNumber = ioSystem.Number;
string ioSystemName = ioSystem.Name;
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 229
TIA Portal Openness API
5.7 Functions on networks

Program code: Subnet of an io system


Modify the following program code to navigate to the subnet the io system is assigned to:

Subnet subnet = ioSystem.Subnet;

5.7.15 Connecting an IO connector to an IO system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Use the action ConnectToIoSystem(IoSystem ioSystem) of IoConnector to connect a profinet or
a DP IoConnector to an existing io system.
Use the action GetIoController to navigate to the remote IoController. For further information
how to navigate to the local IoConnector and the io system see Get master system or IO system
of an interface (Page 231).
Prerequisites:
• The IoConnector is not yet connected to an io system.
• The IoConnector interface is connected to the same subnet as the interface of the desired
IoController.

Program code
Modify the following program code:

IoSystem ioSystem = ...;


IoConnector ioConnector = ...;
ioConnector.ConnectToIoSystem();
IoController ioController = ioConnector.GetIoController();

Openness: API for automation of engineering workflows


230 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

5.7.16 Get master system or IO system of an interface

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The service NetworkInterface provides the navigator IoControllers, each IoController in turn
provides the navigator IoSystem. The class IoSystem represents the master systems and the io
systems. The io device and the slave are both named io device.
• The IoControllers navigator returns IoController objects, if the network interface can have an
io system. At the moment only one io controller will be returned.
• The IoConnectors navigator returns IoConnector objects, if the network interface can be
connected to an io system as an io device. At the moment only one io connector will be
returned.

Program code: Get the io system of the IoController


Modify the following program code to get the io system of the IoController:

NetworkInterface itf = ...


foreach (IoController ioController in itf.IoControllers)
{
IoSystem ioSystem = ioController.IoSystem;
// work with the io system
}

Program code: Get the io system of the IoConnector


Modify the following program code to get the io system of the IoConnector:

NetInterface itf = ...


foreach (IoConnector ioConnector in itf.IoConnectors)
{
IoSystem ioSystem = ioConnector.ConnectedIoSystem;
// work with the io system
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 231
TIA Portal Openness API
5.7 Functions on networks

5.7.17 Get an IO Controller

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Currently only configurations with one IoController are possible. An IoController does not
provide any modelled attributes or actions.

Program code
Modify the following program code to get the io controller:

NetworkInterface itf = ...


foreach (IoController ioController in itf.IoControllers)
{
// work with the io controller
}

5.7.18 Get an IO Connector

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
An IoConnector does provide the modelled attributes or actions.
The following attribute and actions are available at the IoConnector:

Openness: API for automation of engineering workflows


232 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Actions

Action Signature Description


ConnectToIoSystem void ConnectToIoSystem(Sie‐ To connect an IoConnector to an
mens.Engineering.HW.IoSystem existing DP master system
ioSystem
DisconnectFromIoSystem void DisconnectFromIoSystem() To disconnect an IoConnector
from an existing io system
GetIoController Siemens.Engineering.HW.IoCon‐ Returns the IO controller for this
troller GetIoController() connector

Links

Link Type Access


ConnectedToIoSystem Siemens.Engineering.HW.IoSys‐ read-only
tem

Program code
Modify the following program code to get the io connector:

NetworkInterface itf = ...


foreach (IoConnector ioConnector in itf.IoConnectors)
{
// work with the IoConnector
}

5.7.19 Disconnecting an IO connector from an IO system or a DP mastersystem

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Use the action DisconnectFromIoSystem() of IoConnector to disconnect an IoConnector from
an existing io system or an existing DP mastersystem.
For further information how to navigate to the local IoConnector and the io system see Get
master system or IO system of an interface (Page 231).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 233
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code:

IoSystem ioSystem = ...;


IoConnector ioConnector = ...;

ioConnector.DisconnectFromIoSystem();

5.7.20 Accessing attributes of a DP mastersystem

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A DP Mastersystem provides certain attributes that can be read and/or written. The attributes are
only available if they are available at the UI. Writing is generally only allowed if an attribute can
also be changed by the user at the UI. This might vary depending on the DP Master and the DP
Slaves which are assigned to this DP Mastersystem.

Attributes of a dp mastersystem

Attribute Data type Writa‐ Access Description


ble
Name string r/w proper‐ -
ty
Number int r/w proper‐ The property Number accepts values that cannot be set
ty via UI. In this case the compile will fail.

Program code: Get attributes


Modify the following program code to get attributes:

IoSystem dpMastersystem = ...;

string name = dpMastersystem.Name;


int number = dpMastersystem.Number;

Openness: API for automation of engineering workflows


234 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Program code: Set attributes


Modify the following program code to set attributes:

IoSystem dpMastersystem = ...;

dpMastersystem.Name ="myDpMastersystem"
dpMastersystem.Number=42;

5.7.21 Accessing attributes of PN Driver

Application
You can use the TIA Portal Openness to access the attributes in PROFINET Interface of PN Driver
V2.2.

Access to attribute of PN Driver V2.2 submodule object


The following attributes can be accessed at the Interface options using TIA Portal Openness:

Openness Attribute Type ReadOnly


DeviceReplacementWithoutExhangea‐ Boolean False
bleMedium
OverwriteDeviceNames Boolean False
IECV22LLDPMode Boolean False

The following attributes can be accessed at the Real time options using TIA Portal Openness:

Openness Attribute Type ReadOnly


CalculatedBandwidthForCyclicIoData Int32 True
MaxBandwidthForCyclicIoData Int32 True

The following attributes can be accessed at Isochronous mode options using TIA Portal
Openness:

Openness Attribute Type ReadOnly


ApplicationCycle Int64 False
AutomaticMinimum Boolean False
DelayTime Double False

Note
The value of DelayTime cannot be set, unless the value of the AutomaticMinimum is set to False
beforehand.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 235
TIA Portal Openness API
5.7 Functions on networks

5.7.22 Accessing attributes of a profinet io system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
An IO System provides certain attributes that can be read and/or written. The attributes are only
available if they are available at the UI. Writing is generally only allowed if an attribute can also
be changed by the user at the UI. This might vary depending on the IO Controller and the IO
Devices which are assigned to this IO System.

Attributes of a PROFINET io System

Attribute Data type Writa‐ Access Description


ble
MultipleUseIoSystem bool r/w dynam‐ -
ic
Name string r/w proper‐ -
ty
Number int r/w proper‐ The attribute Number accepts values that cannot be set
ty via UI. In this case the compile will fail.
UseIoSystemNameAsDeviceNa‐ bool r/w dynam‐ If MultipleUseIoSystem is set to TRUE, UseIoSystemNa‐
meExtension ic meAsDeviceNameExtension will be set to FALSE and
write access is not possible.
MaxNumberIWlanLinksPerSegment int r/w dynam‐ -
ic

Program code: Get attributes


Modify the following program code to get attributes

IoSystem ioSystem = ...;


string name = ioSystem.Name;

Program code: Set attributes


Modify the following program code to set attributes:

IoSystem ioSystem = ...;


ioSystem.Name = "IOSystem_1";

Openness: API for automation of engineering workflows


236 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Program code: Get attributes with dynamic access


Modify the following program code to get the values of dynamic attributes:

IoSystem ioSystem = ...;


var attributeNames = new[]
{
"MultipleUseIoSystem", "UseIoSystemNameAsDeviceNameExtension",
"MaxNumberIWlanLinksPerSegment"
};
foreach (var attributeName in attributeNames)
{
object attributeValue = ((IEngineeringObject)ioSystem).GetAttribute(attributeName);
}

Program code: Set attributes with dynamic access


Modify the following program code to set the values of dynamic attributes:

IoSystem ioSystem = ...;


((IEngineeringObject)ioSystem).SetAttribute("MultipleUseIoSystem", true);

5.7.23 Deleting a DP master system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code: Deleting a PROFINET io system


Modify the following program code to delete a PROFINET io system:

IoController ioController = ...;


IoSystem ioSystem = ioController.IoSystem;

ioSystem.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 237
TIA Portal Openness API
5.7 Functions on networks

5.7.24 Deleting a profinet io system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to delete a profinet io system:

IoController ioController = ...;


IoSystem ioSystem = ioController.IoSystem;
ioSystem.Delete();

5.7.25 Creating a DP master system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A DP master system is created by calling the action CreateIoSystem(string nameOfIoSystem) on
an object of the type IoController. The io controller is aquired by accessing the attribute
IoControllers object on the NetworkInterface.
Prerequisites for creating a DP master system:
• The interface of the io controller is connected to a subnet.
• The io controller has no io system.

Openness: API for automation of engineering workflows


238 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code to create a dp master system:

using System.Linq;
...
NetworkInterface interface = ...;
IoSystem dpMasterSystem = null;

// Interface is configured as master or as master and slave


if((interface.InterfaceOperatingMode & InterfaceOperatingModes.IoController) != 0)
{
IoControllerComposition ioControllers = interface.IoControllers;
IoController ioController = ioControllers.First();
if(ioController != null)
{
dpMasterSystem = ioController.CreateIoSystem("dp master system");
}
}

5.7.26 Accessing port interconnection information of port device item

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
NetworkPort provides the link ConnectedPorts which is an enumeration of ports to access all
interconnected partner ports of a port.
It is only possible to interconnect ports which can also be interconnected in the TIA UI, e.g. it is
not possible to interconnect two ports of the same Ethernet interface. Recoverable exception are
thrown
• if there is already an interconnection to the same partner port
• when trying to interconnect two ports which cannot be interconnected
• when trying to create a second interconnection to a port which does not support alternative
partners

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 239
TIA Portal Openness API
5.7 Functions on networks

Program code: Get the port interconnection


Modify the following program code to get the port interconnection information of a port device
item:

NetworkPort port = ...;


foreach (NetworkPort partnerPort in port.ConnectedPorts)
{
// work with the partner port
}

Program code: Create port interconnections


Modify the following program code:

NetworkPort port1 = ...;


NetworkPort port2 = ...;
port1.ConnectToPort(port2);

// port supports alternative partners


NetworkPort port1 = ...;
NetworkPort port2 = ...;
NetworkPort port3 = ...;
port1.ConnectToPort(port2);
port1.ConnectToPort(port3);

Program code: Delete port interconnection


Modify the following program code:

NetworkPort port1 = ...;


NetworkPort port2 = ...;
port1.DisconnectFromPort(port2);

5.7.27 Attributes of port inter-connection

Attributes for port inter-connections


TIA Portal Openness supports the following attributes for port inter-connections. If the attributes
are available in UI, the corresponding attributes can also be accessed through TIA Portal
Openness. If the user has access to modifiy the attributes in UI, then they can also be modified
via TIA Portal Openness.

Openness: API for automation of engineering workflows


240 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attribute name Data type Writable Access Description


MediumAttachment‐ MediumAttachment‐ Read-only Dynamic attribute -
Type Type
CableName CabelName Read-Write Dynamic attribute -
AlternativePartnerPorts Boolean Read-Write Dynamic attribute Only available if tool‐
changer functionality
is supported.
SignalDelaySelection SignalDelaySelection Read-Write Dynamic attribute -
CableLength CableLength Read-Write Dynamic attribute -
SignalDelayTime Double Read-Write Dynamic attribute -

Enum values of port inter-connection attributes


The Enum MediumAttachmentType has following values.

Value Description
MediumAttachmentType.None Attachment type cannot be determined.
MediumAttachmentType.Copper Attachment type is copper.
MediumAttachmentType.FiberOptic Attachment type is fiber optic.

The Enum CableName has following value

Value Description
CableName.None No cable name is specified
CableName.FO_Standard_Cable_9 FO standard cable GP (9 µm)
CableName.Flexible_FO_Cable_9 Flexible FO cable (9 µm)
CableName.FO_Standard_Cable_GP_50 FO standard cable GP (50 µm)
CableName.FO_Trailing_Cable_GP FO trailing cable / GP
CableName.FO_Ground_Cable FO ground cable
CableName.FO_Standard_Cable_62_5 FO standard cable (62.5 µm)
CableName.Flexible_FO_Cable_62_5 Flexible FO cable (62.5 µm)
CableName.POF_Standard_Cable_GP POF standard cable GP
CableName.POF_Trailing_Cable POF trailing cable
CableName.PCF_Standard_Cable_GP PCF trailing cable / GP
CableName.GI_POF_Standard_Cable GI-POF standard cable
CableName.GI_POF_Trailing_Cable GI-POF trailing cable
CableName.GI_PCF_Standard_Cable GI-PCF standard cable
CableName.GI_PCF_Trailing_Cable GI-PCF trailing cable
CableName.GI_POF_Standard_Cable GI-POF standard cable
CableName.GI_POF_Trailing_Cable GI-POF trailing cable

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 241
TIA Portal Openness API
5.7 Functions on networks

Value Description
CableName.GI_PCF_Standard_Cable GI-PCF standard cable
CableName.GI_PCF_Trailing_Cable GI-PCF trailing cable

The Enum SignalDelaySelection has following values.

Value Description
SignalDelaySelection.None -
SignalDelaySelection.CableLength CableLength is used to define the signal delay.
SignalDelaySelection.SignalDelayTime SignalDelayTime is used to define the signal delay

The Enum CableLength has following values

Value Description
CableLength.None CableLength is not specified.
CableLength.Length20m Cable length is 20m.
CableLength.Length50m Cable length is 50m.
CableLength.Length100m Cable length is 100m.
CableLength.Length1000m Cable length is 1000m.
CableLength.Length3000m Cable length is 3000m.

Attributes of port options


The attributes of port options are given below.

Attribute name Data type Writable Access


PortActivation bool Read-Write Dynamic attribute
TransmissionRateAnd‐ TransmissionRateAnd‐ Read-Write Dynamic attribute
Duplex Duplex
PortMonitoring bool Read-Write Dynamic attribute
TransmissionRateAuto‐ bool Read-Write Dynamic attribute
Negotiation
EndOfDetectionOfAc‐ bool Read-Write Dynamic attribute
cessibleDevices
EndOfTopologyDiscov‐ bool Read-Write Dynamic attribute
ery
EndOfSyncDomain bool Read-Write Dynamic attribute

The Enum TransmissionRateAndDuplex has following values.

Openness: API for automation of engineering workflows


242 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Value Description
TransmissionRateAndDuplex.None -
TransmissionRateAndDuplex.Automatic Automatic
TransmissionRateAndDuplex.AUI10Mbps 10 Mbps AUI
TransmissionRateAndDuplex.TP10MbpsHalfDu‐ TP 10 Mbps half duplex
plex
TransmissionRateAndDuplex.TP10MbpsFullDuplex TP 10 Mbps full duplex
TransmissionRateAndDuplex.AsyncFib‐ async fiber 10Mbit/s half duplex mode
er10MbpsHalfDuplex
TransmissionRateAndDuplex.AsyncFib‐ async fiber 10Mbit/s full duplex mode
er10MbpsFullDuplex
TransmissionRateAndDuplex.TP100MbpsHalfDu‐ TP 100 Mbps half duplex
plex
TransmissionRateAndDuplex.TP100MbpsFullDu‐ TP 100 Mbps full duplex
plex
TransmissionRateAndDuplex.FO100MbpsFullDu‐ FO 100 Mbps full duplex
plex
TransmissionRateAndDuplex.X1000MbpsFullDu‐ X1000 Mbps full Duplex
plex
TransmissionRateAndDuplex.FO1000MbpsFullDu‐ FO 1000 Mbps full duplex LD
plexLD
TransmissionRateAndDuplex.FO1000MbpsFullDu‐ FO 1000 Mbps full Duplex
plex
TransmissionRateAndDuplex.TP1000MbpsFullDu‐ TP 1000 Mbps full duplex
plex
TransmissionRateAndDuplex.FO10000MbpsFull‐ FO 10000 Mbps full Duplex
Duplex
TransmissionRateAndDuplex.FO100MbpsFullDu‐ FO 100 Mbps full duplex LD
plexLD
TransmissionRateAndDuplex.POFPCF100MbpsFull‐ POF/PCF 100 Mbps full duplex
DuplexLD

5.7.28 Accessing the attributes of a port

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
SeeConnecting to the TIA Portal (Page 81)
• A profect is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 243
TIA Portal Openness API
5.7 Functions on networks

Application
If a device item is a port, it provides additional functionality over a simple device item.
• It is possible to access the linked partner ports of the port
• It is possible to access the interface of the port
To access this additional functionality, the NetworkPort feature, a specific service of the device
item, must be used.

Program code: Accessing a port


Modify the following program code to access attributes of a channel:

NetworkPort port = ((IEngineeringServiceProvider)deviceItem).GetService<NetworkPort>();


if (port != null)
{
... // Work with the port
}

Attributes of a port
A port has the following attributes:

NetworkPort port = ...;


var connectedPorts = port.ConnectedPorts;
var myInterface = port.Interface;

5.7.29 Enumerate DP master systems of a subnet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Enumeration of IoSystem provides all DP mastersystems that are present on a subnet. The class
IoSystem represents the master systems and the io systems.

Openness: API for automation of engineering workflows


244 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code to enumerate DP master systems from subnet:

Subnet subnet = ...;


foreach (IoSystem ioSystem in subnet.IoSystems)
{
// work with the io system
}

5.7.30 Enumerate assigned IO connectors

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The class IoSystem represents the master systems and the io systems.
It is used for:
• Enumeration of io connectors of a dp mastersystem
• Enumeration of io connectors of a profinet io system

Program code
Modify the following program code to enumerate assigned io connectors of the dp
mastersystem:

IoSystem ioSystem = ...;


foreach (IoConnector ioConnector in ioSystem.ConnectedIoDevices)
{
// work with the io connector
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 245
TIA Portal Openness API
5.7 Functions on networks

5.7.31 Connecting a DP IO connector to a DP master system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Use the action ConnectToIoSystem(IoSystem ioSystem) of IoConnector to connect an
IoConnector to an existing DP mastersystem.
Use the action GetIoController to navigate to the remote IoController. For further information
how to navigate to the local IoConnector and the io system see Get master system or IO system
of an interface (Page 231).
Prerequisites:
• The IoConnector is not yet connected to an io system.
• The IoConnector interface is connected to the same subnet as the interface of the desired
IoController.

Program code
Modify the following program code:

IoSystem ioSystem = ...;


IoConnector ioConnector = ...;
ioConnector.ConnectToIoSystem(ioSystem);
IoController ioController = ioConnector.GetIoController();

5.7.32 Accessing AS-i profile and parameter attributes for virtual slaves

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


246 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Application
The TIA Portal Openness supports the following additional AS-i profile parameters for the Virtual
Slaves of the CTT5 AS-i Slave using the StructuredData names:

Name Description
AsiProfileVirtualSlave1 This contains the AS-i profile parameters for the
Virtual Slave 1
AsiProfileVirtualSlave2 This contains the AS-i profile parameters for the
Virtual Slave2
AsiProfileVirtualSlave3 This contains the AS-i profile parameters for the
Virtual Slave 3

The AS-i slave parameters for the Virtual slaves can be found below:

Name Description
AsiParameterVirtualSlave1 This contains the AS-i parameter for the Virtual
Slave 1
AsiParameterVirtualSlave2 This contains the AS-i parameter for the Virtual
Slave 2
AsiParameterVirtualSlave3 This contains the AS-i parameter for the Virtual
Slave 3

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 247
TIA Portal Openness API
5.7 Functions on networks

Program code
Modify the following program code to get and set the additional attributes of AS-i Slaves:

DeviceItem slaveModule= ...;


var structuredDataNamesProfile = new[]
{
"AsiProfileVirtualSlave1", "AsiProfileVirtualSlave2", "AsiProfileVirtualSlave3"
};
var structuredDataNamesAsiParameter = new[]
{
"AsiParameterVirtualSlave1", "AsiParameterVirtualSlave2", "AsiParameterVirtualSlave3"
};
var attributeNamesProfile = new[]{"AsiProfileID", "AsiProfileIO", "AsiProfileID2",
"AsiProfileID1"};
string attributeNameAsiParameter = "AsiSlaveParameter"
foreach (var structuredDataName in structuredDataNamesProfile)
{
foreach (var attributeName in attributeNamesProfile)
{
StructuredData structuredData =
(StructuredData)slaveModule.GetAttribute(structuredDataName);
//get
UInt32 attributeValue = (UInt32)structuredData.GetAttribute(attributeName);}
//set
slaveHead.SetAttribute(attributeName, (UInt32)5);
}
}
foreach (var structuredDataName in structuredDataNamesAsiParameter)
{
StructuredData structuredData =
(StructuredData)slaveModule.GetAttribute(structuredDataName);
//get
UInt32 attributeValue = (UInt32)structuredData.GetAttribute(attributeNameAsiParameter);
//set
slaveHead.SetAttribute(attributeName, (UInt32)5);
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


248 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

5.7.33 Accessing CM DP as DP slave and transfer area

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to configure an ET200SP PLC as DP slave if a CM DP has been
plugged. It is also possible in TIA Portal Openness to create, configure and delete transfer areas
at the DP interface. The handling will be similar to the handling of transfer areas at PN interface
described in Openness transfer areas for PnPn coupler (Page 256)
The following dynamic attributes are supported at the device item DP interface.

Attribute name Data type Access Writeable


DpUseForTestCommissioning‐ Boolean only available if config‐ r/w
Routing ured as DP slave
DpWatchdog Boolean only available if config‐ r/w
ured as DP slave and as‐
signed to DP Master

Program code: Creating transfer areas


Modify the following program code to create a transfer area at the DP interface:

NetworkInterface cpuItf = CpuInterface.GetService<NetworkInterface>();


// Create TransferAreas
TransferAreaComposition transferAreas = cpuItf.TransferAreas;
// Simple TranferArea
TransferArea transferAreaExample = transferAreas.Create("Example TA MS",
TransferAreaType.MS);

Parameter of transfer areas


The following parameters are supported in transfer areas of DP slave configuration:

Parameter name Data type Access


Name string read/write
Direction enum read/write
Comment string read/write
LocalToPartnerLength Int32 read/write
PartnerToLocalLength Int32 read/write
LocalAddresses AddressComposition object read

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 249
TIA Portal Openness API
5.7 Functions on networks

Parameter name Data type Access


PartnerAddresses AddressComposition object read
PositionNumber Int32 read
Type enum read

Program code: Deleting transfer area


Modify the following program code to delete transfer area for DP slave configuration:

TransferArea transferAreaExample = transferAreas.Create("Example TA MS",


TransferAreaType.MS);
transferAreaExample.Delete();

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Openness transfer areas for PnPn coupler (Page 256)

5.7.34 Coupling 1516 isochron central and decentral Profinet

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to perform the following operations:
• Given a 1516 PLC with one isochron capable module and it is possible to set the PLC into
isochronous mode
• Given the previous configuration where the module is assigned to OB61 and it is possible to
set the module into isochronous mode
• Given the previous config with an additional ET200SP assigned to the PLC and a module
configured in isochronous mode assigned to the same OB61 where the source of sendclock
can be set (PLC and decentral are coupled, Source of sendclock is set to PN X1).

Openness: API for automation of engineering workflows


250 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attributes

Attribute name Data type Writeable Available Prerequisites Description Access


range/values
Isochronous‐ bool r/w True/False Isochronous ca‐ get/set Isochro‐ Dynamic attrib‐
Mode pable device nus mode ute
SourceCycle‐ int r/w Device specific Isochronous get/set Source Dynamic attrib‐
Time mode is enabled of sendclock ute
SendClock float r/w Device specific Isochronous get/set Send Dynamic attrib‐
mode is enabled clock ute
IsochronousTi‐ enum r/w FromOB, Auto‐ Isochronous get/set Ti/To val‐ Dynamic attrib‐
ToCalculation‐ maticMini‐ mode is enabled ues ute
Mode mum, Manual
IsochronousTi double r/w Device specific Isochronous get/set Time Ti Dynamic attrib‐
mode is enabled ute
IsochronousTo double r/w Device specific Isochronous get/set Time To Dynamic attrib‐
mode is enabled ute

Program code: Examples with S71500/ET200MP station


Modify the following program code for PLC represents an S71500/ET200MP station:

//plc represents an S71500/ET200MP station


//Getting headmodule of the station
DeviceItem plcHeadModule = plc.DeviceItems[1];
//Getting and I/O module of the station
DeviceItem module = plc.DeviceItems[2];

Modify the following program code to set isochoronous mode properties on PLC headmodule:

//Turn on isochronous mode


plcHeadModule.SetAttribute("IsochronousMode", true);
//Set source of sendclock to "Use send clock of PROFINET interface [X1]"
plcHeadModule.SetAttribute("SourceCycleTime", 1);
//Set source of sendclock to "Local send clock"
plcHeadModule.SetAttribute("SourceCycleTime", 0);
//Set sendclock
plcHeadModule.SetAttribute("SendClock", (float)2.1);
//Set calculation mode to Automatic minimum
plcHeadModule.SetAttribute("IsochronousTiToCalculationMode",
IsochronousTiToCalculationMode.AutomaticMinimum);
//Set calculation mode to Manual
plcHeadModule.SetAttribute("IsochronousTiToCalculationMode",
IsochronousTiToCalculationMode.Manual);
//Set Time Ti
plcHeadModule.SetAttribute("IsochronousTi", (double)0.55);
//Set Time To
plcHeadModule.SetAttribute("IsochronousTo", (double)0.65);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 251
TIA Portal Openness API
5.7 Functions on networks

Modify the following program code to set isochoronous mode properties on I/O modules:

//Isochronous relevant properties can be found on the Address of the submodule


DeviceItem subModule = module.DeviceItems[0];
Address address = subModule.Addresses[0];
//Turn on isochronous mode
address.SetAttribute("IsochronousMode", true);
//Set Process image to 3
address.SetAttribute("ProcessImage", 3);

Program code: Examples with SIMATIC Drive Controller

//Simatic Drive controller is usually created in a DeviceGroup (group)


//Getting headmodule of the SIMATIC Drive Controller
DeviceItem plcHeadModule = group.Devices[0].DeviceItems[1];
//Getting headmodule of the S120
DeviceItem s120HeadModule = group.Devices[1].DeviceItems[0];
//Getting address of central module (X142)
Address x142address = plcHeadModule.Items.First(x => x.PositionNumber == 8).Addresses[0];
//Getting address of drive controller telegram
DriveObjectContainer driveObjectService =
s120HeadModule.GetService<DriveObjectContainer>();
Telegram telegram = driveObjectService.DriveObjects.First().Telegrams.First();
Address telegramAddress = telegram.Addresses[0];
//Getting PROFIdrive integrated subnet named "PROFIdrive Integrated_1"
Subnet profiDriveSubnet = project.Subnets.First(x => x.Name.Equals("PROFIdrive
Integrated_1"));

For Setting isochoronous mode properties on PLC headmodule, It is same as in case of S71500/
ET200MP station.
Modify the following program code to set isochoronous mode properties of central module
(X142):

//Turn on isochronous mode


x142address.SetAttribute("IsochronousMode", true);
//Set Process image to 2x142address.SetAttribute("ProcessImage", 2);

Modify the following program code to set isochoronous mode properties of an integrated
telegram:

//Turn on isochronous mode


telegramAddress.SetAttribute("IsochronousMode", true);
//Set Process image to 11
telegramAddress.SetAttribute("ProcessImage", 11);

Openness: API for automation of engineering workflows


252 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Modify the following program code to set isochoronous mode properties of PROFIdrive
integrated subnet:

//Couple PROFIdrive Integrated to X150 (PROFINET)


profiDriveSubnet.SetAttribute("SourceCycleTime", 3);

5.7.35 Openness for CP 1604/CP 1616/CP 1626

General
You can use the TIA Portal Openness application to configure transfer areas and transfer area
mapping rules for the communication processors CP 1604/CP 1616 as of V2.8 (also as of V2.7
depending on the article number) and CP 1626 as of V1.1.

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See "Establishing a connection to the TIA Portal".
• A project is open.
See "Open project".
• To compile the project, all devices must be "offline".

Configuration of transfer areas

Creating transfer areas


For example, to create a "CD" type transfer area for a CP 1604, use the following program code:
NetworkInterface cpItf = CP
1604Interface.GetService<NetworkInterface>();
// Create TransferAreas
TransferAreaComposition transferAreas = cpItf.TransferAreas;

// Simple TranferArea of type Input

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 253
TIA Portal Openness API
5.7 Functions on networks

TransferArea transferAreaInput =
transferAreas.Create("Input CD", TransferAreaType.CD);

Attribute Description
name Specifies the name of the transfer area to be created.
type Specifies the type of the transfer area to be created. The following types are possible:
TransferAreaType.CD Data exchange controller device
TransferAreaType.F_PS Data exchange PROFIsafe
TransferAreaType.TM Transfer module mapping
Note: It is not possible to change the type at a later date.

Setting attributes of the transfer areas


To set attributes of a transfer area, use the following program code, for example:
transferAreaTm.LocalToPartnerLength = 8;
transferAreaTm.Direction = TransferAreaDirection.LocalToPartner;
string name = transferAreaTm.Name

Some attributes must be set or queried, but all of them can be set or queried using the general
calls "GetAttribute()" or "SetAttribute()". Use the following program code, for example:
const string myIndividualComment = "MyIndividualComment";
transferAreaTm.SetAttribute("Comment", myIndividualComment);
Int32 updateTime = transferAreaTm.GetAttribute("TransferUpdateTime")

Attribute Description
Name (string) Specifies the name of the transfer area.
Direction Specifies the direction in which the data of the transfer area is transferred. The following
directions are possible:
TransferAreaDirection.LocalToPart‐ Data of the transfer area is transferred from the IO de‐
ner vice to the higher-level IO controller.
TransferAreaDirection.partnerToLo‐ Data of the transfer area is transferred from the higher-
cal level IO controller to the IO device.
TransferAreaDirection.bidirectional Data of the transfer area can be transferred in both
directions between the higher-level IO controller and
the IO device.
The "LocalToPartnerLength" attribute determines the
length of the transferred data from IO device to the
higher-level IO controller. The "PartnerToLocalLength"
attribute determines the amount of data from the high‐
er-level IO controller to the IO device
Comment (string) Text box for a comment on the transfer area.
LocalToPartnerLength Specifies the data length of the transfer area that is transferred from the IO device to the
higher-level IO controller.
PartnerToLocalLength Specifies the data length of the transfer area that is transferred from the higher-level IO
controller to the IO device.

Openness: API for automation of engineering workflows


254 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Attribute Description
LocalAdresses Specifies the input and output addresses of the transfer area from the local device.
PartnerAdresses Specifies the input and output addresses of the transfer area in the higher-level IO controller.
TransferUpdateTime(Int32) Specifies the update time of the transfer area. Only set or queried for a transfer area of the type
"TransferAreaType.TM".
PositionNumber Specifies the number of the virtual submodule of this transfer area.
Type Specifies the type of transfer area, read-only.
TransferAreaMappingRules Specifies the routing table of the routing area, read-only.

Deleting transfer areas


To delete transfer areas, use the following program code:
transferAreaInput.Delete();

Iteration through transfer areas


To iterate transfer areas, use the following program code:
TransferAreaComposition transferAreas = cpItf.TransferAreas;
foreach (TransferArea transferArea in transferAreas)
{
transferArea.Delete();
}

Configuration of IO routing

Creating IO routes
To create IO routes, use the following program code:
// Create TransferAreaMappingRule
TransferAreaMappingRuleComposition routingTable
= transferArea.TransferAreaMappingRules;

// Create a new IO route


TransferAreaMappingRule route1 =
routingTable.Create();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 255
TIA Portal Openness API
5.7 Functions on networks

Setting attributes of IO routes


The following attributes can be set for IO routing:

Attribute Description
Offset Bit-based offset within the routing area to which the data is to be assigned. The length of the offset is
determined by the "Begin" and "End" attributes.
Target Specifies the module or submodule of the IO device that contains the data to be assigned to the configura‐
tion of the IO device, a transfer area of the type "TM".
IoType The “IoType” attribute can only be changed in a transfer area of the “Input” type. In addition, a mixed module
must be configured as “Target” for this transfer area. Only then can you select whether the data of the inputs
(IoType.Input) are to be read or whether the data of the outputs (IoType.Output) are to be read (back).
Begin Specifies the beginning of the data to be read by the "Target" attribute.
End Specifies the end of the data to be read by the "Target" attribute.

Deleting IO routes
To delete IO routes, use the following program code:
transferAreaMappingRule.Delete();

Iteration via IO routing


To iterate via IO routing, use the following program code:
TransferAreaMappingRuleComposition routingTable =
transferArea.TransferAreaMappingRules;
foreach (TransferAreaMappingRule route in routingTable)
{
route.Delete();
}

5.7.36 Openness transfer areas for PnPn coupler

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• To compile the project, all device must be "offline"

Openness: API for automation of engineering workflows


256 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Introduction
You can use the TIA Portal Openness to add module/submodule, delete and search transfer areas
for PnPn coupler.

Configuration of transfer areas

Creating transfer areas


For example, to create module on the next free position, use the following program code:

NetworkInterface coupler_Itf = deviceItem.GetService<NetworkInterface>();


TransferAreaComposition transferAreas = coupler_Itf.TransferAreas;
// Create a transfer area of type input at next free positionnumber
TransferArea transferAreaInput = transferAreas.Create("Input", TransferAreaType.IN);

Note
It is not possible to create a submodule without Positionnumber.

For example, to create module on PositionNumber and submodule at the next free
submodulepositionnumber at positionNumber, use the following program code:

// Create a transfer area of type input at positionnumber 5


TransferArea transferAreaInput = transferAreas.Create("Input", TransferAreaType.IN, 5);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 257
TIA Portal Openness API
5.7 Functions on networks

Attribute Description
Type Specifies the type of the transfer area to be created. The following types are possible:
TransferAreaType.None Default value
TransferAreaType.IN Transfer area Input
TransferAreaType.OUT Transfer area Output
TransferAreaType.MSI Transfer area Shared Input (MSI)
TransferAreaType.MSO Transfer area Shared Output (MSO)
TransferAreaType.MSO_LOCAL Transfer area Local Shared Output
(MSO_LOCAL)
TransferAreaType.RECORD_WRITE_STO Transfer area for Record Data Write up to
8 data records will be buffered
TransferAreaType.RECORD_WRITE_PUB Transfer area for Record Data Write over‐
writes previous data record
TransferAreaType.RECORD_READ_STO Transfer area for Record Data Read reads
the oldest data record in the buffer
TransferAreaType.RECORD_READ_PUB Transfer area for Record Data Read reads
data record written last
TransferAreaType.MSI_MSO Transfer area Shared Input (MSI) / Trans‐
fer area Shared Output (MSO)
TransferAreaType.IN_OUT Transfer area Input / Transfer area Output
TransferAreaType.LOCAL_RECORD_STO Transfer area for local data record cou‐
pling, up to 8 data records are buffered
TransferAreaType.LOCAL_RECORD_PUB Transfer area for local data record cou‐
pling, overwrites previous data record
TransferAreaType.SUB_MSI Transfer area copy of Shared Input (MSI)
TransferAreaType.SUB_MSO Transfer area copy of Shared Output
(MSO)
TransferAreaType.SUB_LOCAL_RE‐ Transfer area for Record Data Read for
CORD_STO_READ reading the oldest data record in the buf‐
fer
TransferAreaType.SUB_LOCAL_RE‐ Transfer area for Record Data Read for
CORD_PUB_READ reading the most recently written data
record
TransferAreaType.PROFI‐ Transfer area with 12 byte input and 6
SAFE_IN12_OUT6 byte output
TransferAreaType.PROFI‐ Transfer area with 6 byte input and 12
SAFE_IN6_OUT12 byte output

Setting attributes of the transfer areas


To set attributes of a transfer area, use the following program code, for example:

// Change input length 


CouplerTransf.LocalToPartnerLength = 5; 
// Change output length 
CouplerTransf.PartnerToLocalLength = 5; 
// Change name 
CouplerTransf.Name = "Testname";

Openness: API for automation of engineering workflows


258 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Some attributes must be set or queried, but all of them can be set or queried using the general
calls TransferArea.GetAttribute() or SetAttribute(). Use the following program code, for example

// Set Comment of Transferarea


string myIndividualComment = "MyIndividualComment";
CouplerTransf.SetAttribute("Comment", myIndividualComment);
// Get positionNumber of Transferarea
Int32 positionNumber = (Int32)CouplerTransf.GetAttribute("PositionNumber");

Attribute Description
Name (string) Specifies the name of the transfer area
Direction Specifies the direction in which the data of the transfer area is transferred. The following direc‐
tions are possible:
TransferAreaDirection.Lo‐ Data of the transfer area is transferred from the IO device to the
calTo‐ Partner higher-level IO controller.
TransferAreaDirection.part‐ Data of the transfer area is transferred from the higherlevel IO
nerTo‐ Local controller to the IO device.
TransferAreaDirection.bidir‐ Data of the transfer area can be transferred in both directions
ectional between the higher-level IO controller and the IO device. The "Lo‐
calToPartnerLength" attribute determines the length of the trans‐
ferred data from IO device to the higher-level IO controller. The
"PartnerToLocal‐ Length" attribute determines the amount of data
from the higher-level IO controller to the IO device
Comment (string) Text box for a comment on the transfer area
LocalToPartnerLength Specifies the input data length of the transfer area
PartnerToLocalLength Specifies the output data length of the transfer area
PositionNumber Specifies the slot number of the transfer area
ExtendedPositionNumber Specifies the sub slot number of the transfer area
Type Specifies the type of transfer area
SharedDeviceAccessConfig‐ Controls the access to PLC
ured
UpdateAlarm Enable the update alarm of the transfer area
RecordIndex Set the data record number that you will be using when writing the data record

Deleting transfer areas


To delete transfer areas, use the following program code:

TransferArea TransferAreaInput = transferAreas.Create("Input", TransferAreaType.IN);


TransferAreaInput.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 259
TIA Portal Openness API
5.7 Functions on networks

Searching transfer areas


To get the TransferArea with posotionNumber and extendedPositionNumber, use the following
program code:

// Find a transfer area with Positionnumber and ExtendedPositionNumber


TransferArea transferAreaFind = transferAreas.Find(4, 3);

Note
ExtendedPositionNumber is only needed for TransferAreas with more than one Submodule like
MSI

To get the first TransferArea with this positionNumber, use the following program code:

// Find a transfer area with Positionnumber 


TransferArea transferAreaFind = transferAreas.Find(5);

Note
If one of this attributes is not available, you will encounter an exception.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.7.37 Openness virtual modules/submodules for ET 200SP PN HF

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Introduction
You can use the TIA Portal Openness to add and delete virtual modules/submodule for ET 200 SP
PN HF.

Openness: API for automation of engineering workflows


260 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

The following property are supported in virtual modules:

Property name Data type EomAtomVal‐ EomAtom descrip‐


ue tion
SharedDeviceAccessConfigured Boolean
Name String
PositionNumber Int32
VirtualType UInt64 1 MsoLocal
AddSubModules Int64

The following property are supported in virtual submodules:

Property Data type EomAtom value EomAtom Description


SharedDeviceAccessConfig‐ Boolean
ured
Comment String
PositionNumber Int32
Name String
ActivateDataStatus Boolean
InputAddressLength Int64
OutputAddressLength Int64
VirtualSubType UInt64 1 MsoLocal
2 MsoSub

Program code: Create and delete virtual module


Modify the following program code to add a new module:

string Type = "OrderNumber:6ES7 155-6AU30-0CN0/V4.2";


Device ET200SP = newProject.Devices.CreateWithItem(Type, "ET200SP",
"ET200SP");
DeviceItem Rack = ET200SP.DeviceItems.First();
string TypeIdentifier = "OrderNumber:ET200SP.Virtual.Module";
string Name = "VirtualIO_1";
int PositionNumber = 100;
DeviceItem VIM = Rack.PlugNew(TypeIdentifier, Name, PositionNumber);

Modify the following program delete a module

DeviceItem Rack = ET200SP.DeviceItems.First();


string TypeIdentifier = "OrderNumber:ET200SP.Virtual.Module";
string Name = "VirtualIO_1";
int PositionNumber = 100;
DeviceItem VIM = Rack.PlugNew(TypeIdentifier, Name, PositionNumber);
VIM.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 261
TIA Portal Openness API
5.7 Functions on networks

Program code: Create and delete virtual sub module


Modify the following program code to create virtual submodules in Openness:

VIM1.SetAttribute("AddSubModules", (Int64)1);
VIM2.SetAttribute("AddSubModules", (Int64)2);

Note
To add a submodule, you have to set the module property "AddSubModules" to count of added
submodules. If you try to add more submodulesthan allowed, there is an exception.

Modify the following program code to delete a submodule:

SubModule3.Delete();

Note
You cannot delete the first two submodules.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.7.38 Accessing domain settings

Requirements
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Introduction
You can use the TIA Portal Openness to access the complete domain management. The
following two new services are added to the Subnet class for accessing domain management via
TIA Portal Openness:
• service MrpDomainOwner
• service SyncDomainOwner

Openness: API for automation of engineering workflows


262 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.7 Functions on networks

Program code: Accessing MrpDomainOwner


The service MrpDomain provides the navigator MrpDomains which contains the
MrpDomainComposition. The composition contains objects of type MrpDomain.

Subnet subnet = …;
MrpDomainOwner mrpDomainOwner = subnet.GetService<MrpDomainOwner>();
MrpDomainComposition mrpDomainComposition = mrpDomainOwner.MrpDomains;

Modify the following program code to create a new domain with a name newMrpDomain;

int countOfMrpDomains = mrpDomainComposition.Count;


MrpDomain someMrpDomain = mrpDomainComposition.ElementAt(3);
MrpDomain firstMrpDomain = mrpDomainComposition.First();
MrpDomain byName = mrpDomainComposition.Find("DomainName");
// create a new domain
MrpDomain newMrpDomain = mrpDomainOwner.MrpDomains.Create("newMrpDomain");

Modify the following program code to read/write attributes value of a MRP domain objects:

NetworkInterface toBeAdded = …;
newMrpDomain.SetAttribute("IsDefault", true);
newMrpDomain.SetAttribute("ManagerOutsideOfProjectActive", false);
var participants = firstMrpDomain.DomainParticipants;
int count = participants.Count;
participants.Add(toBeAdded);
foreach (NetworkInterface networkIf in participants)
{
// do something at the interface
}
newMrpDomain.Delete();

Program code: Accessing SyncDomainOwner


The service provides the navigator SyncDomains which contains the SyncDomainComposition.
This composition contains objects of type SyncDomain.

Subnet subnet = …;
SyncDomainOwner syncDomainOwner = subnet.GetService<SyncDomainOwner>();
SyncDomainComposition syncDomainComposition = syncDomainOwner.SyncDomains;

Modify the following program code to create a new SyncDomain with specific name:

int countOfSyncDomains = syncDomainComposition.Count;


SyncDomain someSyncDomain = syncDomainComposition.ElementAt(3);
SyncDomain firstSyncDomain = syncDomainComposition.First();
SyncDomain byName = syncDomainComposition.Find("DomainName");
// create a new domain
SyncDomain newSyncDomain = syncDomainOwner.SyncDomains.Create("newSyncDomain");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 263
TIA Portal Openness API
5.7 Functions on networks

Modify the following program code to read/write the attribute value of Sync Domain:

NetworkInterface toBeAdded = …;
string convertedName = newSyncDomain.ConvertedName;
newSyncDomain.SetAttribute("IsDefault", true);
newSyncDomain.SetAttribute("HighPerformanceActive", true);
newSyncDomain.SetAttribute("FastForwardingActive", true);
var participants = firstSyncDomain.DomainParticipants;
int count = participants.Count;
participants.Add(toBeAdded);
foreach (NetworkInterface networkIf in participants)
{
// do something at the interface
}
newSyncDomain.Delete();

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


264 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

5.8 Functions on devices

5.8.1 Mandatory attributes of devices

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Every device or device item provides certain mandatory attributes which can be read and/or
written. These attributes are always the same as in the TIA Portal user interface.
The following attributes are supported in Openness:

Attribute name Data type Writeable Access Comment


Author string read/write dynamic
Comment string read/write dynamic sometimes only read access
CommentML MultilingualTex‐ read/write dynamic sometimes only read access
tItem
IsGsd bool read TRUE, if the device description is instal‐
led via GSD/GSDML
Name string read/write sometimes only read access
TypeIdentifier string read
TypeName string read dynamic

Program code: Mandatory attributes of a device


Modify the following program code to get the mandatory attributes of a device:

Device device = ...;


string nameValue = device.Name;
bool isGsdValue = device.IsGsd;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 265
TIA Portal Openness API
5.8 Functions on devices

Program code: Mandatory attributes with dynamic access


Modify the following program code to get the attributes item with dynamic access:

Device device = ...;


var attributeNames = new[] {
"TypeName", "Author", "Comment"
};
foreach (var attributeName in attributeNames) {
object attributeValue = ((IEngineeringObject)device).GetAttribute(attributeName);
}

5.8.2 Get type identifier of devices and device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The attribute TypeIdentifier is used to identify a hardware object that is creatable via TIA
Portal Openness API. The TypeIdentifier is a string consisting of several
parts: <TypeIdentifierType>:<Identifier>
Possible values for TypeIdentifierType are:
• OrderNumber
• GSD
• System

Openness: API for automation of engineering workflows


266 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

OrderNumber
OrderNumber is the common TypeIdentifier for all modules present in the hardware
catalog.

Format of type identifier Example Specifics


<OrderNumber> OrderNumber:3RK1 200-0CE00-0AA2 -
<OrderNumber>/<FirmwareVersion> OrderNumber:6ES7 510-1DJ01-0AB0/ Firmware version is optional in case
V2.0 it does not exist or there is only one
versionexisting in the system. Be
care
<OrderNumber>// OrderNumber:6AV2 124-2DC01-0AX0// The additional type identifier might
<AdditionalTypeIdentifier> Landscape be necessary in case
that OrderNumber
and FirmwareVersion do not
lead to a unique match in the sys‐
tem.

Note
There are a few modules in the hardware catalog which use "wildcard" characters in the order
number to represent a certain cluster of real hardware, e.g. the different lengths of S7-300 racks.
In this case the specific OrderNumber and the "wildcard"-OrderNumber can both be used to
create an instance of the hardware object. However you cannot generically use wildcards at any
position.

GSD
This is the identifier used for modules that are added to the TIA Portal via GSD or GSDML.

Format of type identifier Example Specifics


<GsdName>/<GsdType> GSD:SIEM8139.GSD/DAP GsdName is the name of the GSD or GSDML in upper‐
<GsdName>/<GsdType>/<GsdId> GSD:SIEM8139.GSD/M/4 case letters.
GsdType is one of the following:
• D: Device
• R: Rack
• DAP: HeadModule
• M: Module
• SM: Submodule
GsdId is a identifier for the type.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 267
TIA Portal Openness API
5.8 Functions on devices

System
This is the identifier for objects, which cannot be determined using OrderNumber or GSD.

Format of type identifier Example Specifics


<SystemTypeIdentifier> System:Device.S7300SystemTypeIdentifier is the primary
<SystemTypeIdentifier>/ GSD:SIEM8139.GSD/M identifier of an object.
<AdditionalTypeIdentifier> /4 AdditionalTypeIdentifier might be
necessary in case
the SystemTypeIdentifier is not
unique. The prefix for certain object types
are:
• Connection.
• Subnet.
• Device.
• Rack.

Program code
Modify the following program code to get the type identifier for user manageable and separately
creatable objects for GSD:

HardwareObject hardwareObject = ...;


string typeIdentifier = hardwareObject.TypeIdentifier;

Openness: API for automation of engineering workflows


268 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

Displaying type identifiers in TIA Portal


If you need to know a type identifier you inquire it in TIA Portal as follows:
1. Enable the setting "Enable display of the type identifier for devices and modules" in "Options
> Settings > Hardware configuration > Display of the type identifier".
2. Open the editor "Devices & networks".
3. Select a device in the Catalog.
The type identifier is displayed in the viewlet "Information"

5.8.3 Set App ID on device and device Items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal
• A project is open
See Opening a Project

Introduction
You can use the TIA Portal Openness to set the Application ID on device and device items of TIA
Portal project, so that these Application IDs are retained in the current session of TIA Portal for
later use.
You can use the TIA Portal Openness to set the Application ID by providing "Application Key" and
"Application Value" pair to the API.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 269
TIA Portal Openness API
5.8 Functions on devices

The following constraints applicable for the Application ID of device and device item object:
• An object of type supporting this feature can have maximum of 64 Application IDs available
for it
• The Application IDs Key or/and Value length can be maximum 128 Characters in length.
• The Application ID Key for a given object is unique
• Only one Application ID can be set using one "Application Key"
• When different Application Value is set with the same "Application Key", the last set
Application Value is retained

Program code
Modify the following program code to set the Application ID for device and device item object:

Device device = ...;


// Ask for Service CustomIdentityProvider on the device/device item
var customIdentityProviderService = device.GetService<CustomIdentityProvider>();
//Set the Application ID (Key-Value) pair
customIdentityProviderService.Set("Application_Key", "Application_Value");

5.8.4 Get App ID on device and device Items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Introduction
You can use the TIA Portal Openness to get the Application ID on device and device items of TIA
Portal project, if the device or device items is already set with an Application ID.
Application IDs are stored as "Application Key" and "Application Value" pair as part of TIA Portal.
You can use the TIA Portal Openness to get the Application ID value by providing "Application
Key".

Openness: API for automation of engineering workflows


270 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

Program code
Modify the following program code to get the Application ID value for an object, which was
already set using the Application Key:

Device device = ...;


// Ask for Service CustomIdentityProvider on the device/device item
var customIdentityProviderService = device.GetService<CustomIdentityProvider>();
customIdentityProviderService.Set("Application_Key", "Application_Value");
//Get the Application ID (Value) for the given Application Key
var applicationValue = customIdentityProviderService.Get("Application_Key");

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.8.5 Remove App ID on device and device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Principle
You can use the TIA Portal Openness to remove Application ID (Custom Identity) for a device and
device items of TIA Portal project, so that device and device item objects are updated with
relevant Application ID.
A CustomIdentityNotFoundException will be thrown, if the Application ID which is passed as an
argument does not exist.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 271
TIA Portal Openness API
5.8 Functions on devices

Program code
Modify the following program code to remove the Application ID for device and device items:

Device device = ...;


// Ask for Service CustomIdentityProvider on the device/device item
var customIdentityProviderService = device.GetService<CustomIdentityProvider>();
//Remove the CustomIdentity corresponding to Application ID
try
{
customIdentityProviderService.Remove("Application_Key");
}
catch(CustomIdentityNotFoundException ex)
{
// When CustomIdentity is not found for a the given key "Application_Key".
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.8.6 Creating a device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A device can be created via two methods, within a project or a device group:
• Create a device via a device item type identifier like in TIA hardware catalog
Device CreateWithItem(DeviceItemTypeId, DeviceItemName,
DeviceName)
• Create only the device
Device Create(DeviceTypeId, DeviceName)

Name Type Description


DeviceItemTypeId string Type identifier of the device item
DeviceTypeId string Type identifier of the device
DeviceItemName string Name of the created device item
DeviceName string Name of the created device

Openness: API for automation of engineering workflows


272 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

See: Type identifier (Page 266)

Program code: Create device with type identifier


Modify the following code to create a device object via a type identifier:

DeviceComposition devices = ...;


Device device = devices.CreateWithItem("OrderNumber:6ES7 510-1DJ01-0AB0/V2.0", "PLC_1",
"NewDevice");
Device gsdDevice = devices.CreateWithItem("GSD:SIEM8139.GSD/M/4 ", "GSD Module",
"NewGsdDevice");

Program code: Create only the device


Modify the following code to create only the device object:

DeviceComposition devices = ...;


Device deviceOnly = devices.Create("System:Device.S7300", "S7300Device");
Device gsdDeviceOnly = devices.Create("GSD:SIEM8139.GSD/D", "GSD Device");

5.8.7 Enumerating devices

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application: Enumerating devices


The TIA Portal Openness API positions devices similar to the project navigation in TIA Portal. PNV.
• Devices located as direct children of project are aggregated using the "Devices" composition
of the project
• Devices located in device folders are aggregated using the "Devices" composition of the
folder.

Note
Observe the Hierarchy of hardware objects of the object model (Page 65).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 273
TIA Portal Openness API
5.8 Functions on devices

Use one of the following options to enumerate the devices of a project:


• Enumerate all devices at root level
• Enumerate all devices in groups or sub-groups
• Enumerate all devices of a project that contains no device groups
• Enumerate all devices of the ungrouped device system groups
Examples of devices that can be enumerated:
• Central station
• PB-Slave / PN-IO device
• HMI Device

Program code: Enumerating devices at root level


Modify the following program code to enumerate devices at root level:

private static void EnumerateDevicesInProject(Project project)


{
DeviceComposition deviceComposition = project.Devices;
foreach (Device device in deviceComposition)
{
// add code here
}
}

Modify the following program code to access an individual device.

private static void AccessSingleDeviceByName(Project project)


{
DeviceComposition deviceComposition = project.Devices;
// The parameter specifies the name of the device
Device device = deviceComposition.Find("MyDevice");
}

Program code: Enumerating devices in groups or sub-groups


To access devices in a group, you have to navigate to the group at first, after that to the device.

Openness: API for automation of engineering workflows


274 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

Modify the following program code:

//Enamerate devices in groups or sub-groups


private static void EnumerateDevicesInGroups(Project project)
{
foreach (DeviceUserGroup deviceUserGroup in project.DeviceGroups)
{
EnumerateDeviceUserGroup(deviceUserGroup);
}
}
private static void EnumerateDeviceUserGroup(DeviceUserGroup deviceUserGroup)
{
EnumerateDeviceObjects(deviceUserGroup.Devices);
foreach (deviceUserGroup subDeviceUserGroup in deviceUserGroup.Groups)
{
// recursion
EnumerateDeviceUserGroup(subDeviceUserGroup);
}
}
private static void EnumerateDeviceObjects(DeviceComposition deviceComposition)
{
foreach (Device device in deviceComposition)
{
// add code here
}
}

Programm Code: Finding specific devices


Modify the following program code to find a specific device by name:

//Find a specific device by name


Project project = ...
Device plc1 = project.Devices.First(d => d.Name == "Mydevice");
... // Work with the device

Modify the following program code to find a specific device via "Find" method:

//Find a specific device via "Find" method


Project project = ...
Device plc1 = project.Devices.Find("MyDevice");
... // Work with the device

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 275
TIA Portal Openness API
5.8 Functions on devices

Program code: Enumerating devices of a project that contains no device groups


Modify the following program code:

//Enumerate all devices which are located directly under a project that contains no device
groups
Project project = ...
foreach (Device device in project.Devices)
{
... // Work with the devices
}

Program code: Enumerating all devices located in a folder


Modify the following program code:

//Enumerate all devices located in a folder


Project project = ...
DeviceUserGroup sortingGroup = project.DeviceGroups.Find ("Sorting");
Device plc1 = sortingGroup.Devices.First(d => d.Name == "MyStationName");
... // Work with the device

Program code: Enumerating devices of the ungrouped device system groups


To structure the projects, decentral devices have been put to the UngroupedDevices group. To
access this group, navigate to the group at first, after that to the device.
Modify the following program code:

//Enumerate devices of the ungrouped device system group


Project project = ...
DeviceSystemGroup group = project.UngroupedDevicesGroup;
Device plc1 = group.Devices.First(d => d.Name == "MyStationName");
... // Work with the device

5.8.8 Accessing devices

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


276 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

Application
Every GSD or GSDML based IO device has attributes. Some of them are used to identify the
specific type of the device.

Name Data type Writeable Access Description


Author string read/write dynamic -
Comment string read/write dynamic -
GsdName string read dynamic Name of the GSD or GSDML file.
GsdType string read dynamic Type of the hardware object. For devices
the value is always "D".
GsdId string read dynamic Specific identifier for the hardware object.
For devices always empty.
IsGsd bool read modeled TRUE in case of a GSD device or a GSDML
device
Name string read/write modeled -
TypeIdentifier string read modeled -

Program code: Get identification attributes


Modify the following program code to get the attributes:

Device device = ...;


var attributeNames = new[] {
"GsdName", "GsdType", "GsdId"
;
foreach (var attributeName in attributeNames) {
object attributeValue = device.GetAttribute(attributeName);
}

Program code: Attributes


Modify the following program code to get the attributes:

Device device = ...;


string nameValue = device.Name;
bool isGsdValue = device.IsGsd;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 277
TIA Portal Openness API
5.8 Functions on devices

Program code: Attributes with dynamic access


Modify the following program code to get the attributes:

Device device = ...;


var attributeNames = new[] {
"GsdName", "GsdType", "GsdId"
;
foreach (var attributeName in attributeNames) {
object attributeValue = device.GetAttribute(attributeName);
}

Specifics of GSD devices


If a device is a GSD device, it provides additional functionality. To get the GsdDevice feature, the
GetService method is used.

GsdDevice gsdDevice = ((IEngineeringServiceProvider)deviceItem).GetService<GsdDevice>();


if (gsdDevice != null) {
... // work with the GSD device
};

Program code: Attributes of a GSD device


Modify the following program code to get the attributes:

Device device = ...;


GsdDevice gsdDevice = ...;
string gsdId = gsdDevice.GsdId;
string gsdName = gsdDevice.GsdName;
string gsdType = gsdDevice.GsdType;
bool isProfibus = gsdDevice.IsProfibus;
bool isProfinet = gsdDevice.IsProfinet;

5.8.9 Deleting a device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


278 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.8 Functions on devices

Program code
Modify the following program code to delete a device:

Project project = ...;


Device deviceToDelete = project.UngroupedDevices.Devices.Find("......");

// delete device
deviceToDelete.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 279
TIA Portal Openness API
5.9 Functions on device items

5.9 Functions on device items

5.9.1 Mandatory attributes of device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Every device or device item provides certain mandatory attributes which can be read and/or
written. These attributes are always the same as in the TIA Portal user interface.
The following attributes are supported in TIA Portal Openness:

Attribute name Data type Writable Access Comment


Author string read/write dynamic -
Classification DeviceItemClassifi‐ read modeled The classification the device item belongs to, flags enum,
cation see Device item classification description below.
Comment string read/write dynamic sometimes only read access
CommentML MultilingualTextI‐ read/write dynamic sometimes only read access
tem
FirmwareVersion string read dynamic -
InterfaceOpera‐ InterfaceOpera‐ read/write dynamic For device items that provides the
tingMode tingModes feature NetworkInterface
InterfaceType NetType readwrite dynamic For device items that provides the
feature NetworkInterface
IsBuiltIn bool read modeled FALSE for objects creatable by the user
IsGsd bool read modeled TRUE, if the device description is installed via GSD/GSDML
IsPlugged bool read modeled TRUE for devices that are plugged
Label string read dynamic For device items that provides the feature NetworkPort
or NetworkInterface.
If the interface or port has no label Label will
be String.Empty.
LocationIdentifier string read/write dynamic -
Name string read/write modeled sometimes only read access
OrderNumber string read dynamic -
PlantDesignation string read/write dynamic -
PositionNumber int read modeled -
TypeIdentifier string read modeled -
TypeName string read dynamic The language independent type name. Optional for device
items that are not manageable by the user as auto-created
items or fixed sub-modules).

Openness: API for automation of engineering workflows


280 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Attribute name Data type Writable Access Comment


InstallationDate DateTime read/write dynamic -
AdditionalInfor‐ string read/write dynamic -
mation

Device item classification

Value Description
Siemens.Engineering.HW.DeviceItem‐ No classification.
Classifications.None
Siemens.Engineering.HW.DeviceItem‐ The device item is a CPU
Classifications.CPU
Siemens.Engineering.HW.DeviceItem‐ The device item is a head module.
Classifications.HM

Program code: Mandatory attributes of a device item


Modify the following program code to get the mandatory attributes of a device item:

DeviceItem deviceItem = ...;


string nameValue = deviceItem.Name;
string typeIdentfierValue = deviceItem.TypeIdentifier;
int positionNumberValue = deviceItem.PositionNumber;
bool isBuiltInValue = deviceItem.IsBuiltIn;
bool isPluggedValue = deviceItem.IsPlugged;

Program code: Mandatory attributes with dynamic access


Modify the following program code to get the attributes item with dynamic access:

Device device = ...;


var attributeNames = new[] {
"TypeName", "Author", "Comment", "OrderNumber", "FirmwareVersion", "PlantDesignation",
"LocationIdentifier"
};
foreach (var attributeName in attributeNames) {
object attributeValue = ((IEngineeringObject)deviceItem).GetAttribute(attributeName);
}

DeviceItem deviceItem = ...;


((IEngineeringObject)deviceItem).SetAttribute("Comment", "This is a comment.");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 281
TIA Portal Openness API
5.9 Functions on device items

5.9.2 Creating and plugging a device item

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The action PlugNew(string typeIdentifier, string name, int
positionNumber) of HardwareObject is used to
• create a new device item and plug it into an existing hardware object
• create a new sub device item, e.g. a submodule, and plug it into a device item
If the action was succseful it returns the created device item object, otherwise a recoverable
exception will be thrown.
By using the action CanPlugNew(string typeIdentifier, string name, int
positionNumber) you can determine if creating and plugging is possible. If executing is not
possible the action returns false.
If the method returns true, the action might still fail for the following unforeseen reasons.
• a position number is already taken by another device item
• the current device item cannot be plugged at the position although it is free
• the container does not provide the position number
• the name of the device item is already taken by an existing device item in the same container
• the device item cannot be plugged into the container
• the device is online

The following table shows the needed method parameters:

Name Type Description


typeIdentifier string type identifier of the created device item
name string name of created device item
positionNumber int position number of the created device
item

Openness: API for automation of engineering workflows


282 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Program code
Modify the following program code to plug a device item into an exisitng hardware object:

HardwareObject hwObject = ...;


string typeIdentifier = ...;
string name = ...;
int positionNumber = ...;
if(hwObject.CanPlugNew(typeIdentifier, name, positionNumber))
{
DeviceItem newPluggedDeviceItem = hwObject.PlugNew(typeIdentifier, name,
positionNumber);
}

Accessing module information


The TIA Portal Openness user can access information about the pluggable modules using
ModuleInformationProvider object. The user can access
• the container types in which a specified module has to be plugged (ex. Device and Rack)
using FindContainerTypes method.
• the available versions for a certain partly specified module using FindModuleTypes method.

Program code: Accessing ModuleInformationProvider object

Project project = ...;


HardwareUtilityComposition extensions = project.HwUtilities;
var result = extensions.Find("ModuleInformationProvider") as ModuleInformationProvider;

Program code: Accessing container types using FindContinerTypes method


FindContinerTypes method returns the continer types of a given module. The module is
speicified uisng typeIdentifier parameter. The resulting list contains the TypeIdentifiers of all
container types of the requested type. Usually this includes a Device and a Rack and the
containers are given in their order of the hierarchy in the project, beginning with the Device.

Name of the parameter Type Description


typeIdentifier string type identifier of a device item.

NOTICE
This method works only for the modules visible in the network view.
This method works only for modules, and not for sub-modules.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 283
TIA Portal Openness API
5.9 Functions on device items

string typeIdentifier = ...;


string[] containerTypes = moduleInformationProvider.FindContainerTypes(typeIdentifier);

Program code: Accessing versions using FindModuleTypes method


FindModuleTypes method returns all possible versions of a hardware object using partial type
identifier of the device item. This method returns a list of strings. Each string will be the complete
TypeIdentifier of a possible match for the partial TypeIdentifier.
A valid partial type identifier must contain only complete parts, where each complete part is
separated by "/" in the type identifier. Wildcards or incomplete parts are not supported. Also the
following constraints with respect to the minimal number of specified parts must be observed:
• OrderNumber: at least one part. Ex. OrderNumber:6ES7 317-2EK14-0AB0
• GSD: at least two parts. Ex. GSD:SI05816A.GSD/M
• System: at lease one part. Ex. System:Rack.ET200SP

Name of the parameter Type Description


partialTypeIdentifier string partial type identifer of a device
item

string partialTypeIdentifier = ...;


string[] moduleTypes = moduleInformationProvider.FindModuleTypes(partialTypeIdentifier);

Program code: Accessing plug locations using GetPlugLocations method


GetPlugLocations method returns the information about slots such as plug location, position
number (designation of a slot), and available slots for the hardware object.
The class PlugLocation has the following peroperites.

Name of the property Type Description


PositionNumber int The position number of the free
slot
Label string The label of the free slot

• In case no "label" exists for a certain position number, the string representation of the
position number is used.
• PlugLocation objects are provided only for free slots.

Openness: API for automation of engineering workflows


284 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

HardwareObject hardwareObject = ...;


IList<PlugLocation> result = hardwareObject.GetPlugLocations();
foreach (PlugLocation item in result)
{
Console.WriteLine("{0} - {1}", item.PositionNumber, item.Label);
}

5.9.3 Moving device items into another slot

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The action PlugMove(DeviceItem deviceItem, int positionNumber) of HardwareObject is used to
move an existing device item and plug it to an existing hardware object. The method PlugMove
inserts the device items where the module was unable to plug in the UI. In these cases, there
PlugMove action completes with complie errors.
The action CanPlugMove(DeviceItem deviceItem, int positionNumber) is used to determine
possiblity of movement. If the movement is not possible, CanPlugMove returns false. If the
method returns true, the action might still fail for the following unforeseen reasons.
• a position number is already taken by another device item
• the current device item cannot be plugged at the position although it is free
• the container does not provide the position number
• the name of the device item is already taken by an existing device item in the same container
• the device item cannot be plugged into the container
• the device item cannot be plugged by the user
• the device item cannot be removed by the user
• the device is online

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 285
TIA Portal Openness API
5.9 Functions on device items

Program code
Modify the following program code:

HardwareObject hwObject = ...;


DeviceItem deviceItemToMove = ...;
int positionNumber = ...;
if(hwObject.CanPlugMove(deviceItemToMove, positionNumber)
{
DeviceItem movedDeviceItem = hwObject.PlugMove(deviceItemToMove, positionNumber);
}

5.9.4 Copying a device item

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Use the action PlugCopy(DeviceItem deviceItem, int positionNumber) of HardwareObject to
copy a device within a project and to plug it into an existing hardware. In rare cases the method
PlugCopy might work where it is not possible to plug a module in the UI. In this case compile
errors will occur after the copy. When PlugCopy was successful it returns the copy of the device
item object, otherwise a recoverable exception is thrown.
Possible reasons for a failed action:
• a position number is already used by another device item
• the current device item cannot be plugged at the position although it is free
• the container does not provide the position number
• the name of the device item is already used by an existing device item in the same container
• the device item cannot be plugged into the container
• the device item cannot be plugged in the UI
• ...
Use the action CanPlugCopy(DeviceItem deviceItem, int positionNumber) is it possible to
determine if copying should be possible. When it is not possible to execute the copy action
CanPlugCopy returns false. However if the method returns true the action might still fail for
unforeseen reasons.

Openness: API for automation of engineering workflows


286 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Name of the parameter Type Description


deviceItem DeviceItem Device item to copy
positionNumber int position number for the copy of
the device item

Program code
Modify the following program code:

HardwareObject hwObject = ...;


DeviceItem deviceItemToCopy = ...;
int positionNumber = ...;
if(hwObject.CanPlugCopy(deviceItemToCopy, positionNumber))
{
DeviceItem copiedDeviceItem = hwObject.PlugCopy(deviceItemToCopy, positionNumber);
}

5.9.5 Deleting a device item

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to delete a device item:

Project project = ...;


var device = project.UngroupedDevicesGroup.Devices.Find("......");
var deviceItem = deviceItem.DeviceItems.First();

// delete device item


deviceItem.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 287
TIA Portal Openness API
5.9 Functions on device items

5.9.6 Enumerate device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
To get to a device item use the HardwareObject. The items of a hardware objects are, what the
user of the TIA Portal sees as being plugged into the hardware object:
• a rack which resides in a device
• a module which resides in a rack
• a sub module which resides in a module
• a sub module which resides in a sub module

Note
You can find more detailed information on this topic in the section Hierarchy of hardware objects
of the object model (Page 65).

Program code: Enumerating device items of a device


Modify the following program code to enumerate device items of a hardware object:

private static void EnumerateDeviceItems(HardwareObject hardwareObject)


{
foreach (DeviceItem deviceItem in hardwareObject.Items)
{
// add code here
}
}

Openness: API for automation of engineering workflows


288 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Program code: Enumerating with composition hierarchy


Modify the following program code if you want to enumerate the device items of a device by
means of the composition hierarchy:

//Enumerates devices using an composition


private static void EnumerateDeviceItems(Device device)
{
DeviceItemComposition deviceItemComposition = device.DeviceItems;
foreach (DeviceItem deviceItem in deviceItemComposition)
{
// add code here
}
}

Program code: Enumerating devices items using an association


Modify the following program code to enumerate the device items using an association:

//Enumerates devices using an association


private static void EnumerateDeviceItemsWithAssociation(Device device)
{
DeviceItemAssociation deviceItemAssociation = device.Items;
foreach (DeviceItem deviceItem in deviceItemAssociation)
{
// add code here
}
}

5.9.7 Accessing device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application: Accessing device items


To access objects of the type "DeviceItem" use the following attributes:
• Name (string): the name of the device item
• Container (HardwareObject): the container into which the device item is plugged

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 289
TIA Portal Openness API
5.9 Functions on device items

Name Data type Writeable Access Description


Author string read/write dynamic -
Comment string read/write dynamic -
FirmwareVersion string read dynamic Only for head modules
GsdName string read dynamic Name of the GSD file.
GsdType string read dynamic Type of the hardware object. For devices
the value is always "D".
GsdId string read dynamic Specific identifier for the hardware object.
For devices always empty.
IsBuiltIn bool read - -
IsGsd bool read modeled TRUE in case of a GSD device or a GSDML
device
IsPlugged bool read modeled -
IsProfibus bool read modeled -
IsProfinet bool read modeled -
Name string read/write modeled -
OrderNumber string read dynamic Only for head modules
PositionNumber bool read modeled -
TypeIdentifier string read modeled -

Program code: Accessing a device item


Modify the following program code to access a device item:

public static DeviceItem AccessDeviceItemFromDevice(Device device)


{
DeviceItem deviceItem = device.DeviceItems[0];
return deviceItem;
}

Program code: Accessing a device item of a device item


Modify the following program code to access a device item of a device item:

public static DeviceItem AccessDeviceItemFromDeviceItem(DeviceItem deviceItem)


{
DeviceItem subDeviceItem = deviceItem.DeviceItems[0];
return subDeviceItem;
}

Openness: API for automation of engineering workflows


290 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Program code: Navigating to the container of a device item


Modify the following program code to navigate back to the container of a device item via the
"Container" attribute of DeviceItem:

DeviceItem deviceItem = ...;


HardwareObject container = deviceItem.Container;

Program code: Get identification attributes


Modify the following program code to get the attributes:

Device device = ...;


var attributeNames = new[] {
"GsdName", "GsdType", "GsdId" };
foreach (var attributeName in attributeNames) {
object attributeValue = ((IEngineeringObject)deviceItem).GetAttribute(attributeName);
}

Program code: Get attributes


Modify the following program code to get the attributes:

DeviceItem deviceItem = ...;


GsdDeviceItem gsdDeviceItem =
((IEngineeringServiceProvider)deviceItem).GetService<GsdDeviceItem>();

string gsdName = gsdDeviceItem.GsdName;


string gsdType = gsdDeviceItem.GsdType;
string gsdId = gsdDeviceItem.GsdId;
bool isProfinet = gsdDeviceItem.IsProfinet;
bool isProfibus = gsdDeviceItem.IsProfibus;;

Program code: Get attributes with dynamic access


Modify the following program code to get the attributes:

DeviceItem deviceItem = ...;


GsdDeviceItem gsdDeviceItem =
((IEngineeringServiceProvider)deviceItem).GetService<GsdDeviceItem>();

var attributeNames = new[] {


"TypeName", "Author", "Comment", ...
;
foreach (var attributeName in attributeNames) {
object attributeValue =
((IEngineeringObject)gsdDeviceItem).GetAttribute(attributeName);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 291
TIA Portal Openness API
5.9 Functions on device items

Program code: Set attributes


Modify the following program code to set the attributes:

DeviceItem deviceItem = ...;


((IEngineeringObject)deviceItem).SetAttribute("Comment", "This is a comment.");

Program code: Get prm data of a head module


Modify the following program code to get the prm data:

DeviceItem deviceItem = ...;


GsdDeviceItem gsdDeviceItem =
((IEngineeringServiceProvider)deviceItem).GetService<GsdDeviceItem>();

int dsNumber = 0; // For Profibus GSDs, dataset number zero must be used!
int byteOffset = 0;
int lengthInBytes = 5;

// read complete data set:


byte[] prmDataComplete = gsdDeviceItem.GetPrmData(dsNumber, byteOffset, lengthInBytes);

// read partial data set (only second byte):


byteOffset = 1;
lengthInBytes = 1;
byte[] prmDataPartial = gsdDeviceItem.GetPrmData(dsNumber, byteOffset, lengthInBytes);

Program code: Set prm data of a head module


Modify the following program code to get the prm data:

DeviceItem deviceItem = ...;


GsdDeviceItem gsdDeviceItem =
((IEngineeringServiceProvider)deviceItem).GetService<GsdDeviceItem>();

// The parameters byteOffset and the length of the byte array prmData define the range
within the
// dataset which is written to.
// For Profibus GSDs, dataset number zero must be used!

// Change the highlighted bytes 2-4 from 0x0 to 0x1


// to write only the first two bytes: byte[] prmData = {0x05, 0x21};

int dsNumber = 0;
int byteOffset = 0;
byte[] prmData = {0x05, 0x21, 0x01, 0x01, 0x01};

gsdDeviceItem.SetPrmData(dsNumber, byteOffset, prmData);

Openness: API for automation of engineering workflows


292 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

See also
Hierarchy of hardware objects of the object model (Page 65)

5.9.8 Accessing device item as interface

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
If a device item is an interface, it provides additional functionalities over a simple device item.
Using this interface, the user can access the nodes and operation mode of the interface. Due to
this functionality, the device item can used as IoDevice (Slave) or IoController (Master) by
accessing the NetworkInterface feature (a specific Service of the device item).
The properities of the interface is accessed using enum InterfaceOperatingModes.

Value Description
InterfaceOperatingModes.None Default
InterfaceOperatingModes.IoDevice Interface operation mode "IoDevice" (Slave).
InterfaceOperatingModes.IoController Interface operation mode "IoController" (Master).
InterfaceOperatingModes.IoDevice Interface operation made both of the above.
or
InterfaceOperatingModes.IoController

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 293
TIA Portal Openness API
5.9 Functions on device items

Program code: Accessing the network interface feature


Modify the following program code to get the network interface feature

NetworkInterface itf =
((IEngineeringServiceProvider)deviceItem).GetService<NetworkInterface>();
if (itf != null)
{
... // work with the interface
}

//Accessing nodes and operating mode


NodeComposition nodes = itf.Nodes;
InterfaceOperationModes mode = itf.InterfaceOperatingMode;

//Accessing the type of interface


NetType itfType = itf.InterfaceType;

//Modififying the operating mode and interface type


itf.InterfaceOperatingMode = InterfaceOperatingModes.IoDevice;
itf.InterfaceType = NetType.Profibus

//Accessing the ports linked to an interface.


NetworkPortAssociation nodes = itf.Ports;

5.9.9 Accessing attributes of an I/O device interface

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• For writing access, the PLC is offline.

Application
You can use the TIA Portal Openness API interface to get or set attributes for IRT ans isochronous
mode on the I/O device interface.

Access to the interface of an I/O controller


The following attributes can be accessed to the interface of an I/O controller. The controller has
to be the sync master:

Attribute name Data type Writeable Access Description


PnSendClock Int64 r/w Dynamic attribute Send clock in nanoseconds

Openness: API for automation of engineering workflows


294 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Access to the interface of an I/O system


The following attributes can be accessed to the interface of an I/O system. The Ti/To values can
be used by all modules and sub modules which belong to the I/O system.

Attribute name Data type Writeable Access


IsochronousTiToAutoCalculation BOOL r/w Dynamic attribute
IsochronousTi DOUBLE r/w Dynamic attribute
IsochronousTo DOUBLE r/w Dynamic attribute

Access to the interface of an I/O device


The following attributes can be accessed to the interface of an I/O device. The Ti/To values can
be used by all modules and submodules which belong to the I/O sytem.

Attribute name Data type Writeable Access


IsochronousMode BOOL r/w Dynamic attribute
IsochronousTiToCalculationMode IsochronousTiToCal‐ r/w Dynamic attribute
culationMode
IsochronousTi DOUBLE r/w Dynamic attribute
IsochronousTo DOUBLE r/w Dynamic attribute

The following ENUM values are provided for the attribute


IsochronousTiToCalculationMode:

Value Description
IsochronousTiToCalculationMode.None -
IsochronousTiToCalculationMode.FromOB Ti/To values of the OB (configured at the IoSystem) are used.
IsochronousTiToCalculationMode.FromSubnet This value is not used by PROFINET interfaces.
IsochronousTiToCalculationMode.AutomaticMini Ti/To values are calculated automatically for the IO Device.
mum
IsochronousTiToCalculationMode.Manual The user can enter Ti/To values for this IO Device manually.

Program code: Get or set attributes of an I/O device interface


Modify the following program code to access the send clock value:

DeviceItem pnInterface = ...;


// read attribute
long attributeValue = (long)pnInterface.GetAttribute("PnSendClock");
// write attribute
long sendClock = 2000000;
pnInterface.SetAttribute("PnSendClock", sendClock);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 295
TIA Portal Openness API
5.9 Functions on device items

Modify the following program code to access the Ti/To values of OB:

IoSystem ioSystem = ...;


bool titoAutoCalculation = (bool)ioSystem.GetAttribute("IsochronousTiToAutoCalculation");
ioSystem.SetAttribute("IsochronousTiToAutoCalculation", true);

Modify the following program code to access the isochronous setting of an I/O device interface:

DeviceItem pnInterface = ...;


bool isochronousMode = (bool)pnInterface.GetAttribute("IsochronousMode");
pnInterface.SetAttribute("IsochronousMode", true);

5.9.10 Accessing attributes of IoController

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• For writing access, the PLC is offline.

Application
You can use the TIA Portal Openness API interface to get or set attributes for IoController. The
following attributes are only available at PROFINET IoController (located below a Profinet
interface). If the user can modify an attribute in UI, then the user can set the corresponding
attribute through TIA Portal Openness.

Attribute name Data type Type Access Description


SyncRole SyncRole Read-write Dynamic attribute -
PnDeviceNumber int Read-only Dynamic attribute In TIA Portal UI, this
property is located
at the ethernet
node (PROFINET
section)

The Synchronication role property is available in PROFINET interface of the TIA Portal UI. The
Enum SyncRole has the following values.

Openness: API for automation of engineering workflows


296 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Enum value Numerical value


SyncRole.NotSynchronized 0
SyncRole.SyncMaster 1
SyncRole.SyncSlave 2
SyncRole.RedundantSyncMaster 4

Program code: Setting attributes of IoController

IoController ioController= ...;


SyncRole syncRole = (SyncRole)((IEngineeringObject)ioController).GetAttribute("SyncRole");
((IEngineeringObject)ioController).SetAttribute("SyncRole", SyncRole.SyncMaster);

5.9.11 Accessing attributes of IoConnector

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• For writing access, the PLC is offline.

Application
You can use the TIA Portal Openness API interface to get or set attributes for IoConnector. The
following attributes are only available at PROFINET IoController (located below a Profinet
interface). If the user can modify an attribute in UI, then the user can set the corresponding
attribute through TIA Portal Oopenness.
There are four types of attributes such as update time attributes, watchdog time attributues,
synchronization attributes and , device number attributes.

Update time attributes


The update time attributes are given below.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 297
TIA Portal Openness API
5.9 Functions on device items

Attribute name Data type Type Access Description


PnUpdateTimeAutoCal‐ Boolean Read-write Dynamic attribute If this attribute is true,
culation then the update time is
calculated automatical‐
ly.
PnUpdateTime Int64 Read-write Dynamic attribute Update time is meas‐
ured in nano seconds.
PnUpdateTimeAdap‐ Boolean Read-write Dynamic attribute -
tion

Watchdog time attributes


The watchdog time attributes are given below.

Attribute name Data type Type Access Description


PnWatchdogFactor Int32 Read-write Dynamic attribute -
PnWatchdogTime Int64 Read-only Dynamic attribute Watchdog time is meas‐
ured in nano seconds.

Synchronization attributes
The synchronization attributes are given below.

Attribute name Data type Type Access Description


RtClass RtClass Read-write Dynamic attribute -
SyncRole SyncRole Read-only Dynamic attribute -

The Enum RtClass has following values.

Enum value Numerical value


RtClass.None 0
RtClass.RT 1
RtClass.IRT 2

The Enum SyncRole has following values.

Enum value Numerical value


SyncRole.NotSynchronized 0
SyncRole.SyncMaster 1
SyncRole.SyncSlave 2
SyncRole.RedundantSyncMaster 4

Openness: API for automation of engineering workflows


298 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Device number attributes


The device number attributes are given below.

Attribute name Data type Type Access Description


PnDeviceNumber int Read-Write Dynamic attribute Indicates the device
number.

Program code: Getting and setting attributes of IoConnector

IoConnector connector = ...

var attributeNames = new[] {


"PnUpdateTimeAutoCalculation", "PnUpdateTime", "PnUpdateTimeAdaption", "PnWatchdogFactor",
"PnWatchdogTime", "RtClass", "SyncRole"
};

foreach (var attributeName in attributeNames)


{
object attributeValue = ((IEngineeringObject)connector ).GetAttribute(attributeName);
}

connector.SetAttribute("PnUpdateTimeAutoCalculation", true);

See also
Opening a project (Page 113)

5.9.12 Accessing address controller

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
If a device item is an address controller, it provides additional functionality. To access the
registered addresses of the address controller the role AddressController is used.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 299
TIA Portal Openness API
5.9 Functions on device items

Program code: Get the address controller


Modify the following program code to get the address controller role:

AddressController addressController =
((IEngineeringServiceProvider)deviceItem).GetService<AddressController>();
if (addressController != null)
{
... // work with the address controller
}

Attributes of an address controller


The attributes of an address controller are:
• RegisteredAddresses
Modify the following program code to get the attributes of an address controller:

AddressController addressController = ...;


foreach (Address registeredAddress in addressController.RegisteredAddresses)
{
...
}

5.9.13 Accessing addresses

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Address objects are aquired via the composition link Addresses of a device item. The
attribute Addresses returns a collection of type AddressComposition which can be
enumerated.

Openness: API for automation of engineering workflows


300 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Program code: Get an address of a device item


To get the address of a device item modify the following program code:

AddressComposition addresses = deviceItem.Addresses;


foreach(Address address in addresses)
{
// work with the address
}

Program code: Get an address of an io controller


To get the address of an io controller modify the following program code:

AddressComposition addresses = ioController.Addresses;


foreach(Address address in addresses)
{
// work with the address
}

Attributes
An address supports the following attributes:

Attribute name Data type Writeable Access Comment


AddressControllers AddressControllerAssoci‐ read - -
ation
Context enum: AddressContext read dynamic only for diagnosis addresses an for special de‐
vice items
IoType enum: AddressIoType read - -
StartAdress Int32 read/write modeled -
Length Int32 read - -

Value Description
AddressIoType.Diagnosis The type of the address io is Diagnosis.
AddressIoType.Input The type of the address io is Input.
AddressIoType.Output The type of the address io is Output.
AddressIoType.Substitute The type of the address io is Substitute.
AddressIoType.None The type of the address io is mot specified.

Value Description
AddressContext.None The address context is not applicable.
AddressContext.Device A device address context.
AddressContext.Head A head address context.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 301
TIA Portal Openness API
5.9 Functions on device items

Program code: Read attributes


Modify the following program code to get the attributes:

AddressControllerAssociation addressControllers = address.AddressControllers;


Int32 startAddress = address.StartAddress;
AddressIoType addressType = address.IoType;
Int32 adressLength = address.Length;

Program code: Write attributes


Modify the following program code to write the attributes:

Address addressControllers = ...;


address.StartAddress = intValueStartAddress;

Program code: Attributes with dynamic access


Modify the following program code to get the attributes:

Address address= ...;


object attributeValue = ((IEngineeringObject)address).GetAttribute("Context");

5.9.14 Accessing hardware identifiers

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Hardware identifier objects are acquired from the following objects:
• Device
• DeviceItem
• IoSystem
The hardware identifier is represented by the class HwIdentifier and is accessed via the
attribute HwIdentifiers.

Openness: API for automation of engineering workflows


302 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Program code: Get the hardware identifier


To make HwIdentifier available modify the following program code:

var hwObject = ...


foreach(HwIdentifier hardwareIdentifier in hwObject.HwIdentifiers)
{
// Work with the HwIdentifer
}

Attributes of a hardware identifier

HwIdentifierControllerAssociation controllers = hwIdentifier.HwIdentifierControllers;


Int64 Identifier = hwIdentifier.Identifier;

5.9.15 Accessing hardware identifier controller

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
If a device item is an hardware identifier controller, it is possible to access the registered
hardware identifiers. To access these HwIdentifierController, a specific service of the device item,
is used.

Program code: Get the hardware identifier controller


To get the HwIdentifierController modify the following program code:

HwIdentifierController hwIdentifierController =
((IEngineeringServiceProvider)deviceItem).GetService<HwIdentifierController>();
if (hwIdentifierController != null)
{
... // work with the hardware identifier controller
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 303
TIA Portal Openness API
5.9 Functions on device items

Program code: Attributes of a hardware identifier controller


The attributes of an address controller are:
• RegisteredHwIdentifiers: The hardware identifier controllers where the hardware
identifier is registered.
Modify the following program code to get the attributes of an address controller:

HwIdentifierController hwIdentifierController = ...;


HwIdentifierAssociation controllers = hwIdentifierController.RegisteredHwIdentifiers;

5.9.16 Accessing channels of device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A channel is represented by the Channel class. Channels are aquired from a device item via the
attribute Channels of the DeviceItem class. The attribute Channels returns an implementation of
ChannelComposition which can be enumerated. If the device items has no channels, the
attribute Channels returns an empty collection.

Mandatory attributes
A channel supports the following mandatory attributes:

Attribute name Data type Writeable Access Comment


IoType ChannelIoType read modelled -
Type ChannelType read modelled -
Number Int32 read modelled -
ChannelAddress Int32 read dynamic Address of the channel in bits
ChannelWidth UInt32 read dynamic Width of the channel in bits

Openness: API for automation of engineering workflows


304 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Program code: Get channels of device item


Modify the following program code to get the channels of a device item:

ChannelComposition channels = deviceItem.Channels


foreach(Channel channel in channels)
{
// work with the channel
}

Program code: Mandatory attributes of a channel


Modify the following program code to get the channels of a device item:

Channel channel = ...;


int channelNumber = channel.Number;
ChannelType type = channel.Type;
ChannelIoType ioType = channel.IoType;

Program code: Get values of attributes with dynamic access


Modify the following program code to get the values of dynamic attributes:

Channel channel = ...;


Int32 channelAddress = (Int32)((IEngineeringObject)channel).GetAttribute("ChannelAddress");
UInt32 channelWidth = (UInt32)((IEngineeringObject)channel).GetAttribute("ChannelWidth");

Program code: Set value of a dynamic attribute


Modify the following program code to set the value of a writeable dynamic attribute:

Channel channel = ...;


((IEngineeringObject)channel).SetAttribute("AnAttribute", 1234);

5.9.17 Creating and exporting psc file

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• Opening a Project
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 305
TIA Portal Openness API
5.9 Functions on device items

Application
You can use the TIA Portal Openness API to create .psc file and download a device into it. In order
to create a.psc file and download a device configuration into it, you can use Export method from
a service CardReaderPscProvider. The service exists in namespace
Siemens.Engineering.HW.Utilities.

Program code
Modify the following program code to create and export a .psc file.

// preconditions
Device ipcDevice = myProject.Devices.Find("IPC427D");
FileInfo exportFile = new FileInfo(@"C:\Users\Ertan\Documents\Automation\PC system
configuration74.psc");
// get the card reader provider from hardware utilities
HardwareUtilityComposition utilities = myProject.HwUtilities;
HardwareUtility utility = utilities.Find("CardReaderPscProvider");
CardReaderPscProvider crp = (CardReaderPscProvider)utility;
// do the export
crp.Export(ipcDevice, exportFile);

Creating and openning a .psc file with separate commands are not supported. In case you give
already existing .psc file as a parameter, the file will not be overwritten and exception will be
thrown. If it is not an existing file, then this .psc file will be created and finally the download will
be made.
You have to make sure that the project can be compiled without problems. Otherwise, exception
will be thrown.

Note
Because of safety reasons, Export operation is not supported for f-activated devices (an
exception will be thrown during export) in V15.1

5.9.18 Connection handling for extension racks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


306 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.9 Functions on device items

Application
You can use the TIA Portal Openness to fetch, add, and remove extension rack connections so
that you can make use of TIA Portal Openness to implement extension rack connection support
during CAx export/import.

Program code

ImConnection imConnection = portDeviceItem.GetService<ImConnection>();


imConnection.Connect(partnerport);
imConnection.Disconnect();
imConnection.GetPartnerPort();
var imConnectionOwner = imConnection.OwnedBy;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 307
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

5.10 Functions for accessing the data of an HMI device

5.10.1 Screens

5.10.1.1 Creating user-defined screen folders

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to create a user-defined screen folder:

//Creates a screen folder


private static void CreateScreenFolder(HmiTarget hmitarget)
{
ScreenUserFolder myCreatedFolder =
hmitarget.ScreenFolder.Folders.Create("myScreenFolder");
}

5.10.1.2 Deleting a screen from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application

Note
You cannot delete a permanent area. A permanent area is a system screen that is always present.

Openness: API for automation of engineering workflows


308 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

Program code
Modify the following program code to delete a screen from a specific folder:

public static void DeleteScreenFromFolder(HmiTarget hmiTarget)


{
ScreenUserFolder screenUserFolder =
hmiTarget.ScreenFolder.Folders.Find("myScreenFolder");
ScreenComposition screens = screenUserFolder.Screens;
Screen screen = screens.Find("myScreenName");
if (screen != null)
{
screen.Delete();
}
}

5.10.1.3 Deleting a screen template from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Program code
Modify the following program code to delete a screen template from a specific folder:

private static void DeleteScreenTemplateFromFolder(HmiTarget hmiTarget)


{
string templateName = "MyScreenTemplate";
ScreenTemplateUserFolder folder =
hmiTarget.ScreenTemplateFolder.Folders.Find("myScreenTemplateFolder");
ScreenTemplateComposition templates = folder.ScreenTemplates;
ScreenTemplate template = templates.Find(templateName);
if (template != null)
{
template.Delete();
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 309
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

5.10.1.4 Deleting all screens from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application

Note
You cannot delete a permanent area. A permanent area is a system screen that is always present.

Program code
Modify the following program code to delete all screens from a specific folder:

private static void DeleteAllScreensFromFolder(HmiTarget hmitarget)


//Deletes all screens from a user folder or a system folder
{
ScreenUserFolder folder = hmitarget.ScreenFolder.Folders.Find("myScreenFolder");
//or ScreenSystemFolder folder = hmitarget.ScreenFolder;
ScreenComposition screens = folder.Screens;
List<Screen> list = new List<Screen>();
foreach(Screen screen in screens)
{
list.Add(screen);
}
foreach (Screen screen in list)
{
screen.Delete();
}
}

Openness: API for automation of engineering workflows


310 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

5.10.2 Cycles

5.10.2.1 Deleting a cycle

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Application
You cannot delete standard cycles.
You can identify whether cycles have actually been deleted based on the composition in the
object model (composition count) of the respective cycle. It is no longer possible to access these
cycles.

Program code
Modify the following program code to delete a cycle from an HMI device:

public static void DeleteCycle(HmiTarget hmiTarget)


{
CycleComposition cycles = hmiTarget.Cycles;
Cycle cycle = cycles.Find("myCycle");
cycle.Delete();
}

5.10.3 Text lists

5.10.3.1 Deleting a text list

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 311
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

Program code
Modify the following program code to delete a selected text list and all associated list entries
from an HMI device:

public static void DeleteTextList(HmiTarget hmiTarget)


{
TextListComposition textLists = hmiTarget.TextLists;
TextList textList = textLists.Find("myTextList");
textList.Delete();
}

5.10.4 Graphic lists

5.10.4.1 Deleting a graphic list

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Program code
Modify the following program code to delete a selected graphic list and all associated list entries
from an HMI device:

private static void DeleteGraphicList(HmiTarget hmiTarget)


{
GraphicListComposition graphicLists = hmiTarget.GraphicLists;
GraphicList graphicList = graphicLists.Find("myGraphicList");
graphicList.Delete();
}

Openness: API for automation of engineering workflows


312 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

5.10.5 Connections

5.10.5.1 Deleting a connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Program code
Modify the following program code to delete a selected communication connection from an HMI
device:

private static void DeleteConnection(HmiTarget hmiTarget)


{
ConnectionComposition connections = hmiTarget.Connections;
Connection connection = connections.Find("HMI_connection_1");
connection.Delete();
}

5.10.6 Tag table

5.10.6.1 Creating user-defined folders for HMI tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 313
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

Program code
Modify the following program code to create a user-defined folder for HMI tags:

private static void CreateUserfolderForHMITags(HmiTarget hmitarget)


// Creates an HMI tag user folder
{
TagSystemFolder folder = hmitarget.TagFolder;
TagUserFolder myCreatedFolder = folder.Folders.Create("MySubFolder");
}

5.10.6.2 Enumerating tags of an HMI tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to enumerate all tags of an HMI tag table:

private static void EnumerateTagsInTagtable(HmiTarget hmitarget)


// //Enumerates all tags of a tag table
{
TagTable table = hmitarget.TagFolder.TagTables.Find("MyTagtable");
// Alternatively, you can access the default tag table:
// TagTable defaulttable = hmitarget.TagFolder.DefaultTagTable;

TagComposition tagComposition = table.Tags;


foreach (Tag tag in tagComposition)
{
// Add your code here
}
}

5.10.6.3 Deleting an individual tag from an HMI tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


314 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

Program code
Modify the following program code to delete a specific tag from an HMI tag table:

private static void DeleteATag(HmiTarget hmiTarget)


{
string tagName = "MyTag";
TagTable defaultTagTable = hmiTarget.TagFolder.DefaultTagTable;
TagComposition tags = defaultTagTable.Tags;
Tag tag = tags.Find(tagName);
tag.Delete();
}

5.10.6.4 Deleting a tag table from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Application
You cannot delete the default tag table

Program code
Modify the following program code:

// Delete a tag table from a specific folder


private static void DeleteTagTable(HmiTarget hmiTarget)
{
string tableName = "myTagTable";
TagSystemFolder tagSystemFolder = hmiTarget.TagFolder;
TagTableComposition tagTables = tagSystemFolder.TagTables;
TagTable tagTable = tagTables.Find(tableName);
tagTable.Delete();
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 315
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

5.10.7 VB scripts

5.10.7.1 Creating user-defined script folders

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to create a user-defined script subfolder below a system
folder or another user-defined folder:

private static void CreateFolderInScriptfolder(HmiTarget hmitarget)


//Creates a script user subfolderVBScriptSystemFolder
{
VBScriptSystemFolder vbScriptFolder = hmitarget.VBScriptFolder;
VBScriptUserFolderComposition vbScriptFolders = vbScriptFolder.Folders;
VBScriptUserFolder vbScriptSubFolder = vbScriptFolder.Folders.Create("mySubfolder");
}

5.10.7.2 Deleting a VB script from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains an HMI device.

Openness: API for automation of engineering workflows


316 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.10 Functions for accessing the data of an HMI device

Program code
Modify the following program code to delete a VB script from a specific folder:

//Deletes a vbscript from a script folderVBScriptSystemFolder


private static void DeleteVBScriptFromScriptFolder(HmiTarget hmitarget)
{
VBScriptUserFolder vbscriptfolder =
hmitarget.VBScriptFolder.Folders.Find("MyScriptFolder");
var vbScripts = vbscriptfolder.VBScripts;
if (null != vbScripts)
{
var vbScript = vbScripts.Find("MyScript");
vbScript.Delete();
}
}

5.10.7.3 Deleting a user-defined folder of an HMI device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to delete an user-defined folder of an HMI device:

HmiTarget hmiTarget = ...;


ScreenUserFolder screenUserGroup = hmiTarget.ScreenFolder.Folders.Find("MyUserFolder");
screenUserGroup.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 317
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11 Functions for accessing the data of an HMI Unified device (RT
Unified)

5.11.1 Object list (RT Unified)

Introduction
The following tables show the available objects and indicate whether these objects are
supported by TIA Portal Openness.

Objects
You can control the following project data for WinCC Unified device:

Object WinCC Scada Runtime Unified


Analog Alarms Yes
Discrete Alarms Yes
Alarm Classes Yes
Data Logs Yes
Alarm Logs Yes
Logging tags Yes
Tag Yes
Connections Yes
Device runtime setting Yes
Screens and Screen items Yes
Plant View Yes
Plant Object Yes
Plant View Node Yes
Plant Object Interface Yes
Plant Object Interface Member Yes
Plant Object Logging Tag Yes

5.11.2 Rename properties and data types (RT Unified)

Introduction
In ES TIA Portal Openness, appropriate changes are made in property names and data types, so
that it is similar to runtime Openness model.
To achieve it, changes are made in all subsystems for example Alarm, Tag, Connection, and
Logging.

Openness: API for automation of engineering workflows


318 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

To have consistency in naming the property and its data type, it is necessary that prefix Hmi is
used for defining their type and name of property should not have this prefix.

Change in property name and data type


Following table shows required changes to have consistent name and data type for composition.

Hmi Object Name Property Name Property New Name Property Data type Property New Data
Type
Analog Alarm AnalogAlarms - AnalogAlarmComposi‐ HmiAnalogAlarmCom‐
tion position
Discrete Alarm DiscreteAlarms - DiscreteAlarmCompo‐ HmiDiscreteAlarm‐
sition Composition
OPC UA Alarm & Condi‐ OpcUaAlarmTypes - OpcUaAlarmTypeCom‐ HmiOpcUaAlarmType‐
tion types position Composition
Alarm Class AlarmClasses - AlarmClassComposi‐ HmiAlarmClassCompo‐
tion sition
Tag Table HmiTagTables TagTables HmiTagTableComposi‐ -
tion
Tag HmiTags Tags HmiTagComposition -
System Tag HmiSystemTags SystemTags HmiSystemTagCompo‐ -
sition
Logging Tag LoggingTags - LoggingTagComposi‐  HmiLoggingTagCom‐
tion position
Connection HmiConnections Connections HmiConnectionCom‐ -
position
Data Log DataLogs - DataLogComposition HmiDataLogComposi‐
tion
Alarm Log AlarmLogs - AlarmLogComposition HmiAlarmLogComposi‐
tion
Plant Object Interface PlantObjectTags - PlantObjectInterface‐ -
Composition
Screen Screens - HmiScreenComposi‐ -
tion

Note
With dash (-) character in columns 'New Name' and 'New Data Type' in above table shows no
change is required.

Changes in name of HmiObject classes


Following table shows required changes to have consistent name for classes for Hmi Object.

Hmi Object Name Class Name New Class Name


Analog Alarm AnalogAlarm HmiAnalogAlarm
Discrete Alarm DiscreteAlarm HmiDiscreteAlarm
OPC UA Alarm & Condition types HmiOpcUaAlarmType HmiOpcUaAlarmType

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 319
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Hmi Object Name Class Name New Class Name


Alarm Class AlarmClass HmiAlarmClass
Tag Table HmiTagTable -
Tag HmiTag -
Connection HmiConnection -
RuntimeSettings RuntimeSetting HmiRuntimeSetting
Data Log DataLog HmiDataLog
Alarm Log AlarmLog HmiAlarmLog
Logging Tag LoggingTag HmiLoggingTag
System Tag HmiSystemTag -
Screen HmiScreen -
Plant Object interface PlantObjectInterface -

Note
With dash (-) character in columns 'New Class Name' in above table shows no change is required.

5.11.3 HMI Unified Software object (RT Unified)

Introduction
You require an HMI Software object to have access to other elements like tags, connections,
alarms and screens.

Requirements
• The TIA Portal Openness application is connected to the TIA Portal
Connecting to the TIA Portal (Page 81)
• A project is open
Opening a project (Page 113)

Openness: API for automation of engineering workflows


320 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access HMI Software object:

private HmiSoftware GetHmiSoftware()


{
HmiSoftware hmiSoftware = null;
Project project = null;
IList<TiaPortalProcess> tiaProcessList = TiaPortal.GetProcesses();
//If no TIA Application instance is running, then following using statement will start it or
//if already running then will attach to it.
TiaPortal tiaApp = tiaProcessList.Count > 0? tiaProcessList[0].Attach(): new
TiaPortal(TiaPortalMode.WithUserInterface);
//If there is device projects are present in given TIA instance, then take first one to work
upon.
if (tiaApp.Projects.Count > 0)
project = tiaApp.Projects[0];
else
{
//if there is no device project in given TIA instance, open the existing project.
FileInfo file = new FileInfo(@"d:\Automation\Project1\Project1.apx");
if (!file.Exists)
throw new FileNotFoundException("Project1.apx not found");
project = tiaApp.Projects?.Open(file);
}
//After getting project, get the object representing UA software HMI device.
var devices = project.Devices;
if (devices != null)
{
var device = devices[0];
var deviceItems = device.DeviceItems;
if (deviceItems != null)
{
foreach (DeviceItem deviceItem in deviceItems)
{
SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
hmiSoftware = softwareContainer?.Software as HmiSoftware;
}
}
}
return hmiSoftware;
}

Note
In the above program code, the extension .apx refers to the installed version of TIA Portal.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 321
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.4 Querying errors (RT Unified)

Introduction
You can use TIA Portal Openness to get error information about properties for the following
WinCC objects:
• Analog Alarm
• Discrete Alarm
• Alarm Class
• Data Log
• Alarm Log
• Tag
• Connection
• Logging Tag
• Device runtime settings
• OPC UA Alarms

Note
This feature is not applicable to System Tag and Tag Table as they don’t have any property which
can be in error state.

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to HMI Unified Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


322 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to query errors for tag, alarms, runtime setting and screens:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 323
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

//For Tag
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagComposition hmiTags = hmiSoftware.HmiTags;
HmiTag hmiTag = hmiTags.Find("Tag-l");
if(hmiTag != null)
{
//validate method usage
IList<HmiValidationResult> validationResult = hmiTag.Validate();
if (validationResult = null && validationResult.Count > 0)
{
foreach (HmiValidationResult propertyErrors in validationResult)
{
//browse error for different property
string propertyName = propertyErrors. PropertyName;
foreach (string propertyError in propertyErrors.Errors)
{
//work with propertyerrors
}
}
}
}
//For Discrete Alarm
HmiSoftware hmiSoftware = ...;
HmiDiscreteAlarmComposition discreteAlarms = hmiSoftware.DiscreteAlarms;
HmiDiscreteAlarm alarm = discreteAlarms.Find("Alarm_1");
if (alarm != null)
{
//Validate Method Usage
Ilist<HmiValidationResult> validationResult = alarm.Validate();
if (validationResult != null && validationResult.Count > 0)
{
foreach (HmiValidationResult propertyErrors in validationResult)
{
//browse error for different property
string propertyName = propertyErrors.PropertyName;
foreach (string propertyError in propertyErrors.Errors)
{
//work with property errors
}
}
}
}
//For Runtime Setting
HmiSoftware hmiSoftware = ...;
HmiRuntimeSetting runtimeSettings = hmiSoftware.RuntimeSettings;
//Validate Method Usage
Ilist<HmiValidationResult> validationResult = runtimeSettings.Validate();
if (validationResult != null && validationResult.Count > 0)
{
foreach (HmiValidationResult propertyErrors in validationResult)
{
//browse error for different property
string propertyName = propertyErrors.PropertyName;
foreach (string propertyError in propertyErrors.Errors)
{

Openness: API for automation of engineering workflows


324 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

//work with property errors


}
}
}
// List of Many objects (Tag, Alarm, etc,)
HmiSoftware hmiSoftware = ...;
IList<IValidator> objectsToValidate = new List<IValidator>();
//Put tags in validation list
HmiTagComposition hmiTags = hmiSoftware.Tags;
foreach (HmiTag hmiTag in hmiTags)
{
objectsToValidate.Add(hmiTag);
}
//Put alarms in validation list
HmiDiscreteAlarmComposition discreteAlarms = hmiSoftware.DiscreteAlarms;
foreach (HmiDiscreteAlarm discreteAlarm in discreteAlarms)
{
objectsToValidate.Add(discreteAlarm);
}
//Put RuntimeSettings in validation list
objectsToValidate.Add(hmiSoftware.RuntimeSettings);
foreach (IValidator validator in objectsToValidate)
Ilist<HmiValidationResult> validationResult = validator.Validate();
if (validationResult != null && validationResult.Count > 0)
{
foreach (HmiValidationResult propertyErrors in validationResult)
{
//browse error for different property
string propertyName = propertyErrors.PropertyName;
foreach (string propertyError in propertyErrors.Errors)
{
//work with property errors
}
}
}
}

See also
HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 325
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.5 Alarms (RT Unified)

5.11.5.1 Working with analog alarms (RT Unified)

Introduction
You can perform the following tasks with analog alarms while using TIA Portal Openness:
• Creating analog alarms
• Enumerating analog alarms
• Deleting analog alarms
• Accessing analog alarm properties

Properties
The following properties are supported in analog alarm:

Property Name Data Type Description Access


EventText MultilingualText Specifies event/alarm R/W
text of alarm
Id uint32 Specify alarm number R/W
to identify alarm. This
is unique value for each
analog alarm
AlarmClass String Specifies alarm class R/W
Name String Specifies alarm name R/W
Priority byte Specifies alarm Priority R/W
Origin String Specifies origin of alarm R/W
Area String Specifies area of alarm R/W
RaisedStateTag String Specifies tag that trig‐ R/W
ger/raise the alarm
ConditionValue object Supported type: Double, Condition Value can be R/W
int16, , uint16, int32, uint32, specified as constant
int64, uint64, byte value
Condition HmiAlarmCondition Specifies Limit Mode R/W
InfoText MultilingualText Specifies Info Text R/W
AlarmParameterTags Object SupportedType: If array of 10 parameter R/W
IList<string> tags which specifies
alarm parameter. Each
parameter take tag
name as string. These
parameters can be
used in event text.
EventText1 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText2 MultilingualText Event Text of HmiAna‐ R/W
logAlarm

Openness: API for automation of engineering workflows


326 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Data Type Description Access


EventText3 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText4 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText5 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText6 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText7 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText8 MultilingualText Event Text of HmiAna‐ R/W
logAlarm
EventText9 MultilingualText Event Text of HmiAna‐ R/W
logAlarm

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to the HMI Software object.
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with alarms.

Creating analog alarms


Modify the following program code to create analog alarms:

private void AnalogAlarmCreate()


{
//Create Analog Alarm
HmiSoftware hmiSoftware = GetHmiSoftware();
AnalogAlarmComposition analogAlarms = hmiSoftware.AnalogAlarms;
AnalogAlarm analogAlarm = analogAlarms.Create("Alarm_1");
}

Deleting analog alarms

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 327
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to delete analog alarm:

private void AnalogAlarmDelete()


{
//Delete Analog Alarm
hmiSoftware = GetHmiSoftware();
AnalogAlarmComposition analogAlarms = hmiSoftware.AnalogAlarms;
AnalogAlarm analogAlarm = analogAlarms.Find("Alarm_1");
if (analogAlarm != null)
{
analogAlarm.Delete();
}
}

Enumerating analog alarms


Modify the following program code to enumerate an analog alarm:

private void AnalogAlarmBrowse()


{
//Browse Analog Alarms
hmiSoftware = GetHmiSoftware();
AnalogAlarmComposition analogAlarms = hmiSoftware.AnalogAlarms;
foreach (AnalogAlarm analogAlarm in analogAlarms)
{
//work with analog alarms.
}
//Other way to get alarm by using Find function on Alarm Composition. AnalogAlarm
analogAlarmObj = analogAlarms.Find("Alarm_1");
}

Accessing analog alarm properties


Modify the following program code to set and get analog alarm properties:

private void AnalogAlarmPropertiesAcess()


{
hmiSoftware = GetHmiSoftware();
AnalogAlarmComposition analogAlarms = hmiSoftware.AnalogAlarms;
AnalogAlarm analogAlarm = analogAlarms.Find("Alarm_1");
int id = analogAlarm.Id
analogAlarm.Id = 10;
int priority = analogAlarm.Priority; analogAlarm.Priority = 7;
analogAlarm.Area = "Area_1";
string area = analogAlarm.Area;
analogAlarm.Name = "NewAlarm";
string name = analogAlarm.Name;
}

Openness: API for automation of engineering workflows


328 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.5.2 Working with discrete alarms (RT Unified)

Introduction
You can perform the following tasks with discrete alarms while using TIA Portal Openness:
• Creating discrete alarms
• Deleting discrete alarms
• Enumerating discrete alarms
• Accessing discrete alarm properties

Properties
The following properties are supported in discrete alarms:

Property Name Data Type Description Access


EventText MultilingualText Specifies event/alarm text of R/W
alarm
Id uint32 Specify alarm number to iden‐ R/W
tify alarm. This is unique value
for each Discrete alarm
AlarmClass String Specifies alarm class R/W
Name String Specifies alarm name R/W
Priority byte Specifies alarm Priority. R/W
Origin String Specifies origin of alarm R/W
Area String Specifies area of alarm R/W
RaisedStateTag String Specifies tag that raise/trigger R/W
the alarm
RaisedStateTagBitNumber uint32 Trigger bit on trigger tag R/W
TriggerMode HmiDiscreteAlarmTigger‐ Specifies Trigger mode for dis‐ R/W
Mode crete alarm
InfoText MultilingualText Specifies Info Text R/W
AlarmParameterTags Object If array of 10 parameter tags R/W
which specifies alarm param‐
eter. Each parameter take tag
name as string. These param‐
eters can be used in alarm text
EventText1 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText2 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText3 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText4 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText5 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 329
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Data Type Description Access


EventText6 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText7 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText8 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
EventText9 MultilingualText Event Text of HmiDiscreteA‐ R/W
larm
AcknowledgmentStateTag String Acknowledgment tag for dis‐ R/W
crete alarm
AcknowledgmentStateTagBit‐ uint32 Acknowledgment tag bit R/W
Number number for discrete alarm
AcknowledgmentControlTag String Control Tag for Acknowledge‐ R/W
ment of discrete alarm
AcknowledgmentControlTag‐ uint32 Control tag bit number for Ac‐ R/W
BitNumber knowledgement of discrete
alarm

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to HMI Software object.
See HMI Unified Software object (Page 320).

Program code
You can modify and use the following program code examples while working with alarms.

Creating discrete alarms


Modify the following program code to create a discrete alarm:

HmiSoftware hmiSoftware = ...;


DiscreteAlarmComposition discreteAlarms = hmiSoftware.DiscreteAlarms;
DiscreteAlarm discreteAlarm = discreteAlarms.Create("Alarm_1");

Deleting discrete alarms

Openness: API for automation of engineering workflows


330 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to delete a discrete alarm:

public void Delete()


//User wants to delete a discrete alarm with the alarm name Alarm_1
{
HmiSoftware hmiSoftware = ...:
DiscreteAlarmComposition discreteAlarms = hmiSoftware.DiscreteAlarms;
DiscreteAlarm discreteAlarm = discreteAlarms.Find("Alarm_1");
discreteAlarm.Delete();
}

Enumerating discrete alarms


Modify the following program code to enumerate a discrete alarm:

private void DiscreteAlarmBrowse()


{
//Browse Discrete Alarms
HmiSoftware hmiSoftware = GetHmiSoftware();
DiscreteAlarmComposition discreteAlarms = hmiSoftware.DiscreteAlarms;
foreach (DiscreteAlarm discreteAlarm in discreteAlarms)
{
//work with discrete alarms.
}
//Other way to get alarm by using Find function on Alarm Composition.
DiscreteAlarm discreteAlarmObj = discreteAlarms.Find("Alarm_1");
}

Accessing discrete alarm properties


Modify the following program code to access discrete alarm properties:

HmiSoftware hmiSoftware = ...:


DiscreteAlarm discreteAlarm = hmiSoftware.DiscreteAlarms[0];

int id = discreteAlarm.Id;
discreteAlarm.Id = 10;

int priority =discreteAlarm.Priority;


discreteAlarm.Priority = 7;

discreteAlarm.area = "Aread1";
string area = discreteAlarm.Area;

discreteAlarm.Name = "NewAlarm";
string name = discreteAlarm.Name;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 331
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.5.3 Working with alarm classes (RT Unified)

Introduction
You can perform the following tasks with alarm classes while using TIA Portal Openness:
• Creating alarm class
• Deleting alarm classes
• Enumerating alarm classes
• Accessing properties of alarm class

Properties
The following properties are supported in alarm class:

Property Name Data Type Description Access


Name String Name of alarm class Depend on type of alarm class
(system / user)
Priority byte Priority of alarm class R/W
IsSystem Bool Specifies if alarm class is sys‐ R
tem provided
StateMachine HmiAlarmStateMachine Specifies state machine of Depend on type of alarm class
alarm class (system / user)
RaisedState HmiRaisedState Alarm Incoming or raised Sta‐ R
tus
RaisedState.BackColor Color Specifies Back color R/W
RaisedState.TextColor Color Specifies Text Color R/W
RaisedState.Flashing Bool Specifies flashing R/W
ClearedState HmiClearedState Specifies Alarm coming going R
or cleared status
ClearedState.BackColor Color Specifies Backcolor R/W
ClearedState.TextColor Color Specifies TextColor R/W
ClearedState.Flashing Bool Specifies flashing R/W
AcknowledgedState HmiAcknowledgedState Specifies Alarm incoming ac‐ R
knowledge or acknowledged
status
AcknowledgedState.BackCol‐ Color Specifies Backcolor R/W
or
AcknowledgedState.TextCol‐ Color Specifies TextColor R/W
or
AcknowledgedState.Flashing Bool Specifies flashing R/W
AcknowledgedClearedState HmisAcknowledgedCleared‐ Specifies Alarm incoming out‐ -
State going acknowledge or Ac‐
knowledgedCleared status
AcknowledgedCleared‐ Color Specifies Backcolor R/W
State.BackColor

Openness: API for automation of engineering workflows


332 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Data Type Description Access


AcknowledgedCleared‐ Color Specifies TextColor R/W
State.TextColor
AcknowledgedCleared‐ Bool Specifies flashing R/W
State.Flashing
Id uint32 Specify id to identify alarm R
class. This is unique value for
each Alarm class.
Log System.String Log of Alarm class R/W
CommonAlarmClass System.String Common Alarm Class R

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with alarm classes.

Creating alarm classes


Modify the following program code to create alarm class:

private void AlarmClassCreate()


{
//Create Alarm Class
HmiSoftware hmiSoftware = GetHmiSoftware();
AlarmClassComposition alarmClasses = hmiSoftware.AlarmClasses;
AlarmClass alarmClass = alarmClasses.Create("AlarmClass_1");
}

Deleting alarm classes

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 333
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to delete alarm class:

public void Delete()


//User wants to delete an alarm class with the alarm name AlarmClass_1
{
HmiSoftware hmiSoftware = ...:
AlarmClassComposition alarmClasses = hmiSoftware.AlarmClasses;
AlarmClass alarmClass = alarmClasses.Find("AlarmClass_1");
alarmClass.Delete();
}

Enumerating alarm classes


Modify the following program code to enumerate alarm class:

//User wants to enumerate all discrete alarms of device with following code
{
HmiSoftware hmiSoftware = ...:
AlarmClassComposition alarmClasses = hmiSoftware.AlarmClasses;
foreach (AlarmClass alarmClass in alarmClasses)
}
{
...
}

Accessing alarm class properties


Modify the following program code to access alarm class properties:

HmiSoftware hmiSoftware = ...:


AlarmClassComposition alarmClasses = hmiSoftware.AlarmClasses;
AlarmClass alarmClass = hmiSoftware.AlarmClasses.Find("MostCritical");
int priority = alarmClass.Priority;
alarmClass.Priority = 10;
alarmClass.Acknowledgement = StateMachine.AlarmWithDualModeAcknowledgement;
alarmClass.IncomingOutgoingAcknowledgeStatus.BackColor = Color.Red;
alarmClass.IncomingOutgoingAcknowledgeStatus.TextColor = Color.Black;
alarmClass.IncomingOutgoingAcknowledgeStatus.Flashing = true;

5.11.6 Logs (RT Unified)

5.11.6.1 Working with data logs (RT Unified)

Introduction
You can perform the following tasks with data logs while using TIA Portal Openness:
• Create data log
• Delete data log

Openness: API for automation of engineering workflows


334 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

• Enumerate data log


• Access properties of data log

Properties
The following properties are supported in data log:

Property Name Data Type Description Access


Name String Specifies name of data log R/W
Settings LogSettings Complex property. Having properties R
(StorageFolder, LogMaxSize and LogTi‐
mePeriod) as members which specifies
setting related to log.
StorageFolder String Path for storage R/W
LogMaxSize Unsigned int Defines maximum size of log on storage R/W
Medium in units of megabytes
LogTimePeriod LogDuration Defines maximum time period covered R/W
by log
StorageDevice DeviceNode Defines which storage device R/W
Seg‐ LogSegment Complex property. Having properties R
ment (SegementMaxSize, StartTime and Seg‐
mentTimePeriod) as members which
specifies setting related to Segment
SegmentMaxSize Unsigned int Define maximum size of segment ol log R/W
in units of megabytes
SegmentStart‐ DateTime Define exact point in time when seg‐ R/W
Time ment shall be started.
SegmentTime‐ SegmentDuration Maximum time period covered by seg‐ R/W
Period ment of log.
Backup LogBackup Complex property. Having properties R
(PrimaryPath, and BackupMode) as
members which specifies setting rela‐
ted to log backup.
BackupMode HmiBackupMode Defines back up mode R/W
PrimaryPath String Path for back up R/W

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with data logs.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 335
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Creating data log


Modify the following program code to create a data log:

private void DatalogCreate()


{
//Create Datalog
HmiSoftware hmiSoftware = GetHmiSoftware();
DataLogComposition dataLogs = hmiSoftware.DataLogs;
DataLog dataLog = dataLogs.Create("Datalog_1");
}

Deleting data log


Modify the following program code to delete a data log:

private void DatalogDelete()


{
//user wants to delete datalog with name "Datalog_1"
HmiSoftware hmiSoftware = GetHmiSoftware();
DataLogComposition dataLogs = hmiSoftware.DataLogs;
DataLog dataLog = dataLogs.Find("Datalog_1");
dataLog.Delete();
}

Enumerating data log


Modify the following program code to enumerate data log:

private void DatalogBrowse()


{
//Browse Datalog.
HmiSoftware hmiSoftware = GetHmiSoftware();
DataLogComposition dataLogs = hmiSoftware.DataLogs;
foreach (DataLog dataLog in dataLogs)
{
//work with data log.
}
//Other way to get data log by using Find function on datalog Composition.
DataLog dataLogObj = dataLogs.Find("Datalog_1");
}

Openness: API for automation of engineering workflows


336 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of data log


You can modify and use the following program code to accessing data log properties:

private void DatalogProperties()


{
//Set/Get Data Log properties.
HmiSoftware hmiSoftware = GetHmiSoftware();
DataLogComposition dataLogs = hmiSoftware.DataLogs;
DataLog dataLog = dataLogs.Find("Datalog_1");
string name = dataLog.Name;
dataLog.Settings.StorageFolder = @"C:\Logs\Log";
dataLog.Settings.LogMaxSize = Int32.MaxValue;
dataLog.Settings.LogMaxSize = 2000;
LogDuration duration = dataLog.Settings.LogTimePeriod;
double durationInDouble = duration.GetDoubleLogDuration();
string durationInString = duration.GetStringLogDuration();
duration.Days = 7;
duration.Hours = 23;
duration.Minutes = 50;
duration.Seconds = 0;
duration.Ticks = 1;
//Method to set log duration.
duration.SetLogDuration(10, 12, 4, 5, 0);
dataLog.Backup.BackupMode = BackupMode.NoBackup;
dataLog.Backup.BackupMode = BackupMode.PrimaryPath;
dataLog.Backup.PrimaryPath = @"C:\Logs\Backup";
dataLog.Segment.SegmentMaxSize = 500;
dataLog.Segment.SegmentStartTime = DateTime.Now;
dataLog.Segment.SegmentStartTime = DateTime.Now.Date;
}

5.11.6.2 Working with alarm logs (RT Unified)

Introduction
You can perform the following tasks with alarm logs while using TIA Portal Openness:
• Create alarm log
• Delete alarm log
• Enumerate alarm log
• Access properties of alarm log

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 337
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Properties
The following properties are supported in alarm log:

Property Name Data Type Description Access


Name String Specifies name of alarm log R/W
Settings LogSettings Complex property. Having properties R
(StorageFolder, LogMaxSize and LogTi‐
mePeriod) as members which specifies
setting related to log.
StoragePath String Path for storage R/W
LogMaxSize Unsigned int Defines maximum size of log on storage R/W
Medium in units of megabytes
LogTimePer‐ LogDuration Defines maximum time period covered R/W
iod by log
Segment LogSegment Complex property. Having properties R
(SegementMaxSize, StartTime and Seg‐
mentTimePeriod) as members which
specifies setting related to Segment
SegmentMax‐ Unsigned int Define maximum size of segment ol log R/W
Size in units of megabytes
SegmentStart‐ DateTime Define exact point in time when seg‐ R/W
Time ment shall be started.
SegmentTime‐ SegmentDuration Maximum time period covered by seg‐ R/W
Period ment of log.
Backup LogBackup Complex property. Having properties R
(PrimaryPath, and BackupMode) as
members which specifies setting rela‐
ted to log backup.
BackupMode HmiBackupMode Defines back up mode R/W
PrimaryPath String Path for back up R/W

The following properties are supported in LogDuration:

Property Name Data Type Description Access


Days Unsigned int Get / Set number of days R/W
Hours Unsigned int Get / Set hours R/W
Segment LogSegment Complex property. Having properties R
(SegementMaxSize, StartTime and Seg‐
mentTimePeriod) as members which
specifies setting related to Segment
Backup LogBackup Complex property. Having properties R
(PrimaryPath, and BackupMode) as
members which specifies setting rela‐
ted to log backup.

Openness: API for automation of engineering workflows


338 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with alarm logs.
Creating alarm logs
Modify the following program code to create an alarm log:

private void AlarmLogCreate()


{
//Create Alarmlog
HmiSoftware hmiSoftware = GetHmiSoftware();
AlarmLogComposition alarmLogs = hmiSoftware.AlarmLogs;
AlarmLog alarmLog = alarmLogs.Create("Alarmlog_1");
}

Deleting alarm logs


Modify the following program code to delete an alarm log:

private void AlarmLogDelete()


{
//User wants to delete alarm log with name "Alarmlog_1"
HmiSoftware hmiSoftware = GetHmiSoftware();
AlarmLogComposition alarmLogs = hmiSoftware.AlarmLogs;
AlarmLog alarmLog = alarmLogs.Find("Alarmlog_1");
alarmLog.Delete();
}

Enumerating alarm logs

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 339
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to enumerate an alarm log:

private void AlarmLogBrowse()


{
//Browse alarm log.
HmiSoftware hmiSoftware = GetHmiSoftware();
AlarmLogComposition alarmLogs = hmiSoftware.AlarmLogs;
foreach (AlarmLog alarmLog in alarmLogs)
{
//work with alarm log.
}
//Other way to get alarmlog by using Find function on alarmlog Composition.
AlarmLog alarmLogObj = alarmLogs.Find("Alarmlog_1");
}

Accessing properties of alarm log


You can modify and use the following program code to accessing alarm log properties:

private void AlarmLogProperties()


{
//Set/Get alarm log properties.
HmiSoftware hmiSoftware = GetHmiSoftware();
AlarmLogComposition alarmLogs = hmiSoftware.AlarmLogs;
AlarmLog alarmLog = alarmLogs.Find("Alarmlog_1");
string name = alarmLog.Name;
alarmLog.Settings.StorageFolder = @"C:\Logs\Log";
alarmLog.Settings.LogMaxSize = Int32.MaxValue;
alarmLog.Settings.LogMaxSize = 2000;
LogDuration duration = alarmLog.Settings.LogTimePeriod;
double durationInDouble = duration.GetDoubleLogDuration();
string durationInString = duration.GetStringLogDuration();
duration.Days = 7;
duration.Hours = 23;
duration.Minutes = 50;
duration.Seconds = 0;
duration.Ticks = 1;
//Log duration can be set by using function also.
duration.SetLogDuration(10, 12, 4, 5, 0);
alarmLog.Backup.BackupMode = BackupMode.NoBackup;
alarmLog.Backup.BackupMode = BackupMode.PrimaryPath;
alarmLog.Backup.PrimaryPath = @"C:\Logs\Backup";
alarmLog.Segment.SegmentMaxSize = 500;
alarmLog.Segment.SegmentStartTime = DateTime.Now;
alarmLog.Segment.SegmentStartTime = DateTime.Now.Date;
}

See also
HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


340 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.6.3 Working with logging tags (RT Unified)

Introduction
You can perform the following tasks with logging tags while using TIA Portal Openness:
• Create logging tag
• Delete logging tag
• Enumerate logging tag
• Access properties of logging tags

Properties
The following properties are supported in logging tag:

Property Name Data Type Description Access


AggregationDelay System.TimeSpan Aggregation delay value R/W
AggregationMode HmiAggregationMode Aggregation Mode value R/W
Cycle System.String Logging Cycle of logging tag R/W
CycleFactor System.UInt32 Logging Cycle Factor vlaue R/W
DataLog System.String Data log of logging tag R/W
HighLimit System.Object High limit of logging tag R/W
LimitScope HmiLimitScope Limit scope of logging tag R/W
LoggingMode HmiLoggingMode Logging mode of logging tag R/W
LowLimit System. Object Low limit of logging tag R/W
Name System.string Name of logging tag R/W
SmoothingDeltaValue System.Double Delta of logging tag R/W
SmoothingMaxTime System. TimeSpan Maximum time of logging tag R/W
SmoothingMinTime System.TimeSpan Minimum time of logging tag R/W
SmoothingMode HmiSmoothingMode Smoothing mode logging tag R/W
Source System.string Source Logging Tag R/W
TriggerMode HmiTriggerMode TriggerMode of Logging tag R/W
TriggerTag System.String TriggerTag Value R/W
TriggerTagBitNumber System.UInt32 TriggerTagBitNumber value R/W

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 341
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
You can modify and use the following program code examples while working with logging tags.
Creating logging tags
You can modify and use the following program code to create a logging tag:

private void LoggingTagCreate()


{
//Create Logging Tag for given tag.
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagComposition hmiTags = hmiSoftware.HmiTags;
//Tag_1 exists in TIA project.
HmiTag hmiTag = hmiTags.Find("Tag_1");
LoggingTagComposition loggingTags = hmiTag.LoggingTags;
LoggingTag loggingTag = loggingTags.Create("LoggingTag_1");
}

Deleting logging tags


You can modify the following program code to delete a logging tag:

private void LoggingTagDelete()


{
//user wants to delete Logging tag with name "LoggingTag_1" for tag "Tag_1";
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagComposition hmiTags = hmiSoftware.HmiTags;
//Tag_1 exists in TIA project.
HmiTag hmiTag = hmiTags.Find("Tag_1");
LoggingTagComposition loggingTags = hmiTag.LoggingTags;
//LoggingTag_1 exists in TIA project.
LoggingTag loggingTag = loggingTags.Find("LoggingTag_1");
loggingTag.Delete();
}

Enumerating Logging tags

Openness: API for automation of engineering workflows


342 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to enumerate logging tag:

private void LoggingTagBrowse()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagComposition hmiTags = hmiSoftware.HmiTags;
//Tag_1 exists in TIA project.
HmiTag hmiTag = hmiTags.Find("Tag_1");
LoggingTagComposition loggingTags = hmiTag.LoggingTags;
foreach (LoggingTag loggingTag in loggingTags)
{
//...
}
//LoggingTag_1 exists in TIA project.
LoggingTag loggingTagObj = loggingTags.Find("LoggingTag_1");
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 343
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of logging tags


You can modify and use the following program code to accessing logging tag properties:

private void LoggingTagProperties()


{
//Set/Get LoggingTag properties.
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagComposition hmiTags = hmiSoftware.HmiTags;
//Tag_1 exists in TIA project.
HmiTag hmiTag = hmiTags.Find("Tag_1");
LoggingTagComposition loggingTags = hmiTag.LoggingTags;
//LoggingTag_1 exists in TIA project.
LoggingTag loggingTag = loggingTags.Find("LoggingTag_1");

string name = loggingTag.Name;

SmoothingMode smoothingMode = loggingTag.SmoothingMode;


loggingTag.SmoothingMode = SmoothingMode.SwingingDoor;

LimitScope limitScope = loggingTag.LimitScope;


loggingTag.LimitScope = LimitScope.WithinLimits;

string lowLimit = loggingTag.LowLimit;


loggingTag.LowLimit = "-32768";

string highLimit = loggingTag.HighLimit;


loggingTag.HighLimit = "-3";

TimeSpan smotthingMinTime = loggingTag.SmoothingMinTime;


TimeSpan tsMin = TimeSpan.Parse("500");
loggingTag.SmoothingMinTime = tsMin;

TimeSpan smotthingMaxTime = loggingTag.SmoothingMaxTime;


TimeSpan tsMax = TimeSpan.Parse("1000");
loggingTag.SmoothingMaxTime = tsMax;

double smoothingDeltaValue = loggingTag.SmoothingDeltaValue;


loggingTag.SmoothingDeltaValue = 5;

string dataLog = loggingTag.DataLog;


loggingTag.DataLog = "Datalog_1";
}

See also
HMI Unified Software object (Page 320)

5.11.6.4 Working with audit trail (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of audit trail.

Openness: API for automation of engineering workflows


344 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

The following line properties are supported in audit trail:

Property Name Data Type Description Access


Name String Specifies name of audit trail R/W
Settings LogSettings Complex property. Having properties R
(StorageFolder, LogMaxSize and LogTi‐
mePeriod) as members which specifies
setting related to audit trail.
StorageFolder String Path for storage R/W
LogMaxSize Unsigned int Defines maximum size of log on storage R/W
Medium in units of megabytes
LogTimePeriod LogDuration Defines maximum time period covered R/W
by log
StorageDevice DeviceNode Defines which storage device R/W
Seg‐ LogSegment Complex property. Having properties R
ment (SegementMaxSize, StartTime and Seg‐
mentTimePeriod) as members which
specifies setting related to Segment
SegmentMaxSize Unsigned int Define maximum size of segment ol au‐ R/W
dit trail in units of megabytes
SegmentStart‐ DateTime Define exact point in time when seg‐ R/W
Time ment shall be started.
SegmentTime‐ SegmentDuration Maximum time period covered by seg‐ R/W
Period ment of audit trail.
Backup LogBackup Complex property. Having properties R
(PrimaryPath, and BackupMode) as
members which specifies setting rela‐
ted to audit trail backup.
BackupMode HmiBackupMode Defines back up mode R/W
PrimaryPath String Path for back up R/W

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 345
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code

HmiAuditTrailComposition auditLog = hmiSoftware.AuditTrails;


HmiAuditTrail auditLogObject = auditLog [01];
string auditTrailName = auditLogObject.Name;
Console.WriteLine("Name {0}" auditTrailName);
auditLogObject.Name = "Audit Log_100";
auditLogObject.Settings.StorageFolder = @"C:\\Testsl23";
auditLogObject.Settings.LogMaxSize = Int32.MaxValue;
auditLogObject.Settings.LogMaxSize = 2000;
LogDuration duration = auditLogObject.Settings.LogTimePeriod;
double durationlnDouble = duration.GetDoubleLogDuration();
string durationlnString = duration .GetStringLogDuration();
duration.Days = 200;
duration.Hours = 10;
duration.Minutes = 22;
duration.Seconds = 39;
duration.Ticks = 0;
//Log duration can be set by function also
duration.SetLogDuration(10,12,4,5,0);
auditLogObject.Backup.BackupMode = HmiBackupMode.NoBackup;
auditLogObject.Backup.BackupMode = HmiBackupMode.PrimaryPath;
auditLogObject.Backup.PrimaryPath = @"C:\Logs\Backup";
auditLogObject.Segment.SegmentMaxSize = 500;
auditLogObject.Segment.SegmentStartTime = DateTime.Now;
auditLogObject.Segment.SegmentStartTime = DateTime.Now.Date;

See also
HMI Unified Software object (Page 320)

5.11.7 Tags and tag tables (RT Unified)

5.11.7.1 Working with tag tables (RT Unified)

Introduction
You can perform the following tasks with tag tables while using TIA Portal Openness:
• Create tag tables
• Delete tag tables
• Enumerate tag tables
• Access tag table properties

Openness: API for automation of engineering workflows


346 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Properties
The following properties are supported in tag table:

Property Name Data Type Description Access


Name String Specifies alarm name R/W
Tags HmiTagComposition List of tags R

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).

Program code
You can modify and use the following program code examples while working with tag tables.
Creating tag tables
Modify the following program code to create a tag table:

private void TagTableCreate()


{
//Create Tag Table
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagTableComposition tagTables = hmiSoftware.TagTables;
HmiTagTable hmiTagTable = tagTables.Create("TagTable_1");
}

Deleting tag tables


Modify the following program code to delete a tag table:

private void TagTableDelete()


{
//User wants to delete tag table with name "TagTable_1"
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagTableComposition tagTables = hmiSoftware.TagTables;
HmiTagTable tagTable = tagTables.Find("TagTable_1");
tagTable.Delete();
}

Enumerating tag tables

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 347
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to enumerate tag table:

private void TagTableBrowse()


{
//Browse Tag Tables
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagTableComposition tagTables = hmiSoftware.TagTables;
foreach (HmiTagTable tagTable in tagTables)
{
//Work with tag table
}
//Other way to get tag table by using Find function on tag table Composition.
HmiTagTable tagTableObj = tagTables.Find("TagTable_1");
}

Accessing tag table properties


Modify the following program code to accessing properties of a tag table:

private void TagTableProperties()


{
//Set/Get Tag Table properties.
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiTagTableComposition tagTables = hmiSoftware.TagTables;
HmiTagTable tagTable = tagTables.Find("TagTable_1");
tagTable.Name = "NewTagTable";
string name = tagTable.Name;
}

5.11.7.2 Working with HMI tags (RT Unified)

Introduction
You can perform the following tasks with HMI tags while using TIA Portal Openness:
• Create HMI tags
• Delete HMI tags
• Enumerate HMI tags
• Access a HMI tag
• Access HMI tag properties
• Usage of UDT datatype for tags
• Properties of member tags of UDT

Openness: API for automation of engineering workflows


348 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Properties
The following properties are supported in HMI tag:

Property Name Data Type Description Access


AccessMode HmiAccessMode The Hmi Tag Access Mode R/W
AcquisitionCycle String The Acquisition cycle attribute R/W
AcquisitionMode HmiTagAcquisitionMode Hmi Tag AcquisitionMode R/W
Comment MultilingualText Get/set comment of tag R/W
Connection String The Hmi Connection R/W
DataType String DataType of the Tag R/W
MaxLength UInt32 The hmi tag DataTypeLength R/W
Address String The Hmi Tag Address Attribute R/W
InitialMinValue LowerRange Lower limit R
Name String Name of Hmi Tag R/W
Persistent Boolean The Persistence attribute R/W
PlcName String The Plc Name attribute R
PlcTag String The Plc Tag attribute R/W
InitialValue Object The Start value attribute R/W
SubstituteValue HmiSubstituteValue The SubstituteValue R
UpdateId UInt32 The Update Id Attribute R/W
InitialMaxValue UpperRange Upper limit R
TagTableName String Tag Table Name to which tag R
belongs
HmiDataType String HmiDataType of the Tag
LinearScaling Boolean LinearScaling R/W
HmiStartValue Object R/W
HmiEndValue Object R/W
PlcStartValue Object R/W
PlcEndValue Object R/W
GmpRelevant Boolean R/W

The following properties are available in LowerRange/UpperRange:

Property Name Data Type Description Access


Value Object Value of upper/lower R/W
ValueType HmiLimitValueType Get and set Value type R/W

The following properties are available in SubstituteValue:

Property Name Data Type Description Access


Value Object Get and set Value type R/W
SubstituteValueUsage Hmi SubstituteValueUs‐ Describe when to use R/W
age substitute value

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 349
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to the HMI Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with HMI tag.
Creating HMI tags
Modify the following program code to create a HMI tag:

private void CreateTag(


{
HmiSoftware hmiSoftware = GetHmiSoftware();
//Four ways to create tag.
//1. Create tag by accessing HmiTags property at HmiSoftware level, by using Create method
with two parameters.
HmiTagComposition hmiTags1 = hmiSoftware.HmiTags;
//TagTable1 exists in TIA project.
HmiTag hmiTag1 = hmiTags1.Create("Tag1", "TagTable1");
//2. Create tag by accessing HmiTags property at HmiSoftware level, by using Create method
with single parameter.
HmiTag hmiTag2 = hmiTags1.Create("Tag2");
//Tags will be created in default tag table.
//3. Creation of tag by accessing HmiTags property at Tag Table, by using Create method with
two parameters.
//Tag creation will fail and it will result in recoverable exception,
HmiTagComposition hmiTags2 = hmiSoftware.HmiTagTables.Find("Default tag table").HmiTags;
HmiTag hmiTag3 = hmiTags2.Create("Tag_3", "TableTableName");
//4. Create tag by accessing HmiTags property at Tag Table, by using Create method with
single parameter.
HmiTag hmiTag4 = hmiTags2.Create("Tag_4");
}

Deleting HMI tags

Openness: API for automation of engineering workflows


350 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to delete a HMI tag:

private void DeleteTag()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
//1. Delete tag at HmiSoftware level.
HmiTagComposition hmiTags1 = hmiSoftware.HmiTags;
HmiTag hmiTag1 = hmiTags1.Find("Tag1");
hmiTag1.Delete();
//2. Delete tag at tag table level.
HmiTagComposition hmiTags2 = hmiSoftware.HmiTagTables.Find("Default tag table").HmiTags;
HmiTag hmiTag2 = hmiTags1.Find("Tag2");
hmiTag2.Delete();
}

Enumerating HMI tags


Modify the following program code to enumerate HMI tag:

private void BrowseTag()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
//1. User can navigate all tag of device with following code.
HmiTagComposition hmiTags = hmiSoftware.HmiTags;
foreach (HmiTag hmiTag in hmiTags)
{
//...
}
//2. User can navigate all tags of given tag table with following code.
HmiTagComposition hmiTags2 = hmiSoftware.HmiTagTables.Find("Default tag table").HmiTags;
foreach (HmiTag hmiTag2 in hmiTags2)
{
//...
}
}

Accessing a HMI tag


Modify the following program to access single HMI tag by name:

private void AccessTag()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
//User can search tag present in UA device with following code.
HmiTag hmiTag3 = hmiSoftware.HmiTags.Find("Tag1");
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 351
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access a HMI tag by table name:

{
HmiSoftware hmiSoftware = GetHmiSoftware();
// User can search tag present in given tag table with following code.
HmiTag hmiTag4 = hmiSoftware.HmiTagTables.Find("Default tag
table").HmiTags.Find("Tag1");
}

Accessing HMI tag properties


Modify the following program code to accessing properties of HMI tag:

private void TagProperties()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
//Tag_1 exists in TIA device project.
HmiTag hmiTag = hmiSoftware.HmiTags.Find("Tag_1");
//Enumeration type properties
AccessMode accessMode = hmiTag.AccessMode;
UpdateScope scope = hmiTag.UpdateScope;
//Substitute value depends on data type of tag.
hmiTag.SubstituteValue.Value = "144";
hmiTag.SubstituteValue.OnCommunicationError = false;
hmiTag.Name = "Tag_2";
//Assign valid cycle name.
hmiTag.AcquisitionCycle = "T1s";
hmiTag.DataType = "int";
hmiTag.PlcTag = "PlcTag_1";
//Start value depends on data type of tag.
hmiTag.StartValue = "1";
hmiTag.LowerLimit.ValueType = LimitValueType.Constant;
hmiTag.LowerLimit.Value = "HmiTag_1";
//Comment property (multilingual text)
string culture = "en-US";
//get the language based on given culture. Culture is standard and it should have correct
value.
Language language = GetDeviceProject().LanguageSettings.Languages.Find(new
System.Globalization.CultureInfo(culture));
//get comment as multilingual text.
MultilingualText multiLingualComment = hmiTag.Comment;
//get all text items from comment property.
MultilingualTextItemComposition texts = multiLingualComment.Items;
//find text from text list based on language.
MultilingualTextItem textItemEnglish = texts.Find(language);
//get value in selected culture.
string commentEng = textItemEnglish.Text;
}

Openness: API for automation of engineering workflows


352 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Usage of UDT datatype for tags


You can modify and use the following program code to assign UDT datatype for tags and access
member tags.
Assigning UDT datatype to HMI tag
Modify the following program code to assign UDT datatype to HMI tag with no connection:

HmiSoftware hmiSoftware = GetHmiSoftware();


HmiTagComposition tags = hmiSoftware.HmiTags;
tags[0].Data Type = @"\Project library\Types\New folder_3\HmiUdt_string\V
0.0.1";

Modify the following ptogram code to assign UDT datatype to HMI tag with connection:

HmiSoftware hmiSoftware = GetHmiSoftware();


HmiTagComposition tags = hmiSoftware.HmiTags;
tags[0].Connection = "Connection_1";
tags[0].Data Type = @"\Project library\Types\New folder_3\HmiUdt_string\V
0.0.1";

Note
You can use full paths to assign Hmi UDT as data type

Modify the following program code to assign PLC UDT to HMI tag with connection:

HmiSoftware hmiSoftware = GetHmiSoftware();


HmiTagComposition tags = hmiSoftware.HmiTags;
tags[0].Connection = "HMI_Connection_1";
tags[0].Data Type = "PlcTag_1";

Accessing datatype member properties for HMI tag

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 353
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access datatype member properties for HMI tag:

private static void GetProperties(HmiTagComposition hmiTags)


{
foreach (HmiTag hmiTag in hmiTags)
{
switch(hmiTag.TagType)
{
case HmiTagType.Simple
Console.WriteLine("Name : "+ hmiTag.Name);
GetSimpleTagProperties(HmiTag hmiTag)
break;
case HmiTagType.UDT;
case HmiTagType.Array;
GetProperties(hmiTag.Members); //recursive call to current function.
break;
}
}
}
private static void GetSimpleTagProperties(HmiTag hmiTag)
{
Console.WriteLine("Name : " +hmiTag.Name);
Console.WriteLine("Date type : " +hmiTag.DataType);
// List the properties of hmi tag
//
//...
}
private static void GetProperties(HmiTag hmiTag.Members)
{
Console.Writeline("Name : " +hmiTag.Members.Name);
Console.Writeline("Date type: " +hmiTag.Members.DataType);
// List the properties of hmi tag members
//...
//...
}

Properties of member tags of UDT


You can modify and use the following program code to set and get member tags properties of
user defined datatype.

Openness: API for automation of engineering workflows


354 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to set properties of member tags of user defined datatype:

public HmiTag GetTag()


{
DeviceItem deviceItem = Tiaproject.Devices[0].DeviceItems[1];
SoftwareContainer softCont = deviceItem.GetService<SoftwareContainer>();
HmiSoftware hmiSoftware = softCont.Software as HmiSoftware;
if (hmiSoftware == null)
{
Device device = Tiaproject.Devices.Find("PC-System_1");
DeviceItem deviceItem1 = device.DeviceItems[1];
SoftwareContainer softCont1 = deviceItem1.GetService<SoftwareContainer>();
hmiSoftware = softCont1.Software as HmiSoftware;
}
HmiTagComposition tagComposition = hmiSoftware.Tags;
var tag = tagComposition.Create("Test_Tag");
return tag;
}
public void ReadWrite_HMIUDTTagDisplayNamePropertyWithInternalConn_Succeeds()
{
HmiTag tag = GetTag();
tag.DataType = "HmiUdt_1_WithInternalConn V 0.0.1";
for (int i = 0; i < tag.Members.Count; i++)
{
for (int j = 0; j < tag.Members[i].DisplayName.Items.Count; j++)
{
tag.Members[i].DisplayName.Items[j].Text = "DisplayNameTest" + j;
Console.WriteLine("Display Name : ", tag.Members[i].DisplayName.Items[j].Text);
}
}
}
/// <summary>
/// HMI UDT Tag Display Name Property with S7 1500 PLC Connection.
/// </summary>
public void ReadWrite_HMIUDTTagDisplayNamePropertyWithS71500_Succeeds()
{
HmiTag tag = GetTag();
tag.Connection = "HMI_Connection_1";
tag.DataType = "HmiUdt_1_WithS71500Conn V 0.0.1";
for (int i = 0; i < tag.Members.Count; i++)
{
for (int j = 0; j < tag.Members[i].DisplayName.Items.Count; j++)
{
tag.Members[i].DisplayName.Items[j].Text = "DisplayNameTest" + j;
Console.WriteLine("Display Name : ", tag.Members[i].DisplayName.Items[j].Text);
}
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 355
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to get access properties of member tags of user defined
datatype:

public HmiTag GetTag()


{
DeviceItem deviceItem = Tiaproject.Devices[0].DeviceItems[1];
SoftwareContainer softCont = deviceItem.GetService<SoftwareContainer>();
HmiSoftware hmiSoftware = softCont.Software as HmiSoftware;
if (hmiSoftware == null)
{
Device device = Tiaproject.Devices.Find("PC-System_1");
DeviceItem deviceItem1 = device.DeviceItems[1];
SoftwareContainer softCont1 = deviceItem1.GetService<SoftwareContainer>();
hmiSoftware = softCont1.Software as HmiSoftware;
}
HmiTagComposition tagComposition = hmiSoftware.Tags;
var tag = tagComposition.Create("Test_Tag");
return tag;
}
public void Read_HMIUDTTagNamePropertyWithInternalConn_Succeeds()
{
HmiTag tag = GetTag();
tag.DataType = "HmiUdt_1_WithInternalConn V 0.0.1";
for (int i = 0; i < tag.Members.Count; i++)
{
var name = tag.Members[i].Name;
Console.WriteLine("Name : ", name );
}
}
/// <summary>
/// HMI UDT Tag Display Name Property with S71500 connection
/// </summary>
public void Read_HMIUDTTagNamePropertyWithS71500Conn_Succeeds()
{
HmiTag tag = GetTag();
tag.Connection = "HMI_Connection_1";
tag.DataType = "HmiUdt_1_WithS71500Conn V 0.0.1";
for (int i = 0; i < tag.Members.Count; i++)
{
var name = tag.Members[i].Name;
Console.WriteLine("Name : ", name );
}
}

See also
HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


356 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.7.3 Working with system tags (RT Unified)

Introduction
You can perform the following tasks with system tags while using TIA Portal Openness:
• Access a system tag
• Access system tag properties

Properties
The following properties are supported in System tag:

Property Name Data Type Description Access


Name String Specify System Tag Name R
DataType String Specify data type of System R
Tag

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• Access to the HMI Software object
See HMI Unified Software object (Page 320)

Program code
Accessing a system tag
Modify the following program code to access single system tag by name:

private void SystemTagName()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiSystemTagComposition hmiSystemTags = hmiSoftware.HmiSystemTags;
//Find system tag by using its name.
HmiSystemTag hmiSystemTagObj = hmiSystemTags.Find("@UserName");
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 357
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing system tag properties


Modify the following program code to access properties of system tags:

private void SystemTagProperties()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiSystemTagComposition hmiSystemTags = hmiSoftware.HmiSystemTags;
HmiSystemTag hmiSystemTag = hmiSystemTags.Find("@UserName");
string name = hmiSystemTag.Name;
string dataType = hmiSystemTag.DataType;
}

See also
HMI Unified Software object (Page 320)

5.11.8 Connections (RT Unified)

5.11.8.1 Working with connections (RT Unified)

Introduction
You can perform the following tasks with connections while using TIA Portal Openness:
• Create connections
• Delete connections
• Enumerate connections
• Access connection properties

Properties
The following properties are supported in HMI Connections:

Property Name Data Type Description Access


Name String Name of connection R/W
DisabledAtStartup Boolean Connection initially will be on‐ R/W
line or not in runtime.
CommunicationDriver String Gives the communication R/W
driver
Node String Shows access point of Partner R
(eg PLC).
Partner String Name of connected PLC. R

Openness: API for automation of engineering workflows


358 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Data Type Description Access


Station String Name of the station to which R
PLC is located.
Comment String Additional comments if any R/W
InitialAddress String Provide parameters of con‐ R/W
nection like type of interface
(DP, TCP/IP), IP address, Rack
etc.

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
Connecting to the TIA Portal (Page 81)
• A project is open.
Opening a project (Page 113)

Program code
You can modify and use the following program code examples while working with connections.
Creating connections
Modify the following program code to create a connection:

private void ConnectionCreate()


{
//Create Connection
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiConnectionComposition connections = hmiSoftware.HmiConnections;
HmiConnection connection = connections.Create("Connection_1");
}

Deleting connections
Modify the following program code to delete a connection:

private void ConnectionDelete()


{
//User wants to delete connection with name "Connection_1"
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiConnectionComposition connections = hmiSoftware.HmiConnections;
HmiConnection connection = connections.Find("Connection_1")
connection.Delete();
}

Enumerating connections

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 359
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to enumerate connection:

private void ConnectionBrowse()


{
//Browse Connections
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiConnectionComposition connections = hmiSoftware.HmiConnections;
foreach (HmiConnection connection in connections)
{
//Work with connections
}
//Other way to get connection by using Find function on connection Composition
HmiConnection connectionObj = connections.Find("Connection_1");
}

Openness: API for automation of engineering workflows


360 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing connection properties


Modify the following program code to accessing connection properties:

private void ConnectionProperties()


{
//Set/Get Connection properties.
HmiSoftware hmiSoftware = GetHmiSoftware();
HmiConnectionComposition connections = hmiSoftware.HmiConnections;
HmiConnection connection = connections.Find("Connection_1");
string name = connection.Name;
connection.Name = "Connection_2";
bool online = connection.DisabledAtStartup;
connection.DisabledAtStartup = true;
string node = connection.Node;
string station = connection.Station;
string partner = connection.Partner;
string communicationDriver = connection.CommunicationDriver;
connection.CommunicationDriver = "SIMATIC S7 300/400";
//valid Initial Address strings
connection.InitialAddress = "PlcRack = 4";
connection.InitialAddress = "HostAddress = 127.157.2.2";
connection.InitialAddress = "hostAddress = 127.157.2.2";//key name is case insensitive so
it is valid"
connection.IntialAddress = "CommunicationInterface = Industrial Ethernet; HostAddress =
127.157.8.1; HostAccessPoint = S7ONLINE; PlcExpansionSlot = 1; PlcRack = 1;
PlcIsCyclicOperation = false";
connection.InitialAddress = "CommunicationInterface = Industrial Ethernet; HostAddress =
127.157.8.1; HostAccessPoint = S7ONLE; PlcRack = 5; PlcIsCyclicOperation = true";
//Below are Wrong Value or Wrong Formats which leads to recorverable exceptions.
//Wrong Value
connection.InitialAddress = null;
connection.InitialAddress = string.Empty;
connection.InitialAddress = "HostAddress = 127.157.2.2.1";
connection.InitialAddress = "HostAddress = 127.157.2.2.1; PlcRack = 5";
//key value format is not followed.
connection.InitialAddress = "HostAccessPoint = S7ONINE; PlcAddress * 155.166.8.2;
PlcExpansionSlot ; 1; PlcRack = 5; PlcIsCyclicOperation = true";
//semicolon with empty key value pair
connection.InitialAddress = ";;CommunicationInterface = Industrial Ethernet; HostAddress =
127.157.0.1";
connection.InitialAddress = ";CommunicationInterface = Industrial Ethernet; HostAddress =
127.157.0.1";
connection.InitialAddress = "CommunicationInterface = Industrial Ethernet; HostAddress =
127.157.0.1;";
connection.InitialAddress = "CommunicationInterface = Industrial Ethernet;; HostAddress =
127.157.0.1;";
connection.CommunicationDriver = "SIMATIC S7 1500";
//wrong as PlcRack is not valid key / property for Simatic S71500 connection.
connection.InitialAddress = "PlcRack = 4";
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 361
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.9 Runtime settings (RT Unified)

5.11.9.1 Working with runtime settings (RT Unified)

Introduction
You can perform the following tasks with runtime settings while using TIA Portal Openness:
• Read/write runtime settings

Properties
The following properties are supported in Runtime Settings:

Property Name Data Type Description Access


HmiSoftware.RuntimeSet‐ HmiRuntimeSetting Runtime Setting object R
tings
RuntimeSettings.StartScreen String Start Screen. R/W
RuntimeSettings.OperateA‐ Boolean Specifies that given device R/W
sOpcServer should act as OPC Server.
RuntimeSettings.Langua‐ HmiLanguageAndFont Asso‐ List of language and fonts R
geAndFonts ciation
RuntimeSettings. Langua‐ Boolean Enable / Disable runtime lan‐ R/W
geAndFonts [index].Enable guage.
RuntimeSettings.Langua‐ Boolean Specifies language use for log‐ R/W
geAndFonts [index].Enable‐ ging on runtime
ForLogging
RuntimeSettings. Langua‐ Short Specifies order for transfer‐ R
geAndFonts [index].Order ring fonts to device.
RuntimeSettings. Langua‐ String Name of language R
geAndFonts [index].Lan‐
guage
RuntimeSettings. Langua‐ String Predefined font family availa‐ R
geAndFonts [index].Fixed‐ ble for font configuration
Font1
RuntimeSettings. Langua‐ String Predefined font family availa‐ R
geAndFonts [index].Fixed‐ ble for font configuration
Font2
RuntimeSettings. Langua‐ String Predefined font family availa‐ R
geAndFonts [index].Fixed‐ ble for font configuration
Font3
RuntimeSettings.Langua‐ String Predefined font family availa‐ R
geAndFonts[index].Fixed‐ ble for font configuration
Font4
RuntimeSettings.GMPEna‐ Boolean Specifies that given device R/W
bled should be enabled for Audit
Logging or not.

Openness: API for automation of engineering workflows


362 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
Connecting to the TIA Portal (Page 81)
• A project is open.
Opening a project (Page 113)
• Access to the HMI Software object.
HMI Unified Software object (Page 320)

Program code

private void RuntimeSettingsPropertiesAcccess()


{
HmiSoftware hmiSoftware = GetHmiSoftware();
hmiSoftware.RuntimeSettings.OperateAsOpcServer = true;
hmiSoftware.RuntimeSettings.StartScreen = "Screen_1";
hmiSoftware.RuntimeSettings.LanguageAndFonts[0].Enable = true;
hmiSoftware.RuntimeSettings.LanguageAndFonts[0].EnableForLogging = true;
hmiSoftware.RuntimeSettings.GMPEnabled = true;
}

5.11.10 Screens and dynamizations (RT Unified)

5.11.10.1 Working with screens (RT Unified)

Introduction
You can perform the following tasks with screens while using TIA Portal Openness:
• Creating screens
• Deleting screens
• Enumerating screens
• Accessing screen properties

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to the HMI Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 363
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
You can modify and use the following program code example while working with screens.

Creating screens
Modify the following program code to create screens:

HmiSoftware hmisoftware = GetHMISoftware();


HmiScreenComposition objScreens = hmisoftware.Screens;
HmiScreen objHmiScreen = objScreens.Create("TestScreen");

Recoverable Exception will be raised if the Create method is called with Screen Name with which
Screen already exists in TIA Portal.

Deleting screens
Modify the following program code to delete screens:

public void Delete()


//Case 1
HmiSoftware hmisoftware = GetHMISoftware();
HmiScreenComposition objScreens = hmisoftware.Screens;
HmiScreen objHmiScreen = objScreens.Create("TestScreen");
if (objHmiScreen != null)
{
objHmiScreen.Delete();
}
//Case 2
HmiSoftware hmisoftware = GetHMISoftware();
HmiScreenComposition objScreens = hmisoftware.Screens;
objScreens.Create("TestScreen1");
IEngineeringObject alarmClassEnggObj = (IEngineeringObject)objScreens[0];
if (alarmClassEnggObj != null)
{
alarmClassEnggObj.Invoke("Delete", null);
}

Enumerating screens
Modify the following program code to enumerate all screens of device:

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreenComposition objScreens = hmiSoftware.Screens;
foreach (HmiScreen ObjHmiScreen in objScreens);
{
//work with Screens
}

Modify the following program code to searching screen from screens list on the basis of name:

HmiScreen objHmiScreen = objScreens.Find("TestScreen3");

Openness: API for automation of engineering workflows


364 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to get screen from screens list on basis of index:

HmiScreen objHmiScreen = hmiSoftware.Screens[0];

Modify the following program code to checking a particular screen item exist in screen item list
by using Contains method:

HmiScreenComposition objScreens = hmisoftware.Screens;


HmiScreen screen1 = objScreen.Create("TestScreen1");
bool isExist = objScreens.Contains(screen1);

Accessing screen properties


Modify the following program code to set and get properties of screen:

HmiSoftware hmisoftware = GetHmiSoftware();


HmiScreenComposition objScreens = hmisoftware.Screens;
HmiScreen objHmiScreen = objScreens.Create("TestScreen");
objHmiScreen.Width = 50;
objHmiScreen.ScreenNumber = 1;
objHmiScreen.BackGraphic = "DownArrow";
objHmiScreen.DisplayName.Items[0].Text = "screen";
objHmiScreen.Name = "ScreenTest";
objHmiScreen.Enabled = true;
objHmiScreen.Height = 123;

Modify and use the following program code to get all properties of screen using GetAttributes
( ):

HmiSoftware hmisoftware = GetHMISoftware();


HmiScreenComposition objScreens = hmisoftware.Screens;
HmiScreen objHmiScreen = objscreens.Create("TestScreen");
List<string> getlststring = new List<string>();
{
"AlternateBackColor", "BackColor", "BackFillPattern", "BackGraphic",
"BackGraphicStretchMode", "BackgroundFillMode", "DisplayName", "Dynamization", "Enabled",
"EnabledExplicitRelease", "Height", "HorizontalAlignment", "Layers", "Name", "Parent",
"ScreenElements", "ScreenItems", "ScreenNumber", "VerticalAlignment", "Width"
};
var getallpropValue = objHmiScreen.GetAttributes(getlsstring);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 365
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to set all properties of screen using SetAttributes( ):

HmiSoftware hmisoftware = GetHMISoftware();


HmiScreenComposition objScreens = hmisoftware.Screens;
HmiScreen objHmiScreen = objscreens.Create("TestScreen");
Dictionary<string, object> setPropertyName = new Dictionary<string, object>();
setPropertyName.Add("AlternateBackColor", Color.Aqua);
setPropertyName.Add("BackColor", Color.Aqua);
setPropertyName.Add("BackFillPattern", HmiFillPattern.GradientHorizontalTricolor);
setPropertyName.Add("BackGraphic", "DownArrow");
setPropertyName.Add("BackGraphicStretchMode", HmiGraphicStretchMode.Fill);
setPropertyName.Add("BackgroundFillMode", HmiBackgroundFillMode.Screen);
setPropertyName.Add("DisplayName", "AnalogAlarmByDiffMethod");
setPropertyName.Add("Enabled", "AnalogAlarmByDiffMethod");
setPropertyName.Add("EnabledExplicitRelease", "AnalogAlarmByDiffMethod");
setPropertyName.Add("Height", "AnalogAlarmByDiffMethod");
setPropertyName.Add("HorizontalAlignment", "AnalogAlarmByDiffMethod");
setPropertyName.Add("Name", "AnalogAlarmByDiffMethod");
setPropertyName.Add("ScreenNumber", "AnalogAlarmByDiffMethod");
setPropertyName.Add("VerticalAlignment", "AnalogAlarmByDiffMethod");
setPropertyName.Add("Name", "AnalogAlarmByDiffMethod");
setPropertyName.Add("Width", "AnalogAlarmByDiffMethod");
objHmiScreen.SetAttributes(setPropertyName);

Openness: API for automation of engineering workflows


366 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify and use the following program code to get the value from property using
IEngineeringObject's GetAttribute:

HmiSoftware hmisoftware = GetHMISoftware();


HmiScreenComposition objScreens = hmisoftware.Screens;
HmiScreen objHmiScreen = objScreens.Create("Testscreen");
IEngineeringObject obj = objHmiScreen;
Color clraltntvbk = (Color)obj.GetAttribute("AlternateBackColor");
Color clrbk = (Color)obj.GetAttribute("BackColor");
HmiFillPattern filptrns = (HmiFillPattern)obj.GetAttribute("BackFillPattern");
string bkgrphic = (string)obj.GetAttribute("BackGraphic");
HmiGraphicStretchMode strmode =
(HmiGraphicStretchMode)obj.Getattribute("BackGraphicStretchmode");
HmiBackgroundFillMode bkgrndfilmode = (HmiBackgroun
dFillMode)obj.GetAttribute("BackgroundFillMode");
string dsplyName = (string)obj.GetAttribute("DisplayName");
DynamizationBaseComposition dymztns =
(DynamizationBaseComposition)obj.GetAttribute("Dynamizations");
b00l enble = (b00l)obj.GetAttritute("Enabled");
SomRef objsom = (SomRef)obj.GetAttribute("EnableExplicitRelease");
uint fight = (uint)obj.GetAttribute("Height");
HmiHorizontalAlignment hrzntl =
(HmiHorizontalAlIgnment)obj.GetAttribute("HorizontalAlignment");
HmiverticalAlignment vrtcle = (HmiverticalAlignment)obj.GetAttribute("VerticalAlignment");
HmiLayerPartComposition objlyrs = (HmiLayerPartComposition)Obj.GetAttribute("layers");
string name = (string)obj.GetAttribute("Name");
IEngineeringObject objparen = (IEngineeringobject)obj.GetAttribute("Parent");
HmiscreenElementBaseComposition objelemnt =
(HmiscreenElementBaseComposition)obj.GetAttribute("ScreenElements");
HmiScreenItemBaseComposition objitems =
(HmiScreenItemBaseComposition)obj.GetAttribute("ScreenItems");
byte scrnmumber = (byte)obj.GetAttribute("ScreenNumber");
uint width = (uint)obj.GetAttribute(Width");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 367
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to determine if all properties have valid values:

HmiSoftware hmiSoftware = GetHMISoftware ();


HmiScreen objHmiScreen = hmiSoftware.Screens.Create("HmiScreen_1");
objHmiScreen.DisplayName.Items[0].Text = GetMorethan512BoundaryString();
IList<IValidator> objectsToValidate = new List<IValidator>();
foreach (var item in hmiSoftware.Screens)
{
objectsToValidate.Add(item);
}
foreach (IValidator validator in objectsToValidate)
{
IList<HmiValidationResult> errors = validator.Validate();
if (errors != null && errors.Count > 0)
{
foreach (var errornotification in errors)
{
var propName = errornotification.PropertyName;
foreach (var errormasage in errornotification.Errors)
{
Console.WriteLine(errormasage);
}
}
}
}

Note
If during set of properties the set operation is not able to set the value then a Recoverable
exception would be raised.

5.11.10.2 Basic screen items (RT Unified)

Working with basic screen items (RT Unified)

Introduction
You can perform the following tasks with basic screen items while using TIA Portal Openness:
• Creating screen items (Basic)
• Deleting screen items (Basic)
• Enumerating screen items (Basic)

Openness: API for automation of engineering workflows


368 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

The following basic screen items are supported by the TIA Portal Openness:

Table 5-8 Types and Namespace (s)

Screen Item Class Namespace (s)


Line HmiLine Siemens.Engineering.HmiUnified.UI.Shapes
Polyline HmiPolyline Siemens.Engineering.HmiUnified.UI.Base
Polygon HmiPolygon
Ellipse HmiEllipse
Ellipse Segment HmiEllipseSegment
Circle Segment HmiCircleSegment
Elliptical arc HmiEllipticalArc
Circular arc HmiCircularArc
Circle HmiCircle
Rectangle HmiRectangle
Graphic view HmiGraphicView

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 81)

Program code
You can modify and use the following program code example while working with basic screen
items.

Creating screen items (Basic)


Modify the following program code to create basic screen items:

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiLine hmiLine = screenitems.Create<HmiLine>("ScreenItem_1");

Note
The above example can be used to create line screen item. To create other basic screen items,
you will have to replace line screen item with screen item related class in above code example.

Recoverable Exception will be raised if the Create method is called with Screen item Name with
which Screen item already exists in TIA.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 369
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Deleting screen items (Basic)


Modify the following program code to delete basic screen items.

public void Delete()


//Case 1
HmiSoftware hmiSoftware = GetHMISoftware();
HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screen[0].ScreenItems;
HmiLine hmiLine = screenitems.Create<HmiLine>("ScreenItem_1");
if (hmiLine != null)
{
hmiLine.Delete();
}
//Case 2
HmiSoftware hmiSoftware = GetHMISoftware();
HmiScreen hmiScreen = hmiSoftware.Screens.Create("Scren1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiLine hmiLine = screenitems.Create<HmiLine>("ScreenItem_1");
IEngineeringObject ObjhmiLineEnggObj = hmiLine;
if (ObjhmiLineEnggObj != null)
{
ObjHmiScreenItemssEnggObj.Invoke("Delete", null);
}

Note
The above example can be used to delete line screen item. To delete other basic screen items,
you will have to replace the line screen item with screen item related class in above code
example.

Enumerating screen items (Basic)


Modify the following program code to enumerate all screen items of screen.

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
foreach (var item in screenitems)
{
//work with screenitems
}

Modify the following program code to find Screen item from Screen items list on the basis of
name:

HmiScreenItemBase screenitems = hmiSoftware.Screens[0].ScreenItems.Find("ScreenItems_1");

Modify the following program code to get Screen item from Screenitems list on basis of index:

HmiScreenItemBase screenitem = hmiSoftware.Screens[0].ScreenItems[0];

Openness: API for automation of engineering workflows


370 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to check a particular screen item exist in Screen item list by
using Contains method:

HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;


HmiLine hmiLine = screenitems.Create<HmiLine>("ScreenItems_1);
bool isexists = screenitems.Contains(hmiLine);

Note
The above example can be used to enumerate line screen item. To enumerate other basic screen
item, you will have to replace line screen item with screen item related class in above code
example.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)

Accessing properties of line (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of line screen item.
The following line properties are supported in screen item:

Property Name Property Type Accessibility


X1 int False
Y1 int False
X2 int False
Y2 int False
Enabled bool True
CurrentQuality HmiQuality False
LineColor Color False
AlternateLineColor Color False
DashType HmiDashType False
EndType HmiLineEndType False
StartType HmiLineStartType False
CapType HmiCapType False
LineWidth byte False
Top int False
Left int False
Width uint False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 371
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Height uint False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
RotationCenterPlacement HmiRotationCenterPlacement False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiLineEventHandlerComposition True
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following code to access basic properties of Line:

//Name
var name = hmiline.Name;
hmiline.Name = "Default Value";
//AlternateLineColor
var linecolor = hmiline.AlternateLineColor;
hmiline.AlternateLineColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//Height
var height = hmiline.Height;
hmiline.Height = 100;

Modify the following code to access multilingual property:

//ToolTipText
var tooltip = hmiline.ToolTipText;
var tooltiptext = hmiline.ToolTipText.Items[0].Text;
hmiline.ToolTipText.Items[0].Text = "<body><p>TestforMultilinugualProperty</p></body>";

Openness: API for automation of engineering workflows


372 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following code to access other typical property of Line:

//DashType
var dashtype = hmiline.DashType;
hmiline.DashType = HmiDashType.DashDotDot;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Working with basic screen items (Page 368)
HMI Unified Software object (Page 320)

Accessing properties of polyline (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of polyline.
The following polyline properties are supported in basic screen item:

Property Name Property Type Accessibility


LineColor Color False
Enabled bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
AlternateLineColor Color False
DashType HmiDashType False
EndType HmiLineEndType False
StartType HmiLineStartType False
CapType HmiCapType False
LineWidth byte False
JoinType HmiLineJoinType False
Top int False
Left int False
Width uint False
Height uint False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 373
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiPolylineEventHandlerComposition True
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic properties of Polyline:

//Name
var name = polyline.Name;
polyline.Name = "Default Value";
//AlternateLineColor
var linecolor = polyline.AlternateLineColor;
polyline.AlternateLineColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//Height
var height = polyline.Height;
polyline.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = polyline.ToolTipText;
var tooltiptext = polyline.ToolTipText.Items[0].Text;
polyline.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


374 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property:

//Joint Type
var dashtype = polyline.JoinType;
polyline.JoinType = HmiLineJoinType.Miter;
//Points
var points = polyline.Points;
var point = points[0];
var x = point.X;
point.X = 10;
var y = point.Y;
point.Y = 10;
var newPoint = points.Create(15, 100);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with basic screen items (Page 368)

Accessing properties of polygon (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of polygon.
The following polygon properties are supported in basic screen item:

Property Name Property Type Accessibility


BorderColor Color False
AlternateBorderColor Color False
BackColor Color False
AlternateBackColor Color False
Points HmiPointComposition True
BorderWidth byte False
BackFillPattern HmiFillPattern False
FillLevel byte False
FillDirection HmiFillDirection False
Enabled bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
DashType HmiDashType False
ShowFillLevel bool False
JoinType HmiLineJoinType False
Top int False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 375
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Left int False
Width uint False
Height uint False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiPolylgonEventHandlerComposition True
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic properties of Polygon:

//Name
var name = polygon.Name;
polygon.Name = "Default Value";
//AlternateBorderColor
var linecolor = polygon.AlternateBorderColor;
polygon.AlternateBorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//Height
var height = polygon.Height;
polygon.Height = 100;

Openness: API for automation of engineering workflows


376 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = polygon.ToolTipText;
var tooltiptext = polygon.ToolTipText.Items[0].Text;
polygon.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property:

//BackFillPattern
var backfill = polygon.BackFillPattern;
polygon.BackFillPattern = HmiFillPattern.GradientBackwardDiagnol;
//Points
var points = polygon.Points;
var point = points[0];
var x = point.X;
point.X = 10;
var y = point.Y;
point.Y = 10;
var newPoint = points.Create(15, 100);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with basic screen items (Page 368)

Accessing properties of ellipse (RT Unified)

Introduction
You can use the TIA Portal Openness to get/set properties of ellipse screen item.
The following ellipse properties are supported in basic screen item:

Property Name Property Type Accessibility


BorderColor Color False
AlternateBorderColor Color False
BackColor Color False
AlternateBackColor Color False
BorderWidth byte False
Enabled bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
BackFillPattern HmiFillPattern False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 377
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


FillLevel byte False
FillDirection HmiFillDirection False
DashType HmiDashType False
ShowFillLevel bool False
RadiusX uint False
RadiusY uint False
CenterX int False
CenterY int False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiEllipseEventHandlerComposition True
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• Opening a Project
See Opening a Project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic properties of Ellipse:

//Name
var name = ellipse.Name;
ellipse.Name = "Default Value";
//AlternateBorderColor
var bordercolor = ellipse.AlternateBorderColor;
ellipse.AlternateBorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//BorderWidth
var borderwidth = ellipse.BorderWidth;
ellipse.BorderWidth = 10;

Openness: API for automation of engineering workflows


378 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access Multilingual property:

//ToolTipText
var tooltip = ellipse.ToolTipText;
var tooltiptext = ellipse.ToolTipText.Items[0].Text;
ellipse.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property of ellipse:

//BackFillPattern
var backfill = ellipse.BackFillPattern;
ellipse.BackFillPattern = HmiFillPattern.GradientBackwardDiagonal;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with basic screen items (Page 368)

Accessing properties of ellipse segment (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of ellipse segment.
The following ellipse segment properties are supported in screen item:

Property Name Property Type Accessibility


StartAngle int False
AngleRange int False
BorderColor Color False
AlternateBorderColor Color False
BackColor Color False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
BorderWidth byte False
BackFillPattern HmiFillPattern False
FillLevel byte False
FillDirection HmiFillDirection False
DashType HmiDashType False
ShowFillLevel bool False
RadiusX uint False
RadiusY uint False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 379
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


CenterX int False
CenterY int False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
RotationCenterPlacement HmiRotationCenterPlacement False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiEllipseSegmentEventHandlerCom‐ True
position
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• Opening a Project
See Opening a Project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic properties of Ellipse Segment:

//Name
var name = ellipsesegment.Name;
ellipsesegment.Name = "Default Value";
//AlternateBorderColor
var bordercolor = ellipsesegment.AlternateBorderColor;
ellipsesegment.AlternateBorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//BorderWidth
var borderwidth = ellipsesegment.Height;
ellipsesegment.BorderWidth = 10;

Openness: API for automation of engineering workflows


380 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = ellipsesegment.ToolTipText;
var tooltiptext = ellipsesegment.ToolTipText.Items[0].Text;
ellipsesegment.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property:

//BackFillPattern
var backfill = ellipsesegment.BackFillPattern;
ellipsesegment.BackFillPattern = HmiFillPattern.GradientBackwardDiagonal;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)

Accessing properties of circle segment (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of circle segment.
The following circle segment properties are supported in screen item:

Property Name Property Type Accessibility


StartAngle int False
AngleRange int False
BorderColor Color False
AlternateBorderColor Color False
BackColor Color False
AlternateBackColor Color False
Enabled Bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
BorderWidth byte False
BackFillPattern HmiFillPattern False
FillLevel byte False
FillDirection HmiFillDirection False
DashType HmiDashType False
ShowFillLevel bool False
Radius uint False
CenterX int False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 381
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


CenterY int False
RotationCenterX float False
RotationCenterY float False
RotationAngle short False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiCircleSegmentEventHandlerCompo‐ True
sition
ShowFocusVisual bool False
Dynamizations DynamizationBaseComposition True
PropertyEventHandlers PropertyEventHandlerComposition True

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• Opening a Project
See Opening a Project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program
Modify the following program code to access basic property of Circle Segment:

//Name
var name = circlesegment.Name;
circlesegment.Name = "Default Value";
//AlternateBorderColor
var bordercolor = circlesegment.AlternateBorderColor;
circlesegment.AlternateBorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//BorderWidth
var borderwidth = circlesegment.BorderWidth;
circlesegment.BorderWidth = 10;

Openness: API for automation of engineering workflows


382 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = circlesegment.ToolTipText;
var tooltiptext = circlesegment.ToolTipText.Items[0].Text;
circlesegment.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property:

//ToolTipText
var tooltip = circlesegment.ToolTipText;
var tooltiptext = circlesegment.ToolTipText.Items[0].Text;
circlesegment.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with basic screen items (Page 368)

Accessing properties of elliptical arc (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of elliptical arc.
The following elliptical arc properties are supported in screen item:

Property Name Property Type Accessibility


StartAngle int False
AngleRange int False
LineColor Color False
AlternateLineColor Color False
StartType HmiLineStartType False
EndType HmiLineEndType False
CapType HmiCapType False
Enabled Bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
DashType HmiDashType False
LineWidth byte False
RadiusX uint False
RadiusY uint False
CenterX int False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 383
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


CenterY int False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiEllipticalArcEventHandlerComposi‐ True
tion
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic property of Elliptical arc:

//Name
var name = ellipticalarc.Name;
ellipticalarc.Name = "Default Value";
//LineColor
var linecolor = ellipticalarc.LineColor;
ellipticalarc.LineColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//LineWidth
var linewidth = ellipticalarc.LineWidth;
ellipticalarc.LineWidth = 10;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = ellipticalarc.ToolTipText;
var tooltiptext = ellipticalarc.ToolTipText.Items[0].Text;
ellipticalarc.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


384 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property:

//CapType
var captype = ellipticalarc.CapType;
ellipticalarc.CapType = HmiCapType.Round;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with basic screen items (Page 368)

Accessing properties of circular arc (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of circular arc.
The following circular arc properties are supported in screenitem:

Property Name Property Type Accessibility


StartAngle int False
AngleRange int False
LineColor Color False
AlternateLineColor Color False
DashType HmiDashType False
EndType HmiLineEndType False
StartType HmiLineEndType False
Enabled Bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
CapType HmiCapType False
LineWidth byte False
Radius uint False
CenterX int False
CenterY int False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 385
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiCircularArcEventHandlerComposi‐ True
tion
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic property of Circle arc:

//Name
var name = circulararc.Name;
circulararc.Name = "Default Value";
//LineColor
var linecolor = circulararc.LineColor;
circulararc.LineColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//LineWidth
var linewidth = circulararc.LineWidth;
circulararc.LineWidth = 10;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = circulararc.ToolTipText;
var tooltiptext = circulararc.ToolTipText.Items[0].Text;
circulararc.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property :

//CapType
var captype = circulararc.CapType;
circulararc.CapType = HmiCapType.Round;

Openness: API for automation of engineering workflows


386 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with basic screen items (Page 368)

Accessing properties of circle (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of circle.
The following circle properties are supported in screenitem:

Property Name Property Type Accessibility


BorderColor Color False
AlternateBorderColor Color False
BackColor Color False
AlternateBackColor Color False
Enabled Bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
BorderWidth byte False
BackFillPattern HmiFillPattern False
FillLevel byte False
FillDirection HmiFillDirection False
DashType HmiDashType False
ShowFillLevel bool False
Radius uint False
CenterX int False
CenterY int False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiCircleEventHandlerComposition True
ShowFocusVisual bool False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 387
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Dynamizations DynamizationBaseComposition True
PropertyEventHandlers PropertyEventHandlerComposition True

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic property of circle:

//Name
var name = circle.Name;
circle.Name = "Default Value";
//BorderColor
var bordercolor = circle.BorderColor;
circle.BorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//BorderWidth
var borderwidth = circle.BorderWidth;
circle.BorderWidth = 10;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = circle.ToolTipText;
var tooltiptext = circle.ToolTipText.Items[0].Text;
circle.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property :

//DashType
var dashtype = circle.DashType;
circle.DashType = HmiDashType.Solid;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


388 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

HMI Unified Software object (Page 320)


Working with basic screen items (Page 368)

Accessing properties of rectangle (RT Unified)

Introduction
You can use the TIA Portal Openness to set and get properties of rectangle.
The following rectangle properties are supported in screen item:

Property Name Property Type Accessibility


BorderColor Color False
AlternateBorderColor Color False
BackColor Color False
AlternateBackColor Color False
BorderWidth byte False
BackFillPattern HmiFillPattern False
Enabled Bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
Corners HmiCornersPart True
FillLevel byte False
FillDirection HmiFillDirection False
DashType HmiDashType False
ShowFillLevel bool False
Top int False
Left int False
Width uint False
Height uint False
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiRectangleEventHandlerComposition True
ShowFocusVisual bool False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 389
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic properties:

//Name
var name = rectangle.Name;
rectangle.Name = "Default Value";
//BorderColor
var bordercolor = rectangle.BorderColor;
rectangle.BorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//BorderWidth
var borderwidth = rectangle.BorderWidth;
rectangle.BorderWidth = 10;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = rectangle.ToolTipText;
var tooltiptext = rectangle.ToolTipText.Items[0].Text;
rectangle.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property:

//Corners
var corner = rectangle.Corners;
var bottomleftradius = corner.BottomLeftRadius;
corner.BottomLeftRadius = 50;
var bottomrightradius = corner.BottomRightRadius;
corner.BottomRightRadius = 30;
var topleftradius = corner.TopLeftRadius;
corner.TopLeftRadius = 50;
var toprightradius = corner.TopRightRadius;
corner.TopRightRadius = 30;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


390 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

HMI Unified Software object (Page 320)


Working with basic screen items (Page 368)

Accessing properties of graphic view (RT Unified)

Introduction
You can use the TIA Portal Openness to set and get properties of graphic view.
The following rectangle properties are supported in screen item:

Property Name Property Type Accessibility


GraphicStretchMode HmiGraphicStretchMode False
FillLevel byte False
FillDirection HmiFillDirection False
ShowFillLevel bool False
BackFillPattern HmiFillPattern False
AlternateBackColor Color False
Enabled Bool False
CurrentQuality HmiQuality True
RotationCenterPlacement HmiRotationCenterPlacement False
Top int False
Left int False
Width uint False
Height uint False
Padding HmiPaddingPart True
RotationAngle short False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
Visible bool False
Graphic string False
TabIndex ushort False
ToolTipText MultilingualText False
Authorization string False
EventHandlers HmiGraphicViewEventHandlerComposi‐ True
tion
ShowFocusVisual bool False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 391
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 368)

Program code
Modify the following program code to access basic property:

//Name
var name = graphicview.Name;
graphicview.Name = "Default Value";
//AlternateBackColor
var backcolor = graphicview.AlternateBackColor;
graphicview.AlternateBackColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//Height
var height = graphicview.height;
graphicview.Height = 10;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = graphicview.ToolTipText;
var tooltiptext = graphicview.ToolTipText.Items[0].Text;
graphicview.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property:

//Padding
var padding = graphicview.Padding;
var bottom = padding.Bottom;
padding.Bottom = 50;
var left = padding.Left;
padding.Left = 60;
var right = padding.Right;
padding.Right = 70;
var top = padding.Top;
padding.Top = 50;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


392 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

HMI Unified Software object (Page 320)


Working with basic screen items (Page 368)

5.11.10.3 Element screen items (RT Unified)

Working with element screen items (RT Unified)

Introduction
You can perform the following tasks with element screen items while using TIA Portal Openness:
• Creating screen item (element)
• Deleting screen item (element)
• Enumerating screen item (element)
The following screen items are supported by the TIA Portal Openness . To access the screen item
related classes and datatype, use the followiing namespace and types:

Table 5-9 Types and Namespace (s)

Screen Item Class Namespace (s)


IO Field HmiIOField Siemens.Engineering.HmiUnified.ModernUI.Widgets
Button HmiButton Siemens.Engineering.HmiUnified.ModernUI.Base
Switch HmiToggleSwitch
Checkbox HmiCheckBoxGroup
Bar HmiBar
Gauge HmiGauge
Slider HmiSlider
RadioButton HmiRadioButtonGroup
List Box HmiListBox
Clock HmiClock
Text Box HmiTextBox

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 393
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
You can modify and use the following program code example while working with element
screen items.

Creating screen items (Element)


Modify the following program code to create element screen items:

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screen[0].ScreenItems;
HmiIOField hmiIOField = screenitems.Create<HmiIOField>("ScreenItem_1");

Recoverable Exception will be raised if the Create method is called with Screen item Name with
which Screen item already exists in TIA

Note
The above example can be used to create IO Field element screen item. To create other element
screen items, you will have to replace IO Field screen item with screen item related class in above
code example.

Deleting screen items (Element)


Modify the following program code to delete element screen item:

public void Delete()


//Case 1
HmiSoftware hmiSoftware = GetHMISoftware();
HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiIOField hmiIOField = screenitems.Create<HmiIOField>("ScreenItems_1");
if (hmiIOField != null)
{
hmiIOField.Delete();
}
//Case 2
HmiSoftware hmiSoftware = GetHMISoftware();
HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiIOField hmiIOField = screenitems.Create<HmiIOField>("ScreenItem_1");
IEngineeringObject ObjhmiIOFieldEnggObj = hmiIOField;
if (ObjhmiIOFieldEnggObj != null)
{
ObjhmiIOFieldEnggObj.Invoke("Delete", null);
}

Openness: API for automation of engineering workflows


394 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Note
The above example can be used to delete IO Field element screen item. To delete other element
screen items, you will have to replace IO Field screen item with screen item related class in above
code example.

Enumerating screen items (Element)


Modify the following program code to enumerate all Screen Items of Screen.

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
foreach (var item in screenitems)
{
//work with screenitems
}

Modify the following program code to searching Screen item from Screen items list on the basis
of name:

HmiScreenItemBase screenitems = hmiSoftware.Screens[0].ScreenItems.Find("ScreenItems_1");

Modify the following program code to get Screen item from Screenitems list on basis of index:

HmiScreenItemBase screenitem = hmiSoftware.Screens[0].ScreenItems[0];

Modify the following program code to checking a particular screen item exist in Screen item list
by using Contains method:

HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;


HmiIOField hmiIOField = screenitems.Create<HmiIOField>("ScreenItems_1);
bool isexists = screenitems.Contains(hmiIOField);

Note
The above example can be used to enumerate IO Field element screen item. To enumerate other
element screen items, you will have to replace IO Field screen item with screen item related class
in above code example.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 395
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of IO Field (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of IO field.
The following IO Field properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackColor Color False
Enabled Bool False
AlternateBorderColor Color False
Authorization String True
BackColor Color False
BorderColor Color False
BorderWidth byte False
CurrentQuality HmiQuality True
Font HmiFontPart False
ForegroundColor Color False
Height uint False
HorizontalTextAlignment HmiHorizontalAlignment False
IOFieldType HmiIOFieldType False
Top int False
Left int False
Rotation short False
VisualizeQuality bool False
TextTrimming HmiTextTrimming False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Name string False
OutputFormat string False
Padding HmiPaddingPart True
RotationCenterPlacement HmiRotationCenterPlacement False
ProcessValue string False
TabIndex ushort False
ToolTipText MultilingualText False
VerticalTextAlignment HmiVerticalAlignment False
Visible bool False
Width uint False
EventHandlers HmiIOFieldEventHandle rComposition True
ShowFocusVisual bool False
InputBehavior HmiInputBehaviorPart True

Openness: API for automation of engineering workflows


396 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with basic screen items (Page 393)

Program code
Modify the following code to access basic properties of IO Field:

//Name
var name = iofield.Name;
iofield.Name = "DefaultName";
//AlternateBackColor
var altbackcolor = iofield.AlternateBackColor;
iofield.AlternateBackColor = Color.Beige;
//Height
var height = iofield.Height;
iofield.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
HmiIOField ioField = createdscreen.ScreenItems.Create<HmiIOField>("hmiIOField");
string culture = "en-US";
Language lang = Tiaproject.LanguageSettings.Languages.Find(new CultureInfo(culture));
MultilingualText mltprop = ioField.ToolTipText;
MultilingualTextItemComposition textItemComp = mltprop.Items;
MultilingualTextItem mlttextitem = textItemComp.Find(lang);
mlttextitem.Text = "CommentInEnglish";

Modify the following program code to access other typical properties:

//Padding
var padding = iofield.Padding;
var bottom = padding.Bottom;
padding.Bottom = 50;
padding.Left = 60;
padding.Right = 70;
padding.Top = 50;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 397
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Accessing properties of button (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of button in element screen items.
The following button properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackgroundColor Color False
AlternateBorderColor Color False
Authorization String True
BackgroundColor Color False
BorderColor Color False
BorderWidth byte False
Contents HmiContentPart False
CurrentQuality HmiQuality True
Enabled bool False
Font HmiFontPart False
ForegroundColor Color False
Graphic string False
Height uint False
Top int False
Left int False
Rotation short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
Style Item Appearance HmiStyleItem Appearance False
Opacity float False
Name string False
Padding HmiPaddingPart False
RotationCenterPlacement HmiRotationCenterPlacement False
TabIndex ushort False
Text MultiLingualText True
ToolTipText MultilingualText True
Visible bool False

Openness: API for automation of engineering workflows


398 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Width uint False
EventHandlers HmiButtonEventHandlerComposition True
ShowFocusVisual bool False
AlternateGraphic string False
AlternateText MultiLingualText False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Program code
Modify the following program code to access basic properties of button:

//Name
var name = hmiButton.Name;
hmiButton.Name = "Default Value";
//AlternateBackColor
var altbackcolor = hmiButton.AlternateBackColor;
hmiButton.AlternateBackColor = Color.Beige;
//Height
var height = hmiButton.Height;
hmiButton.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
string culture = "en-US";
Language lang = Tiaproject.LanguageSettings.Languages.Find(new CultureInfo(culture));
MultilingualText mltprop = hmiButton.ToolTipText;
MultilingualTextItemComposition textItemComp = mltprop.Items;
MultilingualTextItem mlttextitem = hmiButton.Find(lang);
mlttextitem.Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 399
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property:

//Padding
var padding = hmiButton.Padding;
var bottom = padding.Bottom;
padding.Bottom = 50;
padding.Left = 60;
padding.Right = 70;
padding.Top = 50;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Accessing properties of switch (RT Unified)

Introduction
You can use the TIA Portal Openness to get or set properties of switch in element screen items.
The following switch properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackgroundColor Color False
AlternateBorderColor Color False
IsAlternateState bool False
Authorization string True
BackgroundColor Color False
BorderColor Color False
BorderWidth byte False
Contents HmiContentPart False
CurrentQuality HmiQuality True
Enabled bool False
Font HmiFontPart False
ForegroundColor Color False
Height uint False
Top int False
Left int False
Rotation short False
Text MultiLingualText True
VisualizeQuality bool False
RotationCenterX float False

Openness: API for automation of engineering workflows


400 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


RotationCenterY float False
Opacity float False
Name string False
Padding HmiPaddingPart False
RotationCenterPlacement HmiRotationCenterPlacement False
TabIndex ushort False
ToolTipText MultilingualText False
Visiblity bool False
Width uint False
EventHandlers HmiToggleSwitchEventHandlerCompo‐ True
sition
ShowFocusVisual bool False
Graphic string False
AlternateGraphic string False
AlternateText MultiLingualText True
Padding HmiPaddingPart True
SystemItemClass HmiButtonStyleItemClass True

Note
As StyleItemClass property is ReadOnly, thus Get Operation is supported for it and Set Operation
will throw an exception.

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 401
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access basic properties of switch:

//Name
var name = toggleswitch.Name;
toggleswitch.Name = "Default Value";
//AlternateBackColor
var altbackcolor = toggleswitch.AlternateBackColor;
toggleswitch.AlternateBackColor = Color.Beige;
//Height
var height = toggleswitch.Height;
toggleswitch.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = toggleswitch.ToolTipText;
var tooltiptext = toggleswitch.ToolTipText.Items[0].Text;
toggleswitch.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property of switch:

//Font
var font = toggleswitch.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var.underline = font.Underline;
font.Underline = false;
font.Bold = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


402 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of check box (RT Unified)

Introduction
You can use the TIA Portal Openness to get or set properties of checkbox in element screen items.
The following check box properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackgroundColor Color False
AlternateBorderColor Color False
Authorization string False
BackgroundColor Color False
BorderColor Color True
BorderWidth byte False
Content HmiContentPart False
CurrentQuality HmiQuality False
Enabled bool False
Font HmiFontPart True
ForegroundColor Color False
Height uint False
Top int False
Left int False
Name string False
Rotation short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
Opacity float False
Process value string False
RotationCenterPlacement HmiRotationCenterPlacement False
SelectionItemHeight uint16 False
SelectionItems HmiSelectionItemPartComposition True
TabIndex ushort False
ToolTipText MultilingualText True
Visible bool False
Width uint False
EventHandlers HmiCheckBoxGroupEventHandler Com‐ True
position
ShowFocusVisual bool False
Padding HmiPaddingPart False
SelectionPosition HmiHorizontalAlignment False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 403
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Program code
Modify the following program code to access basic properties of Checkbox:

//Name
var name = chkbox.Name;
chkbox.Name = "DefaultName";
//AlternateBackColor
var altbackcolor = chkbox.AlternateBackColor;
chkbox.AlternateBackColor = Color.Beige;
//Height
var height = chkbox.Height;
chkbox.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = chkbox.ToolTipText;
var tooltiptext = chkbox.ToolTipText.Items[0].Text;
chkbox.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


404 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property of checkbox:

//Font
var font = chkbox.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var.underline = font.Underline;
font.Underline = false;
font.Bold = true;
//Selection Items
var selectionItem = chkbox.SelectionItems;
var newselectionitem = selectionItem.Create("NewSelectionItem");
var graphic = newselection.Graphic;
newselectionitem.Graphic = "abcd";
newselectionitem.Isselected = false;
newselectionitem.Text.Item[0].Text = "Testformultilingual";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Accessing properties of bar (RT Unified)

Introduction
You can use the TIA Openness API V16 to get and set bar properties in element screen items.
The following bar properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackColor Color False
AlternateBorderColor Color False
Authorization string True
BackgColor Color False
BorderColor Color False
BarMode HmiBarMode False
BorderWidth byte False
CurrentQuality HmiQuality True
Enabled bool False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 405
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Font HmiFontPart False
Label HmiTextPart
Height uint False
StraightScale HmiStraightScalePart
Top int False
Left int False
Name string False
NormalRangeColor Color False
OriginValue double False
OutputFormat string False
PeakIndicators HmiPeakIndicator False
Process Value string False
ProcessValueIndicatorBackColor Color False
ProcessValueIndicatorForeColor Color False
ProcessValueIndicatorMode HmiProcessIndicatorMode False
RotationAngle short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
Opacity float False
RotationCenterPlacement HmiRotationCenterPlacement False
ScaleBackColor uint16 False
ScaleForeColor Color False
ShowTrendIndicator bool False
Visible bool False
Width uint False
TabIndex ushort False
TrendIndicateColor Color False
ToolTipText MultilingualText False
EventHandlers HmiBarEventHandlerComposition True
ShowFocusVisual bool False
Title HmiTextPart True

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


406 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access basic properties of bar:

//Name
var name = bar.Name;
bar.Name = "Default Value";
//RotationCenterPlacement
var rotation = bar.RotationCenterPlacement;
bar.RotationCenterPlacement = HmiRotationCenterPlacement.AbsoluteToContainer;
//Width
var width = bar.Width;
bar.Width = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = bar.ToolTipText;
var tooltiptext = bar.ToolTipText.Items[0].Text;
bar.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property of bar:

//Font
var title = bar.Title;
title.Text.items[0].Text = "teststing";
title.Visible = false;
title.Forecolor = Color.Black;
var font = title.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var underline = font.Underline;
font.Underline = false;
font.Bold = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 407
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of gauge (RT Unified)

Introduction
You can use the TIA Portal Openness to get or set properties of gauge in element screen items.
The following gauge properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackColor Color False
AlternateBorderColor Color False
Authorization string True
BackgroundColor Color False
BorderColor Color False
BorderWidth byte False
RelativeToOrigin bool False
CurrentQuality HmiQuality True
Enabled bool False
Title HmiTextPart True
Font HmiFontPart False
Label HmiTextPart True
Height uint False
Top int False
Left int False
Name string False
NormalRangeColor Color False
OriginValue double False
OutputFormat string False
PeakIndicators HmiPeakIndicator False
ProcessValue string False
ProcessValueIndicatorBackColor Color False
ProcessValueIndicatorForeColor Color False
ProcessValueIndicatorMode HmiProcessIndicatorMode False
Rotation short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
Opacity float False
RotationCenterPlacement HmiRotationCenterPlacement False
ScaleBackgroundColor Color False
ScaleForegroundColor Color False
TrendIndicatorColor Color False
Visible bool False
Width uint False
TabIndex ushort False

Openness: API for automation of engineering workflows


408 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


ShowTrendIndicator bool False
ToolTipText string False
EventHandlers HmiGaugeEventHandlerComposition True
ShowFocusVisual bool False
CurvedScale HmiCurvedScalePart True

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Program code
Modify the following program code to access basic properties of gauge:

//Name
var name = gauge.Name;
gauge.Name = "Default Value";
//RotationalCenterPlacement
var rotation = gauge.RotationCenterPlacement;
gauge.RotationCenterPlacement = HmiRotationCenterPlacement.AbsoluteToContainer;
//Width
var width = gauge.Width;
gauge.Width = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = gauge.ToolTipText;
var tooltiptext = gauge.ToolTipText.Items[0].Text;
gauge.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 409
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property of gauge:

//Font
var title = gauge.Title;
title.Text.items[0].Text = "teststing";
title.Visible = false;
title.Forecolor = Color.Black;
var font = title.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var underline = font.Underline;
font.Underline = false;
font.Bold = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Accessing properties of slider (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of slider in element screen items.
The following slider properties are supported in element screen items:

Property Name Property Type Accessibility


AlternativeBackColor Color False
AlternativeBorderColor Color False
Authorization string True
BackgroundColor Color False
BorderColor Color False
BorderWidth byte False
BarMode HmiBarMode False
RelativeToOrigin bool False
CurrentQuality HmiQuality True
Enabled bool False
Title HmiTextPart True

Openness: API for automation of engineering workflows


410 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Font HmiFontPart False
Label HmiTextPart True
Height uint False
Top int False
Left int False
Name string False
NormalRangeColor Color False
OriginValue double False
OutputFormat string False
PeakIndicators HmiPeakIndicator False
Process Value string False
ProcessValueIndicatorBackColor Color False
ProcessValueIndicatorForeColor Color False
ProcessValueIndicatorMode HmiProcessIndicatorMode False
Rotation short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
Opacity float False
RotationCenterPlacement HmiRotationCenterPlacement False
ScaleBackgroundColor Color False
ScaleForegroundColor Color False
TrendIndicatorColor bool False
Visible bool False
Width uint False
ValuePosition HmiSimplePosition False
WriteDuringChange(Write process value bool False
Immediatly)
TabIndex ushort False
ShowTrendIndicator bool False
ToolTipText string False
ShowValue bool False
ShowFocusVisual bool False
EventHandlers HmiSliderEventHandlerComposition True
ThumbBackColor color False
ThumbForeColor color False
StraightScale HmiStraightScalePart True

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 411
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Program code
Modify the following program code to access basic properties of slider:

//Name
var name = slider.Name;
slider.Name = "Default Value";
//RotationalCenterPlacement
var rotation = slider.RotationCenterPlacement;
slider.RotationCenterPlacement = HmiRotationCenterPlacement.AbsoluteToContainer;
//Width
var width = slider.Width;
slider.Width = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = slider.ToolTipText;
var tooltiptext = slider.ToolTipText.Items[0].Text;
slider.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


412 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical properties of slider:

//Font
var title = slider.Title;
title.Text.items[0].Text = "teststing";
title.Visible = false;
title.Forecolor = Color.Black;
var font = title.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var underline = font.Underline;
font.Underline = false;
font.Bold = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Accessing properties of radio button (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of radio button in element screen
items.
The following radio button properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackgroundColor Color False
AlternateBorderColor Color False
Authorization string True
BackgroundColor Color False
BorderColor Color False
BorderWidth byte False
Content HmiContentPart False
CurrentQuality HmiQuality True
Enabled bool False
Font HmiFontPart False

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 413
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


ForegroundColor Color False
Height uint False
Top int False
Left int False
Name string False
Process Value string False
Rotation short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
SelectionItemHeight uint16 False
SelectionItems IList<IHmiSelectionItemPart> True
SelectorPosition HmiHorizontalAlignment
Opacity float False
RotationCenterPlacement HmiRotationCenterPlacement False
Visible bool False
Width uint False
TabIndex ushort False
ToolTipText string False
EventHandlers HmiRadioButtonGroup EventHandler‐ True
Composition
Padding HmiPaddingPart True
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


414 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access basic properties of radio button:

//Name
var name = radio.Name;
radio.Name = "Default Value";
//AlternateBackColor
var altbackcolor = radio.AlternateBackColor;
radio.AlternateBackColor = Color.Beige;
//Height
var height = radio.Height;
radio.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = radio.ToolTipText;
var tooltiptext = radio.ToolTipText.Items[0].Text;
radio.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical properties of radio button:

//Font
var font = radio.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var underline = font.Underline;
font.Underline = false;
font.Bold = true;
//Selection Items
var selectionItem = radio.SelectionItems;
var newselectionitem = selectionItem.Create("NewSelectionItem");
var graphic = newselectionitem.Graphic;
newselectionitem.Graphic = "abcd";
newselectionitem.IsSelected = false;
newselectionitem.Text.Items[0].Text = "Testformultilingual";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 415
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of listbox (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of listbox in element screen items.
The following listbox properties are supported in element screen items:

Property Name Property Type Accessibility


AlternateBackgroundColor Color False
AlternateBorderColor Color False
Authorization string True
BackgroundColor Color False
BorderColor Color False
BorderWidth byte False
Content HmiContentPart False
CurrentQuality HmiQuality True
Enabled bool False
Font HmiFontPart False
ForeGroundColor Color False
Top int False
Left int False
Name string False
Process Value string False
Rotation short False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
SelectionItemHeight uint16 False
SelectionItems IList<IHmiSelectionItemPart> True
SelectionMode HmiSelectionMode False
SelectorPosition HmiHorizontalAlignment
Opacity float False
RotationCenterPlacement HmiRotationCenterPlacement False
Visible bool False
Width uint False
TabIndex ushort False
ToolTipText string False
EventHandlers HmiListBoxEventHandler Composition True
ShowFocusVisual bool False
Padding HmiPaddingPart True

Openness: API for automation of engineering workflows


416 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Program code
Modify the following program code to access basic properties of list box:

//Name
var name = listbox.Name;
listbox.Name = "Default Value";
//AlternateBackColor
var altbackcolor = listbox.AlternateBackColor;
listbox.AlternateBackColor = Color.Beige;
//Height
var height = listbox.Height;
listbox.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = listbox.ToolTipText;
var tooltiptext = listbox.ToolTipText.Items[0].Text;
listbox.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 417
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property of list box:

//Font
var font = listbox.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var.underline = font.Underline;
font.Underline = false;
font.Bold = true;
//Selection Items
var selectionItem = listbox.SelectionItems;
var newselectionitem = selectionItem.Create("NewSelectionItem");
var graphic = newselectionitem.Graphic;
newselectionitem.Graphic = "abcd";
newselectionitem.Isselected = false;
newselectionitem.Text.Item[0].Text = "Testformultilingual";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Accessing properties of textbox (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of textbox in element screen
items.
The following textbox properties are supported in element screen items:

Property Name Property Type Accessibility


ReadOnly bool False
TextWrapping HmiTextWrapping False
VerticalTextAlignment HmiVerticalAlignment False
HorizontalTextAlignment HmiHorizontalAlignment False
TextTrimming HmiTextTrimming False
ForeColor Color False
BorderColor Color False
AlternateBorderColor Color False

Openness: API for automation of engineering workflows


418 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Authorization string False
BackColor Color False
BorderWidth byte False
CurrentQuality HmiQuality True
Enabled bool False
Font HmiFontPart False
Height uint False
Top int False
Left int False
Name string False
RotationAngle short False
VisualizeQuality bool False
AlternateBackColor Color False
RotationCenterX float False
RotationCenterY float False
Opacity float False
RotationCenterPlacement HmiRotationCenterPlacement False
Visible bool False
Width uint False
TabIndex ushort False
ToolTipText string False
EventHandlers HmiTextBoxEventHandler Composition True
ShowFocusVisual bool False
Text MultilingualText True
Padding HmiPaddingPart True

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 419
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access basic property of textbox:

//Name
var name = textbox.Name;
texttbox.Name = "Default Value";
//BorderColor
var bordercolor = textbox.BorderColor;
textbox.BorderColor = Color.FromArgb(0xCC, 0xF0, 0x80, 0x80);
//BorderWidth
var borderwidth = textbox.BorderWidth;
textbox.BorderWidth = 10;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = textbox.ToolTipText;
var tooltiptext = textbox.ToolTipText.Items[0].Text;
textbox.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical property of textbox:

//Font
var font = textbox.Font;
var italic = font.Italic;
font.Italic = false;
var fontname = font.FontName;
font.FontName = HmiFontName.SimSun;
var size = font.Size;
font.Size = 10.2f;
var stike = font.StrikeOut;
font.StrikeOut = true;
var.underline = font.Underline;
font.Underline = false;
font.Bold = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

Openness: API for automation of engineering workflows


420 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of clock (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set the properties of clock in element screen item.
The following clock properties are supported in element screen item:

Property Name Property Type Accessibility


AlternativeBackgroundColor Color False
AlternativeBorderColor Color False
BorderColor Color False
Authorization string True
BackgroundColor Color False
BorderWidth byte False
CurrentQuality HmiQuality True
DialBackColor Color False
DialLabelColor Color False
DialMode HmiScaleMode False
DialTickColor Color False
Enabled bool False
Height uint False
Top int False
Left int False
Name string False
VisualizeQuality bool False
RotationCenterX float False
RotationCenterY float False
ShowHours bool False
ShowMinutes bool False
ShowSeconds bool False
Opacity float False
TimeSource string False
Rotation short False
RotationCenterPlacement HmiRotationCenterPlacement False
Visiblility bool False
Width uint False
TabIndex ushort False
Title HmiTextPart True
ToolTipText MultiLingualText False
EventHandlers HmiClockEventHandlerComposition True
ShowFocusVisual bool False
DialLabelFont HmiFontPart True

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 421
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with element screen items (Page 393)

Program code
Modify the following program code to access basic property of Clock:

//Name
var name = clock.Name;
clock.Name = "Default Value";
//AlternateBackColor
var altbackcolor = clock.AlternateBackColor;
clock.AlternateBackColor = Color.Beige;
//Height
var height = clock.Height;
clock.Height = 100;

Modify the following program code to access multilingual property:

//ToolTipText
var tooltip = clock.ToolTipText;
var tooltiptext = clock.ToolTipText.Items[0].Text;
clock.ToolTipText.Items[0].Text = "TestforMultilingualProperty";

Modify the following program code to access other typical properties:

//DialLabelFont
var dialfont = clock.DialLabelFont;
dialfont.Italic = false;
var fontname = dialfont.FontName;
dialfont.FontName = HmiFontName.SimSun;
var size = dialfont.Size;
dialfont.Size = 10.2f;
var stike = dialfont.StrikeOut;
dialfont.StrikeOut = true;
var underline = dialfont.Underline;
dialfont.Underline = false;
dialfont.Bold = true;
//ShowHours
var showhour = clock.ShowHours;
clock.ShowHours = false;

Openness: API for automation of engineering workflows


422 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Note
If during set of properties the set operation is not able to set the value then a Recoverable
exception would be raised. Values beyond the ranges if not set will send a Recoverable exception
or if set will put the property in invalid state.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with element screen items (Page 393)

5.11.10.4 Control screen items (RT Unified)

Working with control screen items (RT Unified)

Introduction
You can perform the following tasks with control screen items while using TIA Portal Openness:
• Creating screen items (controls)
• Deleting screen items (controls)
• Enumerating screen items (controls)
The following screen items are supported by the TIA Portal Openness. To access the screen item
related classes and datatype, use the followiing namespace and types:

Table 5-10 Types and Namespace (s)

Screen Item Class Namespace (s)


Alarm Control HmiAlarmControl Siemens.Engineering.HmiUnified.ModernUI.Controls
Media Player HmiMediaControl Siemens.Engineering.HmiUnified.ModernUI.Base
Screen Window HmiScreenWindow
Trend Control HmiTrendControl
Trend Companion HmiTrendCompanion
Process Control HmiProcessControl
Function Trend HmiFunctionTrendControl
Control
Web Control HmiWebControl
System Diagnosis HmiSystemDiagnosisCon‐
Control trol
Parameter Set HmiDetailedParameterCon‐
Control trol

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 423
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code example while working with control screen
items.

Creating screen items (Controls)


Modify the following program code to create control screen items:

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiAlarmControl hmiAlarmControl = screenitems.Create<HmiAlarmControl>("ScreenItem_1");

Recoverable Exception will be raised if the Create method is called with Screen item Name with
which Screen item already exists in TIA

Note
The above example can be used to create alarm control screen item. To create other control
screen items, you will have to replace alarm control screen item with screen item related class
in above code example.

Openness: API for automation of engineering workflows


424 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Deleting screen items (Controls)


Modify the following program code to delete control screen items:

public void Delete()


//Case 1
HmiSoftware hmiSoftware = GetHMISoftware();
HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiAlarmControl hmiAlarmControl = screenitems.Create<HmiAlarmControl>("ScreenItem_1");
if (hmiAlarmControl != null)
{
hmiAlarmControl Delete();
}
//Case 2
HmiSoftware hmiSoftware = GetHMISoftware();
HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
HmiAlarmControl hmiAlarmControl = screenitems.Create<HmiAlarmControl>("ScreenItem_1");
IEngineeringObject ObjhmiAlarmControlEnggObj = hmiAlarmControl;
if (ObjhmiAlarmControlEnggObj != null)
{
ObjhmiAlarmControlEnggObj.Invoke("Delete", null);
}

Note
The above example can be used to delete alarm control screen item. To delete other control
screen items, you will have to replace alarm control screen item with screen item related class
in above code example.

Enumerating screen items (Control)


Modify the following program code to enumerate all Screen Items of Screen:

HmiSoftware hmiSoftware = GetHMISoftware();


HmiScreen hmiScreen = hmiSoftware.Screens.Create("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;
foreach (var item in screenitems)
{
//work with screenitems
}

Modify the following program code to searching Screen item from Screen items list on the basis
of name:

HmiScreenItemBase screenitems = hmiSoftware.Screens[0].ScreenItems.Find("ScreenItems_1");

Modify the following program code to get Screen item from Screenitems list on basis of index:

HmiScreenItemBase screenitem = hmiSoftware.Screens[0].ScreenItems[0];

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 425
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to checking a particular screen item exist in Screen item list
by using Contains method:

HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;


HmiAlarmControl hmiAlarmControl = screenitems.Create<HmiAlarmControl>("ScreenItems_1);
bool isexists = screenitems.Contains(hmiAlarmControl);

Note
The above example can be used to enumerate alarm control screen item. To enumerate other
control screen items, you will have to replace alarm control screen item with screen item related
class in above code example.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)

Accessing properties of alarm control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of alarm control in control screen
items.
The following alarm control properties are supported in control screen items.

Property Name Property Type Accessibility


UseAlarmColors bool False
Filter string False
AlwaysShowRecent bool False
AlarmSourceType HmiAlarmSourceType False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top Int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False

Openness: API for automation of engineering workflows


426 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
EditMode HmiEditMode False
TimeZone int False
AlarmDefinitionViewSetup HmiVisibleAlarms False
ActiveAlarmsViewSetup HmiVisibleAlarms False
SuppressFlashing bool False
AcknowledgmentFlashingRate HmiFlashingRate False
ResetFlashingRate HmiFlashingRate False
DefaultSortDirection HmiSortDirection False
BackColor Color False
AlarmView HmiDataGridViewPart True
EventHandlers HmiAlarmControlEventHandlerCompo‐ True
sition
CaptionColor Color False
AlarmStatisticsView HmiDataGridViewPart True
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of alarm control:

//Width
var autoplay = hmialarmcontrol.Width;
hmialarmcontrol.Width = 1;
//BackColor
var backcolor = hmialarmcontrol.BackColor;
hmialarmcontrol.BackColor = Color.Beige;
//Name
var name = hmialarmcontrol.Name;
hmialarmcontrol.Name = "DefaultName";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 427
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access multilingual property:

//Caption
var caption = hmialarmcontrol.Caption.Items[0].Text;
hmialarmcontrol.Caption.Items[0].Text = "<body><p>TestforMultilingualProperty</p></body>";

Modify the following program code to access other typical properties:

//Status bar
var statusBar = hmialarmcontrol.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of media player (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of media player in control screen
items.
The following media player properties are supported in control screen items.

Property Name Property Type Accessibility


Url string False
AutoPlay bool False
VideoOutput HmiVideoOutput False
BackColor Color False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True

Openness: API for automation of engineering workflows


428 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
EventHandlers HmiMediaControlEventHandlerCompo‐ True
sition
CaptionColor Color False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of media player:

//Autoplay
var autoplay = hmimediacontrol.AutoPlay;
hmimediacontrol.AutoPlay = true;
//BackColor
var backcolor = hmimediacontrol.BackColor;
hmimediacontrol.BackColor = Color.Beige;
//Name
var name = hmimediacontrol.Name;
hmimediacontrol.Name = "DefaultName";

Modify the following program code to access multilingual property:

//Caption
var caption = hmimediacontrol.Caption.Items[0].Text;
hmimediacontrol.Caption.Items[0].Text = "<body><p>TestforMultilingualProperty</p></body>";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 429
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access other typical property:

var statusBar = hmimediacontrol.StatusBar;


var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of screen window (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of screen window in control screen
items.
The following screen window properties are supported in control screen items:

Property Name Property Type Accessibility


TabIntoWindow bool False
Screen string False
ScreenName string True
ScreenNumber byte True
System byte False
CurrentZoomFactor double False
VerticalScrollBarVisibility HmiScrollBarVisibility False
VerticalScrollBarPosition int False
HorizontalScrollBarVisibility HmiScrollBarVisibility False
HorizontalScrollBarPosition int False
Adaption HmiScreenWindowAdaption False
InteractiveZooming bool True
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top int False
Left int False
Width uint False

Openness: API for automation of engineering workflows


430 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
EventHandlers HmiScreenWindowEventHandlerCom‐ True
position
CaptionColor Color False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of screen window:

//Width
var autoplay = hmiscreenwindow.Width;
hmiscreenwindow.Width = 1;
//HorizontalScrollBarVisibility
var horizontalscrollbarvisibilityValue = hmiscreenwindow.HorizontalScrollBarVisibility;
hmiscreenwindow.HorizontalScrollBarVisibility = HmiScrollBarVisibility.Visible;
//Name
var name = hmiscreenwindow.Name;
hmiscreenwindow.Name = "DefaultName";

Modify the following program code to access multilingual property:

//Caption
var caption = hmiscreenwindow.Caption.Items[0].Text;
hmiscreenwindow.Caption.Items[0].Text = "<body><p>TestforMultilingualProperty</p></body>";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 431
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of trend control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of trend control in control screen
items.
The following trend control properties are supported in control screen items.

Property Name Property Type Accessibility


ShowStatisticRulers bool False
AreaSpacing ushort False
ExtendRulerToAxis bool False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
Font HmiFontPart True
TimeZone int False
ShowRuler bool False
ShiftAxes bool False
BackColor Color False
Legend HmiLegendPart True
EventHandlers HmiTrendControlEventHandlerComposi‐ True
tion
CaptionColor Color False
ShowFocusVisual bool False

Openness: API for automation of engineering workflows


432 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Note
The LabelFont is a Time Axis property of trend base controls.

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of trend control:

//Width
var autoplay = hmitrendcontrol.Width;
hmitrendcontrol.Width = 1;
//BackColor
var backcolor = hmitrendcontrol.BackColor;
hmitrendcontrol.BackColor = Color.Beige;
//Name
var name = hmitrendcontrol.Name;
hmitrendcontrol.Name = "DefaultName";

Modify the following program code to access multilingual property access:

//Caption
var caption = hmitrendcontrol.Caption.Items[0].Text;
hmitrendcontrol.Caption.Items[0].Text = "<body><p>TestforMultilingualProperty</p></body>";

Modify the following program code to access other typical properties:

//Status bar
var statusBar = hmitrendcontrol.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 433
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of trend companion (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of trend companion in control
screen items.
The following trend companion properties are supported in control screen items.

Property Name Property Type Accessibility


TrendCompanionMode HmiTrendCompanionMode False
UseSourceControlTrendColors bool False
ShowAlways bool False
UseSourceControlBackColor bool False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
SourceTrendControl string False
TimeZone int False
SnapToSourceControl bool False
TrendRulerView HmiDataGridViewPart True
TrendStatisticAreaView HmiDataGridViewPart True
BackColor Color False
TrendStatisticResultView HmiDataGridViewPart True
EventHandlers HmiTrendCompanionEventHandler‐ True
Composition

Openness: API for automation of engineering workflows


434 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


CaptionColor Color False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Pogram code
Modify the following program code to access basic properties of trend companion:

//Width
var autoplay = hmitrendcompanion.Width;
hmitrendcompanion.Width = 1;
//BackColor
var backcolor = hmitrendcompanion.BackColor;
hmitrendcompanion.BackColor = Color.Beige;
//Name
var name = hmitrendcompanion.Name;
hmitrendcompanion.Name = "DefaultName";

Modify the following program code to access multilingual property access:

//Caption
var caption = hmitrendcompanion.Caption.Items[0].Text;
hmitrendcompanion.Caption.Items[0].Text = "<body><p>TestforMultilingualProperty</p></
body>";

Modify the following program code to access other typical properties of trend companion:

//Status bar
var statusBar = hmitrendcompanion.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 435
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of process control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of process control in control screen
items.
The following process control properties are supported in control screen items:

Property Name Property Type Accessibility


Online bool False
TimeStepSmoothingBase HmiTimeRangeBase False
TimeStepSmoothingFactor int False
BackColor Color False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
EditMode HmiEditMode False
TimeZone int False
ProcessView HmiDataGridViewPart True
EventHandlers HmiProcessControlEventHandlerCom‐ True
position
CaptionColor Color False
ShowFocusVisual bool False

Openness: API for automation of engineering workflows


436 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of process control:

//Width
var autoplay = hmiprocesscontrol.Width;
hmiprocesscontrol.Width = 1;
//BackColor
var backcolor = hmiprocesscontrol.BackColor;
hmiprocesscontrol.BackColor = Color.Beige;
//Name
var name = hmiprocesscontrol.Name;
hmiprocesscontrol.Name = "DefaultName";

Modify the following program code to access multilingual property:

//Caption
var caption = hmiprocesscontrol.Caption.Items[0].Text;
hmiprocesscontrol.Caption.Items[0].Text= "<body><p>TestforMultilingualProperty</p></
body>";

Modify the following program code to access other typical properties:

//status bar
var statusBar = hmiprocesscontrol.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 437
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of function trend control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of function trend control in control
screen items.
The following function trend control properties are supported in control screen items.

Property Name Property Type Accessibility


ShowStatisticRulers bool False
AreaSpacing ushort False
Online bool True
ExtendRulerToAxis bool False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top Int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
Font HmiFontPart True
TimeZone int False
ShowRuler bool False
ShiftAxes bool False
BackColor Color False
Legend HmiLegendPart True
EventHandlers HmiFunctionTrendControlEventHandler‐ True
Composition
FunctionTrendAreas HmiFunctionTrendAreaPartComposition True

Openness: API for automation of engineering workflows


438 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


CaptionColor Color False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of function trend control:

//Width
var autoplay = hmifunctiontrendcontrol.Width;
hmifunctiontrendcontrol.Width = 1;
//BackColor
var backcolor = hmifunctiontrendcontrol.BackColor;
hmifunctiontrendcontrol.BackColor = Color.Beige;
//Name
var name = hmifunctiontrendcontrol.Name;
hmifunctiontrendcontrol.Name = "DefaultName";

Modify the following program code to access multilingual property access:

//Caption
var caption = hmifunctiontrendcontrol.Caption.Items[0].Text;
hmifunctiontrendcontrol.Caption.Items[0].Text =
"<body><p>TestforMultilingualProperty</p></body>";

Modify the following program code to access other typical properties of function trend control:

//Status bar
var statusBar = hmifunctiontrendcontrol.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 439
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code: TrendArea in FunctionTrendControl using part


Modify the following program code to create a trendarea in a HmiFunctionTrendControl using
parts:

HmiSoftware hmiSoftware = GetHmiSoftware();


var screen = hmiSoftware.Screens;
var createdscreen = screen.Create("TestScreen_1");
HmiFunctionTrendControl funtntrend =
hmiSoftware.Screens[0].ScreenItems.Create<HmiFunctionTrendControl>("CTrendControl_1");
HmiFunctionTrendAreaPart part = funtntrend.FunctionTrendAreas.Create("part1");

Modify the following program code to searching a trendarea in HmiFunctionTrendControl using


part:

HmiFunctionTrendAreaPart part = funtntrend.FunctionTrendAreas.Find("part1");

Modify the following program code to checking a trendarea in HmiFunctionTrendControl using


part:

HmiSoftware hmiSoftware = GetHmiSoftware();


HmiFunctionTrendControl funtntrend =
hmiSoftware.Screens[0].ScreenItems.Create<HmiFunctionTrendControl>("CTrendControl_1");
HmiFunctionTrendAreaPart part = funtntrend.FunctionTrendAreas.Create("part1");
bool bPresent = funtntrend.FunctionTrendAreas.Contains(part);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Working with control screen items (Page 423)
HMI Unified Software object (Page 320)

Accessing properties of web control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of web control in control screen
items.
The following web control properties are supported in control screen items.

Property Name Property Type Accessibility


Url string False
BackColor Color False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False

Openness: API for automation of engineering workflows


440 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


Icon string False
Top Int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality False
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
EventHandlers HmiWebControlEventHandlerComposi‐ True
tion
CaptionColor Color False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access basic properties of web control:

//Width
var autoplay = hmiwebcontrol.width;
hmiwebcontrol.Width = 1;
//BackColor
var backcolor = hmiwebcontrol.BackColor;
hmiwebcontrol.BackColor = Color.Beige;
//Name
var name = hmiwebcontrol.Name;
hmiwebcontrol.Name = "DefaultName";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 441
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the followng program code to access multilingual property:

//Caption
var caption = hmiwebcontrol.Caption.Items[0].Text;
hmiwebcontrol.Caption.Items[0].Text= "<body><p>TestforMultilingualProperty</p></body>";

Modify the following program code to access other typical properties:

//Status bar
var statusBar = hmiwebcontrol.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of system diagnosis control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of system diagnosis control.
The following system diagnosis control properties are supported in control screen items:

Property Name Property Type Accessibility


SystemDiagnosisView HmiDataGridViewPart True
TimeZone Int32 False
Caption HmiTextPart True
BackColor Color False
WindowFlags HmiWindowFlag False
Icon string False
Top int32 False
Left int32 False
Width uint32 False
Height uint32 False
CurrentQuality HmiQuality True
Name string False

Openness: API for automation of engineering workflows


442 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Property Type Accessibility


ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
TimeZone int False
CaptionColor Color False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 81)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• System Diagnosis Control is created
See Working with control screen items (Page 423)

Program code
Modify the following program code to access properties of system diagnosis control:

HmiScreen screen = hmiSoftware.Screens.Create("Screen_1");


HmiSystemDiagnosisControl syscontrol =
screen.ScreenItems.Create<HmiSystemDiagnosisControl>("SysDiag_1");
syscontrol.SystemDiagnosisView.RowHeight = 50;
Debug.Assert(syscontrol.SystemDiagnosisView.RowHeight.Equals(50));
syscontrol.TimeZone = 28;
Debug.Assert(syscontrol.TimeZone.Equals(28));

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing properties of parameter set control (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of parameter set control in control
screen items.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 443
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

The following parameter set control properties are supported in control screen items.

Property Name Property Type Accessibility


ParameterSetTypeFixed string False
BackColor Color False
Caption MultilingualProperty False
WindowFlags HmiWindowFlag False
Icon string False
Top int False
Left int False
Width uint False
Height uint False
CurrentQuality HmiQuality True
Name string False
Visible bool False
Enabled bool False
TabIndex ushort False
ToolBar HmiToolBarPart True
StatusBar HmiStatusBarPart True
EditMode HmiEditMode False
TimeZone int False
ParameterView HmiDataGridViewPart True
ForeColor Color False
SelectionBackColor Color False
SelectionForeColor Color False
Font HmiFontPart True
EventHandlers HmiDetailedParameterControlEven‐ True
tHandlerComposition
CaptionColor Color False
HideDetails bool False
ShowFocusVisual bool False

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Screen and screenitem is created
See Working with control screen items (Page 423)

Openness: API for automation of engineering workflows


444 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access basic properties of parameter set control:

//Width
var autoplay = hmidetailedparametercontrol.Width;
hmidetailedparametercontrol.Width = 1;
//BackColor
var backcolor = hmidetailedparametercontrol.BackColor;
hmidetailedparametercontrol.BackColor = Color.Beige;
//Name
var name = hmidetailedparametercontrol.Name;
hmidetailedparametercontrol.Name = "Default";

Modify the following program code to access multilingual property:

//Caption
var caption = hmidetailedparametercontrol.Caption.Items[0].Text;
hmidetailedparametercontrol.Caption.Items[0].Text=
"<body><p>TestforMultilingualProperty</p></body>";

Modify the following program code to access other typical property:

//Status bar
var statusBar = hmidetailedparametercontrol.StatusBar;
var backColor = statusBar.BackColor;
statusBar.BackColor = Color.Aqua;
var enabled = statusBar.Enabled;
statusBar.Enabled = true;
var visible = statusBar.Visible;
statusBar.Visible = true;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 445
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.10.5 Faceplate instance screen items (RT Unified)

Working with faceplate instance in control screen items (RT Unified)

Introduction
You can perform the following tasks with faceplate instance items while using TIA Portal
Openness:
• Creating faceplate instance (controls)
• Deleting faceplate instance (controls)
• Enumerating faceplate instance (controls)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)
• Plant object type should be created

Program code
You can modify and use the following program code example while working with faceplate
instance.

Creating faceplate instance


Modify the following program code to create faceplate instance screen item:

HmiSoftware hmiSoftware = GetHMISoftware ();


HmiScreen hmiScreen= hmiSoftware.Screens.Create ("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens [0].ScreenItems;
HmiFaceplateContainer faceplate = hmiScreen.ScreenItems.Create<HmiFaceplateContainer>
("abcd");

Recoverable Exception will be raised if the Create method is called with Screen Name with which
Screen already exists in TIA Portal.

Openness: API for automation of engineering workflows


446 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Deleting faceplate instance


Modify the following program code to delete faceplate instance screen item:

//Case 1
HmiSoftware hmiSoftware = GetHMISoftware ();
HmiScreen hmiScreen = hmiSoftware.Screens.Create ("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens [0].ScreenItems;
HmiFaceplateContainer faceplate = hmiScreen .ScreenItems.Create<HmiFaceplateContainer>
("abcd");
If (faceplate! = null)
{
faceplate.Delete ();
}
//Case 2
HmiSoftware hmiSoftware = GetHMISoftware ();
HmiScreen hmiScreen = hmiSoftware.Screens.Create ("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens [0].ScreenItems;
HmiFaceplateContainer faceplate = hmiScreen .ScreenItems.Create<HmiFaceplateContainer>
("abcd");
IEngineeringObject ObjhmiLineEnggObj = faceplate;
if (ObjhmiLineEnggObj != null)
{
ObjhmiLineEnggObj.Invoke ("Delete", null);
}

Enumerating faceplate instance


Modify the following program code to enumerate faceplate instance screen items of screen:

HmiSoftware hmiSoftware = GetHMISoftware ();


HmiScreen hmiScreen = hmiSoftware.Screens.Create ("Screen_1");
HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens [0].ScreenItems;
foreach (var item in screenitems)
{
//work with screenitems
}

Modify the following program code to searching faceplate instance from screen items list on the
basis of name:

HmiScreenItemBase screenitems = hmiSoftware.Screens [0].ScreenItems.Find ("ScreenItems_1");

Modify the following program code to get faceplate instance from screenitems list on basis of
index:

HmiScreenItemBase screenitem = hmiSoftware.Screens [0].ScreenItems [0];

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 447
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to checking a particular faceplate instance exist in screen
item list by using Contains ( ):

HmiScreenItemBaseComposition screenitems = hmiSoftware.Screens[0].ScreenItems;


HmiFaceplateContainer faceplate = screenitems .Create<HmiFaceplateContainer> ("abcd");
bool isexists = screenitems.Contains(faceplate);

See also
Connecting to the TIA Portal (Page 81)
HMI Unified Software object (Page 320)
Opening a project (Page 113)

Accessing properties of faceplate instance (RT Unified)

Introduction
You can use the TIA Portal Openness to get and set properties of faceplate instance in control
screen items.
The following faceplate instance properties are supported in control screen items.

Property Name Datatype Description Accessibility


Name System.String Name of the faceplate instance R/W
ContainedType System.String Specifies contained faceplate type R/W
EventHandlers HmiFaceplateContai‐ EventHandlers of HmiFaceplate‐ R
nerEventHandlerCom‐ Container
position
Enabled System.Boolean Allow operator control R/W
CurrentQuality HmiQuality Connection Status R
Height System.UInt32 Specifies height of the control win‐ R/W
dow
Icon System.String specifies the icon on the control R/W
window
Caption Siemens.Engineer‐ Text to be shown in the caption of a R
ing.MultilingualTex screen window or windowed con‐
trol (Label)
TabIndex System.UInt16 Screen items specifying a tab index R/W
of 0 are not part of the tab order
Visible System.Boolean Specifies the visiblity of screen item R/W
Width System.UInt32 Specifies the width of the control R/W
window
WindowFlags Siemens.Engineering Specifies the window configuration R/W
miUnified.UI.Enum like ShowCaption, ShowBorder, Al‐
waysOnTop.
WindowFlag

Openness: API for automation of engineering workflows


448 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Datatype Description Accessibility


Top System.Int32 Specifies the value of the Y coordi‐ R/W
nates of control window
Left System.Int32 Specifies the value of the X coordi‐ R/W
nates of control window
Interface Siemens.Engineer‐ Faceplate interfaces R
ing.HmiUni‐
fied.UI.Parts.HmiFace‐
plateInterfaceCompos‐
tion
EventHandlers HmiFaceplateContai‐ eventHandlers of HmiFaceplate‐ R
nerEventHandlerCom‐ Container
position
ShowFocusVisual Boolean R/W
RotationAngle Int16 Specifies the rotation angle of the R/W
screen item in degree

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 449
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to get properties usage of faceplate instance:

HmiScreen screen = m_hmiSoftware.Screens[0];


HmiFaceplateContainer faceplate = screens[0].ScreenItems[0] as HmiFaceplateContainer;
//Get_faceplateContainedType
Var containedtype = faceplate.ContainedType;
Console.Writeline("Faceplate Container Type: " + containedtype);
Example Result = "Default Version No.\Faceplate type name";
//Get_CaptionText
string Caption = faceplate.Caption.Items[0].Text;
Console.WriteLine("Faceplate Caption: " + Caption);
//Get_WindowFlags
HmiWindowFlag WindowFlags = faceplate.WindowFlags;
Console.WriteLine("Faceplate WindowFlags: " + WindowFlags);
//Get_Icon
string Icon = faceplate.Icon;
Console.WriteLine("Faceplate Icon: " + Icon);
//Get_Top
int Top = faceplate.Top;
Console.WriteLine("Faceplate Top: " + Top);
//Get_Left
int Left = faceplate.Left;
Console.WriteLine("Faceplate Left: " + Left);
//Get_Width
uint Width = faceplate.Width;
Console.WriteLine("Faceplate Width: " + Width);
//Get_Height
uint Height = faceplate.Height;
Console.WriteLine("Faceplate Height: " + Height);
//Get_CurrentQuality
HmiQuality CurrentQuality = faceplate.CurrentQuality;
Console.WriteLine("Faceplate CurrentQuality: " + CurrentQuality);
//Get_Name
string Name = faceplate.Name;
Console.WriteLine("Faceplate Name : " + Name);
//Get_Visible
bool Visible = faceplate.Visible;
Console.WriteLine("Faceplate Visible: " + Visible);
//Get_Enabled
bool Enabled = faceplate.Enabled;
Console.WriteLine("Faceplate Enabled: " + Enabled);
//Get_TabIndex
ushort TabIndex = faceplate.TabIndex;
Console.WriteLine("Faceplate TabIndex: " + TabIndex);

Openness: API for automation of engineering workflows


450 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following programme code to set properties usage of faceplate instance:

//Set_ContainedType
faceplate.ContainedType = "V0.0.1\Faceplate_1";
//Set_CaptionText:
faceplate.Caption.Items[0].Text = "testCaption";
//Set_WindowFlags
faceplate.WindowFlags = HmiWindowFlag.CanSize;
//Set_Icon
faceplate.Icon = “testCaption”;
//Set_Top
faceplate.Top = 50;
//Set_Left
faceplate.Left = 50;
//Set_Width
faceplate.Width = 50;
//Set_Height
faceplate.Height = 50;
//Set_Name
faceplate.Name = “TestName”;
//Set_Visible
faceplate.Visible = true;
//Set_Enabled
faceplate.Enabled = true;
//Set_TabIndex
faceplate.TabIndex = 10;

Note
Get - Recoverable exception will be thrown in case respective consistency check fails for the
specified property. During setting of properties, the set operation fails consistency checks then
a Recoverable exception would be raised.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with control screen items (Page 423)

Accessing Unified Faceplates (RT Unified)

Introduction
You can use the TIA Portal Openness to set and update ContainedType property of Faceplate
container with the new location of Faceplate types in Library.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 451
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code

HmiFaceplateContainer faceplatecontainer = CreateFacePlateContainer("FacePlateContainer");


faceplateContainer ContainedType = "Faceplate_1";
var containedType = faceplateContainer.ContainedType;
//Output: "V0.0.2\\Faceplate_1
HmiFaceplateContainer faceplatecontainer = CreateFacePlateContainer("FacePlateContainer");
faceplateContainer ContainedType = "V0.0.1\Faceplate_1";
var containedType = faceplateContainer.ContainedType;
//Output: "V0.0.1\\Faceplate_1"

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Working with dynamization and events of faceplate instance (RT Unified)

Introduction
You can perform the following tasks related to dynamizations and event objects of faceplate
properties using TIA Portal Openness:
• Accessing dynamization (tag connections, animations, local scripts) for faceplate instances
• Accessing faceplate instance events with scripts and system functions
• Accessing property events of faceplate instance

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Openness: API for automation of engineering workflows


452 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code: Accessing dynamization for faceplate instances


For description on Accessing dynamization for faceplate instances, see Working with
dynamization for screen/ screen items (Page 459).

Program code: Accessing faceplate instance events with scripts and system functions
For description on Accessing faceplate instance events with scripts and system functions,
see Working with dynamization & events for screen/screen items using scripts (Page 456)

Program code: Accessing property events for faceplate instance


For description on Accessing property events for faceplate instance, see Working with events for
screen/screen items & properties (Page 453)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Working with dynamization for screens/screen items (Page 459)
Working with dynamization & events for screen/screen items using scripts (Page 456)
Working with events for screen/screen items & properties (Page 453)

5.11.10.6 Working with events for screen/screen items & properties (RT Unified)

Introduction
You can perform the followings tasks with property events and events for screen and screen
items while using TIA Portal Openness:
• Creating property events
• Enumerating property events
• Deleting property events
• Accessing properties of events
• Creating events for screens and screen items
• Enumerating events for screens and screen items
• Accessing properties of events for screen and screen items
• Deleting events for screen and screen items

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 453
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Unified Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with events for
screen/screen items.

Creating property events


Modify the following program code to create property events:

HmiScreen screen = ((HmiSoftware)targetSW).Screens.Create("MyScreen");


HmiCircle hmiCircle = screen.ScreenItems.Create<HmiCircle>("MYCircle");
//Event Creation
PropertyEventHandler propertyEvent = hmiCircle.PropertyEventHandlers.Create("ToolTipText",
PropertyEventType.Change);

Enumerating property events


Modify the following program code to enumerate property events:

HmiScreen screen = ((HmiSoftware)targetSW).Screens.Create("MyScreen");


HmiCircle hmiCircle = screen.ScreenItems.Create<HmiCircle>("MYCircle");
var hmiScreenPropeventDyn = screen.PropertyEventHandlers.Create(“Enabled”,
PropertyEventType.Change);
var enabledEvent = screen.PropertyEventHandlers.Find("Enabled", PropertyEventType.Change);
//Event Browse
Console.WriteLine("CountofEventActions"+ screen PropertyEventHandlers.Count.ToString());

Deleting property events


Modify and use the following program code to delete property events:

public void Delete()


PropertyEventHandler propertyEvent =
((HmiSoftware)targetSW).Screens[0].ScreenItems[0].PropertyEventHandlers.Create("ToolTipTex
t", PropertyEventType.Change);
var changedEvent = screen.PropertyEventHandlers.Find(“ToolTipText”,
PropertyEventType.Change);
//Event Deletion
changedEvent.Delete();

Openness: API for automation of engineering workflows


454 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of events


Modify the following program code to get event properties:

//Event Get
PropertyEventType eventType = propertyEvent.EventType;
string propertyName = propertyEvent.PropertyName;
IHmiScript hmiScript = propertyEvent.Script;
//Script Action in Event Get
bool hmiScriptEventAsync = hmiScript.Async;
string hmiScriptEventGlobal = hmiScript.GlobalDefinitionAreaScriptCode;
string hmiScriptEventCode = hmiScript.ScriptCode;
HmiValidationResult result = hmiScript.SyntaxCheck();

Creating events for screen and screen items


Modify the following program code to create the event at the screen or screen item level object
using EventHandler navigator:

var screenComp = ((HmiSoftware)targetSWTag).Screens;


HmiScreen screenOne = screenComp.Create("Screen2");
HmiScreenEventHandler screenHandler =
screenOne.EventHandlers.Create(HmiScreenEventType.Unloaded);

Enumerating events for screen and screen items:


Modify the following program code to enumerate events for screen and screen items:

public EventHandler Find(string propertyName);


var screenComp = ((HmiSoftware)targetSWTag).Screens;
HmiScreen screenOne = screenComp.Create("Screen2");
HmiScreenEventHandler screenHandler =
screenOne.EventHandlers.Create(HmiScreenEventType.Unloaded);
HmiScreenEventHandler screenHandlerSearched =
screenOne.EventHandlers.Find(HmiScreenEventType.Unloaded);

Accessing properties of events for screen and screen items:


Modify the following program code to get properties of events for screen and screen items:

var screenComp = ((HmiSoftware)targetSWTag).Screens;


HmiScreen screenOne = screenComp.Create("Screen2");
HmiScreenEventHandler screenHandler =
screenOne.EventHandlers.Create(HmiScreenEventType.Unloaded);
Console.WriteLine(screenOne.Name + ".EventHandler.EventType - {0}",
screenHandler.EventType);
Console.WriteLine(screenOne.Name + ".EventHandler.Script.Async - {0}",
screenHandler.Script.Async);
Console.WriteLine(screenOne.Name + ".EventHandler.Script.GlobalDefinitionAreaScriptCode -
{0}", screenHandler.Script.GlobalDefinitionAreaScriptCode);
Console.WriteLine(screenOne.Name + ".EventHandler.Script.ScriptCode - {0}",
screenHandler.Script.ScriptCode);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 455
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Deleting events for screen and screen items:


Modifythe following program code to delete events for screen and screen items:

public void Delete ()


HmiSoftware hmisoftware = GetHMISoftware();
HmiScreen hmiscreen = hmisoftware.Screens.Create(Guid.NewGuid().ToString());
var hmiscreenPropEventDyn = hmiscreen.PropertyEventHandlers.Create("Enabled",
PropertyEventType.Change);
var enabledevent = hmiscreen.PropertyEventHandlers.Find("Enabled",
PropertyEventType.Change);
enabledevent.Delete();

Note
Create - Recoverable exception will be thrown in case respective property events and events for
screen and screen items is not supported for the specified property. If during set of properties the
set operation fails consistency checks then a Recoverable exception would be raised.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)

5.11.10.7 Working with dynamization & events for screen/screen items using scripts (RT
Unified)

Introduction
You can perform the following tasks with script to configure property dynamization and events
for screen/screen items while using TIA Portal Openness:
• Creating script dynamizations
• Enumerating script dynamizations
• Deleting script dynamizations
• Accessing properties of script dynamizations
• Accessing properties of trigger
• Checking syntax

Openness: API for automation of engineering workflows


456 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connecte to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Uinified Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with script
dynamization for screen/screen items.

Creating script dynamizations


Modify the following program code to create script dynamizations for a property:

public DynamizationBase Create<DynamizationBase>(string propertyName);


HmiScreen screen = m_hmisoftware.Screen[0];
DynamizationBaseComposition dyns = screen.Dynamizations;
ScriptDynamization scriptDynamic = dyns.Create<ScriptDynamization>("BackColor");

Enumerating script dynamizations


Modify the following program code to enumerate script dynamization of a property:

public DynamizationBase Find(string propertyName);


HmiScreen screen = m_hmiSoftware.Screens[0];
DynamizationBaseComposition dyns = screen.Dynamizations;
if (dyns is ScriptDynamization)
{
ScriptDynamization scriptDynamic = (ScriptDynamization)dyns.Find("BackColor");
}

Deleting script dynamizations


Modify the following program code to delete script dynamization for a property:

HmiScreen screen = m_hmiSoftware.Screens[0];


DynamizationBaseComposition dyns = screen.Dynamizations;
if (dyns is ScriptDynamization)
ScriptDynamization scriptDynamic = (ScriptDynamization)dyns.Find("BackColor");
scriptDynamic.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 457
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of script dynamizations


Modify the following program code to get and set properties of script dynamization:

HmiScreen screen = m_hmiSoftware.Screens[0];


DynamizationBaseComposition dyns = screen.Dynamizations;
foreach (DynamizationBase dynamic in dyns)
{
if (dynamic.DynamizationType == DynamizationType.Script)
{
ScriptDynamization scriptDynamization = (ScriptDynamization)dynamic;
scriptDynamization.Async = true;
scriptDynamization.GlobalDefinitionAreaScriptCode = @"Add(parameter1,parameter2)";
scriptDynamization.ScriptCode = @"
var value;
let tag1 = Tags('Tag_1');
let tagValue1 = tag1.Read();
HMIRuntime.Trace('value of MyTag1: ' + tagValue1);
return value; ";
Trigger triggerObj = scriptDynamization.Trigger;
}
}

Accessing properties of Trigger


Modify the following program code to get and set properties of trigger:

HmiScreen screen = m_hmiSoftware.Screens[0];


DynamizationBaseComposition dyns = screen.Dynamizations;
foreach (DynamizationBase dynamic in dyns)
{
if (dynamic.DynamizationType == DynamizationType.Script)
{
ScriptDynamization scriptDynamization = (ScriptDynamization)dynamic;
// Property write
scriptDynamization.Trigger.Type = TriggerType.CustomCycle;
scriptDynamization.Trigger.CustomDuration = "T500ms";
scriptDynamization.Trigger.Tags = new List<string>() { "Tag_1" };
// Property read
Console.WriteLine(scriptDynamization.Trigger.Type);
Console.WriteLine(scriptDynamization.Trigger.CustomDuration);
Console.WriteLine(scriptDynamization.Trigger.Tags);
}
}

Openness: API for automation of engineering workflows


458 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Syntax Check
Modify the following program code to check syntax for script code or global script code using
SyntaxCheck action (method) of script dynamization:

HmiScreen screen = m_hmiSoftware.Screens[0];


DynamizationBaseComposition dyns = screen.Dynamizations;
foreach (DynamizationBase dynamic in dyns)
{
if (dynamic.DynamizationType == DynamizationType.Script)
{
ScriptDynamization scriptDynamization = (ScriptDynamization)dynamic;
scriptDynamization.ScriptCode = @"
var value;let tag1 = Tags('Tag_1');
let tagValue1 = tag1.Read();
HMIRuntime.Trace('value of MyTag1: ' + tagValue1);
return value; ";
HmiValidationResult syntaxCkResult = scriptDynamization.SyntaxCheck();
IEnummerable<string> error = syntaxCkResult.Errors;
IEnumerable<string> warnings = syntaxCkResult.Warning;
}
}

Note
Create - Recoverable exception will be thrown in case respective dynamization is not supported
for the specified property. If during set of properties the set operation fails consistency checks
then a Recoverable exception would be raised.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)

5.11.10.8 Working with dynamization for screens/screen items (RT Unified)

Introduction
You can perform the following tasks with dynamization feature of screens/screen items while
using TIA Portal Openness:
• Creating dynamization for a property
• Enumerating dynamization for a property
• Deleting dynamization for a property
• Accessing common properties of dynamization
• Accessing properties of tag dynamization

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 459
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

• Accessing properties of flasing dynamization


• Accessing properties of resourcelist dynamization

Note
For accessing dynamization for a properties at part level, you need to access respective part of
Control. For part information, see Accessing properties of trend control (Page 81)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A Project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Program code
You can modify and use the following program code examples while working with
dynamizations for screen/screen items.

Creating dynamization for a property


Modify the following program code to create dynamization for a property:

HmiScreen screen = m_hmiSoftware.Screens[0];


DynamizationBaseComposition dyns = screen.Dynamizations;
// Flashing dynamization
FlashingDynamization FlashingDyn = dyns.Create<FlashingDynamization>("BackColor");
// ResourceList dynamization
ResourceListDynamization ResListDyn = dyns.Create<ResourceListDynamization>("DisplayName");
// Tag dynamization
TagDynamization tagDyn = dyns.Create<TagDynamization>("Width");

Enumerating dynamization of a property


Modify the following program code to enumerate dynamization for a property:

HmiScreen screen = m_hmiSoftware.Screens[0];


DynamizationBaseComposition dyns = screen.Dynamizations;
// Flashing dynamization
FlashingDynamization FlashDyn = (FlashingDynamization)dyns.Find("BackColor");
// ResourceList dynamization
ResourceListDynamization resourceDyn = (ResourceListDynamization)dyns.Find("DisplayName");
// Tag dynamization
TagDynamization tagDyn = (TagDynamization)dyns.Find("Width");

Openness: API for automation of engineering workflows


460 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Deleting dynamization of a property


Modify the following program code to delete dynamization of a property:

public void Delete ()


HmiScreen screen = m_hmiSoftware.Screens[0];
DynamizationBaseComposition dyns = screen.Dynamizations;
DynamizationBase dynamization = dyns.Find("BackColor");
dynamization.Delete();

Accessing common properties of dynamization


Modify the following program code to get common properties of dynamization:

HmiSoftware m_hmiSoftware = ..;


DynamizationBaseComposition screenDynamizations = m_hmiSoftware.Screens[0].Dynamizations;
DynamizationBase screenDynamization = screenDynamizations.Find("BackColor");
string propertyName = screenDynamization.PropertyName;
DynamizationType dynamizationType = screenDynamization.DynamizationType;

Accessing properties of tag dynamization


Modify the following program code to get and set properties of tag dynamization:

HmiScreen screen = m_hmiSoftware.Screens[0];


TagDynamization tagDynamization = (TagDynamization)screen.Dynamizations.Find("Width");
foreach (DynamizationBase dynamization in screen.Dynamizations)
{
if (dynamization.DynamizationType == DynamizationType.Tag)
{
TagDynamization TagDynamization = (TagDynamization)dynamization;
TagDynamization.Tag = "HmiTagName";
TagDynamization.UseIndirectAddressing = true;
TagDynamization.ReadOnly = true;
}
}

Accessing properties of flashing dynamization


Modify the following program to get and set properties of flashing dynamization:

HmiScreen screen = m_hmiSoftware.Screens[0];


foreach (DynamizationBase dynamization in screen.Dynamizations)
{
if (dynamization.DynamizationType == DynamizationType.Flashing)
{
FlashingDynamization flashingDynamization = (FlashingDynamization)dynamization;
flashingDynamization.AlternateColor = Color.Beige;
flashingDynamization.Color = Color.FromArgb(12, 22, 152, 200);
flashingDynamization.FlashingCondition = FlashingCondition.Always;
flashingDynamization.FlashingRate = FlashingRate.Medium;
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 461
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Accessing properties of resourcelist dynamization


Modify the following program code to get and set properties of resourcelist dynamization

HmiScreen screen = m_hmiSoftware.Screens[0];


foreach (DynamizationBase dynamization in screen.Dynamizations)
{
if (dynamization.DynamizationType == DynamizationType.ResourceList)
{
ResourceListDynamization resourceListDyn = (ResourceListDynamization)dynamization;
resourceListDyn.Tag = "Tag name";
resourceListDyn.ResourceList = "Resource list name";
}
}

Note
Create - Recoverable exception will be thrown in case respective dynamization is not supported
for the specified property. If during set of properties the set operation fails consistency checks
then a Recoverable exception would be raised.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
HMI Unified Software object (Page 320)
Accessing properties of trend control (Page 432)

5.11.10.9 Checking license for access Unified device (RT Unified)

Introduction
You can use the TIA Openness interface to check any Openness client application for the
presence of WinCC Unified license, so that a client application cannot bypass licensing using
Openness interfaces.
You are only able to access to an HMI Unified device and all its underlying objects (e.g. tags,
alarms, screen, etc.) when HMI Unified license is available. If WinCC Unified is not licensed than
any operation on device level (e.g. create, find, delete) results in a null value being returned from
Openness API.

Note
For HMI Unified Software, If license is invalid, then a null value will be returned.

Openness: API for automation of engineering workflows


462 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Access to HMI Software object
See HMI Unified Software object (Page 320)

Program code
Modify the following program code to access the device or device sub systems when license is
not available, a null value is returned:

private static void ListDevices(Project project)


{
foreach (var device in project.Devices)
{
ListDeviceItem(device);
}
}
private static void ListDeviceItem(Device device)
{
Console.Write("HMI device - " + device.Name);
foreach (var item in device.DeviceItems)
{
Console.WriteLine("HMI device type - " + item.TypeIdentifier);
var softContainer = item.GetService<SoftwareContainer>();
if (softContainer != null)
{
var softTarget = softContainer.Software;
if (softTarget != null)
{
Console.WriteLine("HMI device software - " + softTarget.Name);
}
}
}
}

Note
While accessing the above program code, the softTarget will be null, and accessing sub-systems,
such as alarms, tags will not be posssible.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 463
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to access the device or device sub systems when license is
available, a null value is returned.

private static void ListDevices(Project project)


{
foreach (var device in project.Devices)
{
ListDeviceItem(device);
}
}
private static void ListDeviceItem(Device device)
{
Console.Write("HMI device - " + device.Name);
foreach (var item in device.DeviceItems)
{
Console.WriteLine("HMI device type - " + item.TypeIdentifier);
var softContainer = item.GetService<SoftwareContainer>();
if (softContainer != null)
{
var softTarget = softContainer.Software;
}
if (softTarget != null)
{
Console.WriteLine("HMI device software - " + softTarget.Name);
}
}
}
}

Note
While accessing the above program code, the softTarget will have device container, and
accessing sub-systems, such as alarms, tags will be possible.

The return value of NULL for device container denotes that the license is not available. The
recoverable exception does not support custom exception messages, hence the use of NULL as
a return value.

See also
Connecting to the TIA Portal (Page 81)
HMI Unified Software object (Page 320)

5.11.11 Accessing device name of HMI Panel (RT Unified)

Introduction
You can use the TIA Portal Openness application to read and write the device names of the
unified and non-unified HMI device.

Openness: API for automation of engineering workflows


464 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Properties
The following attribute can be accessed and edited in HMI device:

Attribute Data type Description Access


Name String Name of HMI device R/W

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113)

Program code

Tiaproject = tiaPortal.Projects[0];
var deviceUnderTest = Tiaproject.Devices[0];
//Set
deviceUnderTest.Name = "Test1";
//Get
var deviceName = deviceUnderTest.Name;
foreach (var deviceItem in deviceUnderTest.DeviceItems)
{
//Set
deviceItem.Name = "TestDeviceItem1";
//Get
var deviceName = deviceItem.Name;
}

5.11.12 Accessing common plant model hierarchies (RT Unified)

5.11.12.1 Working with plant view (RT Unified)

Introduction
You can perform the following tasks related to plant view while using TIA Portal Openness:
• Create plant view
• Delete plant view
• Rename plant view

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 465
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code to create a plant view:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Create("ABCManufacturingPlant");

Note
You can create only one plant view inside a project.

Modify the following program code to delete or remove a plant view:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
plantView.Delete();

Modify the following program code to rename a plant view by updating the 'Name' property:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
plantView.Name = "New_PlantView_Name";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.12.2 Working with plant view nodes (RT Unified)

Introduction
You can perform the following tasks related to plant view node while using TIA Portal Openness:
• Create plant view nodes
• Delete plant view nodes
• Rename plant view nodes

Openness: API for automation of engineering workflows


466 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Properties
The following properties are supported in Plant View Node using TIA Portal Openness:

Property Name Data Type Accessibility


HierarchyPath String R
PlantObject Siemens.Engineering.HmiUni‐ R
fied.Cpm.PlantObject
Name String R/W
PlantView String R
ViewPath String R
PlantViewNodes PlantViewNodeComposition R

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code to create plant view node under a plant view:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNodeComposition viewNodes = plantView.PlantViewNodes;
PlantViewNode mixingNode = viewNodes.Create("Mixing");

Modify the following program code to create plant view node under another plant view node:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNodeComposition viewNodes = plantView.PlantViewNodes;
PlantViewNode mixingNode = viewNodes.Create("Mixing");
PlantViewNode motorNode = mixingNode.Create("Motor");

Note
You can create any number of plant view nodes inside a plant view or plant view node itself.

Modify the following program code to remove or delete a plant view node:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNode mixingNode = plantView.PlantViewNodes.Find("Mixing");
mixingNode.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 467
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to rename a plant view node by updating the 'Name'
property:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNodeComposition viewNodes = plantView.PlantViewNodes;
PlantViewNode mixingNode = viewNodes.Create("Mixing");
mixingNode.Name = "New_PlantViewNode_Name";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.12.3 Enumerating plant view (RT Unified)

Introduction
You can use the TIA Portal Openness to enumerate plant view present on given project in TIA
Portal.

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code to enumerate all plant views of the project:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


foreach (var item in plantViews)
{
// work with plant views (currently only 1 plant view can be created inside a project)
}

Modify the following program code to find a plant view from plant view list based on the name:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");

Openness: API for automation of engineering workflows


468 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to find a plant view from plant view list based on index:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews[0];

Modify the following program code to find plant view node from the plant view list based on the
hierarchy path of the required plant view node:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantViewNode plantViewNode = plantViews.FindPlantViewNode("ABCManufacturingPlan\Mixing
\Motor");

Modify the following program code to find a plant view node from the plant view node list based
on the name of the plant view:

PlantViewNodeComposition plantViewNodes =
m_tiaPortalApp.Projects[0].PlantViews[0].PlantViewNodes;
PlantViewNode plantViewNode = plantViewNodes.Find("Mixing");

Modify the following program code to enumerate all plant view nodes list available inside plant
view:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantViewNodeComposition nodes = plantView.PlantViewNodes;
foreach (var item in nodes)
{
// work with plant view nodes inside plant view
}

Modify the following program code to enumerate all plant view nodes available inside any
hierarchial level:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantViewNodeComposition nodes = plantView.PlantViewNodes;
PlantViewNodeComposition subNodes = nodes[2].PlantViewNodes;
foreach (var item in subNodes)
{
// work with plant view nodes inside 2nd node within the plant view
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 469
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

5.11.12.4 Working with plant view to device (RT Unified)

Introduction
You can perform the following tasks related to accessing plant view hierarchies and plant object
while using TIA Portal Openness:
• Assign device to the plant view
• Change device to the plant view
• Remove device to the plant view

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code to assign a device to the plant view by setting the
AssignedHmiDevice property:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Create("ABCManufacturingPlant");
plantView.AssignedHmiDevice = "HMI_RT_1";

Modify the follwing program code to change a device to the plant view by setting a device name
to AssignedHmiDevice property.

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Create("ABCManufacturingPlant");
plantView.AssignedHmiDevice = "HMI_RT_2";

Modify the following program code to remove device to the plant view by setting a blank device
name to AssignedHmiDevice property.

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Create("ABCManufacturingPlant");
plantView.AssignedHmiDevice = string.Empty;

Note
To remove the device, use only string.empty. Passing NULL or whitespace (" "), will be treated as
a device name and will return device not found error message

Openness: API for automation of engineering workflows


470 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.13 Accessing common plant model instance (RT Unified)

5.11.13.1 Working with CPM object instance (RT Unified)

Introduction
You can perform the following tasks related to access CPM instance based on CPM type while
using TIA Portal Openness:
• Create CPM object instances
• Delete CPM object instances
• Rename CPM object instances

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• Create a Plant

Program code
Modify the following program code to create CPM object instance:

// Instance inside plant view


PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;
PlantView plantView = plantViews.Create("ABCManufacturingPlant");
plantView.AssignedHmiDevice = "HMI_RT_1";
PlantViewNodeComposition nodes = plantView.PlantViewNodes;
PlantViewNode node = nodes.Create("ObjectLevel1", "Plant_Object_Type_1");
//Instance inside plant view node
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer",
"Plant_Object_Type_1");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 471
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to remove or delete a CPM object instance:

PlantViewNode mixingNode = plantView.PlantViewNodes.Find("Mixing");


PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Find("IngredientMixer");
mixerObject.Delete();

Modify the following program code to rename a CPM object instance by updating the 'Name'
property:

PlantViewNode mixingNode = plantView.PlantViewNodes.Find("Mixing");


PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Find("IngredientMixer");
mixerObject.Name = "New_PlantViewNode_Name";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.13.2 Working with plant view nodes of CPM object instance (RT Unified)

Introduction
You can perform the following tasks related to access plant view nodes of CPM object instances
while using TIA Portal Openness:
• Create plant view nodes
• Delete plant view nodes
• Rename plant view nodes

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


472 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to create a plant view node inside a CPM object instance

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNode mixerObject = plantView.PlantViewNodes.Create("ObjectLevel1",
"Plant_Object_Type_1");
PlantViewNode mixingNode = mixerObject.PlantViewNodes.Create("Mixing");

Note
You can create any number of plant view node inside a CPM object

Modify the following program code to create a CPM object instance inside a plant view node:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject = mixingNode.PlantViewNodes.Create("ObjectLevel1",
"Plant_Object_Type_1");

Note
You can create any number of CPM object instances inside a plant view node

Modify the following program code to remove or delete a plant view node from a plant view
node:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNode mixerObject = plantView.PlantViewNodes.Find("ObjectLevel1");
PlantViewNode mixingNode = mixerObject.PlantViewNodes.Find("Mixing");
mixingNode.Delete();

Modify the following program code to rename a plant view node of CPM object instance by
updating the 'Name' property:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews.Find("ABCManufacturingPlant");
PlantViewNode mixerObject = plantView.PlantViewNodes.Find("ObjectLevel1",
"Plant_Object_Type_1");
PlantViewNode mixingNode = mixerObject.PlantViewNodes.Find("Mixing");
mixingNode.Name = "New_PlantViewNode_Name";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 473
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.13.3 Enumerating interface tags of CPM object instance (RT Unified)

Introduction
You can use the TIA Portal Openness to enumerate a member of a CPM object instance.

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code to enumerate all members of the CPM object instance:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews[0];
PlantViewNodeComposition plantViewNodes = plantView.PlantViewNodes;
PlantViewNode plantViewNode = plantViewNodes.Find("MixerObject_1");
PlantObject plantObject = plantViewNode.PlantObject;
PlantObjectInterfaceComposition interfaces = plantObject?. PlantObjectInterfaces;

Note
In the above example, the ?.operator refers to null check

Modify the following program code to find an interface tag from interfaces list based on ‘Name’:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews[0];
PlantViewNodeComposition plantNodes = plantView.PlantViewNodes;
PlantViewNode plantViewNode = plantNodes.Find("MixerObject_1");
PlantObject plantObject = plantViewNode.PlantObject;
PlantObjectInterface interface = plantObject. PlantObjectInterfaces.Find("Interface_1");

Openness: API for automation of engineering workflows


474 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to find an interface tag from interface list based on index:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews[0];
PlantViewNodeComposition plantViewNodes = plantView.PlantViewNodes;
PlantViewNode plantViewNode = plantViewNodes.Find("MixerObject_1");
PlantObject plantObject = plantViewNode.PlantObject;
PlantObjectInterfaceComposition interfaces = plantObject.PlantObjectInterfaces;
PlantObjectInterface interface = interfaces[0];

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.14 Accessing properties for interface/logging tags of plant object instances (RT
Unified)

5.11.14.1 Accessing/Updating properties of interface tags of CPM plant object instances (RT
Unified)

Introduction
You can use the TIA Portal Openness to access and update the properties on interface tags of
CPM plant object instance.
The following properties can be accessed on interface tags of CPM plant object instance:

Property Name Data type Description Accessibility


Name System.String Name of interface tags R/W
PlcTag System.String PLC tag associated with R/W
interface tags
Connection System.String Connection of inter‐ R/W
face tags
PlcName System.String PLC name associated R
with interface tags
AccessMode PlantObjectTagAccessMode Access mode for inter‐ R
face tags
DataType System.String Object type of the inter‐ R
face tags
MaxLength System.Int Length of interface tags R
HmiDataType System.Int HMI data type of inter‐ R
face tags
AcquisitionMode PlantObjectTagAcquisitionMode Acquisition mode of in‐ R/W
terface tags

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 475
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Property Name Data type Description Accessibility


AcquisitionCycle System.Int Acquisition cycle for in‐ R/W
terface tags
Persistent System.Bool Persistence for internal R
tags of CPM object in‐
stance
Comment System.String Comment R/W
Members PlantObjectInterfaceMemberCom‐ Members of Interface R
position Tag

Note
PLCTag & Connection property can only be configured after assigning Hmi device to the plant
view.

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code to access all the properties of interface tags:

// Instance inside plant view node


PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer", "Mixer");
PlantObjectInterfaceComposition interfaceTags =
mixerObject.PlantObject.PlantObjectInterfaces;
PlantObjectInterface interfaceTag = interfaceTags.FirstOrDefault();
string name = interfaceTag.Name;
MultilingualText comment = interfaceTag.Comment

Openness: API for automation of engineering workflows


476 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to update some properties of an interface tag, such as
Comment, PLC Tag, Connection, Acquisition Mode, Acquisition Cycle:

// Instance inside plant view node


PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer", "Mixer");
PlantObjectInterfaceComposition interfaceTags =
mixerObject.PlantObject.PlantObjectInterfaces;
PlantObjectInterface interfaceTag = interfaceTags.FirstOrDefault();
interfaceTag.Name = "New_InterfaceTag_Name";
interfaceTag.Comment.Items[0].Text = "New_InterfaceTag_Comment";
interfaceTag.AcquisitionMode = PlantObjectTagAcquisitionMode.CyclicContinuous;
interfaceTag.AcquisitionCycle = "T12s";
interfaceTag.Connection = "Connection_1";
interfaceTag.PlcTag = "PLC_Tag_1";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.14.2 Accessing/Updating properties of members tags of interface tags (RT Unified)

Introduction
You can use the TIA Portal Openness to access and update properties of member tags of
interface tags.
The following properties can be accessed on member tags of interface tags:

Property Name Data type Description Accessibility


Name System.String Name of member tags R
DataType System.String Object type of the R
member tags
MaxLength System.Int Length of member tags R
HmiDataType System.String HMI data type of mem‐ R
ber tags
InitialMinValue PlantObjectTagLowerRange Lower range value R/W
InitialMaxValue PlantObjectTagUpperRange Upper range value R/W
InitialValue System.Object Initial value R/W
SubstituteValue PlantObjectTagSubstituteValue Substitute value R
Comment MultilingualText Comment R/W
Members PlantObjectInterfaceMemberCom‐ Members of Member R
position Tag
LoggingTags PlantObjectLoggingTagComposi‐ LoggingTags of Mem‐ R
tion berTag

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 477
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Program code
Modify the following program code:

PlantViewComposition plantViews = m_tiaPortalApp.Projects[0].PlantViews;


PlantView plantView = plantViews[0];
PlantViewNodeComposition plantViewNodeComposition = plantView.PlantViewNodes;
PlantViewNode plantViewNode = plantViewNodeComposition[0];
PlantObjectInterfaceComposition tagComposition =
plantViewNode.PlantObject.PlantObjectInterfaces;
PlantObjectInterface interfaceTag = tagComposition[0];
PlantObjectInterfaceMemberComposition memberTags = interfaceTag.Members;
PlantObjectInterfaceMember memberTag = memberTags.FirstOrDefault();
//GetAttributes
List<string> listOfPropertyNames = new List<string>()
{
"Name"
};
var listOfPropertyValues = memberTag.GetAttributes(listOfPropertyNames);
//SetAttributes
IEnumerable<KeyValuePair<string, object>> propertyNameValuePairList = new
List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("Name", "MemberTag_1");
};
memberTag.SetAttributes(propertyNameValuePairList);

Modify the following program code to access all the properties of member tags:

// Instance inside plant view node


PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer", "Mixer");
PlantObjectInterfaceComposition interfaceTags =
mixerObject.PlantObject.PlantObjectInterfaces;
PlantObjectInterfaceMemberComposition memberTags = interfaceTag.Members;
PlantObjectInterfaceMember memberTag = memberTags.FirstOrDefault();
string name = memberTag.Name;
string comment = memberTag.Comment.Items[0].Text;

Openness: API for automation of engineering workflows


478 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Modify the following program code to update properties of a member tag of a CPM object
instance:

// Instance inside plant view node


PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer", "Mixer");
PlantObjectInterfaceComposition interfaceTags =
mixerObject.PlantObject.PlantObjectInterfaces;
PlantObjectInterfaceMember memberTag = memberTags.FirstOrDefault();
memberTag.Comment.Items[0].Text = "New_MemberTag_Comment";
memberTag.InitialValue = 2;
memberTag.InitialMinValue.Value = 2;
memberTag.InitialMinValue.ValueType = PlantObjectTagLimitValueType.Constant;
memberTag.InitialMaxValue.Value = 2;
memberTag.InitialMaxValue.ValueType = PlantObjectTagLimitValueType.Constant;

Modify the following code to access all the logging tags of a member tag of CPM object instance:

// Instance inside plant view node


PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer", "Mixer");
PlantObjectInterfaceComposition interfaceTags =
mixerObject.PlantObject.PlantObjectInterfaces;
PlantObjectInterface interfaceTag = interfaceTags.FirstOrDefault();
PlantObjectInterfaceMemberComposition memberTags = interfaceTag.Members;
PlantObjectInterfaceMember memberTag = memberTags.FirstOrDefault();
PlantObjectLoggingTagComposition loggingTags = memberTag.LoggingTags;
PlantObjectLoggingTag loggingTag = loggingTags.FirstOrDefault();

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.11.14.3 Accessing/Updating properties of logging tags of member tags (RT Unified)

Introduction
You can use the TIA Portal Openness to access logging tags of member tags present inside CPM
object instance.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 479
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

The following properties can be accessed on logging tags of member tags present inside CPM
object instance:

Property name Data type Description Accessibilty


AggregationDelay System.TimeSpan Aggregation delay value R
AggregationMode PlantObjectLoggingTagAg‐ Aggregation Mode value R
gregationMode
Cycle System.String Logging Cycle of logging tag R
CycleFactor System.UInt32 Logging Cycle Factor vlaue R
DataLog  System.String R
Source System.string Source Logging Tag R
TriggerMode PlantObjectLoggingTagTrig‐ TriggerMode of Logging tag R
gerMode
TriggerTag System.String TriggerTag Value R
TriggerTagBitNumber System.UInt32 TriggerTagBitNumber value R
Name System.string Name of logging tag R
LogConfiguration System.String Data log of logging tag R
LoggingMode PlantObjectLoggingTagLog‐ Logging mode of logging tag R
gingMode
SmoothingMode PlantObjectLoggingTagS‐ Smoothing mode of logging R
moothingMode tag
SmoothingMinTime System.TimeSpan Minimum time of logging tag R
SmoothingMaxTime System.TimeSpan Maximum time of logging tag R
SmoothingDeltaValue System.Double Delta of logging tag R
LimitScope PlantObjectLoggingTagLimit‐ Limit scope of logging tag R
Scope
HighLimit System.Object High limit of logging tag R
LowLimit System. Object Low limit of logging tag R

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


480 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.11 Functions for accessing the data of an HMI Unified device (RT Unified)

Program code
Modify the following program code to access all the properties of logging tags:

// Instance inside plant view node


PlantViewNode mixingNode = plantView.PlantViewNodes.Create("Mixing");
PlantViewNode mixerObject =
plantView.PlantViewNodes.Find("Mixing").PlantViewNodes.Create("IngredientMixer", "Mixer");
PlantObjectInterfaceMemberComposition interfaceTags =
mixerObject.PlantObject.PlantObjectInterfaceMembers;
PlantObjectInterfaceMember interfaceTag = interfaceTags.FirstOrDefault();
PlantObjectInterfaceMemberComposition memberTags = interfaceTag.Members;
PlantObjectInterfaceMember memberTag = memberTags.FirstOrDefault();
PlantObjectLoggingTagComposition loggingTags = memberTag.LoggingTags;
PlantObjectLoggingTag loggingTag = loggingTags.FirstOrDefault();
string name = loggingTag.Name;
object lowLimit = loggingTag.LowLimit;

Note
You will not be able to update any property of PlantObjectLoggingTag class, associated to a CPM
object instance logging tag.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 481
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12 Functions for accessing the data of a PLC device

5.12.1 Functions for downloading data to PLC device

5.12.1.1 Downloading PC System

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can download PC-Station Plus and the SW-CPU independently. In order to download the PC-
Station Plus configuration, you must retrieve stationmanager device item of rack of device and
get the download provider as a service. SW-CPU itself must be retrieved as a device item for the
same operation.

Program code: Download software and hardware components


You are able to download software and hardware components to a device via DownloadProvider
service that can be acquired from a given DeviceItem. If a DeviceItem represents a downloadable
target an instance of DownloadProvider will be returned on GetService call. Otherwise it will be
null.l

DeviceItem stationManager = dev.DeviceItems.First(p => p.PositionNumber ==


0).DeviceItems.First(a => a.PositionNumber == 125);
DownloadProvider downloadProviderStationManager =
stationManager.GetService<DownloadProvider>();
if (downloadProviderStationManager == null)
{
//no download is possible for PC-Station
}
DeviceItem swCpu = dev.DeviceItems.First(p => p.Name == "Software PLC_1");
DownloadProvider downloadProviderSwCpu = swCpu.GetService<DownloadProvider>();

Openness: API for automation of engineering workflows


482 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to configure Network parameters:

ConnectionConfiguration connConfig = downloadProviderStationManager.Configuration;


ConfigurationMode configurationMode = connConfig.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces.Find("ASIX AX88179
USB 3.0 to Gigabit Ethernet Adapter", 1);
ConfigurationTargetInterface targetInterface = pcInterface.TargetInterfaces.Find("2 X2");
IConfiguration targetConfiguration = pcInterface.TargetInterfaces[0];
bool isConfigured = connConfig.ApplyConfiguration(targetInterface);
if (isConfigured)
...

It must be noted that, in case the target system reboots after downloading PC-Station Plus
configuration, the default behavior in openness is waiting. This means that, the openness code
flow is stopped until the first stage download is successful (and target system is rebooted) or
timed out or failed.
In case you do not want to wait for the reboot, you can use a post download option which is
called WaitOnReboot

//Post Download Configuration Delegate


DownloadConfigurationDelegate postDownloadForPcStation = downloadConfiguration =>
{
WaitOnReboot waitOnReboot = downloadConfiguration as WaitOnReboot;
if (waitOnReboot != null)
{
//In case user does not want to wait...
waitOnReboot.CurrentSelection = WaitOnRebootSelections.NoAction;
//In case user wants to wait... This is the default option anyway...
//waitOnReboot.CurrentSelection = WaitOnRebootSelections.Wait;
return;
}
};

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 483
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You must continue downloading SW-CPU separately, but it must be made sure that the
download of PC-Station was executed before.

DownloadResult downloadResult = null;


try
{
//WE FIRST DOWNLOAD PC-STATION
downloadResult = downloadProviderStationManager.Download(targetConfiguration,
preDownloadForPcStation, postDownloadForPcStation, DownloadOptions.Hardware);
if (DownloadResultState.Error != downloadResult.State)
{
Console.WriteLine("The download is successful for pc-station");
}
}
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine("Exception Thrown, Message: " + e.Message.ToString());
}
downloadResult = null;
try
{
downloadResult = downloadProviderSwCpu.Download(targetConfiguration, preDownloadForSwCpu,
postDownloadForWinac, DownloadOptions.Hardware | DownloadOptions.Software);
if (DownloadResultState.Error != downloadResult.State)
{
Console.WriteLine("The download is successful for SW-CPU");
}
}
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine("Exception Thrown, Message: " + e.Message.ToString());
}

Downloading SW-CPU is similar to downloading a regular plc. For downloading SW-CPU, please
see Hotspot-Text (Page 485).

Note
Download of F-Activated PLCs is not currently supported for SW-CPU as well; as it is in HW-CPU.

A download method also triggers compilation. It is also possible to compile a device item stand
alone, with the following code snippet:

ICompilable compileServiceSwCpu = swCpu.GetService<ICompilable>();


ICompilable compileServiceStationManager = stationManager.GetService<ICompilable>();
CompilerResult compileResultStationManager = compileServiceStationManager.Compile();
CompilerResult compileResultSwCpu = compileServiceStationManager.Compile();
bool compileCheck = !compileResultStationManager.State.Equals(CompilerResultState.Error);
if (compileCheck != true)
{
...
}

Openness: API for automation of engineering workflows


484 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Downloading hardware and software components to PLC device (Page 485)

5.12.1.2 Downloading hardware and software components to PLC device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to download software and hardware components to PLC
device through DownloadProvider (accessed from the DeviceItem). If a DeviceItem represents a
downloadable target, an instance of DownloadProvider will be returned on GetService call, else
the service will return null.

Program code: Retrieving DownloadProvider service from a device item

DeviceItem deviceItem = ...;


DownloadProvider downloadProvider = deviceItem.GetService<DownloadProvider>();
if (downloadProvider != null)
{
...
}

In order to execute a download to a device, you will have to call Download method of
DownloadProvider.
The parameters are an IConfiguration object, two delegates and DownloadOptions (Hardware,
Software or Hardware and Software).

...
IConfiguration targetConfiguration = ...
DownloadConfigurationDelegate preDownloadDelegate = ...
DownloadConfigurationDelegate postDownloadDelegate = ...
DownloadOptions loadOption = DownloadOptions.Hardware | DownloadOptions.Software;
...
DownloadResult result = downloadProvider.Download(targetConfiguration,
preDownloadDelegate, postDownloadDelegate, loadOption);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 485
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

An optional parameter can be used for downloading to an IP address where the IP address of the
running PLC differs from the IP address configured offline.

...
ConfigurationAddress onlineAddress = ...
DownloadResult result = downloadProvider.Download(targetConfiguration, onlineAddress,
preDownloadDelegate, postDownloadDelegate, loadOption);

Parameters of download method


In order to download to a PLC device, you have to call Download method of DownloadProvider.
The Download method has four parameters which are IConfiguration object, two delegates and
DownloadOptions (Hardware, Software or Hardware and Software).

Parameter name Type Description


configuration Siemens.Engineering.Connection.ICon‐ Connection configuration to a device.
figuration
onlineAddress Siemens.Engineering.Connection.Con‐ Optional parameter for download to a
figurationAddress changed IP address
preDownloadConfigurationDelegate Siemens.Engineering.Download.Down‐ Delegate to be called for checking con‐
loadConfigurationDelegate figuration before download operation.
postDownloadConfigurationDelegate Siemens.Engineering.Download.Down‐ Delegate to be called for checking con‐
loadConfigurationDelegate figuration after download operation.
downloadOptions Siemens.Engineering.Download.Down‐ Download options.
loadOptions

• Openness download is supported only if the configurations that are listed in above table are
encountered and properly handled by you. If the configuration is invalid, then
EngineeringTargetInvocationException is thrown and download process is aborted.
Download of F-activated PLCs is not currently supported.
• Since compliation is a part of download, it is recommended to compile before download to
get a full feedback about the complile results.

IConfiguration
You will have to provide IConfiguration object to the Download method. It will be used to
establish a connection to the given PLC device. IConfiguration interface is implemented by
ConfigurationAddress and ConfigurationTargetInterface. Both the objects can be accessed
through ConnectionConfiguration instance. ConnectionConfiguration instance can be acquired
from DownloadProvider.Connection: ConnectionConfiguration or optionally from
OnlineProvider.Connection: ConnectionConfiguration properties.
Configuration of ConnectionConfiguration object is described in Accessing parameters of an
online connection (Page 524) section.

Openness: API for automation of engineering workflows


486 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the below code example of accessing ConfigurationTargetInterface that implements
IConfiguration:

...
DownloadProvider downloadProvider = null;
ConnectionConfiguration configuration = downloadProvider.Configuration;
ConfigurationMode configurationMode = configuration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces.Find("Intel(R)
Ethernet Connection I217-LM", 1);
IConfiguration targetConfiguration = pcInterface.TargetInterfaces[0];
...

ConfigurationAddress
If the projected IP-address differs from the already downloaded online IP-address, an additional
parameter has to use. This is for identify the correct online PLC.

...
DownloadProvider downloadProvider = ...
ConnectionConfiguration configuration = downloadProvider.Configuration;
ConfigurationMode configurationMode = configuration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces.Find("Intel(R)
Ethernet Connection I217-LM", 1);
IConfiguration targetConfiguration = pcInterface.TargetInterfaces[0];
// Create the address object to reach the PLC online.
ConfigurationTargetInterface targetConfigurationIF = targetConfiguration as
ConfigurationTargetInterface;
ConfigurationAddressComposition downloadAddresses = targetConfigurationIF.Addresses;
ConfigurationAddress onlineAddress = downloadAddresses.Create("10.119.57.223");
DownloadResult result = downloadProvider.Download(targetConfigurationIF, onlineAddress,
preDownloadDelegate, postDownloadDelegate, loadOption);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 487
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

DownloadConfigurationDelegate
You will have to provide two implementations of void
DownloadConfigurationDelegate(DownloadConfiguration downloadConfiguration). First
delegate will be called for pre-download configurations, and the second will be called after
download is completed. The delegates will be called for each configuration that requires an
action from the user. For more information about callback handling, Refer Supporting callbacks
(Page 502). . If configurations are not handled properly, an
EngineeringTargetInvocationException will be thrown and download process will be
aborted. .Certain configurations will only contain an information, therefore your action will not
be required. Also, you can skip the configurations that do not prevent the download.

Note
You should avoid any modifications other than those required to resolve the download
configurations in their delegate implementation.

The possible download configuration types are listed below.

Configuration name Description and properties


DownloadConfiguration • Base class for all the configurations. It will contain information only if it cannot be cast to a
specific configuration. IConfiguration has a single property:
• DownloadConfiguration.Message : string (read only property contains the configuration
message)
DownloadSelectionConfi‐ • Base class for all configuration that can be selected. Properties of DownloadSelectionConfi‐
guration guration
• Does not contain additional properties. A selection must be provided in all child classes de‐
rived from it.
DownloadCheckConfigura‐ • Base class for all configuration that can be checked and unchecked.
tion • Contains single property DownloadCheckConfiguration.Checked: bool<string> (read/write
property identifies whether the configuration is checked or unchecked)
DownloadPasswordConfi‐ • Base class for all configuration that required a password to proceed with download (PLC
guration protection passwords and block binding passwords). Methods of DownloadPasswordConfi‐
guration:
• Conains a single method to set password. DownloadPasswordConfiguration.SetPassword
(password: SecureString) : void - Sets password. SecureString

Openness: API for automation of engineering workflows


488 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The datatype of the configurations are given below.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 489
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Configuration DataType Description and Action


DownloadSelection‐ StartModules Set CurrentSelection:StartModulesSelections. Available
Configuration enum values are
NoAction (No action)
StartModule (Stop module)
These modules are stopped for downloading to a device.
StopModules Set CurrentSelection:StopModulesSelections. Available
enum values:
NoAction (No action)
StopAll (Stop all)
These modules are started after the download operation.
AllBlocksDownload Set CurrentSelection:AllBlocksDownloadSelections.
Available enum value is
DownloadAllBlocks (Download all blocks to the
device)
Download software to device
OverwriteSystemData Set CurrentSelection:OverwriteSystemDataSelections.
Available enum values are
NoAction (No action)
Overwrite (Download to device)
Delete and replace the existing system data in target location.
ConsistentBlocksDown‐ Set
load CurrentSelection:ConsistentBlocksDownloadSelections
. Available enum value is
ConsistentDownload (Consistent download)
Download the software to device.
AlarmTextLibrariesDown‐ Set
load CurrentSelection:AlarmTextLibrariesDownloadSelectio
ns. Available enum values are
ConsistentDownload (Consistent download)
NoAction (No action)
Download all alarm texts and text list texts.
ProtectionLevelChanged Set CurrentSelection:ProtectionLevelChangedSelections. Available
enum values are
NoChange (No change)
ContinueDownloading (Continue downloading to the
device)
CPU protection is changed to the next lower level.
ActiveTestCanBeAborted Set
CurrentSelection:ActiveTestCanBeAbortedSelections.
Available enum values are
NoAction (No action)
AcceptAll (Accept all)
Active test and commissioning functions are canceled during the load‐
ing operation of the device.
ResetModule Set CurrentSelection:ResetModuleSelections Available
enum values are

Openness: API for automation of engineering workflows


490 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Configuration DataType Description and Action


NoAction (No action)
DeleteAll (Delete all)
It resets the module.
LoadIdentificationData Set
CurrentSelection:LoadIdentificationDataSelections.
Available enum values are
LoadNothing (Load nothing)
LoadData (Load data)
Load identification data to the PROFINET IO devices and their modules.
DifferentTargetConfigura‐ Set
tion CurrentSelection:DifferentTargetConfigurationSelect
ions. Available enum values are
NoAction (No action)
AcceptAll (Accept all)
Gives the difference between configured and target modules (online)
InitializeMemory Set CurrentSelection:InitializeMemorySelections.
Available enum values:
NoAction (No action)
AcceptAll (Accept all)
This datatype is used to initialize memory.
ExpandDownload Set CurrentSelection: ExpandDownloadSelections. Avail‐
able enum values:
NoAction (No action)
Download (Download)}}
The download must be expanded beyond your selection.
ActiveTestCanPrevent‐ Set/Get
Download CurrentSelection:ActiveTestCanPreventDownloadSelect
ions
Available enum values:
NoAction (No action)
AcceptAll (Accept all)
Active test and commissioning functions could prevent the donwload.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 491
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Configuration DataType Description and Action


DownloadCheckConfi‐ CheckBeforeDownload Set IsChecked:bool property.
guration Checks before downloading to the device.
UpgradeTargetDevice Set IsChecked:bool property.
Checks the different project versions in the configured device and target
device (online).
OverWriteHMIData Set IsChecked:bool property.
Overwrites if object exists online.
FitHMIComponents Set IsChecked:bool property.
Components with a different version are installed on the target device.
TurnOffSequence Set IsChecked:bool property
Turns off the sequence before loading.
OverwriteTargetLanguag‐ Set IsChecked:bool property.
es To distinguish the settings between the project and PLC programming
DowngradeTargetDevice Set IsChecked:bool property.
To mention the different data formats in online and offline projects.
DownloadPassword‐ ModuleReadAccessPass‐ Set password via SetPassword(password:SecureString)
Configuration word method.
Enter a password to gain read access to the module.
ModuleWriteAccessPass‐ Set password via
word SetPassword(password:SecureString) method.
Enter a password to gain write access to the module.
BlockBindingPassword Set password via SetPassword(password:SecureString)
method.
Block binding password configuration method.
PlcMasterSecretPassword Set password via SetPassword(password:SecureString)
method.
Used for entering the PLC Master Secret password

NOTICE
Please note that download configurations are similar to configurations encountered in
Load preview and Load results dialogs while working with GUI of TIA Portal.

WARNING
The API user is responsible for ensuring the security measures of handling passwords
through code.

Unhandled exceptions inside the delegates

Openness: API for automation of engineering workflows


492 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Unhandled configuration that can prevent the download causes an


EngineeringTargetInvocationException and aborts download. An
EngineeringDelegateInvocationException will be thrown in case of an unhandled exception
within the Delegate.
You can use the below code example for PreDownloadDelegate implementation:

private static void PreConfigureDownload(DownloadConfiguration downloadConfiguration)


{
StopModules stopModules = downloadConfiguration as StopModules;
if (stopModules != null)
{
stopModules.CurrentSelection = StopModulesSelections.StopAll; // This selection will set
PLC into "Stop" mode
return;
}
AlarmTextLibrariesDownload alarmTextLibraries = downloadConfiguration as
AlarmTextLibrariesDownload;
if (alarmTextLibraries != null)
{
alarmTextLibraries.CurrentSelection =
AlarmTextLibrariesDownloadSelections.ConsistentDownload;
return;
}
BlockBindingPassword blockBindingPassword = downloadConfiguration as BlockBindingPassword;
if(blockBindingPassword != null)
{
SecureString password = ...;// Get Binding password from a secure location
blockBindingPassword.SetPassword(password);
return;
}
CheckBeforeDownload checkBeforeDownload = downloadConfiguration as CheckBeforeDownload;
if (checkBeforeDownload != null)
{
checkBeforeDownload.Checked = true;
return;
}
ConsistentBlocksDownload consistentBlocksDownload = downloadConfiguration as
ConsistentBlocksDownload;
if (consistentBlocksDownload != null)
{
consistentBlocksDownload.CurrentSelection =
ConsistentBlocksDownloadSelections.ConsistentDownload;
return;
}
ModuleWriteAccessPassword moduleWriteAccessPassword = downloadConfiguration as
ModuleWriteAccessPassword;
if (moduleWriteAccessPassword != null)
{
SecureString password = ...;// Get PLC protection level password from a secure location
moduleWriteAccessPassword.SetPassword(password);
return;
}
throw new NotSupportedException(); // Exception thrown in the delagate will cancel download
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 493
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the below code example for PostDownloadDelegate implementation:

private static void PostConfigureDownload(DownloadConfiguration downloadConfiguration)


{
StartModules startModules = downloadConfiguration as StartModules;
if (startModules != null)
{
startModules.CurrentSelection = StartModulesSelections.StartModule; // Sets PLC in "Run"
mode
}
}

DownloadOptions
You must specify the download options through DownloadOptions flagged enum. This
parameter will determine the type of download to be performed such as Hardware, Software,
SoftwareOnlyChanges or a combination of them.

[Flags]
public enum DownloadOptions
{
None = 0, // Download nothing
Hardware = 1, // Download hardware. Complete download when used alone, delta download when
used in combination with Software or SoftwareOnlyChanges.
Software = 2, // Download software all. Do not combine with SoftwareOnlyChanges
SoftwareOnlyChanges = 4 // Download software only changes. Do not combine with Software
}

Possible DownloadOptions combinations (C# System Reactions


code)
none exception
Hardware HW complete
Software SW complete
Hardware | Software HW delta, SW complete
SoftwareOnlyChanges SW delta
Hardware | SoftwareOnlyChanges HW delta, SW delta
Software | SoftwareOnlyChanges exception
Hardware | Software | SoftwareOnlyChanges exception
(DownloadOptions)11 exception

DownloadResult
The DownloadResult returned by the Download action provides feedback on the state of the
objects that were downloaded.

Openness: API for automation of engineering workflows


494 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the below code example for Download invocation:

[STAThread]
static void Main()
{
...
DownloadProvider downloadProvider = ...;
IConfiguration targetConfiguration = ...;
DownloadConfigurationDelegate preDownloadDelegate = PreConfigureDownload;
DownloadConfigurationDelegate postDownloadDelegate = PostConfigureDownload;
DownloadResult result = downloadProvider.Download(targetConfiguration,
preDownloadDelegate, postDownloadDelegate, DownloadOptions.Hardware |
DownloadOptions.Software);
if (result.State == DownloadResultState.Error)
{
// Handle error state
}
WriteDownloadResults(result);
...
}
private static void PreConfigureDownload(DownloadConfiguration downloadConfiguration)
{
...
}
private static void PostConfigureDownload(DownloadConfiguration downloadConfiguration)
{
...
}
private void WriteDownloadResults(DownloadResult result)
{
Console.WriteLine("State:" + result.State);
Console.WriteLine("Warning Count:" + result.WarningCount);
Console.WriteLine("Error Count:" + result.ErrorCount);
RecursivelyWriteMessages(result.Messages);
}
private void RecursivelyWriteMessages(DownloadResultMessageComposition messages, string
indent = "")
{
indent += "\t";
foreach (DownloadResultMessage message in messages)
{
Console.WriteLine(indent + "DateTime: " + message.DateTime);
Console.WriteLine(indent + "State: " + message.State);
Console.WriteLine(indent + "Message: " + message.Message);
RecursivelyWriteMessages(message.Messages, indent);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 495
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.1.3 Downloading Master Secret to PLC

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to download Master Secrets to PLCs through
PlcMasterSecretPassword accessed from download configuration. To download, you will have to
provide an implementation of void DownloadConfigurationDelegate (DownloadConfiguration
downloadConfiguration) for the pre-download configuration.
This delegate will be called for each configuration that requires an action from the user. The
PlcMasterSecretPassword configuration handles the user action for entering the Master Secret
password.
For more information about callback handling and Support of download to PLC devices, Refer
Supporting callbacks (Page 502) and Downloading hardware and software components to PLC
device (Page 485)

Openness: API for automation of engineering workflows


496 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: PlcMasterSecretPassword Donwload


You can use the below code sample to download software and hardware components to a device
via DownloadProvider service:

internal bool DownloadDevice(DeviceItem deviceItem)


{
try
{
//Download software and hardware components to a device via DownloadProvider service that
//can be acquired from a given DeviceItem. If a DeviceItem represents a download able
//target an instance of DownloadProvider will be returned on GetService call. Otherwise
//it will be null.
DownloadProvider myDownloadProvider = deviceItem.GetService<DownloadProvider>();
if (myDownloadProvider == null)
{
return false;
}
//Preparation for IConfigurable object to establish a connection to the device.
IConfiguration
//interface is implemented by ConfigurationAddress and ConfigurationTargetInterface. Both
//objects can be accessed via ConnectionConfiguration instance. ConnectionConfiguration
//instance can be acquired from DownloadProvider.Configuration
ConnectionConfiguration connConfiguration = myDownloadProvider.Configuration;
ConfigurationMode confMode = connConfiguration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = ("Intel(R) Ethernet Connection I217-LM", 1);
ConsoleOutput.PrintInterfaces(connConfiguration);
//In order to execute a download to a device, Download method of DownloadProvider have to
//be called. The parameters are an IConfiguration object, two delegates and DownloadOptions
// (Hardware, Software or Hardware and Software).
IConfiguration targetConfiguration = pcInterface.TargetInterfaces[0];
DownloadConfigurationDelegate preDownloadConfigurationDelegate = PreConfigureDownload;
DownloadConfigurationDelegate postDownloadConfigurationDelegate = PostConfigureDownload;
DownloadOptions downloadOptions = DownloadOptions.Hardware | DownloadOptions.Software;
// Apply the the configuration and start the download
myDownloadProvider.Configuration.ApplyConfiguration(pcInterface.TargetInterfaces.First());
var downLoadResult = myDownloadProvider.Download(targetConfiguration,
preDownloadConfigurationDelegate,
postDownloadConfigurationDelegate, downloadOptions);
return downLoadResult != null && downLoadResult.State != DownloadResultState.Error;
}
catch (EngineeringTargetInvocationException ex)
{
//Exception catch-ed on purpose. Client can write own code to handle the exception
//In case of PLC Master Secret exception will be thrown if:
// 1) If a different Master Secret has already been set in the PLC.
//Exception Message: An error has occurred during download: 'A different Master Secret
//has already been set. The PLC has to be reset!
//Possibly provide custom exception handling here
Console.WriteLine("An exception during download was thrown:");
Console.WriteLine(ex.DetailMessageData);
return false;
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 497
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the below code sample for PlcMasterSecretPassword handling in
PreDownloadDelegate:

private static void PreConfigureDownload(DownloadConfiguration downloadConfiguration)


{... ... ... ... ...
// Set the PLC Master Secret password configured in the offline project's PLC,
// when the password was never set in the real PLC
if (downloadConfiguration is PlcMasterSecretPassword plcMasterSecret)
{
// Get the PLC Master Secret password from a secure location
SecureString plcMasterSecretPsw = ...;
plcMasterSecret.SetPassword(plcMasterSecretPsw);
return;
}
catch (EngineeringTargetInvocationException ex)
{
// Exception catch-ed on purpose. Client can write own code to handle the exception
// Exception will be thrown if:
// 1) plcMasterSecret password is null.
// Exception Message: The argument "password" may not be null
// 2) plcMasterSecret password is an empty string.
// Exception Message: The password provided is invalid
// 3) plcMasterSecret password is wrong.
// Exception Message: The password provided is invalid
// Possibly provide custom exception handling here
Console.WriteLine("PlcMasterSecretPassword has thrown an exception:");
Console.WriteLine(ex.DetailMessageData);
return;
}
}
... ... ... ... ...
throw new NotSupportedException();
// Exception thrown in the delagate will cancel download
}

Note
An EngineeringDelegateInvocationException will be thrown in case of an unhandled exception
within the Delegate.

5.12.1.4 Managing PLC Master Secret in PLCs

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connectng to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


498 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness to protect the sensitive PLC configuration data. You can
configure the PLC master secret key which will be used to encrypt the certificate configuration.
Additionally, you can disable if protecting the PLC configuration data is not a priority.
In TIA Portal Openness, the PLC master secret key can be configured via the HW feature
PlcMasterSecretConfigurator at the Device Item CPU of Device. This feature provides actions to
Protect, Unprotect and Change the Master secret key.
• void Protect ( SecureString password)
• void Unprotect ( SecureString password)
• void Unprotect ( )
• void ChangePassword ( SecureString oldPassword, SecureString newPassword)
• attribute MasterSecretConfiguration MasterSecretConfiguration{get;}

enum MasterSecretConfiguration
{
None=0 , // The checkbox option “Protect the PLC Configuration data…” is unchecked.
WithPassword =1, // The PLC Master Secret is configured.
WithoutPassword=2 // The checkbox option “Protect the PLC Configuration data…” is
//checked and the PLC Master Secret is not configured.
}

• void Reset ( )

Program code: Configuring PLC master secret key


Configuring PLC master secret key is implemented as SecureString for security reasons. It is only
possible to set / change the passwords . Reading the passwords is not supported.

PlcMasterSecretConfigurator plcMasterSecretConfigurator =
plcCpu.GetService<PlcMasterSecretConfigurator>();
plcMasterSecretConfigurator.Protect(new SecureString(“TiaPassword123”));
plcMasterSecretConfigurator.ChangePassword(new SecureString(“TiaPassword123”),new
SecureString(“TiaPassword1234”));

Program code: Disabling PLC Master Secret Functionality


Disabling PLC Master Secret password is implemented using overloaded Unprotect methods ,
based on the master secret configuration user can disable PLC master secret functionality with
and without master secret key. Reading the passwords is not supported.

//Unprotect method that will be called when PlcMasterSecret is not


configuredplcMasterSecretConfigurator.Unprotect();
//Unprotect method that will be called when PlcMasterSecret is configured
plcMasterSecretConfigurator.Unprotect(new SecureString(“TiaPassword123”));

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 499
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Reset PLC Master Secret Functionality


If you forget master secret key , the reset will remove the Master secret configuration and the
certificates will be lost.

plcMasterSecretConfigurator.Protect(new SecureString(“TiaPassword123”));
plcMasterSecretConfigurator.Reset();

Affected modules
PLC master secret configuration is supported by S7-1500, ET200 SP, ET200 pro, S7-1200,
Controller PLC with version V2.9(1500, ET200 SP and pro), V4.5(1200), V21.9(Controller PLC)
and above.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.1.5 Setting / deleting a PLC Master Secret in a PLCs

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connectng to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to set or reset the PlcMasterSecret to PLCs. To achieve this
TIA Portal Openness,-OnlineProvider are extended by new Methods:
• SetPlcMasterSecret
• ResetPlcMasterSecret.
The SetPlcMasterSecret supports the following parameter:

Parameter Type Description


securePassword SecureString The Master Secret-password.

Note
You cannot delete or reset the PMS by a NULL-password.

Openness: API for automation of engineering workflows


500 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Set and Reset PlcMasterSecret


Modify the following program code to set and reset the PlcMasterSecret via the OnlineProvider
service:

DeviceItem deviceItem = ...;


SecureString password = ...;
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();

Modify the following program code to set the PlcMasterSecret:

DeviceItem deviceItem = ...;


SecureString password = ...;
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
onlineProvider.SetPlcMasterSecret(password);

Modify the following program code to reset the PlcMasterSecret:

DeviceItem deviceItem = ...;


OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
onlineProvider.ResetPlcMasterSecret();

Note
Reset the PMS is the same functionality like Delete in the "Online & diagnostics"-Dialog.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.1.6 Running and stopping PLC

Requirements
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 501
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
When interacting with TIA Portal through Openness API, it may be necessary to change the
operating mode of the PLC. TIA Portal Openness provides a way to modify the operating state of
the PLC either to start or stop.

Program code
Modify the following program code for setting PLC operating state to STOP.

public void ConfigurePreDownload(DownloadConfiguration downloadConfiguration)


{
StopModules stopModules = downloadConfiguration as StopModules;
if (stopModules != null)
{
// Puts PLC in "Stop" mode
stopModules.CurrentSelection = StopModulesSelections.StopAll;
}
}

Modify the following program code for setting PLC operating state to START.

public void ConfigurePostDownload(DownloadConfiguration downloadConfiguration)


{
StartModules startModules = downloadConfiguration as StartModules;
if (startModules != null)
{
// Puts PLC in "Start" mode
startModules.CurrentSelection = StartModulesSelections.StartModule;
}
}

5.12.1.7 Supporting callbacks

Requirements
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Certain API methods require an interaction with the user-defined application code during their
execution. Delegates are used to handle these callback actions in the user-defined application
code. You need to implement a method with a compatible signature, and pass it as a delegate
parameter to the action. To proceed with the execution, TIA Portal calls the implemented
methods.

Openness: API for automation of engineering workflows


502 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code

// This delegate is declared in Siemens.Engineering.dll


public delegate void
Siemens.Engineering.Download.DownloadConfigurationDelegate(Siemens.Engineering.Download.Co
nfigurations.DownloadConfiguration configuration);
...

Example of an user application code using and implementing the delegate:

[STAThread]
static void Main()
{
...
DownloadProvider downloadProvider = ...;
IConfiguration targetConfiguration = ...;
DownloadConfigurationDelegate preDownloadDelegate = PreConfigureDownload;
DownloadConfigurationDelegate postDownloadDelegate = PostConfigureDownload;
DownloadResult result = downloadProvider.Download(targetConfiguration,
preDownloadDelegate, postDownloadDelegate, DownloadOptions.Hardware |
DownloadOptions.Software);
...

//This method will be called back by TIA Portal


private static void ConfigurePreDownload(DownloadConfiguration downloadConfiguration)
{
// Work with the parameter
}

//This method will be called back by TIA Portal


private static void ConfigurePostDownload(DownloadConfiguration downloadConfiguration)
{
// Work with the parameter
}

Note
STAThread attribute will assure that the delegates are called in the Main thread of execution.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 503
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.1.8 Protecting PLC through password

Requirements
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
When interacting with TIA Portal through Openness API, it may be necessary to change the
protection level of the PLC. TIA Portal Openness provides a way to secure the PLC through a
password. The password can be set to both read-protected and write-protected PLCs.

Program code
Modify the following program code for read-protected PLCs

public void ConfigurePreDownload(DownloadConfiguration downloadConfiguration)


{
ModuleReadAccessPassword moduleReadAccessPassword = downloadConfiguration
asModuleReadAccessPassword;
if (moduleReadAccessPassword != null)
{
SecureString password = ...; // Get password from a secure location
moduleReadAccessPassword.SetPassword(password); // enter the password to gain
full access
}
}

Modify the following program code for write-protected PLCs

public void ConfigurePreDownload(DownloadConfiguration downloadConfiguration)


{
ModuleWriteAccessPassword moduleWriteAccessPassword = downloadConfigurationas
ModuleWriteAccessPassword;
if (moduleWriteAccessPassword != null)
{
SecureString password = ...; // Get password from a secure location
moduleWriteAccessPassword.SetPassword(password); // enter the password to gain full
access
}
}

Openness: API for automation of engineering workflows


504 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

WARNING
The API user is responsible for ensuring the security measures of handling passwords
through code.

5.12.1.9 Handling PLC block binding passwords

Requirements
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
TIA Portal Openness supports the data binding of passwords for customer applications. TIA
Portal Openness provides a way for the customer to specify a block binding password. For
example, a block binding password can be configured on the DownloadPasswordConfiguration
class by calling the SetPassword method.

Note
If you want to secure the download action with a password, a password will have to be
provided during every call of download function. This is regardless of whether the device
has already been configured. After the successful acceptance of password for a given
configuration, all subsequent calls to SetPassword are ignored.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 505
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code:

public void ConfigurePreDownload(DownloadConfiguration downloadConfiguration)


{
DownloadPasswordConfiguration downloadPasswordConfiguration = downloadConfiguration as
DownloadPasswordConfiguration;
if(downloadPasswordConfiguration != null &&
downloadPasswordConfiguration.Message.Contains("block_1"))
{
SecureString password = ...; // Get password from a secured location
downloadPasswordConfiguration.SetPassword(password);
}
}

5.12.1.10 Uploading hardware, software and files to PLC device

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
Openness user is able to upload station into a project through StationUploadProvider (accessed
from a given project). An upload into a DeviceGroup is not supported. If a project is used to
execute an upload, an instance of StationUploadProvider will be returned on GetService call,
else the service will return null.

Program code: Retrieving StationUploadProvider service from a project

Project myProject = ...;


StationUploadProvider uploadProviderForProject =
myProject.GetService<StationUploadProvider>();
if (uploadProviderForProject != null)
{
...
}

Openness: API for automation of engineering workflows


506 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Parameters of upload method


In order to execute an upload of a PLC device, user calls StationUpload method of
StationUploadProvider. The Upload method has ConfigurationAddress and
UploadConfigurationDelegte parameters. UploadOptions are optional, because the
StationUpload uploads Software, Hardware, and Files.

Parameter name Type Description


configurationAddress Siemens.Engineering.Connection.Con‐ Address of device that should be uploa‐
figurationAddress ded
uploadConfigurationDelegate Siemens.Engineering.Upload.Upload‐ Delegate that will be called to check con‐
ConfigurationDelegate figuration before upload
uploadOptions Siemens.Engineering.Upload.Uploa‐ Upload options
dOptions

Parameter 1: ConfigurationAddress
The user should provide ConfigurationAddress object to the Upload. The address object is used
to establish a connection to the given PLC device that should be uploaded. The
ConfigurationAddress object must be created in the ConnectionConfiguration of the
StationUploadProvider. The Configuration contains a list of supported Modes. You need to select
one of the Modes that should be used for upload. The selected ConfigurationMode contains a list
of all local PcInterfaces that support the selected Mode, you have to select one of the interfaces.
The desired address can be created in the Address collection of the selected
ConfigurationPcInterface.
Modify the following code to create an address object:

...
StationUploadProvider uploadProvider = null;
...
ConnectionConfiguration configuration = uploadProvider.Configuration;
ConfigurationMode configurationMode = configuration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces.Find("Intel(R)
Ethernet Connection I217-LM", 1);
//"Create an address. This "ConfigurationAddress" is used as parameter for upload."
ConfigurationAddress uploadAddress = pcInterface.Addresses.Create("192.68.0.1");
...

Project upload
The user can start the station upload by calling the action StationUpload.
The following Parameters are mandatory:
• ConfigurationAddress: The address of the device to be uploaded
• UploadConfigurationDelegate: The callback to handle upload inhibits

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 507
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

...
StationUploadProvider uploadProvider = null;
Device uploadedObject = null;
...
UploadConfigurationDelegate preUploadDelegate = PreConfigureUpload;
UploadResult result = uploadProvider.StationUpload(uploadAddress, preUploadDelegate);
// The uploaded device
uploadedObject = result.UploadedStation;
if (uploadedObject == null)
{
...
}
internal void PreConfigureUpload(UploadConfiguration uploadConfiguration)
{
...
}

Parameter2: UploadConfigurationDelegate
Openness user needs to provide an implementation of void UploadConfigurationDelegate
(UploadConfiguration uploadConfiguration). The delegate will be called for pre-upload
configurations. The delegate will be called for each configuration that requires an action from
the user. For more information about callback handling, Refer Supporting callbacks (Page 502).
Certain configurations will only contain an information, therefore the user action will not be
required.

The possible upload configuration types are listed below:

Configuration name Description and properties


UploadConfiguration • Base class for all the configurations. It contains information in the Message attribute
• Contains single property UploadConfiguration.Message : string (read only property contains
the configuration message)
UploadPasswordConfigura‐ • Derived from UploadConfiguration
tion • Base class for all configuration that required a password for upload.
• Contains a single method to set password. UploadPasswordConfiguration.SetPassword (pass‐
word: SecureString) : void - Set password
UploadSelectionConfigura‐ • Derived class of UploadConfiguration
tion • Does not contain additional properties

Openness: API for automation of engineering workflows


508 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The datatype of the configurations are given below:

Configuration DataType Description and Action


UploadPasswordConfi‐ ModuleReadAccessPass‐ Set password via SetPassword(password:SecureString)
guration word method.
Enter a password to gain read access to the module.
PasswordReadAccess Set password via SetPassword(password:SecureString)
method.
Enter a password for SW Upload in classic PLC's to gain read access to the
module.
UploadSelectionConfi‐ UploadMissingProducts Set
guration CurrentSelection:UploadMissingProductsSelections
Available enum values:
TryUpload (Consistent upload)
NoAction (No action)
Set a selection for upload.

The support of a Failsafe password is not necessary. For the read-access by uploading a F-PLC no
password is needed.

Unhandled configuration that can prevent the upload causes an


EngineeringTargetInvocationException and aborts upload.
An EngineeringDelegateInvocationException will be thrown in case of an unhandled exception
within the Delegate.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 509
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

PreUploadDelegate implementation example:


private static void PreConfigureUpload(UploadConfiguration UploadConfiguration)
{
ModuleReadAccessPassword moduleReadAccessPassword = UploadConfiguration as
ModuleReadAccessPassword;
if (moduleReadAccessPassword != null)
{
string passWD = "passWD";
var password = new SecureString();
foreach (var c in passWD)
password.AppendChar(c);

moduleReadAccessPassword.SetPassword(password);
return;
}

ModuleWriteAccessPassword moduleWriteAccessPassword = UploadConfiguration as


ModuleWriteAccessPassword;
if (moduleWriteAccessPassword != null)
{
string passWD = "passWD";
var password = new SecureString();
foreach (var c in passWD)
password.AppendChar(c);

moduleWriteAccessPassword.SetPassword(password);
return;
}
...

throw new NotSupportedException(); // Exception thrown in the delagate will cancel upload
}

Parameter3: UploadOptions
The user cannot specify the Upload options. This Upload options are known as: "Hardware",
"Software", "Hardware and Software" and "Hardware, Software and Files".

UploadResult
The UploadResult returned by the Upload action provides feedback on the state of the objects
that were uploaded.
• UploadResult.Message: UploadResultMessageComposition - Composition of
UploadResultMessage
The following attributes are supported:

Attributes Description
ErrorCount int value of errors while upload
State UploadResultState with possibly values: Success, Information, Warning and Error

Openness: API for automation of engineering workflows


510 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Attributes Description
UploadedStation A Device-Instance of the uploaded station
WarningCount Number of warning while upload as int

The UploadResultMessage contains:


• UploadResultMessage.Messages : UploadResultMessageComposition - Composition of
UploadResultMessage
The following attributes are supported:

Attributes Description
DateTime System.DateTime of the created message.
ErrorCount An int counter for errors.
State UploadResultState with possibly values: Success, Information, Warning and Error.
WarningCount Number of warning while upload as int

Upload invocation example


internal bool UploadPLC()
{
...
UploadResult result = uploadProvider.StationUpload(uploadAddress, preUploadDelegate);
...
PrintAllMessages(result.Messages, 0);
...
}

internal void PrintAllMessages(UploadResultMessageComposition messages, int level)


{
if (messages == null)
return;

if (level == 0)
Console.WriteLine("\n");
foreach (UploadResultMessage message in messages)
{
string messageOut = message.Message.PadLeft(message.Message.Length + level, '\t') + "\n";
Console.WriteLine(messageOut);

if ((message.Messages != null) && (message.Messages.Count > 0))


PrintAllMessages(message.Messages, level+1);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 511
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.1.11 Comparing PLC software

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You have the following options to determine the deviation between the software of two devices:
• Comparing the software of two configured PLCs
• Comparison of the software of a PLC and the project library
• Comparison of the software of a PLC and the global library
• Comparison of the software of a PLC and the master copy of a PLC
• Comparisonof the software of a configured PLC with the software of a connected PLC in
"Online" status

Signature
Use the CompareTo or CompareToOnline methods for the comparison.
public CompareResult CompareTo (ISoftwareCompareTarget compareTarget)

Openness: API for automation of engineering workflows


512 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

public CompareResult CompareToOnline ()

Return value / parameter Function


CompareResult compareResult Returns the comparison result:
• FolderContentsDifferent: Content of the com‐
pared folders differs.
• FolderContentsIdentical: Content of the com‐
pared folders is identical.
• ObjectsDifferent: Content of the compared objects
differs.
• ObjectsIdentical: Content of the compared objects is
identical.
• LeftMissing: The object is not contained in the object
from which the comparison was started.
• RightMissing: The object is not contained in the object
which is being compared.
• CompareIrrelevant: Comparison of these 2 objects is
irrelevant
• FolderContainsDifferencesOwnStateDifferen
t: Folder contents have one or more differences, folder's
own state different
• FolderContentEqualOwnStateDifferent: Folder
content is the same, folder's own state is different
ISoftwareCompareTarget List of comparable objects.
compareTarget

Program code
Modify the following program code to output the comparison result:

private static void WriteResult(CompareResultElement compareResultElement, string indent)


{
Console.WriteLine("{0} <{1}> <{2}> <{3}> <{4}> ",
indent,
compareResultElement.LeftName,
compareResultElement.ComparisonResult,
compareResultElement.RightName,
compareResultElement.DetailedInformation);
WriteResult(compareResultElement.Elements, indent);
}
private static void WriteResult (IEnumerable<CompareResultElement> compareResultElements,
string indent)
{
indent += " ";
foreach (CompareResultElement compareResultElement in compareResultElements)
{
WriteResult(compareResultElement, indent);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 513
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to compare the software of devices:

private static void CompareTwoOfflinePlcs(PlcSoftware plcSoftware0, PlcSoftware


plcSoftware1)
{
if (plcSoftware0 != null && plcSoftware1 != null)
{
CompareResult compareResult = plcSoftware0.CompareTo(plcSoftware1);
WriteResult(compareResult.RootElement, string.Empty);
}
}

Modify the following program code to compare the software of a PLC with the project library:

private static void ComparePlcToProjectLibrary(Project project, PlcSoftware plcSoftware)


{
if (project != null && plcSoftware != null)
{
CompareResult compareResult = plcSoftware.CompareTo(project.ProjectLibrary);
WriteResult(compareResult.RootElement, string.Empty);
}
}

Modify the following program code to compare the software of a PLC with the global library:

private static void ComparePlcToGlobalLibrary(PlcSoftware plcSoftware, GlobalLibrary


globalLibrary)
{
if (plcSoftware != null && globalLibrary != null)
{
CompareResult compareResult = plcSoftware.CompareTo(globalLibrary);
WriteResult(compareResult.RootElement, String.Empty);
}
}

Modify the following program code to compare the software of a PLC with a master copy:

private static void ComparePlcToMasterCopy(Project project, PlcSoftware plcSoftware)


{
if (project != null && plcSoftware != null)
{
CompareResult compareResult =
plcSoftware.CompareTo(project.ProjectLibrary.MasterCopyFolder.MasterCopies[0]);
WriteResult(compareResult.RootElement, string.Empty);
}
}

Openness: API for automation of engineering workflows


514 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to compare the software of a PLC with the software of a
connected PLC:

private static void ComparePlcToOnlinePlc(PlcSoftware plcSoftware)


{
if (plcSoftware != null)
{
CompareResult compareResult = plcSoftware.CompareToOnline();
WriteResult(compareResult.RootElement, string.Empty);
}
}

5.12.1.12 Comparing PLC hardware

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to compare the hardware of two PLC devices.

Signature
Use the CompareTo method for the comparison of two hardware objects.
CompareResult CompareTo (IHardwareCompareTarget compareTarget);

Return value/parameter Function


CompareResult compare result Return the comparision result:
• FolderContainsDifferencesOwnStateDifferent: Folder con‐
tents have one or more differences, folder's own state is
different
• FolderContentEqualOwnStateDifferent: Folder content is
the same, folder's own state is different.
IHardwareCompareTarget compareTarget The compare target for which the hardware compare should
be performed. Must not be null.

If the Parameter compareTarget is null and an attempt is made to compare the hardware will
throw Siemens.Enginnering.EngineeringTargetInvocationExceptions.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 515
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program
Modify the following program code to output the comparision result:

...
CompareResult compareResult = plc_1.CompareTo(plc_2);
CompareResultState resultState = compareResult.RootElement.ComparisonResult;
if (resultState == CompareResultState.FolderContainsDifferencesOwnStateDifferent)
{
// Folder contents have one or more differences, folder's own state is different:
// May occur if the plc has a different subordinate element, e.g., a local module, and
// the plc itself is different, e.g., in a parameter
}
else if (resultState == CompareResultState.FolderContentEqualOwnStateDifferent)
{
// Folder content is the same, folder's own state is different:
// May occur if a folder-style module, e.g., FM 351, has equal subordinate elements but
// the module itself is different, e.g., in a parameter
}
else if (resultState == CompareResultState.FolderContentsIdentical)
{
...
}
...

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2 Functions for accessing PLC service

5.12.2.1 Access level setting

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness API to access the Access level setting via the Hardware
PlcAccessLevelProvider at the Deviceitem CPU of Device.

Openness: API for automation of engineering workflows


516 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

This feature provides actions to set / reset the password and a modeled attribute to set / read the
access level setting.
• void SetPassword ( PlcProtectionAccessLevel accessLevelType, SecureString password )
• void ResetPassword ( PlcProtectionAccessLevel accessLevelType)
• attribute PlcProtectionAccessLevel
In general the handling via Openness is similar to the TIA Portal UI.
• PlcProtectionAccessLevel can always be read and set at S7-1200/1500 PLCs.
• If access level is set to anything different than Full access (or Full access incl. fail-safe) a full
access password has to be set. Otherwise there will be a compile error: "Password must not
be empty"
• It is not allowed to set the same password for different access levels
• It is only possible to set / reset passwords for higher levels than the one set as access level (if
PlcProtectionAccessLevel is set to HMIAccess it is only possible to set a password for
ReadAccess and FullAccess)
Possible exceptions:
• EngineeringTargetInvocationException: "Same password already exists for other access
level" - will be thrown if the user tries to set the same password for different access levels
• EngineeringTargetInvocationException: "Cannot set password for the access level" - will be
thrown if the user tries to set a password for a stricter access level than the one selected
• EngineeringTargetInvocationException: "Password cannot be empty" - will be thrown if the
user tries to set an empty password
• EngineeringTargetInvocationException: "Access Level is not valid" - will be thrown if the
user tries to set the access level to FullAccessIncludingFailsafe at non failsafe PLCs

Access level
In Openness the access level is modelled as an Enum named PlcProtectionAccessLevel. The
name of the Enum fields are based on the "Access Level" entries for S7-1200/1500 PLCs.

TIA UI name Enum entry Value Remarks


- None 0 For enum initialization. This
value must not be set by the
Openness user.
Full access (no protection) FullAccess 1
Read access ReadAccess 2
HMI access HMIAccess 3
No access NoAccess 4
Full access incl. fail-safe (no FullAccessIncludingFailsafe 5 Only available at failsafe PLCs
protection)

An EOM Attribute(Modeled Attribute) named PlcProtectionAccessLevel of type


PlcProtectionAccessLevel enum is available at PLCs to Set/Get the access level.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 517
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the following code example for PlcProtectionAccessLevel with No access:

DeviceItem S71500PLC = ...;


PlcAccessLevelProvider myPlcAccessLevelProvider =
S71500PLC.GetService<PlcAccessLevelProvider>();
myPlcAccessLevelProvider.PlcProtectionAccessLevel = PlcProtectionAccessLevel.NoAccess;

Password
The password is implemented as SecureString for security reasons. It is only possible to set / reset
the passwords for the different access levels using the corresponding action. Reading the
passwords is not supported.

myPlcAccessLevelProvider.SetPassword(PlcProtectionAccessLevel.ReadAccess,
someSecureString);
myPlcAccessLevelProvider.ResetPassword(PlcProtectionAccessLevel.ReadAccess);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.2 Accessing OPC UA server interface

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can create server interface objects and import XML files that define the OPC UA server
interface for the PLC.
You can use the TIA Portal Openness API to access the following functionality using
OpcUaProvider service:
• Adding an OPC UA server interface object
• Enumerating through the server interface belonging to PLC
• Importing a server interface file
• Exporting an existing server interface to XML
• Enabling/ Disabling server interface
• Deleting a server interface

Openness: API for automation of engineering workflows


518 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
You can interact with OPC UA server interfaces via an OpcProvider service that can be acquired
from PlcSoftware.

PlcSoftware software = ....;


OpcUaProvider provider = software.GetService<OpcUaProvider>();
if (provider != null)
{
....
}

Modify the following program code to allow navigation to the OPC UA server interfaces:

PlcSoftware software = ....;


OpcUaProvider provider = software.GetService<OpcUaProvider>();
if (provider != null)
{
OpcUaCommunicationGroup commGroup = provider.CommunicationGroup;
ServerInterfaceGroup serverInterfaceGroup = commGroup.ServerInterfaceGroup;
ServerInterfaceComposition serverInterfaces = serverInterfaceGroup.ServerInterfaces;
}

Modify the following program code to enumerate through the items in the
ServiceInterfaceComposition collection:

ServerInterfaceComposition serverInterfaces = ....;


foreach (ServerInterface serverInterface in serverInterfaces)
{
....;
}

Modify the following program code to add an OPC UA server interface object:

ServerInterfaceComposition serverInterfaces = ....;


if (serverInterfaces != null)
{
ServerInterface serverInterface = serverInterfaces.Create(name);
}

Modify the following program code to get and set the properties of OPC UA server interface
object:

ServerInterfaceComposition serverInterfaces = ....;


if (serverInterfaces != null)
{
ServerInterface serverInterface = serverInterfaces.Create("New Interface");
serverInterface.Author = "James Cornett";
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 519
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to set the contents of the server interface object based on
XML file:

ServerInterfaceComposition serverInterfaces = ....;


if (serverInterfaces != null)
{
ServerInterface serverInterface = serverInterfaces.Create(name);
if (serverInterface != null)
{
serverInterface.Import(new FileInfo(importFilePath));
}
}

Modify the following program code to write the contents of the server interface object to an XML
file:

String exportFilePath = Path.Combine(Directory.GetCurrentDirectory(),


"ExportInterface.xml");
ServerInterface serverInterface = …;
serverInterface.Export(new FileInfo(exportFilePath));

Modify the following program code to remove the object from the containing
ServerInterfaceComposition, and de-allocates the object:

ServerInterface serverInterface = …;
serverInterface.Delete());

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.3 Accessing Software Checksum

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application
See Opening a project (Page 113)

Application
You can use the Openness API to access the software checksum for a PLC station.

Openness: API for automation of engineering workflows


520 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
To access, you get the instance of PlcSoftware and and load a service instance of
PlcChecksumProvider.

PlcSoftware plc = …;
//get PlcSoftware instance
PlcChecksumProvider checksumProvider =
plc.GetService<PlcChecksumProvider>();

In case the PLC does not support the checksum calculation then the GetService call returns null.
At the PlcChecksumProvider instance the software checksum can be reached as follow:

string softwareChecksum = checksumProvider.Software;

The Software attribute is read only and it returns null when the program is not compiled.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.4 Assigning PC interface

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
For the interface assignment, you have to get a PcInterfaceAssignment service from
Siemens.HW.Features on the device item interface.
If the PC-Station version is <= 2.0, the methods of this service will return null and interface
assignment will not be possible for the interfaces that are assigned to PC-Station or Windows
only or none. For the interfaces that are assigned to SW-CPU, this is again possible.

Note
The support of PC Station is very limited in the CAx interchange. Only PC Stations with version
1.0 and the default value for InterfaceAssignment are supported. The reason is these two values
have impact on device structure (what is built-in, what can be plugged where). But since the
parameters are not part of the AutomationML file, the values are not set during import and as a
result the structure of the IPC does not fit and the other modules can not be plugged.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 521
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Interface assignment


Modify and use the following program code for interface assignment:

DeviceItem swCpu = ...;


DeviceItem myInterface = ...;
PcInterfaceAssignment provider = myInterface.GetService<PcInterfaceAssignment>();
//user has to give device item sw cpu in case he/she wants to assign to it. (in the future,
there could be multi sw-cpu cases)
provider.AssignInterface(PcInterfaceAssignmentMode.SoftwarePlc, swCpu);
...
provider.AssignInterface(PcInterfaceAssignmentMode.PcStation);
...
provider.AssignInterface(PcInterfaceAssignmentMode.None);
...

Modify and use the following program code to get information about the current assignment
mode of an interface:

PcInterfaceAssignment provider = myInterface.GetService<PcInterfaceAssignment>();


PcInterfaceAssignmentMode mode = provider.PcInterfaceAssignmentMode;
switch(mode)
{
case PcInterfaceAssignmentMode.None: Console.WriteLine("Assigned to none or windows-
only.");
break;
case PcInterfaceAssignmentMode.PcStation: Console.WriteLine("Assigned to pc-station.");
break;
case PcInterfaceAssignmentMode.SoftwarePlc: Console.WriteLine("Assigned to SoftwarePlc: "
+ provider.SoftwarePlc.Name);
break;
}

Openness: API for automation of engineering workflows


522 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Hardware Resource and IPC Expansion configuration


You can also select correct IPC Expansion and HardwareResource property via
PcInterfaceAssignment sevice using the following code:

DeviceItem myInterface = ...;


PcInterfaceAssignment provider = myInterface.GetService<PcInterfaceAssignment>();
//this method returns a subset of IpcExpansion values which are available for the IPC that
the interface is plugged in. IEnumerable<string> ipcExpansionChoices =
provider.GetAvailableIPCExpansions ();
string myChoice;
foreach(var choice in ipcExpansionChoices)
{
//user must select the desired value depending on his/her configuration
if (choice.Contains("3yxx1")
{
myChoice = choice;
break;
}
}
provider.IpcExpansion = myChoice;
//after assigning IpcExpansion value, user may assign HardwareResource value using the
following enumeration. provider.HardwareResource = HardwareResource.X101;
//OR
//myInterface.SetAttribute("HardwareResource", HardwareResource.X101);
//myInterface.SetAttribute("IpcExpansion", mychoice);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.5 Determining the status of a PLC

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can determine the state of a PLC or all PLCs in a project.
TIA Portal Openness distinguishes between the following states:
• Offline
• PLC is connected ("Connecting")
• Online

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 523
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

• PLC is disconnected ("Disconnecting")


• Incompatible
• Not reachable
• Protected

Program code
Modify the following program code to determine the state of a PLC:

public static OnlineState GetOnlineState(DeviceItem deviceItem)


{
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
return onlineProvider.State;
}

Modify the following program code to determine the state of all PLCs in a project:

public static void DetermineOnlineStateOfAllProjectDevices(Project project)


{
foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
if (onlineProvider != null)
{
OnlineState state = onlineProvider.State;
}
}
}
}

5.12.2.6 Accessing parameters of an online connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


524 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness API interface to determine or set parameters for an online
connection:
• Enumerate the available connection modes to a PLC
• Enumerate the available interfaces to a PLC
• Enumerate the allocated slots
• Enumerate the available addresses of the subnets and gateways
• Set the connection parameters.

Program code: Determining connection parameters


Modify the following program code to enumerate the available connection modes, PC interfaces
and slots:

public static void EnumerateConnectionModesOfPLC(DeviceItem deviceItem)


{
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
if (onlineProvider == null)
{
return; // Only cpu device items can provide OnlineProvider service
}
// Accessing connection configuration object
ConnectionConfiguration configuration = onlineProvider.Configuration;
// Now access connection configuration members
foreach (ConfigurationMode mode in configuration.Modes)
{
Console.WriteLine("Mode name:{0}", mode.Name);
foreach (ConfigurationPcInterface pcInterface in mode.PcInterfaces)
{
Console.WriteLine("PcInterface name:{0}", pcInterface.Name);
Console.WriteLine("PcInterface number:{0}", pcInterface.Number);
foreach (ConfigurationTargetInterface targetInterface in
pcInterface.TargetInterfaces)
{
Console.WriteLine("TargetInterface:{0}", targetInterface.Name);
}
}
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 525
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can also access a connection mode and a PC interface by name:

public static ConfigurationTargetInterface


GetTargetInterfaceForOnlineConnection(OnlineProvider onlineProvider)
{
ConnectionConfiguration configuration = onlineProvider.Configuration;
ConfigurationMode mode = configuration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("PLCSIM", 1);
ConfigurationTargetInterface slot = pcInterface.TargetInterfaces.Find("2 X3");
return slot;
}

Modify the following program code to enumerate the addresses of the subnets and gateways
available on a PC interface:

public static void EnumeratingPCInterfaceSubnetsAndGateways(ConfigurationPcInterface


pcInterface)
{
foreach (ConfigurationSubnet subnet in pcInterface.Subnets)
{
Console.WriteLine("Subnet name:{0}", subnet.Name);
foreach (ConfigurationGateway gateway in subnet.Gateways)
{
//Get the name of the gateway:
Console.WriteLine("Gateway name:{0}", gateway.Name);
//Get the IP address of each gateway:
foreach (ConfigurationAddress gatewayAddress in gateway.Addresses)
{
Console.WriteLine("Gateway Address:{0} has {1}", gatewayAddress.Name,
gatewayAddress.Address);
}
}
}
}

You can also access subnets and gateways by their name or IP address:

public static void AccessSubnetAndGatewayOfPCInterface(ConfigurationPcInterface


pcInterface)
{
ConfigurationSubnet subnet = pcInterface.Subnets.Find("PN/IE_1");
ConfigurationAddress subnetAddress = subnet.Addresses.Find("192.168.0.1");
ConfigurationGateway gateway = subnet.Gateways.Find("Gateway 1");
ConfigurationAddress gatewayAddress = gateway.Addresses.Find("192.168.0.2");
}

Openness: API for automation of engineering workflows


526 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Setting connection parameters

Note
All the connection parameters previously set are overwritten when you set the connection
parameters. If you have already set the connection parameters directly in the TIA Portal, it is not
necessary to call ApplyConfiguration. If there is already an online connection to a PLC
while ApplyConfiguration is called, an exception is thrown.

Modify the following program code to set slot parameters:

public static void SetConnectionWithSlot(OnlineProvider onlineProvider)


{
ConnectionConfiguration configuration = onlineProvider.Configuration;
ConfigurationMode mode = configuration.Modes.Find(@"PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("PLCSIM", 1);
// or network pc interface that is connected to plc
ConfigurationTargetInterface slot = pcInterface.TargetInterfaces.Find("2 X3");
configuration.ApplyConfiguration(slot);
// After applying configuration, you can go online
onlineProvider.GoOnline();
}

Modify the following program code to set gateway address parameters:

public static void SetConnectionWithGatewayAddress(OnlineProvider onlineProvider, string


subnetName, string gatewayAddressName)
{
ConnectionConfiguration configuration = onlineProvider.Configuration;
ConfigurationMode mode = configuration.Modes.Find(@"PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("PLCSIM", 1);
// or network pc interface that is connected to plc
ConfigurationSubnet subnet = pcInterface.Subnets.Find(subnetName);
ConfigurationAddress gatewayAddress = subnet.Addresses.Find(gatewayAddressName);
configuration.ApplyConfiguration(gatewayAddress);
// After applying configuration, you can go online
onlineProvider.GoOnline();
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 527
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to set subnet address parameters:

public static void SetConnectionWithSubnetAddress(OnlineProvider onlineProvider, string


subnetName)
{
ConnectionConfiguration configuration = onlineProvider.Configuration;
ConfigurationMode mode = configuration.Modes.Find(@"PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("PLCSIM", 1);
// or network pc interface that is connected to plc
ConfigurationSubnet subnet = pcInterface.Subnets.Find(subnetName);
ConfigurationAddressComposition addresses = subnet.Addresses;
configuration.ApplyConfiguration(addresses[0]);
// After applying configuration, you can go online
onlineProvider.GoOnline();
}

5.12.2.7 Accessing fingerprint for quick station compare

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
You can use the TIA Portal Openness to get FingerprintData for different aspects of PLC device
configuration which can be used to realize a quick station compare. It is done through
FingerprintDataProvider service that can be acquired from a given TIA Portal. An instance of
FingerprintDataProvider will be returned on GetService call, else the service will return null.

Program code: Retrieving FingerprintDataProvider from TIA Portal

TiaPortal tia = new TiaPortal(TiaPortalMode.WithUserInterface);


FingerprintDataProvider fingerprintDataProvider =
tia.GetService<FingerprintDataProvider>();
if (fingerprintDataProvider != null)
{
...
}

Openness: API for automation of engineering workflows


528 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Parameters of FingerprintDataProvider method


To get the fingerprintData of a device, you have to call GetFingerprintData method of
FingerprintDataProvider.
The following attributes are supported in FingerprintDataProvider:

Parameter name Type Description


configurationAddress Siemens.Engineering.Online.Configura‐ Address of device for which the finger‐
tion printData have to be fetched.
onlineConfigurationDelegate Siemens.Engineering.Online Delegate that will be called to check con‐
figuration before fetching the finger‐
printData.

Configuration Address
You should provide a ConfigurationAddress object to the GetFingerprintData. The address object
will be used to establish a connection to the device for which the fingerprintData have to be
fetched. The ConfigurationAddress object must be created in the ConnectionConfiguration of
the FingerprintDataProvider.
For example, you can use the following code to create an address object:

...
ConnectionConfiguration configuration = fingerprintDataProvider.Configuration;
ConfigurationMode configurationMode = configuration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces.Find("Intel(R)
Ethernet Connection I217-LM", 1);
// Create an address. This "ConfigurationAddress" is used as parameter for getting the
fingerprintData
ConfigurationAddress fingerprintAddress = pcInterface.Addresses.Create("192.68.0.1");
...

The Configuration contains a list of supported Modes. You have to select one of the Modes that
should be used to get fingerprints. The selected ConfigurationMode contains a list of all local
PCInterfaces that support the selected Mode. You have select one of the interfaces. The desired
address can be created in the Address collection of the selected ConfigurationPcInterface.

Program code: Retrieving the FingerprintData


You can start retrieving the FingerprintData of the station by calling the action
GetFingerprintData. The following parameters are supported:

Parameter Description
ConfigurationAddress The address of the device
OnlineConfigurationDelegate The callback to handle inhibits)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 529
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

...
OnlineConfigurationDelegate preConfigurationDelegate = PreConfigureFingerprint;
FingerprintDataResult result =
fingerprintDataProvider.GetFingerprintData(fingerprintAddress , preConfigurationDelegate);
// The fingerprints
FingerprintDataItemComposition allFingerprints = result.FingerprintDataItems;
foreach (FingerprintDataItem item in allFingerprints)
{
// do something with the fingerprint ...
}
internal void PreConfigureFingerprint(OnlineConfiguration onlineConfiguration)
{
...
}

Online configuration delegate


The possible online configuration types are listed below:

Configuration name Description and properties


OnlineConfiguration • Base class for other configurations
• OnlineConfiguration.Message: string (read only property
that contains the configuration message)

Because this is the Base class for all other configurations, this property adapter is therefor
available in all configurations.
The datatype of the configuration is given below:

Configuration DataType Description and Action


OnlineConfiguration OnlineReadAccessPassword Set password via SetPassword(pass‐
word:SecureString) method.
Enter a password to gain read access to
the module

Unhandled configuration that can prevent accessing fingerprint causes


EngineeringDelegateInvocationException and aborts action. An
EngineeringDelegateInvocationException will be thrown in case of an unhandled exception
within the Delegate.

Openness: API for automation of engineering workflows


530 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

PreConfigureFingerprint implementation example

private static void PreConfigureFingerprint(OnlineConfiguration onlineConfiguration)


{
OnlineReadAccessPassword readAccess = onlineConfiguration as OnlineReadAccessPassword;
if (readAccess != null)
{
string passWD = "passWD";
var password = new SecureString();
foreach (var c in passWD) password.AppendChar(c);
moduleReadAccessPassword.SetPassword(password);
return;
}
throw new NotSupportedException(); // Exception thrown in the delagate will cancel get
fingerprints
}

FingerprintDataResult
The FingerprintDataResult returned by the GetFingerprintData action provides a composition of
all the fingerprints defined for the device.
For example, you can use the below code to examine fingerprint items:

{
...
FingerprintDataResult result = dataProvider.GetFingerprintData(fingerprintAddress,
preConfigurationDelegate);
FingerprintDataItemComposition allFingerprints = result.FingerprintDataItems;
foreach (FingerprintDataItem item in allFingerprints)
{
string fingerprintDataIdentifier = item.FingerprintDataIdentifier;
string fingerprintDataValue = plcItem.FingerprintDataValue;
// Do something, e.g. store Identifier and Value in a file
}
}

Error Handling within the Openness fingerprints


All errors within the Openness fingerprints will be mapped as recoverable user exceptions
EngineeringTargetInvocationException. So any error in an Openness action will not lead to a TIA-
Portal crash.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 531
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Precondition is, that the client handle the exception. For example this could happened like
shown in following code

TiaPortal currentTIA = ...;


FingerprintDataProvider dataProviderFingerprints =
currentTIA.GetService<FingerprintDataProvider>();
OnlineConfigurationDelegate configurationDelegate = OnlineConfigurationFingerprintData;
try
{
// The used addr referes a PLC300.
FingerprintDataResult dataResult = dataProviderFingerprints.GetFingerprintData(addrObj,
configurationDelegate);
// Try to get a list of all FingerprintDataItems. But a PLC300 supports no fingerprints.
FingerprintDataItemComposition dataItems = dataResult.FingerprintDataItems;
foreach (FingerprintDataItem searchItem in dataItems)
{
string valueToCompareIdent = searchItem.FingerprintDataIdentifier;
string valueToCompareValue = searchItem.FingerprintDataValue;
DoAnything(valueToCompareIdent, valueToCompareValue);
}
}
catch (EngineeringTargetInvocationException targetException)
{
// In case of the not supported PLC this exception will be catched.
Console.WriteLine(targetException.Message);
}

Helper classes
For this example two classes are needed. You can use the below program code to encapsulate
fingerprint data pairs.

/// <summary>
/// Helperclass to handle a "Dictionary" as serializeable class object
/// </summary>
[Serializable]
public class FingerprintDataPairs : Dictionary<string, string>, ISerializable
{
public FingerprintDataPairs(){}
public FingerprintDataPairs(SerializationInfo si, StreamingContext context)
{
KeyValuePair<string, string>[] dataPair = si.GetValue("KeyValuePairs",
typeof(KeyValuePair<string, string>[])) as KeyValuePair<string, string>[];
if (dataPair != null)
foreach (KeyValuePair<string, string> pair in dataPair)
this.Add(pair.Key, pair.Value);
}
}

Openness: API for automation of engineering workflows


532 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the below example to handle the fingerprint data and compare:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 533
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

/// <summary>
/// Helperclass for handle the fingerprint data and compare two datasets.
/// </summary> public class FingerprintDataCompare
{
internal FingerprintDataPairs m_FingerprintDataPairs;
internal FingerprintDataPairs FingerprintDataPairSet
{
get
{
if (m_FingerprintDataPairs == null) m_FingerprintDataPairs = new FingerprintDataPairs();
return m_FingerprintDataPairs;
}
set
{
m_FingerprintDataPairs = value;
}
}
internal bool CompareDataSets(FingerprintDataPairs dataSet1, FingerprintDataPairs dataSet2)
{
foreach (string key in dataSet1.Keys)
{
if (dataSet2[key] != dataSet1[key])
return false;
}
return true;
}
internal void SaveFingerprintDataItems(FingerprintDataPairs fingerprintDataPairSet, string
filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, fingerprintDataPairSet);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to write fingerprints. See: " + e.Message);
}
finally
{
fs.Close();
}
}
}
internal FingerprintDataPairs LoadFingerprintDataItems(string filename)
{
FingerprintDataPairs dataPair = null;
using(FileStream fs = new FileStream(filename, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
dataPair = (FingerprintDataPairs)formatter.Deserialize(fs);

Openness: API for automation of engineering workflows


534 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

}
catch (System.Runtime.Serialization.SerializationException e)
{
Console.WriteLine("Failed to read fingerprints. See: " + e.Message);
}
finally
{
fs.Close();
}
}
return dataPair;
}
}

Compare Fingerprints
To compare, you can use the FingerprintDataResult

...
// See chapter "FingerprintDataResult"
FingerprintDataResult fingerprintDataResult = dataProvider.GetFingerprintData(address,
preConfigurationDelegate);
...

To save the Fingerprints. you can use the Helper Classes:

string pathDat = "FingerprintDataOverview.dat";


// Create a fingerprint comparer and fill the dataitems with the result of
"GetFingerprintData".
FingerprintDataCompare fingerprintDataSet = new FingerprintDataCompare();
foreach (FingerprintDataItem item in fingerprintDataResult.FingerprintDataItems)
fingerprintDataSet.FingerprintDataPairSet.Add(item.FingerprintDataIdentifier,
item.FingerprintDataValue);
fingerprintDataSet.SaveFingerprintDataItems(fingerprintDataSet.FingerprintDataPairSet,
pathDat);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 535
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

With saved FingerprintDataItems and a current FingerprintDataResult a Compare of Fingerprints


can be realized

...
string pathDat = "FingerprintDataOverview.dat";
FingerprintDataCompare fingerprintDataSet = new FingerprintDataCompare();
foreach (FingerprintDataItem item in fingerprintDataResult.FingerprintDataItems)
fingerprintDataSet.FingerprintDataPairSet.Add(item.FingerprintDataIdentifier,
item.FingerprintDataValue);
FingerprintDataPairs loadDataSet = new FingerprintDataPairs();
loadDataSet = fingerprintDataSet.LoadFingerprintDataItems(pathDat);
if (!fingerprintDataSet.CompareDataSets(loadDataSet,
fingerprintDataSet.FingerprintDataPairSet))
{
// Here is place to implement user actions.
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.8 Setting PLC online of R/H system

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the RHOnlineProvider service to set online either to primary PLC or backup PLCs of
R/H system.

Program code: Accessing RHOnlineProvider service from a device


Modify the following code to access RHOnlineProvider:

Device device = project.Devices.Find("S7-1500R/H-System_1");


RHOnlineProvider rhOnlineProvider = device.GetService<RHOnlineProvider>();

Openness: API for automation of engineering workflows


536 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Setting connection parameters


You can use ConnectionConfiguration object to set a connection to the device. It can be accessed
from Configuration property of the RHOnlineProvider. For more information about how to set
connection, Refer Accessing parameters of an online connection (Page 524)
Modify the following program code to set a connection mode and access a PC interface by name:

ConnectionConfiguration connectionConfiguration = rhOnlineProvider.Configuration;


ConfigurationMode mode = connectionConfiguration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("Broadcom NetXtreme Gigabit
Ethernet", 1);
ConfigurationTargetInterface targetConfiguration = pcInterface.TargetInterfaces.Find("1
X1");
bool success = connectionConfiguration.ApplyConfiguration(targetConfiguration);

Note
R/H system consists of two PLCs, a single connection configuration is provided to you.

Program code: Setting online R/H system


You can set online either to primary or backup PLC. The user attempts to set online to both
targets simultaneously will encounter EngineeringTargetInvocationException from system.
Modify the following program code to set online to the primary PLC:

OnlineState onlineState = rhOnlineProvider.GoOnlineToPrimary();

Modify the following program code to set online to the backup PLC:

OnlineState onlineState = rhOnlineProvider.GoOnlineToBackup();

Note
You are allowed to reuse previously stored password when setting a PLC Online of R/H system.

Program code: Determining online status of R/H system


You can use PrimaryState and BackupState properties of RHOnlineProvider to determine the
online connection status of primary PLC and backup PLC individually . Both properties return
enum OnlineState. For more information on identify the online state of PLC, Refer Determining
the status of a PLC (Page 523)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 537
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to determine the state of primary PLC and backup PLC:

RHOnlineProvider rhOnlineProvider = ...;


OnlineState primaryState = rhOnlineProvider.PrimaryState;
OnlineState backupState = rhOnlineProvider.BackupState;

Program code: Setting offline R/H system


Modify the following program code to set a currently online R/H system to an offline state by
invoking RHOnlineProvider.GoOffline method:

rhOnlineProvider.GoOffline();

See also
Accessing parameters of an online connection (Page 524)
Determining the status of a PLC (Page 523)
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.9 Accessing software container from primary PLC of R/H system

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use primary PLC device of an R/H system to access software container, for example the
R/H system will provide software container for a primary PLC device item representing PLC_1.
Otherwise, it will provide null if you try to access a software container for backup PLC device
representing PLC_2.
The specific of SoftwarContainer and its software property are described in Access software
target. (Page 131)

Openness: API for automation of engineering workflows


538 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Accessing software container


Modify the following program code to access software container from primary device of an R/H
system:

foreach (DeviceItem deviceItem in rhDevice.DeviceItems)


{
if (deviceItem.Name == "PLC_1")
{
SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
... //Work with softwareContainer
}
}

See also
Access software target (Page 131)
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.10 Downloading PLCs of R/H System

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness application to download the primary and backup PLCs of R/
H system. You are able to download both hardware and software components of the system.
(Refer Downloading hardware and software components to PLC device (Page 485))

Program code: Retrieving RHDownloadProvider


You can download to R/H system through RHDownloadProvider service from a device.
Modify the following program code to retrieve RHDownloadProvider:

...
Device device = project.Devices.Find("S7-1500R/H-System_1");
RHDownloadProvider rhDownloadProvider = device.GetService<RHDownloadProvider>();
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 539
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Note
The DownloadProvider service will not be accessed for CPUs that are part of R/H system.

Program code: Retrieving IConfiguration


RHDownloadProvider provides ConnectionConfiguration object through Configuration property
which will be used to configuring the connection to the device.
Modify the following program code to retrieve IConfiguration object from
ConnectionConfiguration on RHDownloadProvider:

...
RHDownloadProvider rhDownloadProvider = device.GetService<RHDownloadProvider>();
ConnectionConfiguration connectionConfiguration = rhDownloadProvider.Configuration;
ConfigurationMode mode = connectionConfiguration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("Broadcom NetXtreme Gigabit
Ethernet", 1);
IConfiguration targetConfiguration = pcInterface.TargetInterfaces.Find("1 X1");
...

Note
R/H systems consist of two PLCs, only one connection configuration object is provided that can
be used for both primary and backup downloads.

Program code: Downloading primary CPU and backup CPU


Modify the following program code to download to the primary CPU by invoking
RHDownloadProvider.DownloadToPrimary:

DownloadResult DownloadToPrimary(configuration, preDownloadConfigurationDelegate,


postDownloadConfigurationDelegate, downloadOptions);

Modify the following program code to download to the backup CPU by invoking
RHDownloadProvider.DownloadToBackup:

DownloadResult DownloadToBackup(configuration, preDownloadConfigurationDelegate,


postDownloadConfigurationDelegate, downloadOptions);

Openness: API for automation of engineering workflows


540 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Parameters of RHDownloadProvider method


Both RHDownloadProvider.DownloadToPrimary and RHDownloadProvider.DownloadToBackup
accept the same parameters and also return a DownloadResult. For more information about the
details of IConfiguration, DownloadConfigurationDelegate, DownloadOptions and
DownloadResult, Refer Downloading hardware and software components to PLC device
(Page 485)

Parameter name Type Description


configuration Siemens.Engineering.Connection.ICon‐ Connection configuration to a device.
figuration
preDownloadConfigurationDelegate Siemens.Engineering.Download.Down‐ Delegate that will be called to check con‐
loadConfigurationDelegate figuration before download
postDownloadConfigurationDelegate Siemens.Engineering.Download.Down‐ Delegate that will be called to check con‐
loadConfigurationDelegate figuration after download
downloadOptions Siemens.Engineering.Download.Down‐ Download options
loadOptions

Depending upon the state of R/H system, you might request to stop the system for the download
via DownloadConfigurations. Therefore, in addition to the configuration described in

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 541
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Downloading hardware and software components to PLC device (Page 485), the following data
type are added to support RHDownload.

Configuration Data Type Action Description


DownloadSelection‐ StopHSystem Set CurrentSelection:StopHSys‐ The modules are stopped for
Configuration temSelections. downloading to device
Available enum values:
• NoAction (No Action)
• StopHSystem (Stop R/H-Sys‐
tem)
StopHSystemOrModule Set CurrentSelection:StopHSys‐ The modules are stopped for
temOrModuleSelections. downloading to device
Available enum values:
• NoAction (No action)
• StopHSystem (Stop R/H-Sys‐
tem)
• StopModule (Stop module)
StartBackupModules Set CurrentSelection:StartBack‐ Start modules after download‐
upModulesSelections. ing to device
Available enum values:
• NoAction (No action)
• SwitchToPrimaryCpu
(Change to Primary) )
• StartModule (Start module)
SwitchBackupToPrimary Set CurrentSelection:Switch‐ Start modules after download‐
BackupToPrimarySelections. ing to device.
Available enum values:
• NoAction (No action)
• SwitchToPrimaryCpu
(Change to Primary)

Openness: API for automation of engineering workflows


542 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Handling download configuration callbacks


Modify the following program code to DownloadToPrimary and DownloadToBackup invocations
while handling configurations in the callbacks:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 543
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Download invocation example


static void Main(string[] args)
{
...
Project project = tiaPortal.Projects[0];
Device device = project.Devices.Find("S7-1500R/H-System_1");
RHDownloadProvider rhDownloadProvider = device.GetService<RHDownloadProvider>();
ConnectionConfiguration connectionConfiguration = rhDownloadProvider.Configuration;
ConfigurationMode mode = connectionConfiguration.Modes.Find("PN/IE");
ConfigurationPcInterface pcInterface = mode.PcInterfaces.Find("Broadcom NetXtreme Gigabit
Ethernet", 1);
IConfiguration targetConfiguration = pcInterface.TargetInterfaces.Find("1 X1");

// Download to primary
DownloadResult primaryDownloadResult =
rhDownloadProvider.DownloadToPrimary(targetConfiguration,
PreConfigureDownloadCallback,
PostConfigureDownloadCallback,
DownloadOptions.Hardware | DownloadOptions.Software);
WriteDownloadResults(primaryDownloadResult);
// Download to backup
DownloadResult backupDownloadResult =
rhDownloadProvider.DownloadToBackup(targetConfiguration,
PreConfigureDownloadCallback,
PostConfigureDownloadCallback,
DownloadOptions.Hardware | DownloadOptions.Software);
WriteDownloadResults(backupDownloadResult);
...
}
private static void PreConfigureDownloadCallback(DownloadConfiguration
downloadConfiguration)
{
StopHSystem stopHSystem = downloadConfiguration as StopHSystem;
if (stopHSystem != null)
{
stopHSystem.CurrentSelection = StopHSystemSelections.StopHSystem;
}
OverwriteTargetLanguages overwriteTargetLanguages = downloadConfiguration as
OverwriteTargetLanguages;
if (overwriteTargetLanguages != null)
{
overwriteTargetLanguages.Checked = true;
}
AlarmTextLibrariesDownload alarmTextLibraries = downloadConfiguration as
AlarmTextLibrariesDownload;
if (alarmTextLibraries != null)
{
alarmTextLibraries.CurrentSelection =
AlarmTextLibrariesDownloadSelections.ConsistentDownload;
return;
}
CheckBeforeDownload checkBeforeDownload = downloadConfiguration as CheckBeforeDownload;
if (checkBeforeDownload != null)
{
checkBeforeDownload.Checked = true;
return;

Openness: API for automation of engineering workflows


544 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Download invocation example


}
ConsistentBlocksDownload consistentBlocksDownload = downloadConfiguration as
ConsistentBlocksDownload;
if (consistentBlocksDownload != null)
{
consistentBlocksDownload.CurrentSelection =
ConsistentBlocksDownloadSelections.ConsistentDownload;
return;
}
OverwriteSystemData overwriteSystenData = downloadConfiguration as OverwriteSystemData;
if (overwriteSystenData != null)
{
overwriteSystenData.CurrentSelection = OverwriteSystemDataSelections.Overwrite;
return;
}
}
private static void PostConfigureDownloadCallback(DownloadConfiguration
downloadConfiguration)
{
StartModules startModules = downloadConfiguration as StartModules;
if (startModules != null)
{
startModules.CurrentSelection = StartModulesSelections.StartModule;
return;
}
}
private static void WriteDownloadResults(DownloadResult result)
{
Console.WriteLine("State:" + result.State);
Console.WriteLine("Warning Count:" + result.WarningCount);
Console.WriteLine("Error Count:" + result.ErrorCount);
RecursivelyWriteMessages(result.Messages);
}
private static void RecursivelyWriteMessages(DownloadResultMessageComposition messages,
string indent = "")
{
indent += "\t";
foreach (DownloadResultMessage message in messages)
{
Console.WriteLine(indent + "DateTime: " + message.DateTime);
Console.WriteLine(indent + "State: " + message.State);
Console.WriteLine(indent + "Message: " + message.Message);
RecursivelyWriteMessages(message.Messages, indent);
}
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Downloading hardware and software components to PLC device (Page 485)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 545
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.2.11 Establishing or disconnecting the online connection to the PLC

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• All devices are enumerated.
See Accessing device items (Page 289).

Application
You can establish the online connection to a PLC, or disconnect an existing online connection.

Program code
Modify the following program code to establish or disconnect the online connection to a PLC:

public static void SetOnlineConnection(DeviceItem deviceItem)


{
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
if (onlineProvider == null) { return; }
// Go online
if (onlineProvider.Configuration.IsConfigured)
{
onlineProvider.GoOnline();
}
// Go offline
onlineProvider.GoOffline();
}

Openness: API for automation of engineering workflows


546 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can also establish or disconnect the online connections to all available PLCs in a project.

public static void SetOnlineConnectionForAllPLCs(Project project)


{
foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
if (onlineProvider != null)
{
// Establish online connection to PLC:
onlineProvider.GoOnline();

// ...

// Disconnect online connection to PLC:


onlineProvider.GoOffline();
}
}
}
}

5.12.2.12 Assigning project language to PLC

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to assign project languages to web server and display
languages of an S71500 PLC. To achieve that a StructuredData type dynamic attributes is
required.
To access multilingual settings the new dynamic attribute MultilingualSupport of type TableData
has been added. This can be split up into Rows. At each Row the assigned project language can
be set or read with the dynamic attribute ProjectLanguage.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 547
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to assign project language to PLC:

//To Set the Project Language


LanguageSettings languageSettings = project.LanguageSettings;
LanguageAssociation activeLanguages = languageSettings.ActiveLanguages;
DeviceItem Plc = …;
Tabledata multilingualSupportTable = Plc.GetAttribute("MultilingualSupport");
StructuredDataComposition structuredDataComp = multilingualSupportTable.Rows; // This will
return a collection of Structured Data.
StrcuturedData firstRow= structuredDataComp[0]; //First row
Language activeGermanLanguage = activeLanguages.Find(CultureInfo.GetCultureInfo("de-DE"));
firstRow.SetAttribute("ProjectLanguage", activeGermanLanguage.Culture);
//To Get the Languages of device displayed
var assignedToGerman = firstRow.GetAttribute("DisplayLanguage");

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.13 Assigning watch & force tables for web server and PLC display

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to assign already created watch and force tables to the web
server. The watch table and force table are software that can be found, created, and deleted in
the software container. You can use the TIA Portal Openness to export/ import Watch and Force
tables. For export/import Watch/Force tables, please see Export/Import Watch & Force Table
(Page 1029)
To assign the watch and force tables to the web server, the WatchAndForceTableAccessManager
service is used at the PLC DeviceItem.
The service contains two navigators for watch and force tables.
• WatchtableAccessRules {WatchtableAccessRuleComposition}
• ForcetableAccessRules {ForcetableAccessRuleComposition}
The navigator WatchTableAccessRules provides the WatchTableAccessRuleComposition which
contains objects of type WatchTableAccessRule. The composition is empty by default. For the
WatchTableAccessRule objects, the actions Find and Create are defined.

Openness: API for automation of engineering workflows


548 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

WatchTable Access Rule & ForceTable AccessRule


• PlcWatchTable watchtable {get;} returns the software object watchtable. In order to
exchange an assigned watch table, the user has to remove the assignment of the current one
(using WatchTableAccessRule.Delete()) and add a new one (using
WatchTableAccessRule.Create()).
• WatchAndForceTableAccess access {get; set;} returns / sets the web server access level
whether it is read or read/write

TIA UI name value Openness enum description


- 0 None
Read 1 Read
Read/Write 2 Write

Error will be thrown in the following cases:


• If the web server has not been activated (WebserverActivate == FALSE), a
EngineeringTargetInvocationException is thrown with error details stating that a
WatchTableAccessRule can be added only if the web server is enabled.
• If the user tries to add a watch table with WatchAndForceTableAccess.None a
ConfigOpenessUserException with error details stating that
WatchAndForceTableAccess.None is not allowed as a access level

Program code: Assigning & unassigning watch table


Modify the following program code to search watch table in the web server:

WatchAndForceTableAccessManager mngr =
deviceItem.GetService<WatchAndForceTableAccessManager>();
WatchTableAccessRuleComposition watchTableCmp = mngr.WatchTableAccesseRules;
WatchTableAccessRule accessRule1 = watchTableCmp.Find(watchTable1);

Note
Null will be returned if that watchtable is not associated with any WatchTableAccessRule in the
Webserver

Modify the following program code to create a new watch table to the web server with read
access:

WatchAndForceTableAccessManager mngr =
deviceItem.GetService<WatchAndForceTableAccessManager>();
WatchTableAccessRuleComposition watchTableCmp = mngr.WatchTableAccesseRules;
watchTableCmp.Create(watchTable1, WatchAndForceTableAccess.Read);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 549
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to delete an existing WatchTableAccessRule and unassign
the watch table from the web server:

WatchTableAccessRule whatchtable= watchTableCmp.Find(watchTable1);


whatchtable.Delete();

Error will be thrown in the following cases:


• If the web server has not been activated (WebserverActivate == FALSE), a
EngineeringTargetInvocationException is thrown with error details stating that a
WatchTableAccessRule can be added only if the web server is enabled
• If a WatchtableAccessRule with the watch table already exists, a
ConfigOpenessUserException is thrown with error details stating that the watchtable already
exists.
• If you try to add a watch table with WatchAndForceTableAccess.None, a
ConfigOpenessUserException with error details stating that
WatchAndForceTableAccess.None is not allowed as a access level.

Program code: Assigning force table to the web server


Modify the following program code to search force table in the web server:

WatchAndForceTableAccessManager mngr =
deviceItem.GetService<WatchAndForceTableAccessManager>();
ForceTableAccessRuleComposition forceTableCmp = mngr.ForceTableAccessRules;
ForceTableAccess forceTable = forceTableCmp.Find(forceTable1);

Modify the following program code to create PLC force table to the web server with read access:

ForceTableAccessRuleComposition forceTableCmp = mngr.ForceTableAccessRules;


forceTableCmp.Create(forceTable1, WatchAndForceTableAccess.Read);

Watch and force tables at the PLC display


You can use the same Openness service WatchAndForceTableAccessManager available at the
Display submodule (DeviceItem) of the PLC DeviceItem. The same web server functionality is
used as described above to assign watch and force tables at the PLC display. In contrast to the
web server, the display cannot be disabled, so here a similar validation as for WebserverActive
is not available.

See also
Export/Import Watch & Force Table (Page 1029)
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


550 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.2.14 Managing certificate

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to handle certificates such as create and delete certificate,
export and import certificate, assign and unassign certificates, and get certificate ID.

Local certificate manager


For device certificates the service LocalCertificateManager at the DeviceItem PLC is provided. The
LocalCertificateManager has a local store for the certificates named LocalCertificateStore. There
the certificates for the specific PLC are stored. To get the device item that owns the instance of
the service, the property OwnedBy can be used.

DeviceItem Plc= ...;


// Get local certificate manager
var localCertificateManager = Plc.GetService<LocalCertificateManager>();
// Disable global certificate manager
localCertificateManager.EnableGlobalCertificatesStore = false;
// Get local certificate store
var localCertificateStore = localCertificateManager.LocalCertificateStore;

Certificate handling
Modify the following program code to create a certificate:

/ Create templates
var templateTls = localCertificateStore.GetCertificateTemplate(CertificateUsage.Tls);
var templateWebserver =
localCertificateStore.GetCertificateTemplate(CertificateUsage.WebServer);
var templateOpcUaServer =
localCertificateStore.GetCertificateTemplate(CertificateUsage.OpcUaServer);//
...
//Template handling and configuration is handled later
// Create certificates
var certificateTls = localCertificateStore.Certificates.Create(templateTls);
var certificateWeb = localCertificateStore.Certificates.Create(templateWebserver);
var certificateOpcUa = localCertificateStore.Certificates.Create(templateOpcUaServer);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 551
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to delete and export a certificate:

var exportPath = …;
// renew a certificatecertificate
Tls.Delete();
certificateTls = localCertificateStore.Certificates.Create(templateTlsNew);
certificateWeb.Export(new FileInfo(exportPath), CertificateExportFormat.Cer);

Modify the following program code to assign certificate to web server and OPC UA server using
dynamic attributes:

DeviceItem opcUaSubmodule = …;
//Find assigned certificates
var foundWebCertificate = Plc.GetAttribute("WebserverCertificate");
var foundOpcUaCertificate = opcUaSubmodule.GetAttribute("OpcUaServerCertificate");
//Assign certificatesPlc.SetAttribute("WebserverCertificate", certificateWeb);
opcUaSubmodule.SetAttribute("OpcUaServerCertificate", certificateOpcUa);
//Unassign certificatesPlc.SetAttribute("WebserverCertificate", null);
opcUaSubmodule.SetAttribute("OpcUaServerCertificate", null);

Modify the following program code to import certificates to the local certificate store for a PLC:

var certificateWithoutPwd = …;
var certificateWithPwd = …;
var password = new SecureString();
//

// Import certificates
// Without password
var importedCertificate1 = certificates.Import(new FileInfo(certificateWithoutPwd));
//With password
var importedCertificate2 = certificates.Import(new FileInfo(certificateWithPwd), password);

Modify the following program code to get certificate ID:

var certificateId = importedCertificate2.Id;

Modify the following program code to indicate if a certificate has a private key the boolean
property HasPrivateKey at the certificate object can be used.

if(importedCertificate2.HasPrivateKey)
{
//Do something
}

Openness: API for automation of engineering workflows


552 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Certificate template
The templates are used as basis for creating certificates. New templates can be created at the
LocalCertificateStore using the action GetCertificateTemplate(CertificateUsage). Where
CertificateUsage is an enumerated with the following possible values:
• None (not supported)
• Tls
• WebServer
• OpcUaServer
• OpcUaClient
• OpcUaClientServer

// Create template
var certTemplate = localCertificateStore.GetCertificateTemplate(CertificateUsage.Tls);

In a certificate template all properties of a certificate can be set. The access is read-write:
• Signature: The used signature algorithm of type SignatureAlgorithm which is an enumerated
with the following possible values
– None (not supported)
– Sha1RSA
– Sha256RSA

certTemplate.Signature = SignatureAlgorithm.Sha1RSA;

• SubjectAlternativeNames: Is a composition which contains objects of type


SubjectAlternativeName (IList of type <SubjectAlternativeName>). With the action
Create(SubjectAlternativeNameType, string) a new SAN can be created. The handed over
parameters are the Type (of type SubjectAlternativeNameType) and the Value (of type string).
• SubjectAlternativeNameType
– None (not supported)
– Dns
– Email
– IP
– Uri

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 553
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

var san1 = certTemplate.SubjectAlternativeNames.Create(SubjectAlternativeNameType.Dns,


"127.0.0.1");
var san2 = certTemplate.SubjectAlternativeNames.Create(SubjectAlternativeNameType.IP,
"192.168.178.1");
var san3 = certTemplate.SubjectAlternativeNames.Create(SubjectAlternativeNameType.Email,
"[email protected]");
var san4 = certTemplate.SubjectAlternativeNames.Create(SubjectAlternativeNameType.Uri,
"something");
san3.Delete();

• SubjectCommonName: string

string subjectCommonName = certTemplate.SubjectCommonName;


certTemplate.SubjectCommonName = "exampleSubjectCommonName";

Usage of type CertificateUsage

var usage = certTemplate.Usage;


certTemplate.Usage = CertificateUsage.OpcUaClientServer;

ValidFrom: Type DateTime


ValidUntil: Type DateTime

var validFrom = certTemplate.ValidFrom;


var validUntilDateTime = new DateTime(2080, 10, 10);
certTemplate.ValidUntil = validUntilDateTime;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.15 Supporting secure S7 communication TLS

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to set up the parameters for an online connection.

Openness: API for automation of engineering workflows


554 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

These online connections are set up on the ConnectionConfiguration object that can be
accessed via Configuration navigator of OnlineProvider service. This service exists on a
DeviceItem that represents PLC.

DeviceItem deviceItem = ...;


OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
ConnectionConfiguration configuration = onlineProvider.Configuration;

Depending upon the available connections for a PLC, you can enumerate through the available
connection modes or specifiy a certain connection mode. For each mode,you can then specify
the PC Interface for that connection type.
The Find-Action of PcInterfaces has two parameters. First the name of the interfaceboard
(ConfigurationPcInterface), and additional to this the number of the interfaceboard. Typically
the number of interfaceboard is "1".
You can specify the slot for the interface.

foreach(ConfigurationMode mode in configuration.Modes)


{
Console.WriteLine("Mode name:{0}", mode.Name);
foreach(ConfigurationPcInterface pcInterface in mode.PcInterfaces)
{
Console.WriteLine("PcInterface name:{0}", pcInterface.Name);
Console.WriteLine("PcInterface number:{0}", pcInterface.Number);
foreach(ConfigurationTargetInterface targetInterface in pcInterface.TargetInterfaces)
{
Console.WriteLine("TargetInterface:{0}", targetInterface.Name);
}
}
}
ConfigurationMode mode = configuration.Modes.Find("PN/IE");ConfigurationPcInterface
pcInterface = mode.PcInterfaces.Find("PLCSIM", 1);
ConfigurationTargetInterface slot = pcInterface.TargetInterfaces.Find("2 X3");

Note
If PLCSIM is not running, it will not be included in the PcInterfaces collection.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 555
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can also choose to set up the connection via the Addresses of a Subnet or a Gateway.

foreach(ConfigurationSubnet subnet in pcInterface.Subnets)


{
Console.WriteLine("Subnet name:{0}", subnet.Name);
foreach(ConfigurationAddress subnetAddress in subnet.Addresses)
{
Console.WriteLine("Subnet address:{0}", subnetAddress.Name);
}
foreach(ConfigurationGateway gateway in subnet.Gateways)
{
Console.WriteLine("Gateway name:{0}", gateway.Name);
foreach(ConfigurationAddress gatewayAddress in gateway.Addresses)
{
Console.WriteLine("Gateway address:{0}", gatewayAddress.Name);
}
}
}
ConfigurationSubnet subnet = pcInterface.Subnets.Find("PN/IE_1");
ConfigurationAddress subnetAddress = subnet.Addresses.Find("192.168.0.1");
ConfigurationGateway gateway = subnet.Gateways.Find("PLC_2");
ConfigurationAddress gatewayAddress = gateway.Addresses.Find("192.168.0.2");

These settings can than be applied to online connection via the ApplyConfiguration call on the
ConnectionConfiguration object. The system will return a boolean value indicating whether the
configuration was set successfully.

bool result;result = configuration.ApplyConfiguration(slot);


or
result = configuration.ApplyConfiguration(subnetAddress);
or
result = configuration.ApplyConfiguration(gatewayAddress);

After setting up the connection, you can then go online with the PLC. Each ApplyConfiguration
call is independent and any subsequent call will override the previously applied settings. The
settings are only valid for the current session, similar to the behavior in the UI. If the settings have
already been configured in the UI, then the ApplyConfiguration call is not necessary and the
online connection will use the already available settings.
If a device is already online, invoking the ApplyConfiguration will cause an exception to be
thrown.
You can determine whether a PLC is already configured by using the IsConfigured property
available on the ConnectionConfiguration target:

bool isConfigured = configuration.IsConfigured;

Openness: API for automation of engineering workflows


556 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

PLCs that only have one possible configuration will always be configured and therefore, the
IsConfigured property will return true without calling ApplyConfiguration.

Note
Configuring the connection and going online will not affect the contents of the offline or online
PLCs. The user will have to either download the software and/or hardware to the online PLC or
upload the software from the online device in order to make the PLCs consistent.

Legacy communication
From TIA-Portal Version-17, PLCs of type S7-1500 with Firmware (FW) 2.9 communicate vis Tls.
Communication without Tls can be used by the EnableLegacyCommunication.

EnableLegacyCommunication Description
true Communication via Tls is enabled
false false Communication via Tls is disabled. This type of commu‐
nication is the same as in TIA-Portal Versions < V17.

DeviceItem deviceItem = ...;


OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
ConnectionConfiguration configuration = onlineProvider.Configuration;
configuration.EnableLegacyCommunication = true;

Connection parameters for communicate over Tls


With TIA-Portal V17 PLCs of type S7-1500 are available with Firmware (FW) 2.9. These PLCs
support a secure communication over Tls.
The "Transport Layer Security" expects some conditions for a communication. If these condition
are not fulfilled, a user decision is necessary whether to trust the communication or not.
For this a event handler can be subscribe on Tls notifications at the ConnectionConfiguration
object. If a user decision is necessary, TIA Portal Openness will call this delegate and the client
can handle it.
The 'ConnectionConfiguration' object can be accessed via Configuration navigator of
OnlineProvider service.

DeviceItem deviceItem = ...;


OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();
ConnectionConfiguration configuration = onlineProvider.Configuration;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 557
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Subscribe to an event of Tls-notification


To subscribe to an event of Tls-notifications you have to register your event handler on
OnlineLegitimation:

private OnlineConfigurationDelegate m_OnlineConfigurationDelegate = null;


...
ConnectionConfiguration OnlineConfiguration = ...
m_OnlineConfigurationDelegate = OnlineCallBackMethod;
OnlineConfiguration.OnlineLegitimation += m_OnlineConfigurationDelegate;

Unsubscribe to an event of Tls-notification


To unsubscribe to an event of Tls-notifications (OnlineLegitimation) you have to register your
event handler:

ConnectionConfiguration OnlineConfiguration = ...


m_OnlineConfigurationDelegate = OnlineCallBackMethod;
OnlineConfiguration.OnlineLegitimation -= m_OnlineConfigurationDelegate;

TlsVerificationConfiguration
When going online to a Plc1500 with a FW 2.9 or higher, a user decision may be necessary as to
whether the connection should be established at the given circumstances. In this case the
registered event handler delegate is called in the client program. For the given case, the
OnlineConfiguration parameter must be checked for "TlsVerificationConfiguration".
The possible values of TlsVerificationConfigurationSelection are:

TlsVerificationConfigurationSelection Description
NonVerified The connection is not verified and not trusted
Trusted The connection is verified and trusted
NonTrusted The connection is verified and not trusted

private void OnlineCallBackMethod(OnlineConfiguration onlineConfiguration)


{
...
TlsVerificationConfiguration verificationConfiguration = onlineConfiguration as
TlsVerificationConfiguration;
if (verificationConfiguration != null)
{
verificationConfiguration.CurrentSelection =
TlsVerificationConfigurationSelection.Trusted;
//To establish a connection the value Trusted is necessary.
}
...

With all other values a go online is not possibly and leads to an user exception.

Openness: API for automation of engineering workflows


558 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Also TlsVerificationConfiguration supports two attributes:

Name of method Description


PlcName The name of the PLC calling the delegate.
VerificationInfo Message for the user. Contains reason for calling the delegate.

Notes for working with OnlineDelegates


• The registration of several delegates via the Configuration Object of the same PLC is not
supported.
• If another client is attached to the same TIA-Portal instance, this client has to register via the
configuration of another PLC.
The delegate of the first client is no longer called for this PLC:
• If a client was ended without reset all delegates, it is recommended to use
"ClearOnlineDelegates" method to remove already registered delegates if the client was
started again.
• If the delegate is set and the user performs actions in the TIA Portal UI that result in the
delegate being called, it is discarded. In this case, the delegate must then be reset by the
client.
• An unregister off the event handler only works at the same instance where the register
occurred.
If a service is requested:

OnlineProvider onlineProvider = deviceItem.GetService<OnlineProvider>();

A new instance of the service is created. All event handlers are registered to the configuration
object of this service. So it is impossible to register an event handler at another facility.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.16 Updating module description

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 559
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
In TIA Portal Openness, a specific service ModuleDescriptionUpdater is used at the device item
to update the current module description to the newest version of the module. To get the device
item that owns the instance of the service, the property OwnedBy can be used.
You can use the CanUpdate attribute to show if a new ConfigObject version for this deviceitem
is available.

Atribute Data type Description


CanUpdate bool TRUE: A new version is available
FALSE: There is no new version

You can use the action UpdateModuleDescription ( ) to update the ConfigObject version of a
deviceitem.

Action Return value Description


UpdateModuleDescription True The deviceitem is up to date:
• The deviceitem was updated successfully
• The deviceitem was already up to date
False The deviceitem is not up to date:
• The deviceitem could not be updated

Program code

DeviceItem deviceItem = ...;


var descriptionUpdater = deviceItem.GetService<ModuleDescriptionUpdater>();
if (descriptionUpdater != null)
{
if (descriptionUpdater.CanUpdate) //e.g is update module version possible
{
bool result = descriptionUpdater.UpdateModuleDescription();
.
.
}
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


560 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.2.17 Supporting IP Accessibility

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 113)
• A project is open
See Opening a project (Page 113)

Introduction
You can use the TIA Portal Openness to support IP accessibility. In TIA Portal Openness, a new
dynamic attribute PlcAccessCommunicationModule gets available at the device item CPU. The
attribute is of type object, so that you can access to the CP object you want to select for IP
Accessibility and assign the object to PlcAccessCommunicationModule.
If a CP has already been selected you can retrieve the CP object by getting the value of
PlcAccessCommunicationModule.

Program code

DeviceItem Plc = ...;


object communicationModule = Plc.GetAttribute("PlcAccessCommunicationModule");
// cP contains the object reference of a plugged CP
Plc.SetAttribute("PlcAccessCommunicationModule", cP);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.18 Setting a display password

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 561
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness to set the display protection password. You can use the
method SetPassword(SecureString password) to set the display protection password where the
parameter for the password to be a SecureString. The confirmation password is not needed in
Openness and therefore not available.
The feature will be available if the following preconditions are met.
• The PLC has a “Display” instance.
• The “Display” supports “Password” protection feature. There are cases eg. Software PLC where
Display is available but no password protection available.

Program code
Modify the following program code to get the device item that owns the instance of the service,
the property OwnedBy can be used.

DisplayProtection displayProtection = plcDisplay.GetService<DisplayProtection>();


var displayDeviceItem = displayProtection.OwnedBy;

Modify the following program code to set the Display Protection password:

displayProtection.SetPassword(someSecuredString);
//Sets the string someSecuredString as the CPU display protection password.

Note
SW controllers have a display submodule, but do not support any display protection. So in TIA
Portal Openness the feature SetPassword is not available at the display submodule of any SW
controllers.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.2.19 Accessing web server and OPC UA user management

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


562 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness to access web server and OPC UA submodule of PLCs. It is
possible to add a user up to maximum number at the web server and the OPC UA submodule of
PLCs. The user has a user name and a password.

User management at Web Server


You can perform the following operations, such as adding user, deleting user, and setting
password at web server for all supported device only if web server is activated at the module.
If the web sever is not activated, the add, delete and set operations will throw a
EngineeringTargetInvocationException, but still the read operations will be available.
The WebServerUserManagement service will be available for the PLC instance of only the
supported devices. For other non-supported devices, the service will be null.

WebServerUserManagement
{
Navigators WebServerUsers
{
WebServerUserComposition
}
}

The Service provides a navigator called WebServerUsers using which a


WebServerUserComposition can be obtained, which manages the WebServerUser instances.

WebServerUserComposition
{
WebServerUser Find(string username);
void Create(string username, WebserverUserPermissions permissions,SecureString password);
}
WebServerUser
{
string UserName{get;}
WebserverUserPermissions Permissions {get;set;}
void Delete();
void SetPassword(SecureString password);
}

Program code: Actions at WebServerUserComposition


Modify the following program to search web server user:

WebServerUserComposition webServerUserComposition = WebServerUserManagement.WebServerUsers;


WebServerUser user1 = webServerUserComposition.Find("user1");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 563
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to create a new web server user with a web server user
permissions:

WebServerUserComposition webServerUserComposition = WebServerUserManagement.WebServerUsers;


WebServerUser user1 = webServerUserComposition.Create("user1",
WebserverUserPermissions.ReadTagStatus, someSecureString);

Modify the following program code to delete the web server user:

WebServerUserComposition webServerUserComposition = WebServerUserManagement.WebServerUsers;


WebServerUser user1 = webServerUserComposition.Find("user1");
user1.Delete();

Modify the following program code to replace the current password of the user with the new
password:

WebServerUserComposition webServerUserComposition = WebServerUserManagement.WebServerUsers;


WebServerUser user1 = webServerUserComposition.Find("user1");
user1.SetPassword(someSecureString);

User Management at OPC UA


You can perform the perform following operations such as adding user, deleting user, and
setting password at the OPC UA Server only if the OPC UA Server is activated and username and
password authentication is enabled.
If these conditions are not met, the operation throws a EngineeringTargetInvocationException
with error details stating that the authentication needs to be enabled.
The OpcUaUserManagement service will be available on the OPC UA submodule of the PLC. The
Service will be available for all supported devices where OPC UA submodule is available for the
device item. In other cases, the service will be returned as null.

OpcUaUserManagement
{
Navigators OpcUaUsers
{
OpcUaUserComposition
}
}

Openness: API for automation of engineering workflows


564 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The Service provides a navigator called OpcUaUsers using which a OpcUaUserComposition can
be obtained. The composition manages the OpcUaUser instances:

OpcUaUserComposition
{
OpcUaUser Find(string username);
void Create(string username, SecureString password);
}
OpcUaUser
{
string UserName{get;}
void Delete();
void SetPassword(SecureString password);
}

Program code: Actions at OpcUaUserComposition


Modify the following program code to search a OpcUaUser:

OpcUaUserComposition opcUaUserComposition = opcUaUserManagement.OpcUaUsers;


OpcUaUser user1 = opcUaUserComposition.Find("user1");

Modify the following program code to create a new OpcUaUser:

OpcUaUserComposition opcUaUserComposition = opcUaUserManagement.OpcUaUsers;


opcUaUserComposition.Create("user1", someSecureString);

Modify the following program code to delete the OpcUaUser:

OpcUaUserComposition opcUaUserComposition = opcUaUserManagement.OpcUaUsers;


OpcUaUser user = opcUaUserComposition.Find("user1");
user.Delete();

Modify and use the program code to replace the current password with a supplied one:

OpcUaUserComposition opcUaUserComposition = opcUaUserManagement.OpcUaUsers;


OpcUaUser user = opcUaUserComposition.Find("user1");
user.SetPassword(someSecureString);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 565
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.3 Blocks

5.12.3.1 Querying the "Program blocks" group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.

Program code
Modify the following program code to query the group "Program blocks":

private static void GetBlockGroupOfPLC(PlcSoftware plcsoftware)


//Retrieves the system group of a block
{
PlcBlockSystemGroup blockGroup = plcsoftware.BlockGroup;
}

5.12.3.2 Querying the system group for system blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


566 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code:
Modify the following program code to determine the group created for system blocks by the
system:

PlcSoftware plcSoftware = ...


foreach (PlcSystemBlockGroup systemGroup in plcSoftware.BlockGroup.SystemBlockGroups)
{
foreach (PlcSystemBlockGroup group in systemGroup.Groups)
{
PlcBlockComposition pbComposition = group.Blocks;
foreach (PlcBlock block in pbComposition)
{
//add your code here
}
}
}

5.12.3.3 Enumerating system subgroups

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 567
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Enumerating all system subgroups


Modify the following program code to enumerate the system subgroups of all system blocks:

//Retrieves the system generated group for system blocks


private static void GetSystemgroupForSystemblocks(PlcSoftware plcSoftware)
{
PlcSystemBlockGroupComposition systemBlockGroups =
plcSoftware.BlockGroup.SystemBlockGroups;
if (systemBlockGroups.Count != 0)
{
PlcSystemBlockGroup sbSystemGroup = systemBlockGroups[0];
foreach (PlcSystemBlockGroup group in sbSystemGroup.Groups)
{
EnumerateSystemBlockGroups(group);
}
}
}
private static void EnumerateSystemBlockGroups(PlcSystemBlockGroup systemBlockGroup)
{
foreach (PlcSystemBlockGroup group in systemBlockGroup.Groups)
{
// recursion EnumerateSystemBlockGroups(group);
}
}

Program code: Accessing a specific subgroup


Modify the following program code to access a specific subgroup:

private static void AccessSbGroup(PlcSystemBlockGroup systemBlockGroup)


{
PlcSystemBlockGroup group1 = systemBlockGroup.Groups.Find("User group XYZ");
PlcSystemBlockGroup group2 = group1.Groups.Find("User group ZYX");
}

See also
Adding an external file (Page 585)

5.12.3.4 Enumerating user-defined block groups

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.

Openness: API for automation of engineering workflows


568 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
Subgroups are taken into account recursively for enumeration.

Program code: Enumerating all groups


Modify the following program code to enumerate the user-defined block groups:

//Enumerates all block user groups including sub groups


private static void EnumerateAllBlockGroupsAndSubgroups(PlcSoftware plcsoftware)
{
foreach (PlcBlockUserGroup blockUserGroup in plcsoftware.BlockGroup.Groups)
{
EnumerateBlockUserGroups(blockUserGroup);
}
}

private static void EnumerateBlockUserGroups(PlcBlockUserGroup blockUserGroup)


{
foreach (PlcBlockUserGroup subBlockUserGroup in blockUserGroup.Groups)
{
EnumerateBlockUserGroups(subBlockUserGroup);
// recursion
}
}

Program code: Accessing a group


Modify the following program code to access a selected user-defined block group:

//Gives individual access to a specific block user group


private static void AccessBlockusergroup(PlcSoftware plcsoftware)
{
PlcBlockUserGroupComposition userGroupComposition = plcsoftware.BlockGroup.Groups;
PlcBlockUserGroup plcBlockUserGroup = userGroupComposition.Find("MyUserfolder");
}

5.12.3.5 Enumerating all blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 569
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
Targeted access to a program block is possible if its name is known.

Program code: Enumerating all blocks


Modify the following program code to enumerate the blocks of all block groups:

private static void EnumerateAllBlocks(PlcSoftware plcsoftware)


//Enumerates all blocks
{
foreach (PlcBlock block in plcsoftware.BlockGroup.Blocks)
{
// Do something...
}
}

Program code: Accessing a specific block


Modify the following program code to access a specific block:

private static void AccessASingleBlock(PlcSoftware plcsoftware)


//Gives individual access to a block
{
// The parameter specifies the name of the block
PlcBlock block = plcsoftware.BlockGroup.Blocks.Find("MyBlock");
}

5.12.3.6 Querying information of a block/user data type

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


570 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
The TIA Portal Openness API supports the querying of the following information for program and
data blocks and for user data types:
• Time stamp in UTC time format.
You check the following with the time stamp:
– When the block was last compiled.
– When the block was last changed.
• "Consistency" attribute
The "Consistency" attribute is set to "True" in the following cases:
– The block has been successfully compiled.
– The block has not been changed since compilation.
– No changes that would require re-compilation have been made to external objects.
• Programming language used (program and data blocks only)
• Block number
• Block name
• Block author
• Block family
• Block title
• Block version
See also Blocks and types of the TIA Portal Openness object model (Page 57) for further
information.

Program code
Modify the following program code to query the information listed above:

private static void GetPlcBlockInformation(PlcSoftware plcSoftware)


{
PlcBlock plcBlock = plcSoftware.BlockGroup.Blocks.Find("MyBlock");
// Read information
DateTime compileDate = plcBlock.CompileDate;
DateTime modifiedDate = plcBlock.ModifiedDate;
bool isConsistent = plcBlock.IsConsistent;
int blockNumber = plcBlock.Number;
string blockName = plcBlock.Name;
ProgrammingLanguage programmingLanguage = plcBlock.ProgrammingLanguage;
string blockAuthor = plcBlock.HeaderAuthor;
string blockFamily = plcBlock.HeaderFamily;
string blockTitle = plcBlock.HeaderName;
System.Version blockVersion = plcBlock.HeaderVersion;
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 571
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Importing configuration data (Page 885)

5.12.3.7 Setting and removing protections from a block

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Application
You can set or remove the password protection of a block via the PlcBlockProtectionProvider class
and the PlcBlockProtectionProvider service. The service PlcBlockProtectionProvider is accessible
on blocks which fulfill the following conditions:
• block is know-how protectable
• block is a code block or a global DB
• block is supported or editable in the current PLC
• block is not in readonly context
• block is not know-how protected
• block is not online
• block is not a CPU-DB
• block is not of classic encryption language, ProDiag or ProDiag-OB
• block is not an encrypted imported classic block
In case the block doesn't fulfill all conditions a null reference is returned by GetService() method.

Program code: Performing know-how protection related operations


Modify the following program code:

PlcBlock block = ...;


PlcBlockProtectionProvider protectionProvider =
block.GetService<PlcBlockProtectionProvider>();
if (protectionProvider != null)
{
... // perform know-how protection related operations here
}

Openness: API for automation of engineering workflows


572 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Protect a block
Use the Protect() method to set the password to protect the porgramming block with.

void Protect(SecureString password)

Errors will occur in case


• of an attempt to protect an already protected block: An
EngineeringTargetInvocationException will be thrown with the message "You can't protect
an already protected object".
• of an attempt to protect with an empty string as password: An
EngineeringTargetInvocationException will be thrown with the message "Password was not
specified".
• of an attempt to protect a failsafe block when the failsafe-program is password protected: An
EngineeringTargetInvocationException will be thrown.
• of an attempt to protect a failsafe block when the block is not called: An
EngineeringTargetInvocationException will be thrown.

Unprotect a block
Use the Unprotect() method to remove the password the porgramming block is protected with.

void Unprotect(SecureString password)

Errors will occur in case


• of an attempt to unprotect an already unprotected block: An
EngineeringTargetInvocationException will be thrown with the message "You can't
unprotect an object without protection".
• of an attempt to unprotect with wrong password: An EngineeringTargetInvocationException
will be thrown with the message "The used password was refused".
• of an attempt to protect with an empty string as password: An
EngineeringTargetInvocationException will be thrown with the message "Password was not
specified".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 573
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Check for invalid characters


Because you can use any characters including backspace, tab etc. to protect a block with the
Protect() method, it could be impossible to remove the protection within the TIA Portal. Since the
passwords are submitted as SecureString, you have to check for yourself if the provided
password has illegal characters. With the GetInvalidPasswordCharacters() method you can
retrieve a list of invalid characters.

SecureString CreatePasswordString(ProtectionProvider protectionProvider, IEnumerable<char>


contentCharacters)
{
IList<char> invalidCharacters = protectionProvider.GetInvalidPasswordCharacters();
SecureString password = new SecureString();
foreach(char ch in contentCharacters)
{
if (!invalidCharacters.Contains(ch))
{
password.AppendChar(ch);
}
else
{
// at least one of the content characters is not valid
// signal an error - e.g. throw an exception
...
}
}
return password;
}

Errors will occur in case


• of an attempt to unprotect an already unprotected block: An
EngineeringTargetInvocationException will be thrown with the message "You can't
unprotect an object without protection".
• of an attempt to unprotect with wrong password: An EngineeringTargetInvocationException
will be thrown with the message "The used password was refused".
• of an attempt to protect with an empty string as password: An
EngineeringTargetInvocationException will be thrown with the message "Password was not
specified".

5.12.3.8 Deleting block

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Openness: API for automation of engineering workflows


574 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to delete a block:

//Runs through block group and deletes blocks


private static void DeleteBlocks(PlcSoftware plcsoftware)
{
PlcBlockSystemGroup group = plcsoftware.BlockGroup;
// or BlockUserGroup group = ...;
for (int i = group.Blocks.Count - 1; i >= 0; i--)
{
PlcBlock block = group.Blocks[i];
if (block != null)
{
block.Delete();
}
}
}

See also
Importing configuration data (Page 885)

5.12.3.9 Creating group for blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to create a group for blocks:

private static void CreateBlockGroup(PlcSoftware plcsoftware)


//Creates a block group
{
PlcBlockSystemGroup systemGroup = plcsoftware.BlockGroup;
PlcBlockUserGroupComposition groupComposition = systemGroup.Groups;
PlcBlockUserGroup myCreatedGroup = groupComposition.Create("MySubGroupName");
}

See also
Importing configuration data (Page 885)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 575
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.3.10 Deleting group for blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Program code
Modify the following program code to delete a group for blocks:

// Deletes user groups from PlcBlockSystemGroup or PlcBlockUserGroup


private static void DeleteBlockFolder(PlcSoftware plcSoftware)
{
PlcBlockUserGroup group = plcSoftware.BlockGroup.Groups.Find("myGroup");
//PlcBlockSystemGroup group = plcSoftware.BlockGroup;
PlcBlockUserGroupComposition subgroups = group.Groups;
PlcBlockUserGroup subgroup = subgroups.Find("myUserGroup");
if (subgroup != null)
{
subgroup.Delete();
}
}

See also
Importing configuration data (Page 885)

5.12.3.11 Accessing attributes of all blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can set the attributes applicable for all blocks using SetAttribute() and SetAttributes()
method.
SetAttributes() can operate on all objects types where writtable openness attribute is available.
With one input item it behaves as SetAttribute.

Openness: API for automation of engineering workflows


576 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Parameter checking:
• Initial checks are done before the first item is being processed by global PE infrastructure:
checking of input items for identical and valid attribute's name, data type mismatch. The
same attribute cannot be set twice by one SetAttributes
• Sequential check happens during running of SetAttributes. The order of the processing is the
same as the order of the input list elements
SetAttributes operates in only one transaction. If any attribute of input list cannot be set, the
values of attributes are remaining unchanged. SetAttributes sets attributes in the same order as
they can be found in the parameter list. The parameters can be dependent or independent of
each other. If one parameter depends on one of the previous parameters in the list, this
parameter is checked and evaluated according to the current value of the other attribute (not
to the original value at the time of calling). If the SetAttributes cannot be executed, details of the
error are indicated. The error message contains the first attribute name and its value which could
not be managed to set and its reason.
The following program code examples were given based on the two attributes AutoNumber and
Number using SetAttribute() (Refer Exporting blocks (Page 998) for all applicable attributes of
blocks).

Program code: SetAttribute

...
PlcBlockGroup blockFolder = YourUtilities.GetFolder();
var block = blockFolder.Blocks.Find("Block_1");
if ((bool)block.GetAttribute(“AutoNumber”)==true)
{
block.SetAttribute("AutoNumber",false);
}
block.SetAttribute("Number",2);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 577
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: SetAttributes

PlcBlock block = SelectBlock("MC-Servo");


if (block != null)
{
IList<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("DataExchangeMode", OBDataExchangeMode.Synchronous),new
KeyValuePair<string, object>("SynchronousApplicationCycleTime", (float)69)
};
try
{
block.SetAttributes(list);
}
catch (EngineeringException e)
{
Console.WriteLine("Exception: " + e.Message);
}
}

5.12.3.12 Creating a ProDiag-FB

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Openness user can use the PLCBlock composition’s create action with the following parameters
to create ProDiag FB.
1. Name
2. Auto number flag
3. Number
– If "auto number flag" is true, the given block number will be set in case it is free, otherwise
a new block will be generated
– If "auto number flag" is false, the given block number will be set to the block
4. Programming language
– If the user invoke create action with ProDiag programming language, then a new FB will
be created without IDB.
– If user invoke create action with IDB of ProDiag, than IDB of ProDiag will be created.
– In any other not supported case, a recoverable exception is thrown.

Openness: API for automation of engineering workflows


578 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Creating a ProDiag-FB

...
PlcBlockGroup blockFolder = plc.BlockGroup;
PlcBlockComposition blockComposition = blockFolder.Blocks;
if (blockComposition != null)
{
string fbName = "ProDiag_Block";
bool isAutoNumber = true;
int number = 1;
var progLang = ProgrammingLanguage.ProDiag;
FB block = blockComposition.CreateFB(fbName, isAutoNumber, number, progLang);
string iDBName="ProDiag_IDB";
string instanceOfName = fbName;
InstanceDB iDbBlock = blockComposition.CreateInstanceDB(iDBName, isAutoNumber, number,
instanceOfName);
}
...

See also
Accessing supervisions and properties of ProDiag-FB (Page 579)

5.12.3.13 Accessing supervisions and properties of ProDiag-FB

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Accessing supervisions of User-FB


Openness user can access the supervisions at FB by using the following code snippet. Every FB
has the list of supervisions inclduing Classic and Plus PLCs.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 579
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Accessing supervisions of ProDiag-FB


PlcBlock iDB = plc.BlockGroup.Blocks.Find("FB_Block_DB");
string fbName = iDB.GetAttribute("InstanceOfName").ToString();
FB fb = (FB)plc.BlockGroup.Blocks.Find(fbName);
if (fb.Supervisions.Count > 0)Console.WriteLine("Contains supervisions");
else
Console.WriteLine("Does not contains supervisions");

Accessing the attributes of FB block


Openness user can set AssignedProDiagFB at InstanceDB via the attribute AssignedProDiagFB
(Refer Exporting blocks (Page 998)). The user can use GetAttribute(), GetAttributes() and
SetAttribute() method for accessing the attributes. The user cannot use SetAttributes() method
for setting the attributes for more than one attribute. TIA Portal Openness throws an exception
for using SetAttributes() method.
If the attribute is not supported (in the given block), recoverable user exception is thrown. If
there is no assigned ProDiag-Block set, GetAttribute() returns an empty string.

Program code: Getting and setting the assigned ProDiag-FB at and IDB

...
PlcBlockGroup blockFolder = plc.BlockGroup;
PlcBlock instanceDB = blockFolder.Blocks.Find("IDB");
PlcBlock plcProdiag = blockFolder.Blocks.Find("block_Prodiag");
instanceDB.SetAttribute("AssignedProDiagFB", plcProdiag.Name);
var assignedProDiagFB = instanceDB.GetAttribute("AssignedProDiagFB");
...

See also
Creating a ProDiag-FB (Page 578)

Openness: API for automation of engineering workflows


580 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.3.14 Assigning ProDiag FB for DBs & Tag Table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to get and set the assigned proDiagFB value of a member
in Global DB and TagTable using GetAttribute/SetAttribute method.
The Siemens.Engineering.SW.Blocks.Interface.Member type name provides the following
properties:

Property Name Data type Access


Name   String Read
AssignedPro‐ String Read/Write
DiagFB        

Program code: Getting proDiagFB Value from DB member & Tag member
Modify the following program code to get prodiagFB in different instances of UDT irrespective of
whether the UDT has supervision or not:

//Simple UDT instance


MemberComposition gdbMembers = dataBlock.Interface.Members;
Member member = gdbMembers.Find("SimpleUdtInstanceMember");
object proDiagFB = member.GetAttribute("AssignedProDiagFB");
//Array of UDT Instance
Member member = dataBlock.Interface.Members.Find("ArrayUdtMember.ArrayUdtMember[0]");
object proDiagFB = member.GetAttribute("AssignedProDiagFB");
//UDT instance inside Struct
Member member = dataBlock.Interface.Members.Find("structMember.UdtInstanceMember");
object proDiagFB = member.GetAttribute("AssignedProDiagFB");
//UDT Instance inside Array of Struct
MemberComposition gdbMembers = dataBlock.Interface.Members;
Member member =
gdbMembers.Find("ArrayOfStructMember.ArrayOfStructMember[0].UdtInstanceMember");
object proDiagFB = member.GetAttribute("AssignedProDiagFB");

Modify the following program code to get prodiagFB in tagTable:

// UDT Instance in TagTable


PlcTagTable tagTable = plc.TagTableGroup.TagTables.Find("Tag table_1");
PlcTag tag = tagTable.Tags.Find("Tag_1");
object proDiagFB = tag.GetAttribute("AssignedProDiagFB ");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 581
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Setting proDiagFB Value to DB & Tag member


Modify the following program code to set assigned ProdiagFB attribute to a member in DB:

//Simple UDT instance


MemberComposition gdbMembers = dataBlock.Interface.Members;
Member member = dataBlock.Interface.Members.Find("SimpleUdtInstanceMember");
member.SetAttribute("AssignedProDiagFB", "ProDiagFBName");
//Array of UDT Instance
Member member = dataBlock.Interface.Members.Find("ArrayUdtMember.ArrayUdtMember[0]");
member.SetAttribute("AssignedProDiagFB", "ProDiagFBName");
//UDT instance inside Struct
Member member = dataBlock.Interface.Members.Find("structMember.UdtInstanceMember");
member.SetAttribute("AssignedProDiagFB", "ProDiagFBName");
//UDT Instance inside Array of Struct
Member member =
dataBlock.Interface.Members.Find("ArrayOfStructMember.ArrayOfStructMember[0].UdtInstanceMe
mber");
member.SetAttribute("AssignedProDiagFB", "ProDiagFBName");

Modify the following program code to set the assigned ProdiagFB attribute to a tag member:

// UDT Instance in TagTable


var tagTable = plc.TagTableGroup.TagTables.Find("Tag table_1");
var tag = tagTable.Tags.Find("Tag_1");
tag.SetAttribute ("AssignedProDiagFB ", "ProDiagFBName");

Note
The GetAttribute and SetAttribute of ProDiagFB is a dynamic attribute and valid only for UDT
instance in Global Db and Tag Table.
Objects like simple datatype for example int, string etc and derived datatype like struct, array, all
system defined types , the user constants, and system constants types do not support this
attribute.
Exception will be thrown if you try to get/set the attribute for an object which are not valid.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


582 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.3.15 Reading ProDiag-FB blocks and attributes

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project via a TIA Portal Openness application
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to read the ProDiag function block version, and other
ProDiag related attribute values. You can use GetAttribute ( ) and GetAttributes ( ) methods to
read the ProDiag FBs language specific attributes present.

Attributes
The following attributes are supported by ProDiag-FB in Openness:

Attributes Type
ProDiagVersion Version
InitialValueAcquisition bool
UseCentralTimeStamp bool

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.3.16 Accessing value of DB parameter without export

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get and set the start value of a member in any DB using
following ways:
• Indexed access of members in the DB
• Finding the member using the member name

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 583
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The Siemens.Engineering.SW.Blocks.Interface.Member type provides the following properties


name:

Property Name Data type Access


Name    String Read
StartValue         Object Read / Write

Program code
Modify the following program code to get Start Value from a DB:

PlcBlockInterface bi = dbbblock.Interface;
MemberComposition members = bi.Members;
Member member = members.Find("Room_Temperature");
//Normal get attribute should be possible as usual
Object startValue = member.GetAttribute("StartValue");
//Array
initialSpeedvar = members.Find("Motor.InitialSpeed[0]");
motorInitialSpeed = initialSpeedvar.GetAttribute("StartValue");
//UDT-struct
axisSpeedvar = members.Find("FillingStation.Conveyer.AxisSpeed");
axisSpeed = axisSpeedvar.GetAttribute("StartValue");
//Struct
initialSpeedvar = paramF.Find("DischargeValve.FlowMeter.InitialSpeed[0]");
initialSpeed = initialSpeedvar.GetAttribute("StartValue");

Modify the following program code to set Start Value to a DB:

PlcBlockInterface bi = dbbblock.Interface;
MemberComposition members = bi.Members;
Member member = members.Find("Room_Temperature");
Member.SetAttribute("Startvalue", "10");
//Normal set attribute should be possible as usual
Member.SetAttribute("StartValue", 20.3);
//Array
initialSpeedvar = members.Find("Motor.InitialSpeed[0]");
initialSpeedvar.SetAttribute("StartValue", 56);
//UDT-struct
axisSpeedvar = members.Find("FillingStation.Conveyer.AxisSpeed");
axisSpeed.SetAttribute("StartValue", 40.5);
//Struct
initialSpeedvar = paramF.Find("DischargeValve.FlowMeter.InitialSpeed[0]");
initialSpeed.SetAttribute("StartValue", 12);
//Writing a PLC User Constant
PlcUserConstant temperatureConstant = plc.TagTableGroup.TagTables[0].UserConstants[0];
members.Find("temperature_string").SetAttribute("StartValue", temperatureConstant);

Note
The "Attribute Not supported" exception will be thrown to you if you try to use get or set Attribute
for StartValue to the member where it is not possible to have Start Value.

Openness: API for automation of engineering workflows


584 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.3.17 Adding an external file

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project via a TIA Portal Openness application:
See Opening a project (Page 113)

Application
You can add an external file to a PLC. This external file is stored in the file system under the
defined path.
The following formats are supported:
• STL
• SCL
• DB
• UDT

Note
Accessing groups in the "External source files" folder is not supported.
An exception is thrown if you specify a file extension other than *.AWL, *.SCL, *.DB or *.UDT.

Program code
Modify the following program code to create an external file in the "External source files" folder
from a block.

private static void CreateBlockFromFile(PlcSoftware plcSoftware)


// Creates a block from a AWL, SCL, DB or UDT file
{
PlcExternalSource externalSource =
plcSoftware.ExternalSourceGroup.ExternalSources.CreateFromFile("SomeBlockNameHere","SomePa
thHere");
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 585
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.3.18 Generate source from block

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Application
The TIA Portal Openness API interface supports the generation of sources in UTF-8 from STL or
SCL blocks, data blocks and PLCTypes (user data types). To generate a source file of a block,
invoke the method GenerateSource on the PlcExternalSourceSystemGroup instance.
The scale of the generated source file depends on the generation option of this function:
• GenerateOptions.None
Generate source from provided blocks only.
• GenerateOptions.WithDependencies
Generate source including all dependent objects.
The interface Siemens.Engineering.SW.ExternalSources.IGenerateSource
indicates that a source can be generated.
Only the STL and SCL programming languages are supported for blocks. Exceptions are thrown
in the following cases:
• Programming language is not STL or SCL
• A file of the same name already exists at the target location
Only the "*.udt" file extension is supported for user data types. Exceptions are thrown in the
following cases:
• The file extension is not "*.db" for DBs
• The file extension is not "*.awl" for STL blocks
• The file extension is not "*.scl" for SCL blocks

Openness: API for automation of engineering workflows


586 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to generate source files from blocks and types:

//method declaration
...
PlcExternalSourceSystemGroup.GenerateSource

(IEnumerable<Siemens.Engineering.SW.ExternalSources.IGenerateSource>
plcBlocks, FileInfo sourceFile, GenerateOptions generateOptions);
...
//examples
...
var blocks = new List<PlcBlock>(){block1};
var fileInfo = new FileInfo(@"C:\temp\SomePathHere.scl");

PlcExternalSourceSystemGroup systemGroup = ...;

systemGroup.GenerateSource(blocks, fileInfo, GenerateOptions.WithDependencies);

// exports all blocks and with all their dependencies(e.g. called blocks, used DBs or UDTs)
// as ASCII text into the provided source file.
...
or
..
var types = new List<PlcType>(){udt1};
var fileInfo = new FileInfo(@"C:\temp\SomePathHere.udt");

PlcExternalSourceSystemGroup systemGroup = ...;

systemGroup.GenerateSource(types, fileInfo, GenerateOptions.WithDependencies );

// exports all data types and their used data types into the provided source file.
...

See also
Importing configuration data (Page 885)

5.12.3.19 Generating blocks from source

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 587
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can generate blocks from all external files in the "External source files" group. Only external
files with the format ASCII are supported.

Note
Access to groups in the "External source files" folder is not supported.
Existing blocks are overwritten.
An Exception is thrown if an error occurs during the calling. The first 256 characters of each error
message are contained in the notification of the Exception. The project is reset to the processing
state prior to the execution of the GenerateBlocksFromSource method.

Program code
Modify the following program code to generate blocks from all external files in the "External
source files" group.

// Creates a block from an external source file


PlcSoftware plcSoftware = ...;
foreach (PlcExternalSource plcExternalSource in
plcSoftware.ExternalSourceGroup.ExternalSources)
{
plcExternalSource.GenerateBlocksFromSource();
}

5.12.3.20 Generating from source of known source format

Requirement

• The TIA Portal Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online

Application
The generator is basically able to create an object (block/UDT) but ‘something inside’ makes that
the generated block/UDT won’t be compilable.
Typical missing or invalid parts what makes the block / type not compilable:
• reference to a not existing type
• missing symbol used

Openness: API for automation of engineering workflows


588 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

In case of genaration errors the current implementation of ‘GenerateBlocksFromSource' void


GenerateBlocksFromSource():
• throws a recoverable exception (due to failed generating)
• Includes the error message(s) of the generating to the exception’s message
• and deletes the generated block/UDT
Due to the Openness Long Term Stability a new overload of GenerateBlocksFromSource is
available:
IList<IEngineeringObject> GenerateBlocksFromSource( GenerateBlockOptions option)
If this new ‘GenerateBlocksFromSource’ called with GenerateBlockOptions.KeepOnError, it
• doesn’t throw recoverable exception (regardless the generating results)
• doesn’t provide information about the generation result of any generated block(s)
• returns with an IList of IEngineeringObjects of the the generated blocks (with or without
generation errors)
If this new ‘GenerateBlocksFromSource’ called with GenerateBlockOptions.None and
generation wasn’t flawless, it
• throws a recoverable exception (due to failed generating)
• includes the error message(s) of the generating to the exception’s message
• and deletes the generated block/UDT
– this is just the same behavior as the current implementation does
In case of flawless generation, it
• doesn’t throw any exception
• doesn’t provide information about the generation result of any generated blocks
• returns with an IList of IEngineeringObjects of the the generated blocks
– this is the same behavior as having called it with GenerateBlockOptions.KeepOnError.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 589
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code

try
{
IList<IEngineeringObject> generatedObjects =
externalSource.GenerateBlocksFromSource(GenerateBlockOptions.KeepOnError);
foreach (IEngineeringObject engineeringObject in generatedObjects)
{
CompilerResult compilerResult = null;
string objectName = null;
if (engineeringObject is PlcBlock)
{
// handle case for PLcBlock
// e.g. retrieve the compiler result
PlcBlock block = (PlcBlock)engineeringObject;
objectName = block.Name;
compilerResult = block.Compile();
}
else if (engineeringObject is PlcType)
{
// handle case for PlcType
// e.g. retrieve the compiler result
PlcType plcType = (PlcType)engineeringObject;
objectName = plcType.Name;
compilerResult = plcType.Compile();
}
// handle the compiler result
if (compilerResult != null)
{
if (compilerResult.State == CompilerResultState.Error)
{
Console.WriteLine("Object '{0}' could not be compiled successfully!", objectName);
Console.WriteLine("Number of compiler errors: {0}", compilerResult.ErrorCount);
foreach (CompilerResultMessage compilerResultMessage in compilerResult.Messages)
{
Console.WriteLine(compilerResultMessage.Description);
}
}
else
{
Console.WriteLine("Object '{0}' could be compiled successfully.", objectName);
}
}
}
}
catch (RecoverableException exception)
{
// handle recoverable exception
Console.WriteLine(exception.Message);
}

Openness: API for automation of engineering workflows


590 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.3.21 Deleting user data type

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Program code
Modify the following program code to delete a user type:

private static void DeleteUserDataType(PlcSoftware plcSoftware)


{
PlcTypeSystemGroup typeGroup = plcSoftware.TypeGroup;
PlcTypeComposition dataTypes = typeGroup.Types;
PlcType dataType = dataTypes.Find("DataTypeName");
if (dataType != null)
{
dataType.Delete();
}
}

See also
Importing configuration data (Page 885)

5.12.3.22 Deleting an external file

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
see Connecting to the TIA Portal (Page 81)
• You have opened a project via a TIA Portal Openness application:
see Opening a project (Page 113)
• PLC is not online

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 591
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to delete an external file in the "External source files" group.

Note
Access to groups in the "External source files" group is not supported.

// Deletes an external source file


private static void DeleteExternalSource(PlcSoftware plcSoftware)
{
PlcExternalSource externalSource =
plcSoftware.ExternalSourceGroup.ExternalSources.Find("myExternalsource");
externalSource.Delete();
}

5.12.3.23 Starting the block editor

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• Instance of the TIA Portal is opened with user interface.

Program code
Modify the following program code to start the associated editor for an object reference of the
type PlcBlock in the TIA Portal instance:

//Opens a block in a block editor


private static void StartBlockEditor(PlcSoftware plcSoftware)
{
PlcBlock plcBlock = plcSoftware.BlockGroup.Blocks.Find("MyBlock");
plcBlock.ShowInEditor();
}

Openness: API for automation of engineering workflows


592 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to open the associated editor for an object reference of the
type PlcType in the TIA Portal instance:

//Opens a udt in udt editor


private static void StartPlcTypEditor(PlcSoftware plcSoftware)
{
PlcTypeComposition types = plcSoftware.TypeGroup.Types;
PlcType udt = types.Find("my_udt");
udt.ShowInEditor();
}

See also
Importing configuration data (Page 885)

5.12.3.24 Changing blocks using fingerprints

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to detect changes inside of blocks or UDT. You can achieve
this by comparing the fingerprints of the object. A fingerprint instance contains an FingerprintId
which defines the kind of fingerprint and the fingerprint value as a string. All provided
fingerprints conisder only user input, no compilation result, or any other change made by the
system.
The enumeration FingerprintId lists all kind of fingerprints supported in Openness:

Value Description
Code Considers all changes in the code inside the body of
the block. It does not consider the compilation re‐
sult.
Interface Considers all changes in the interface of a block.
Including start values of a DB
Properties Considers changes in the properties of a block. e.g.
name, number
Comments Considers changes in the comments of a block. In
case of OBs the fingerprint also changes when the
list of available languages in project language set‐
ting changes
LibraryType Exists when a block is connected to a library type

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 593
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Value Description
Texts With V15 SP1 this fingerprint only exists for Graph
blocks
Alarms Exists when a block uses alarming.
Supervision Exists when a block contains supervision
TechnologyObject Exists only for technology object DBs
Events Exists only for OB
TextualInterface Exists when the block has a textual interface

You need to use the FingerprintProvider service to retrieve the fingerprints of an object. It is
available for blocks (FB, FC, OB, DB),and UDTs, but not for tag tables. The FingerprintProvider
calculates and returns all available fingerprints of an object with each GetFingerprints call. In
order to ensure correct fingerprints, the block or UDT needs to be consistent before calling
fingerprints. Otherwise, an RecoverableException is thrown. When a fingerprint is still invalid
after its calculation, an RecoverableException is thrown.

Program code
Modify the following program code to get the fingerprint instance:

PlcBlock block = ...;


FingerprintProvider provider = block.GetService<FingerprintProvider>();
IList<Fingerprint> fingerprints = provider.GetFingerprints();
foreach(var fingerprint in fingerprints)
{
string fpValue = fingerprint.Value;
FingerprintId fpId = fingerprint.Id;
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.3.25 Generating/deleting blocks for user defined pages

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


594 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness to create user defined web pages within the web server of
PLCs. The data for these user defined pages are stored in specific system generated data blocks
of the PLC. You can also edit and delete these blocks manually. But if you modify any data or
properties in these data blocks the web server will not function correctly.
In TIA Portal Openness, the new service WebserverUserDefinedPages is added at the DeviceItem
PLC. You can use this service to generate the DBs for user defined pages: List<PLCBlock>
GenerateBlocks(Arguments). When this function is called the corresponding DBs are generated
and a list of generated DBs is returned to user.
There are two possible overloads for this function:
• List<PLCBlock> WebserverUserDefinedPages.GenerateBlocks(WebDBGenerateOptions
GenerateOptions);
• List<PLCBlock> WebserverUserDefinedPages.GenerateBlocks(System.IO.DirectoryInfo
htmlDirectory, System.IO.FileInfo defaultHTMLPage, string applicationName,
WebDBGenerateOptionsGenerateOptions);
The parameter values for HTML directory, HTML page and application name are not stored in the
project data. So the values of the corresponding dynamic attributes are not changed.

Parameter Data type Type Descriptions


GenerateOptions WebDBGenerateOptions (enu‐ Mandatory Possible values:
meration) • None - If DBs for user defined
pages already have been cre‐
ated before, no action is per‐
formed and an exception is
thrown
• Override - If DBs for user de‐
fined pages already have
been created before, they
are deleted and the new DBs
are generated
htmlDirectory System.IO.DirectoryInfo Optional Specifies the HTML directory in‐
dependently from the value of
the dynamic attribute Webser‐
verHTMLDirectory
defaultHTMLPage System.IO.FileInfo Optional Specifies the default HTML page
independently from the value
of the dynamic attribute Web‐
serverDefaultHTMLPage
applicationName string Optional Specifies the application name
independently from the value
of the dynamic attribute Web‐
serverApplicationName

GenerateBlocks() will throw recoverable exception:


• If web server is disabled (WebserverActive == False) - "Webserver has to be enabled"
• If WebserverHTMLDirectory is empty or the path is invalid - "HTML directory has invalid path"
• If WebserverdefaultHTMLPage is empty or the path is invalid - "Default HTML page has invalid
path"

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 595
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

• When the WebserverHTMLDirectory is too long - "HTML directory has too large data"
• The Application Name is invalid - "Application Name is invalid"
• The Dynamic Content is invalid - "Dynamic Content is invalid"
• The Control DB number is invalid - "Control DB number is invalid"
• The DB Start Number is invalid - "DB Start Number is invalid"
• Blocks are already present: If the user tries to generate a block with a name which already
exists- ""Delete existing blocks before generating new blocks" (Only thrown if
WebDBGenerateOptions.None is used)
There is no specific function to delete all blocks connected to the user defined pages. You have
to manually delete the blocks that are handed back to them by the generate action or navigate
to the corresponding DBs as it is already possible in TIA Portal Openness.

Program code
Modify the following program code to generate a block for user defined page:

DeviceItem deviceItem = ...;


var WebserverUserDefinedPagesService = deviceItem.GetService<WebserverUserDefinedPages>();
List<PLCBlock> blocks =
WebserverUserDefinedPagesService.GenerateBlocks(WebDBGenerateOptions.None);
List<PLCBlock> blocks = WebserverUserDefinedPagesService.GenerateBlocks(htmlDirectory,
defaultHTMLPage, applicationName, WebDBGenerateOptions.Override);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.3.26 Writing access for OB block priority attribute

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project

Application
You can use the TIA Portal Openness to provide write access for block property especially for OBs.
You can change the priority of a block both in unit and non-unt programming model via TIA
Portal Openness.

Openness: API for automation of engineering workflows


596 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The following property is available to access for block:

Property name Data type Access


Priority Integer Read/Write

Program code
Modify the following program code to set the priority for OB block:

PlcBlock obBlock = sw.BlockGroup.Blocks.Find("CyclicInterrupt");


obBlock.SetAttribute("Priority", 14);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.3.27 Generating block/UDT from external source file in specific user group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project via a TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to generate blocks/ udts under user specific groups in both
PLC programming model and unit programming model..

Program code: Generation of blocks from source under specific user groups
Modify the following program code to retrieve the user group information under which the
blocks to be generated:

Siemens.Engineering.SW.Blocks.PlcBlockUserGroup folder =
plc.BlockGroup.Groups.Find("Group_1");

Modify the following program code to generate blocks under groups without any options.

plc.ExternalSourceGroup.ExternalSources.Find("Block_1.scl").GenerateBlocksFromSource(folde
r, GenerateBlockOption.None);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 597
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to generate blocks with Options as KeepOnError:

plc.ExternalSourceGroup.ExternalSources.Find("Block_1.scl")
GenerateBlocksFromSource(folder, GenerateBlockOption.KeepOnError);

Program code: Generation of UDTs from source under specific user groups

Siemens.Engineering.SW.Types.PlcTypeUserGroup folder1 =
plc.TypeGroup.Groups.Find("Group_1");

Modify the following program code to generate UDTs under groups without any Options:

plc.ExternalSourceGroup.ExternalSources.Find("User_data_type_1.udt").GenerateBlocksFromSou
rce(folder1, GenerateBlockOption.None);

Modify the following program code to generate blocks with Options as KeepOnError:

plc.ExternalSourceGroup.ExternalSources.Find("User_data_type_1.udt").GenerateBlocksFromSou
rce(folder1,GenerateBlockOption. KeepOnError);

Functions
Method name with signature
• Public IList<IEngineeringObject>
PlcExternalSource.GenerateBlocksFromSource(PlcBlockUserGroup blockuserGroup,
GenerateBlockOption generateBlockOption)
• Public IList<IEngineeringObject>
PlcExternalSource.GenerateBlocksFromSource(PlcBlockUserGroup blockuserGroup,
GenerateBlockOption generateBlockOption)

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.4 Technology objects

5.12.4.1 Overview of functions for technology objects


TIA Portal Openness supports a selection of technology object functions for defined tasks that
you can call outside the TIA Portal by means of the Public API.

Openness: API for automation of engineering workflows


598 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

In the following chapters you will find code sample, that can be adapted to your openness
program.

Functions
The following functions are available for technology objects:
• Querying the composition of technology objects (Page 601)
• Creating technology object (Page 602)
• Deleting technology object (Page 603)
• Compiling technology object (Page 604)
• Enumerating technology object (Page 605)
• Finding technology object (Page 606)
• Enumerating parameters of technology object (Page 607)
• Finding parameters of technology object (Page 607)
• Reading parameters of technology object (Page 608)
• Writing parameters of technology object (Page 609)
• Exporting technology objects (Page 1049)
• Importing technology objects (Page 1051)
• Connecting to Hardware components (Page 619)

See also
Standard libraries (Page 73)
Applications (Page 48)
TIA Portal Openness object model (Page 51)

5.12.4.2 Overview of technology objects and versions

Technology objects
The following table shows the available technology objects in the Public API.

CPU Technology Technology object Version of technolo‐ CPU FW


gy object
S7-1200 Motion Con‐ TO_PositioningAxis ≥ V6.0 ≥ V4.2
trol TO_CommandTable
PID Control PID_Compact V2.3 ≥ V4.2
PID_3Step V2.3
PID_Temp V1.1

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 599
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

CPU Technology Technology object Version of technolo‐ CPU FW


gy object
S7-1500 Motion Con‐ TO_SpeedAxis ≥ V3.0 ≥ V2.0
trol TO_PositioningAxis
TO_ExternalEncoder
TO_SynchronousAxis
TO_OutputCam
TO_CamTrack
TO_MeasuringInput
TO_Cam (S7-1500T)1)
TO_Kinematics (S7-1500T) ≥ V4.0 ≥ V2.6
TO_LeadingAxisProxy ≥ V5.0 ≥ V2.8
(S7-1500T)
TO_Cam_10k (S7-1500T)1) ≥ V6.0 ≥ V2.9
Counting High_Speed_Counter ≥ V4.1 any
and measure‐ SSI_Absolute_Encoder ≥ V3.1
ment
PID Control PID_Compact ≥ V2.3 ≥ V2.0
PID_3Step V2.3
PID_Temp V1.1
CONT_C
CONT_S
TCONT_CP
TCONT_S
S7-300/400 PID Control CONT_C V1.1 Any
CONT_S
TCONT_CP
TCONT_S
TUN_EC2)
TUN_ES2)
PID_CP2) V2.0
PID_ES2)

EMC AXIS_REF V2.0

1) The technology object does not support the following Openness functions: Writing parameters.
2) The technology object does not support the following Openness functions: Enumerating parameters,
Finding parameters, Reading parameters, Writing parameters.

See also
S7-1500 Motion Control (Page 619)

5.12.4.3 Overview of data types


The data types of technology object parameters in TIA Portal are mapped to C# data types in the
Public API.

Openness: API for automation of engineering workflows


600 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Data types
The following table shows the data type mapping:

Format Data type in TIA Portal Data type in C#


Binary numbers Bool bool
BBool bool
Byte byte
Word ushort
DWord uint
LWord ulong
Integers SInt sbyte
Int short
Dint int
LInt long
USInt byte
UInt ushort
UDint uint
ULInt ulong
Floating-point numbers Real float
LReal double
Time double
Character strings Char char
WChar char
String string
WString string
Hardware data types HW_* ushort
Block_* ushort

* Placeholder for device type extension in TIA Portal project

5.12.4.4 Querying the composition of technology objects

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 601
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to get all technology objects of a PLC:

// Retrieves all technology objects of a PLC


private static void GetTechnologicalObjectsOfPLC(PlcSoftware plcSoftware)
{
TechnologicalInstanceDBGroup technologicalObjectGroup =
plcSoftware.TechnologicalObjectGroup;
TechnologicalInstanceDBComposition technologicalObjects =
technologicalObjectGroup.TechnologicalObjects;
}

See also
Standard libraries (Page 73)

5.12.4.5 Creating technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)

Application
Only technology objects that are listed in the section Overview of technology objects and
versions (Page 599) can be created. An exception is thrown for unsupported technology objects
or invalid parameters. See also Handling exceptions (Page 862).

Openness: API for automation of engineering workflows


602 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to create a technology object and add it to an existing PLC:

// Create a technology object and add to technology object composition


private static void CreateTechnologicalObject(PlcSoftware plcSoftware)
{
TechnologicalInstanceDBComposition technologicalObjects =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects;

string nameOfTO = "PID_Compact_1"; // How the technology object should be named


string typeOfTO = "PID_Compact"; // How the technology object type is called, e.g. in
// "Add new technology object"-dialog
Version versionOfTO = new Version("2.3"); // Version of technology object
TechnologicalInstanceDB technologicalObject = technologicalObjects.Create(nameOfTO,
typeOfTO, versionOfTO);
}

Possible values and combinations of name, type and version of the technology object can be
found in the section Overview of technology objects and versions (Page 599).

See also
Standard libraries (Page 73)
S7-1500 Motion Control (Page 619)

5.12.4.6 Deleting technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)
• The technology object exists.
See Finding technology object (Page 606)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 603
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to delete a technology object:

// Delete a technology object from DB composition and from PLC


private static void DeleteTechnologicalObject(TechnologicalInstanceDB technologicalObject)
{
technologicalObject.Delete();
}

See also
Standard libraries (Page 73)

5.12.4.7 Compiling technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)
• The technology object exists.
See Creating technology object (Page 602)

Program code: Compiling a technology object


Modify the following program code to compile a technology object:

// Compile a single technology object


private static void CompileSingleTechnologicalObject(TechnologicalInstanceDB
technologicalObject)
{
ICompilable singleCompile = technologicalObject.GetService<ICompilable>();
CompilerResult compileResult = singleCompile.Compile();
}

Openness: API for automation of engineering workflows


604 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Compiling the technology object group


Modify the following program code to compile the technology object group:

// Compile technology object group


private static void CompileTechnologicalObjectGroup(PlcSoftware plcSoftware)
{
TechnologicalInstanceDBGroup technologicalObjectGroup =
plcSoftware.TechnologicalObjectGroup;
ICompilable groupCompile = technologicalObjectGroup.GetService<ICompilable>();
CompilerResult compileResult = groupCompile.Compile();
}

Compile results
Technology objects compilation results are stored recursively.
You can find an example of recursive evaluation of compilation results in the section "Compiling
a project (Page 137)".

Note
Further parameters
Imported data will be expanded after compiling. For example, You can use Openness to create
motion control technology objects with different versions. After the compiling of technology
objects, the motion control versions of other technology objects are adapted to those of the last
technology object created.

See also
Standard libraries (Page 73)

5.12.4.8 Enumerating technology object

Requirement
You can enumerate the top level TOs like "TO_Axis" and "TO_Cam". The finding of sub level TOs
like "TO_OutputCam" see Creating and finding TO_OutputCam, TO_CamTrack and
TO_MeasuringInput (Page 619).
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 605
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to enumerate technology objects:

// Enumerate all technology objects


private static void EnumerateTechnologicalObjects(PlcSoftware plcSoftware)
{
TechnologicalInstanceDBComposition technologicalObjects =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects;
foreach (TechnologicalInstanceDB technologicalObject in technologicalObjects)
{
// Do something ...
}
}

See also
Standard libraries (Page 73)
S7-1500 Motion Control (Page 619)

5.12.4.9 Finding technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)

Program code
Modify the following program code to find a specific technology object:

// Find a specific technology object by its name


private static void FindTechnologicalObject(PlcSoftware plcSoftware)
{
TechnologicalInstanceDBComposition technologicalObjects =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects;
string nameOfTO = "PID_Compact_1";
TechnologicalInstanceDB technologicalObject = technologicalObjects.Find(nameOfTO);
}

See also
Standard libraries (Page 73)

Openness: API for automation of engineering workflows


606 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.4.10 Enumerating parameters of technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)
• A technology object exists.
See Creating technology object (Page 602) or Finding parameters of technology object
(Page 607)
• The technology object (Page 599) supports this function.

Program code
Modify the following program code to enumerate parameters of a specific technology object:

// Enumerate parameters of a technology object


private static void EnumerateParameters(PlcSoftware plcSoftware)
{
string nameOfTO = "PID_Compact_1";
TechnologicalInstanceDB technologicalObject =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects.Find(nameOfTO);

foreach (TechnologicalParameter parameter in technologicalObject.Parameters)


{
// Do something ...
}
}

See also
Standard libraries (Page 73)
Finding technology object (Page 606)

5.12.4.11 Finding parameters of technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 607
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

• A PLC is determined in the project.


See Querying PLC and HMI targets (Page 205)
• A technology object exists.
See Creating technology object (Page 602)
• The technology object (Page 599) supports this function.

Program code
Modify the following program code to find parameters of a specific technology object:

// Find parameters of a technology object


private static void FindParameterOfTechnologicalObject(PlcSoftware plcSoftware)
{
string nameOfTO = "PID_Compact_1";
TechnologicalInstanceDB technologicalObject =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects.Find(nameOfTO);

string nameOfParameter = "Config.InputUpperLimit";


TechnologicalParameter parameter =
technologicalObject.Parameters.Find(nameOfParameter);
}

Parameters of different technology objects


Parameters of S7-1200 Motion Control (Page 610)
Parameters of S7-1500 Motion Control (Page 619)
Parameters of PID Control (Page 640)
Parameters of Counting (Page 641)
Parameters of Easy Motion Control (Page 641)

See also
Standard libraries (Page 73)
Finding technology object (Page 606)

5.12.4.12 Reading parameters of technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


608 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

• A PLC is determined in the project.


See Querying PLC and HMI targets (Page 205)
• A technology object exists.
See Creating technology object (Page 602)
• The technology object (Page 599) supports this function.

Program code
Modify the following program code to read parameters of a specific technology object:

// Read parameters of a technology object


private static void ReadParameterOfTechnologicalObject(PlcSoftware plcSoftware)
{
string nameOfTO = "PID_Compact_1";
TechnologicalInstanceDB technologicalObject =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects.Find(nameOfTO);

string nameOfParameter = "Config.InputUpperLimit";


TechnologicalParameter parameter =
technologicalObject.Parameters.Find(nameOfParameter);

// Read from parameter


string name = parameter.Name;
object value = parameter.Value;
}

See also
Standard libraries (Page 73)
Finding technology object (Page 606)

5.12.4.13 Writing parameters of technology object

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)
• A technology object exists.
See Creating technology object (Page 602)
• The technology object (Page 599) supports this function.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 609
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Exception
An EngineeringException is thrown if:
• You set a new value for a parameter that does not provide write access.
• A new value for a parameter is of an unsupported type.

Program code
Modify the following program code to write parameters of a specific technology object:

// Write parameters of a technology object


private static void WriteParameterOfTechnologicalObject(PlcSoftware plcSoftware)
{
string nameOfTO = "PID_Compact_1";
TechnologicalInstanceDB technologicalObject =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects.Find(nameOfTO);

string nameOfParameter = "Config.InputUpperLimit";


TechnologicalParameter parameter =
technologicalObject.Parameters.Find(nameOfParameter);

// Write to parameter if the value is writable


object value = 3.0;
parameter.Value = value;
}

Parameters of different technology objects


Parameters of S7-1200 Motion Control (Page 610)
Parameters of S7-1500 Motion Control (Page 619)
Parameters of PID Control (Page 640)
Parameters of Counting (Page 641)
Parameters of Easy Motion Control (Page 641)

See also
Standard libraries (Page 73)
Finding technology object (Page 606)

5.12.4.14 S7-1200 Motion Control

Changing version of openness engineering library


If you use "Openness\PublicAPI\V14 SP1\Siemens.Engineering.dll" with TIA Portal V15, your
existing openness application will still work.

Openness: API for automation of engineering workflows


610 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

If you change to "Openness\PublicAPI\V15\Siemens.Engineering.dll" with TIA Portal V15, you


have to adapt all accesses to array tags for S7-1200 Motion Control.
The affected arrays for TO_PositioningAxis are listed in the following table:

Access in Openness < V15 Access in Openness ≥ V15


_Sensor.Sensor[1].<all tags> _Sensor[1].<all tags>
ControlPanel.Input.Command.Command[1].<all ControlPanel.Input.Command[1].<all tags>
tags>
ControlPanel.Output.Command.Command[1].<all ControlPanel.Output.Command[1].<all tags>
tags>
Internal.Internal[n].<all tags> Internal[n].<all tags>
Sensor.Sensor[1].<all tags> Sensor[1].<all tags>
StatusSensor.StatusSensor[1].<all tags> StatusSensor[1].<all tags>

The affected arrays for TO_CommandTable are listed in the following table:

Access in Openness < V15 Access in Openness ≥ V15


Command.Command[n].<all tags> Command[n].<all tags>

Connecting PTO-Outputs

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC with PTO-Outputs is determined in the project.
• The technology object exists.
See Creating technology object (Page 602).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 611
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to connect a PTO-Output to the "TO_PositioningAxis".

//An instance of the technology object axis is already available in the program before  
private static void ConnectingDrive(TechnologicalInstanceDB technologicalObject)
{
//Set axis to PTO mode
technologicalObject.Parameters.Find("Actor.Type").Value = 2;
//Set PTO-Output
technologicalObject.Parameters.Find("_Actor.Interface.PTO").Value = 0; // select
Pulse_1
// 0 = Pulse_1
// 1 = Pulse_2
// 2 = Pulse_3
// 3 = Pulse_4
}

Connecting PROFIdrives by hardware address

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC is determined in the project.
• A PROFIdrive is available in the project and connected with the S7-1200 PLC.
• The technology object exists.
See Creating technology object (Page 602).

Openness: API for automation of engineering workflows


612 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to connect a PROFIdrive by hardware address to the
"TO_PositioningAxis".

//An instance of the technology object axis is already available in the program before  
private static void ConnectingDrive(TechnologicalInstanceDB technologicalObject)
{
//Set axis to PROFIdrive mode
technologicalObject.Parameters.Find("Actor.Type").Value = 1;

//Set axis to drive mode


technologicalObject.Parameters.Find("_Actor.Interface.DataConnection").Value = 0;

//Set connection to address of drive. The output will be set automatically.


technologicalObject.Parameters.Find("_Actor.Interface.ProfiDriveIn").Value = "%I68.0";
technologicalObject.Parameters.Find("Sensor[1].Interface.Number").Value = 1;
// 1 = Encoder1, 2 = Encoder2;
}

Connecting encoders for PROFIdrives by hardware address

Requirement

• The Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC is determined in the project.
• A PROFIdrive is available in the project and connected with the S7-1200 PLC.
• The technology object exists.
See Creating technology object (Page 602).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 613
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to connect an encoder by hardware address to the
"TO_PositioningAxis":

//An instance of the technology object axis is already available in the program before
private static void ConnectingEncoder(TechnologicalInstanceDB technologicalObject)
{
//Set axis to PROFIdrive mode
technologicalObject.Parameters.Find("Actor.Type").Value = 1;

//Set the encoder mode


technologicalObject.Parameters.Find("_Sensor[1].Interface.EncoderConnection").Value =
7;

//Set axis to use PROFINET encoder


technologicalObject.Parameters.Find("_Sensor[1].Interface.DataConnection").Value = 0;

//Set connection to address of drive. The output will be set automatically.


technologicalObject.Parameters.Find("_Sensor[1].Interface.ProfiDriveIn").Value =
"%I68.0";
technologicalObject.Parameters.Find("Sensor[1].Interface.Number").Value = 1;
// 1 = Encoder1, 2 = Encoder2;
}

Connecting analog drives by hardware address

Requirement

• The Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC is determined in the project.
• An analog drive is available in the project and connected with the S7-1200 PLC.
• The technology object exists.
See Creating technology object (Page 602).

Openness: API for automation of engineering workflows


614 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to connect an analog drive by hardware address to the
"TO_PositioningAxis":

//An instance of the technology object axis is already available in the program before  
private static void ConnectingEncoder(TechnologicalInstanceDB technologicalObject)
{
//Set axis to analog drive mode
technologicalObject.Parameters.Find("Actor.Type").Value = 0;

//Set axis to drive mode


technologicalObject.Parameters.Find("_Actor.Interface.DataConnection").Value = 0;

//Set connection to analog address of drive


technologicalObject.Parameters.Find("_Actor.Interface.Analog").Value = "%QW64";
}

Connecting encoders for analog drives by hardware address

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC is determined in the project.
• An analog drive is available in the project and connected with the S7-1200 PLC.
• The technology object exists.
See Creating technology object (Page 602).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 615
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to connect an encoder by hardware address to the
"TO_PositioningAxis":

//An instance of the technology object axis is already available in the program before
//Connecting by High Speed Counter mode
private static void ConnectingEncoder(TechnologicalInstanceDB technologicalObject)
{
//Set axis to analog drive mode
technologicalObject.Parameters.Find("Actor.Type").Value = 0;

//Set encoder for high-speed counter mode


technologicalObject.Parameters.Find("_Sensor[1].Interface.EncoderConnection").Value =
4;
technologicalObject.Parameters.Find("_Sensor[1].Interface.HSC.Name").Value = "HSC_1";
}

//An instance of the technology object axis is already available in the program before
//Connecting by PROFINET/PROFIBUS telegram
private static void ConnectingEncoder(TechnologicalInstanceDB
technologicalObject)
{
//Set axis to analog drive mode
technologicalObject.Parameters.Find("Actor.Type").Value = 0;
//Set encoder for PROFINET/PROFIBUS mode
technologicalObject.Parameters.Find("_Sensor[1].Interface.EncoderConnection").Value =
7;
technologicalObject.Parameters.Find("_Sensor[1].Interface.DataConnection").Value =
"Encoder";
technologicalObject.Parameters.Find("_Sensor[1].Interface.ProfiDriveIn").Value =
"%I68.0";
technologicalObject.Parameters.Find("Sensor[1].Interface.Number").Value = 1;
// 1 = Encoder1, 2 = Encoder2;
}

Connecting drives by data block

Requirement

• The Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC is determined in the project.

Openness: API for automation of engineering workflows


616 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

• A data block is available in the project and set to "Not optimized".


For the PROFIdrive axis type, the data block contains a tag of the type e. g. PD_TEL3.
For an analog drive, the data block contains a tag with the word data type.
• The technology object exists.
See Creating technology object (Page 602).

Program code
Modify the following program code to connect a PROFIdrive by data block to the
"TO_PositioningAxis".

//An instance of the technology object axis is already available in the program before
private static void ConfigureDrivewithDataBlock(TechnologicalInstanceDB
technologicalObject)
{
//Set axis to PROFIdrive mode
technologicalObject.Parameters.Find("Actor.Type").Value = 1;

//Set axis to data block mode


technologicalObject.Parameters.Find("_Actor.Interface.DataConnection").Value = 1;

//Set the tag in the data block


technologicalObject.Parameters.Find("_Actor.Interface.DataBlock").Value =
"Data_block_1.Member_of_type_PD_TEL3";
}

Program code
Modify the following program code to connect an analog drive by data block to the
"TO_PositioningAxis".

//An instance of the technology object axis is already available in the program before
//Connecting an analog drive with data block.
private static void ConfigureDrivewithDataBlock(TechnologicalInstanceDB
technologicalObject)
{
//Set axis to analog mode
technologicalObject.Parameters.Find("Actor.Type").Value = 0;

//Set the tag in the data block


technologicalObject.Parameters.Find("_Actor.Interface.Analog").Value =
"Data_block_1.Static_1";
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 617
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Connecting encoders by data block

Requirement

• The Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1200 PLC is determined in the project.
• A data block is available in the project and set to "Not optimized".
In case of PROFIdrive the data block contains a tag of the type e. g. PD_TEL3
• The technology object exists.
See Creating technology object (Page 602).

Program code
Modify the following program code to connect an encoder by data block:

//An instance of the technology object axis is already available in the program before
private static void ConfigureEncoderwithDataBlock(TechnologicalInstanceDB
technologicalObject)
{
//Set axis to PROFIdrive mode depending by axis type. 1 = PROFIdrive, 0 = Analog Drive.
technologicalObject.Parameters.Find("Actor.Type").Value = 1;

//Set the encoder mode


technologicalObject.Parameters.Find("_Sensor[1].Interface.EncoderConnection").Value =
7;

//Set axis to data block mode


technologicalObject.Parameters.Find("_Sensor[1].Interface.DataConnection").Value = 1;

//Set the tag in the data block. For PD_TEL3 and PD_TEL4 "Encoder1" or "Encoder2".
technologicalObject.Parameters.Find("_Sensor[1].Interface.DataBlock").Value =
"Data_block_1.Member_of_Type_PD_TEL3";
}

Openness: API for automation of engineering workflows


618 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Parameters for TO_PositioningAxis and TO_CommandTable


You can find a list of all available variables in SIMATIC STEP 7 S7-1200 Motion Control function
manual on the internet (https://support.industry.siemens.com/cs/ww/en/view/109754206).

Note
In TIA Portal in the Parameter view of the technology object configuration you can find the
column "Name in Openness".

5.12.4.15 S7-1500 Motion Control

Creating and finding TO_OutputCam, TO_CamTrack and TO_MeasuringInput

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_PositioningAxis, TO_SynchronousAxis or
TO_ExternalEncoder is determined in the project.

Application
The output cam, cam track and measuring input technology objects are associated with
positioning axis, synchronous axis or external encoder technology objects. In order to access an
output cam, cam track or measuring input technology object you use the service
OutputCamMeasuringInputContainer.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 619
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Creating and finding output cam, cam track and measuring input technology objects
Modify the following program code to create or find an output cam, cam track or measuring
input technology object:

/*An instance of the technology object under which the TO_OutputCam, TO_CamTrack or
TO_MeasuringInput should be created is already available in the program before*/
private static void CreateFind_OutputcamCamtrackMeasuringinput(TechnologicalInstanceDB
technologyObject)
{
//Retrieve service OutputCamMeasuringInputContainer
OutputCamMeasuringInputContainer container =
technologyObject.GetService<OutputCamMeasuringInputContainer>();
//Get access to TO_OutputCam / TO_CamTrack container
TechnologicalInstanceDBComposition outputcamCamtrackContainer = container.OutputCams;

//Find technology object TO_OutputCam or TO_CamTrack


TechnologicalInstanceDB outputCam = outputcamCamtrackContainer.Find("OutputCamName");
TechnologicalInstanceDB camTrack = outputcamCamtrackContainer.Find("CamTrackName");

//Create new technology object TO_OutputCam or TO_CamTrack


TechnologicalInstanceDB newOutputCam =
outputcamCamtrackContainer.Create("NewOutputCamName", "TO_OutputCam",
new Version(3, 0));
TechnologicalInstanceDB newCamTrack =
outputcamCamtrackContainer.Create("NewCamTrackName", "TO_CamTrack", new Version(3, 0));

//Get access to TO_MeasuringInput container


TechnologicalInstanceDBComposition measuringInputContainer = container.MeasuringInputs;

//Find technology object TO_MeasuringInput


TechnologicalInstanceDB measuringInput =
measuringInputContainer.Find("MeasuringInputName");

//Create new technology object TO_MeasuringInput


TechnologicalInstanceDB newMeasuringInput =
measuringInputContainer.Create("NewMeasuringInput", "TO_MeasuringInput",
new Version(3, 0));
}

Openness: API for automation of engineering workflows


620 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You create the S7-1500 technology objects OutputCam, CamTrack and MeasuringInput as a
master copy from Siemens.Engineering.Library.MasterCopies.MasterCopy.

/*An instance of the technology object under which the TO_OutputCam, TO_CamTrack or
TO_MeasuringInput should be created is already available in the program before*/
// sourceMasterCopy contains master copy object output cam
private static void CreateFind_OutputcamCamtrackMeasuringinput(TechnologicalInstanceDB
technologyObject, MasterCopy sourceMasterCopy)
{
//Retrieve service OutputCamMeasuringInputContainer
OutputCamMeasuringInputContainer container =
technologyObject.GetService<OutputCamMeasuringInputContainer>();

TechnologicalInstanceDB result = container.OutputCams.CreateFrom(sourceMasterCopy);

Parameters of S7-1500 Motion Control


Most parameters of S7-1500 Motion Control technology objects are directly mapped to data
block tags, but there are also some additional parameters that do not map directly to data blocks.

Parameters mapped directly to technology object data block tags


You have access to all technology object data block tags as described in general except of:
• Read-only tags
• Tags of data type VREF
• Tags of "InternalToTrace" structure
• Tags of "ControlPanel" structure
You can find additional information about the directly mapped parameters in the appendix of:
• SIMATIC S7-1500 Motion Control function manual:
https://support.industry.siemens.com/cs/ww/en/view/109749262 (https://
support.industry.siemens.com/cs/ww/en/view/109749262)
• SIMATIC S7-1500T Motion Control function manual:
https://support.industry.siemens.com/cs/ww/en/view/109749263 (https://
support.industry.siemens.com/cs/ww/en/view/109749263)
• SIMATIC S7-1500T Kinematics Functions function manual:
https://support.industry.siemens.com/cs/ww/en/view/109749264 (https://
support.industry.siemens.com/cs/ww/en/view/109749264)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 621
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Some technology parameters that map to read-only data block tags are writeable in the
PublicAPI. The allowed values are the same ones as for the underlying data block tags. The
affected parameters are listed in the following tables:

Name in Openness Data type TO_SpeedAxis TO_Positionin‐ TO_Synchro‐ TO_ExternalEn‐


gAxis nousAxis coder
Actor.Type int X X X -
Actor.Interface.EnableDri‐ bool X X X -
veOutput
Actor.Interface.DriveReadyIn‐ bool X X X -
put
VirtualAxis.Mode uint X X X -
Sensor[n].Existent 1)
bool - X X -
Sensor[n].Interface.Number1) uint - X X -
Sensor[n].Type 1)
int - X X -
Sensor.Interface.Number uint - - - X
Sensor.Type int - - - X

Name in Openness Data type TO_OutputCam TO_MeasuringInput TO_Kinemat‐


ics2)
Interface. int X - -
Parameter.MeasuringInput‐ int - X -
Type
Kinematics.TypeOfKinematics int - - X
MotionQueue.MaxNumber‐ int - - X
OfCommands

1) S7-1500 PLC: n=1; S7-1500T PLC: 1≤n≤4


2) S7-1500T PLC

Parameters not mapped directly to technology object data block tags


For S7-1500 Motion Control technology objects the following additional parameters which do
not directly map to data block tags are available:

Name in Openness Name in func‐ Possible value Data type in TO_SpeedAxis TO_Position‐ TO_External‐
tion view Openness ingAxis Encoder
TO_Synchro‐
nousAxis
_Properties.Motion‐ Axis type re‐ 0: Linear int - X X
Type spectively 1: Rotary
"Technological
unit of the po‐
sition"
_Properties.UseHigh‐ Use high reso‐ True, False bool - X X
ResolutionPosition‐ lution position‐
Values ing value.

Openness: API for automation of engineering workflows


622 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Name in Openness Name in func‐ Possible value Data type in TO_SpeedAxis TO_Position‐ TO_External‐
tion view Openness ingAxis Encoder
TO_Synchro‐
nousAxis
_CrossPlcSynchronou‐ Activate delay True, False bool - X X
sOperation. time calcula‐
ActivateLocalLeading‐ tion.
ValueDelayTimeCal‐
culation
_Units.LengthUnit Position units See tag uint - X X
Units.LengthU‐
nit3)
_Units.VelocityUnit Velocity units See tag uint X X X
Units.Veloci‐
tyUnit3)
_Units.TorqueUnit Torque units See tag uint X X -
Units.TorqueU‐
nit3)
_Units.ForceUnit Force units See tag uint - X -
Units.ForceU‐
nit3)
_Actor.DataAdaptio‐ Automatically True, False bool X X -
nOffline apply...
_Actor.Interface.Tele‐ Drive telegram Telegram num‐ uint X X -
gram ber4)
_Actor.Interface.Ena‐ Drive output PublicAPI-ob‐ SW.Tags.PlcTag X X -
bleDriveOutputAd‐ address ject
dress
_Actor.Interface.Driv‐ Drive ready in‐ PublicAPI-ob‐ SW.Tags.PlcTag X X -
eReadyInputAddress put address ject
_Sensor[n].Inter‐ Encoder tele‐ Telegram num‐ uint - X -
face.Telegram5) gramm ber4)
_Sensor[n].Active‐ Digital input PublicAPI-ob‐ SW.Tags.PlcTag - X -
Homing.DigitalInpu‐ ject
tAddress5)
_Sensor[n].Passive‐ Digital input PublicAPI-ob‐ SW.Tags.PlcTag - X -
Homing.DigitalInpu‐ ject
tAddress5)
_PositionLi‐ Hardware low PublicAPI-ob‐ SW.Tags.PlcTag - X -
mits_HW.MinSwitch‐ limit switch in‐ ject
Address put
_PositionLi‐ Hardware high PublicAPI-ob‐ SW.Tags.PlcTag - X -
mits_HW.MaxSwitch‐ limit switch in‐ ject
Address put
_Sensor[n].DataA‐ Automatically True, False bool - X -
daptionOffline1) apply...
_Sensor.DataAdaptio‐ Automatically True, False bool - - X
nOffline apply...
_Sensor.Inter‐ Encoder tele‐ Telegram num‐ uint - - X
face.Telegram gram ber4)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 623
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Name in Openness Name in func‐ Possible value Data type in TO_SpeedAxis TO_Position‐ TO_External‐
tion view Openness ingAxis Encoder
TO_Synchro‐
nousAxis
_Sensor.PassiveHom‐ Digital input PublicAPI-ob‐ SW.Tags.PlcTag - - X
ing.DigitalInputAd‐ ject
dress
_CrossPlcSynchronou‐ Distributed PublicAPI-ob‐ SW.Tags.PlcTag - X X
sOperation.Inter‐ synchronous ject
face[n]. AddressOut6) operation

6) V5.0 n=1; ≥V6.0 1≤n≤8


For output cam, cam track and measuring input technology objects the following additional
parameter is available:

Name in Openness Name in function view Possible value Data type


_AssociatedObject Associated object PublicAPI-object SW.TechnologicalObjects.Techno‐
logicalInstanceDB

For kinematics technology object the following additional parameters are available (S7-1500T):

Name in Openness Name in function view Possible value Data type


_KinematicsAxis[1...4] Axis 1 - 3, Orientation axis Axis that can be connec‐ SW.TechnologicalObjects.Techno‐
ted to TO_Kinematics ob‐ logicalInstanceDB
jects
_Units.LengthUnit Units of measurement > Posi‐ See tag Units.LengthU‐ uint
tion nit3)
_Units.LengthVelocityUnit Units of measurement > Ve‐ See tag Units.LengthVe‐ uint
locity locityUnit3)
_Units.AngleUnit Units of measurement > Angle See tag UnitsAngleUnit3) uint
_Units.AngleVelocityUnit Units of measurement > An‐ See tag Units.AngleVelo‐ uint
gle velocity cityUnit3)
_X_Minimum x minimum -1.00E+12 .. +1.00E+12 double
_X_Maximum x maximum -1.00E+12 .. +1.00E+12 double
_Y_Minimum y minimum -1.00E+12 .. +1.00E+12 double
_Y_Maximum y maximum -1.00E+12 .. +1.00E+12 double
_Z_Minimum z minimum -1.00E+12 .. +1.00E+12 double
_Z_Maximum z maximum -1.00E+12 .. +1.00E+12 double
_A3_Maximum A3 maximum -1.00E+12 .. +1.00E+12 double

For TO_LeadingAxisProxy technology object the following additional parameter is available:

Name in Openness Name in function view Possible value Data type


_Interface.AddressIn Transfer area PublicAPI-ob‐ SW.Tags.PlcTag
ject

3) possible values are described in the function manual S7-1500 Motion Control on chapter units
tags (TO)

Openness: API for automation of engineering workflows


624 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

4) possible values are described in the function manual S7-1500 Motion Control on chapter
PROFIdrive telegrams
5) S7-1500 PLC: n=1; S7-1500T PLC: 1≤n≤4

Program code: Directly mapped data block tags


Modify the following program code to access the directly mapped parameters:

//An instance of the technology object is already available in the program before
private static void ReadWriteDataBlockTag(TechnologicalInstanceDB technologyObject)
{
//Read value from data block tag "ReferenceSpeed"
double value =
(double)technologyObject.Parameters.Find("Actor.DriveParameter.ReferenceSpeed").Value;

//Write data block tag "ReferenceSpeed"


technologyObject.Parameters.Find("Actor.DriveParameter.ReferenceSpeed").Value = 3000.0;
}

Program code: Additional parameters


Modify the following program code to access the additional parameters:

//An instance of the technology object is already available in the program before
private static void ReadWriteAdditionalParameter(TechnologicalInstanceDB technologyObject)
{
//Read additional parameter "_Properties.MotionType"
uint value = (uint)technologyObject.Parameters.Find("_Properties.MotionType").Value;

//Write additional parameter "_Properties.MotionType"


technologyObject.Parameters.Find("_Properties.MotionType").Value = 1;
}

Additional information
You can find additional information in:
• SIMATIC S7-1500 Motion Control function manual:
https://support.industry.siemens.com/cs/ww/en/view/109749262 (https://
support.industry.siemens.com/cs/ww/en/view/109749262)
• SIMATIC S7-1500T Motion Control function manual:
https://support.industry.siemens.com/cs/ww/en/view/109749263 (https://
support.industry.siemens.com/cs/ww/en/view/109749263)
• SIMATIC S7-1500T Kinematics Functions function manual:
https://support.industry.siemens.com/cs/ww/en/view/109749264 (https://
support.industry.siemens.com/cs/ww/en/view/109749264)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 625
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Connecting drives

Requirement
You have to use the Bit addresses for a TO connection. Byte addresses can not be used.
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_SpeedAxis, TO_PositioningAxis or TO_SynchronousAxis
is determined in the project.
• A drive is determined in the project.

Application
To connect an axis with a drive, it is necessary to specify several values together in a single call.
The public API type AxisEncoderHardwareConnectionInterface provides the following methods
which can be used to connect and disconnect the actor or sensor interfaces:

Method Description
void Connect(HW.DeviceItem moduleInOut) Connects to input and output addresses at one module.
void Connect(HW.DeviceItem moduleIn, HW.DeviceItem mod‐ Connects to input and output addresses at separate modules.
uleOut)
void Connect(HW.DeviceItem moduleIn, HW.DeviceItem mod‐ Connects to input and output addresses at separate modules,
uleOut, ConnectOption connectOption) specifying an additional ConnectOption
void Connect(HW.Channel channel) Connects to a channel
void Connect(int addressIn, int addressOut, ConnectOption Connects specifying bit addresses directly
connectOption)
void Connect(string pathToDBMember) Connects to a data block tag
void Connect(SW.Tags.PlcTag outputTag) Connects to a PLC tag
void Disconnect() Disconnects an existing connection

Note
Automatic connections
Note that the same behavior as in the user interface also applies here. Whenever the actor
interface is connected via one of the connection methods and the telegram contains a sensor
part or telegram 750. These parts are connected automatically.

Openness: API for automation of engineering workflows


626 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

You can use the following read-only attributes to determine how the technology object is
connected. The respective connection values are set only if the connection of the specific kind
exists.

Attribute Data type Description


IsConnected bool TRUE: Interface is connected
FALSE: Interface is not connected
InputOutputModule HW.DeviceItem Connected module that contains input and output addresses
InputModule HW.DeviceItem Connected module that contains input addresses
The value is also set in case of an existing connection to a module contain‐
ing input and output addresses.
OutputModule HW.DeviceItem Connected module that contains output addresses
The value is also set in case of an existing connection to a module contain‐
ing input and output addresses.
InputAddress int Logical input address of connected object; for example, 256.
OutputAddress int Logical output address of connected object; for example, 256.
ConnectOption ConnectOption Value of the ConnectOption that has been set when the connection was
made:
• Default
Only modules that are recognized as valid connection partners can be
selected.
• AllowAllModules
Corresponds to selecting "Show all modules" in the user interface.
Channel HW.Channel Connected channel
PathToDBMember string Connected technology object data block tag
OutputTag SW.Tags.PlcTag Connected PLC tag (analog connection)
SensorIndexInActorTe‐ int Connected sensor part in actor telegram
legram The attribute is only relevant for sensor interfaces.
0: Encoder is not connected
1: Encoder is connected to first sensor interface in telegram
2: Encoder is connected to second sensor interface in telegram
For the actor interface the value is always 0.

Note
Access the sensor interface
To access the sensor interface you can use SensorInterface[m] with 0≤m≤3.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 627
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program Code: void Connect(HW.DeviceItem moduleInOut)


Modify the following program code to connect a mixed module that contains input and output
addresses:

//An instance of technology object and device item is already available in the program
before
private static void UseServiceAxisHardwareConnectionProvider(TechnologicalInstanceDB
technologyObject, DeviceItem devItem)
{
//Retrieve service AxisHardwareConnectionProvider
AxisHardwareConnectionProvider connectionProvider =
technologyObject.GetService<AxisHardwareConnectionProvider>();

//Connect ActorInterface with DeviceItem


connectionProvider.ActorInterface.Connect(devItem);

//Connect first SensorInterface with DeviceItem


connectionProvider.SensorInterface[0].Connect(devItem);

//Check ConnectionState of ActorInterface


bool actorInterfaceConnectionState = connectionProvider.ActorInterface.IsConnected;

//Check ConnectionState of first SensorInterface


bool sensorInterfaceConnectionState =
connectionProvider.SensorInterface[0].IsConnected;
}

Connecting telegram 750

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_SpeedAxis, TO_PositioningAxis or TO_SynchronousAxis
V4.0 is determined in the project.
• A drive that supports telegram 750 is determined in the project.

Openness: API for automation of engineering workflows


628 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
If telegram 750 was added after connecting the drive and the axis, it is necessary to connect
telegram 750 separately. EnableTorqueData is set to TRUE automatically. The public API type
TorqueHardwareConnectionInterface provides the following methods which can be used to
connect and disconnect telegram 750:

Method Description
void Connect(HW.DeviceItem moduleInOut) Connects to input and output addresses at one
module
void Connect(HW.DeviceItem moduleIn, HW.Devi‐ Connects to input and output addresses at separate
ceItem moduleOut) modules

void Connect(HW.DeviceItem moduleIn, HW.Devi‐ Connects to input and output addresses at separate
ceItem moduleOut, ConnectOption connectOp‐ modules, specifying an additional ConnectOption
tion)
void Connect(int addressIn, int addressOut, Con‐ Connects specifying bit addresses directly
nectOption connectOption)
void Connect(string pathToDBMember) Connects to a data block tag
void Disconnect() Disconnects an existing connection

The TorqueHardwareConnectionInterface can be retrieved via the property TorqueInterface at


the type AxisHardwareConnectionProvider. If the connection to telegram 750 is not supported,
the property value is “null”.
If the drive is connected by data block tags, you cannot connect telegram 750 by module. You
can use the following read-only attributes to determine how the technology object is connected.
The respective connection values are set only if the connection of the specific kind exists:

Attribute Data type Description


IsConnected bool TRUE: Interface is connected
FALSE: Interface is not connected
InputOutput‐ HW.DeviceItem Connected module that contains input and output
Module addresses
InputModule HW.DeviceItem Connected module that contains input addresses
The value is also set in case of an existing connec‐
tion to a module containing input and output ad‐
dresses.
OutputMod‐ HW.DeviceItem Connected module that contains output addresses
ule The value is also set in case of an existing connec‐
tion to a module containing input and output ad‐
dresses.
InputAddress int Logical input address of connected object; for ex‐
ample 256
OutputAd‐ int Logical output address of connected object; for ex‐
dress ample 256

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 629
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Attribute Data type Description


ConnectOp‐ ConnectOption Value of the ConnectOption that has been set when
tion the connection was made:
• Default
Only modules that are recognized as valid con‐
nection partners can be selected.
• AllowAllModules
Corresponds to selecting "Show all modules" in
the user interface.
PathToDB‐ string Connected technology object data block tag
Member

Program Code: Connect telegramm 750


Modify the following program code to connect a mixed module that contains input and output
addresses:

//An instance of technology object and device item is already available in the program
before
private static void ConnectTorqueInterface(TechnologicalInstanceDB technologyObject,
DeviceItem devItem)
{
//Retrieve service AxisHardwareConnectionProvider
AxisHardwareConnectionProvider connectionProvider =
technologyObject.GetService<AxisHardwareConnectionProvider>();
//Connect TorqueInterface with DeviceItem
connectionProvider.TorqueInterface.Connect(devItem);
}

Connecting encoders

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_ExternalEncoder is determined in the project.
• An object is determined in the project that provides PROFIdrive telegram 81 or 83.

Openness: API for automation of engineering workflows


630 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
To connect an external encoder technology object with the encoder hardware, it is necessary to
specify several values together in a single call. The public API type
AxisEncoderHardwareConnectionInterface provides the following methods which can be used
to connect and disconnect the sensor interface:

Method Description
void Connect(HW.DeviceItem moduleInOut) Connects to input and output addresses at one module.
void Connect(HW.DeviceItem moduleIn, HW.DeviceItem mod‐ Connects to input and output addresses at separate modules.
uleOut)
void Connect(HW.DeviceItem moduleIn, HW.DeviceItem mod‐ Connects to input and output addresses at separate modules,
uleOut, ConnectOption connectOption) specifying an additional ConnectOption
void Connect(HW.Channel channel) Connects to a channel
void Connect(int addressIn, int addressOut, ConnectOption Connects specifying bit addresses directly
connectOption)
void Connect(string pathToDBMember) Connects to a data block tag
void Connect(SW.Tags.PlcTag outputTag) Not relevant for connecting encoders
void Disconnect() Disconnects an existing connection

You can use the following read-only attributes to determine how the technology object is
connected. The respective connection values are set only if the connection of the specific kind
exists.

Attribute Data type Description


IsConnected bool TRUE: Interface is connected
FALSE: Interface is not connected
InputOutputModule HW.DeviceItem Connected module that contains input and output addresses
InputModule HW.DeviceItem Connected module that contains input addresses
The value is also set in case of an existing connection to a module contain‐
ing input and output addresses.
OutputModule HW.DeviceItem Connected module that contains output addresses
The value is also set in case of an existing connection to a module contain‐
ing input and output addresses.
InputAddress int Logical input address of connected object, for example 256.
OutputAddress int Logical output address of connected object, for example 256.
ConnectOption ConnectOption Value of the ConnectOption that has been set when the connection was
made:
• Default
Only modules that are recognized as valid connection partners can be
selected.
• AllowAllModules
Corresponds to selecting "Show all modules" in the user interface.
Channel HW.Channel Connected channel
PathToDBMember string Connected data block tag

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 631
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Attribute Data type Description


OutputTag SW.Tags.PlcTag Not relevant for connecting encoders
SensorIndexInActorTe‐ int Connected sensor telegram
legram The attribute is only relevant for sensor interfaces.
0: Encoder is not connected
1: Encoder is connected to first sensor interface in telegram
2: Encoder is connected to second sensor interface in telegram
For the actor interface the value is always 0.

Program code: Connect an encoder


Modify the following program code to connect an external encoder technology object:

//An instance of technology object and device item is already available in the program
before
private static void UseServiceEncoderHardwareConnectionProvider(TechnologicalInstanceDB
technologyObject, DeviceItem devItem)
{
//Retrieve service EncoderHardwareConnectionProvider
EncoderHardwareConnectionProvider connectionProvider =
technologyObject.GetService<EncoderHardwareConnectionProvider>();

//Connect SensorInterface with DeviceItem


connectionProvider.SensorInterface.Connect(devItem);

//Check ConnectionState of SensorInterface


bool sensorInterfaceConnectionState = connectionProvider.SensorInterface.IsConnected;
}

Connecting output cams and cam tracks to hardware

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_OutputCam or TO_CamTrack is determined in the project.
• A digital output module is determined in the project, for example TM Timer DIDQ.

Openness: API for automation of engineering workflows


632 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
To connect an output cam or cam track technology object with a digital output, it is necessary
to specify several values together in a single call. The public API type
OutputCamHardwareConnectionProvider provides the following methods which can be used to
connect and disconnect the actor or sensor interfaces:

Method Description
void Connect(HW.Channel channel) Connects to a channel
void Connect(SW.Tags.PlcTag outputTag) Connects to a PLC tag
void Connect(int address) Connects specifying bit addresses directly
void Disconnect() Disconnects an existing connection

You can use the following read-only attributes to determine how the technology object is
connected:

Attribute Data type Description


IsConnected bool TRUE: Technology object is connected
FALSE: Technology object is not connected
Channel HW.Channel Connected channel
OutputTag SW.Tags.PlcTag Connected PLC tag
OutputAddress int Logical output address of connected object, for example 256.

Program code: Connect output cam or cam track technology object


Modify the following program code to connect an output cam or cam track technology object:

//An instance of technology object and channel item is already available in the program
before
private static void UseServiceOutputCamHardwareConnectionProvider(TechnologicalInstanceDB
technologyObject, Channel channel)

{
//Retrieve service OutputCamHardwareConnectionProvider
OutputCamHardwareConnectionProvider connectionProvider =
technologyObject.GetService<OutputCamHardwareConnectionProvider>();

//Connect technology object with Channel


connectionProvider.Connect(channel);

//Check ConnectionState of technology object


bool connectionState = connectionProvider.IsConnected;
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 633
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Connecting measuring inputs to hardware

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_MeasuringInput is determined in the project.
• A digital input module is determined at drive or in the project, for example TM Timer DIDQ.

Application
To connect a measuring input technology object with a digital input, it is necessary to specify
several values together in a single call. The public API type
MeasuringInputHardwareConnectionProvider provides the following methods which can be
used to connect and disconnect the actor or sensor interface:

Method Description
void Connect(HW.Channel channel) Connects to a channel
void Connect(HW.DeviceItem moduleIn, int channelIndex) Connects to a module, specifying an additional channel index
void Connect(int address) Connects specifying bit addresses directly
• For TM Channels, the bit address can be calculated via the
formula
bit_address = module_start_address * 8 + channel_index
• For telegram 39x, the associated formula is
bit_address = module_start_address * 8 + 24 + num‐
ber_of_measuringinput_in_telegram
void Disconnect() Disconnects an existing connection

You can use the following read-only attributes to determine how the technology object is
connected:

Attribute Data type Description


IsConnected bool TRUE: Technology object is connected
FALSE: Technology object is not connected
InputModule HW.DeviceItem Connected module that contains input addresses
ChannelIndex int Index of connected channel with respect to InputModule
Channel HW.Channel Connected channel
InputAddress int Logical input address of connected object, for example 256.

Openness: API for automation of engineering workflows


634 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Connect a measuring input technology object


Modify the following program code to connect a measuring input technology object:

//An instance of technology object and channel item is already available in the program
before
private static void
UseServiceMeasuringInputHardwareConnectionProvider(TechnologicalInstanceDB
technologyObject, Channel channel)
{
//Retrieve service MeasuringInputHardwareConnectionProvider
MeasuringInputHardwareConnectionProvider connectionProvider =
technologyObject.GetService<MeasuringInputHardwareConnectionProvider>();

//Connect technology object with Channel


connectionProvider.Connect(channel);

//Check ConnectionState of technology object


bool connectionState = connectionProvider.IsConnected;
}

Connecting synchronous axis with leading values

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_PositioningAxis, TO_SynchronousAxis,
TO_ExternalEncoder or TO_LeadingAxisProxy as leading axis is determined in the project.
• A technology object of the type TO_SynchronousAxis as following axis is determined in the
project.

Application
To connect a synchronous axis technology object with leading values, it is necessary to specify
several values together in a single call. The public API type SynchronousAxisMasterValues
provides the following methods which can be used to connect and disconnect leading values.
Leading values can be connected as setpoint coupling (S7-1500 PLC, S7-1500T PLC) or actual
value coupling (S7-1500T PLC). All methods and attributes are relevant for both types of
coupling.

Method Description
int IndexOf (TechnologicalInstanceDB element) Returns the corresponding index of a leading value
bool Contains (TechnologicalInstanceDB element) TRUE: The container contains the leading value
FALSE: The container does not contain the leading value

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 635
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Method Description
IEnumerator GetEnumerator <TechnologicalInstanceDB>() Used to support each iteration
void Add (TechnologicalInstanceDB element) Connects following axis to leading value
bool Remove (TechnologicalInstanceDB element) Disconnects following axis from leading value
TRUE: Disconnection was succesfully
FALSE: Disconnection was not succesfully

You can use the following read-only attributes:

Attribute Data type Description


Count int Count of leading values
IsReadonly bool TRUE: The container is read-only
FALSE: The container is not read-only
Parent IEngineeringObject Returns the parent of the container.
In this case parent means the service SynchronousAxisMasterValues.
this [ id ] { get; } TechnologicalInstan‐ Index-based access to leading values
ceDB

You can use the following attributes to connect a synchronous axis with a leading value:

Attribute Data type Description


SetPointCoupling SW.TechnologicalObjects.TechnologicalInstan‐ The attribute gets container of connected leading
ceDBAssociation axis with setpoint coupling.
ActualValueCoupling SW.TechnologicalObjects.TechnologicalInstan‐ The attribute gets container of connected leading
ceDBAssociation axis with actual value coupling.

DelayedCoupling SW.TechnologicalObjects.TechnologicalInstan‐ The attribute contains all master values that are
ceDBAssociation coupled via delayed values.

Openness: API for automation of engineering workflows


636 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Connect a synchronous axis with a leading value


Modify the following program code to connect a synchronous axis with a leading value:

//An instance of leading axis and following axis is already available in the program before
private static void UseServiceSynchronousAxisMasterValues(TechnologicalInstanceDB
masterTechnologyObject, TechnologicalInstanceDB synchronousTechnologyObject)
{
//Retrieve service SynchronousAxisMasterValues
SynchronousAxisMasterValues masterValues =
synchronousTechnologyObject.GetService<SynchronousAxisMasterValues>();

//Connect following axis and leading axis with setpoint coupling


masterValues.SetPointCoupling.Add(masterTechnologyObject);

//Get container of connected leading axis with setpoint coupling


TechnologicalInstanceDBAssociation setPointMasterValues =
masterValues.SetPointCoupling;

//Remove connected leading axis with setpoint coupling


masterValues.SetPointCoupling.Remove(masterTechnologyObject);

//Connect following axis and leading axis with actual value coupling
masterValues.ActualValueCoupling.Add(masterTechnologyObject);

//Get container of connected leading axis with actual value coupling


TechnologicalInstanceDBAssociation actualValueMasterValues =
masterValues.ActualValueCoupling;

//Remove connected leading axis with actual value coupling


masterValues.ActualValueCoupling.Remove(masterTechnologyObject);
}

Connecting conveyor tracking of kinematics with leading values

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal.
• A project is open.
See Opening a project.
• A S7-1500 PLC is determined in the project.
• A technology object of the type TO_PositioningAxis, TO_SynchronousAxis or
TO_ExternalEncoder as leading axis is determined in the project.
• A technology object of the type TO_Kinematics as following axis is determined in the project.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 637
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
To configure leading values for conveyor tracking, use the service
SW.TechnologicalObjects.Motion.ConveyorTrackingLeadingValues for TO Kinematics ≥ V5.0.

Method Description
int IndexOf (TechnologicalInstanceDB element) Returns the corresponding index of a leading value
bool Contains (TechnologicalInstanceDB element) TRUE: The container contains the leading value
FALSE: The container does not contain the leading
value
IEnumerator GetEnumerator <TechnologicalIn‐ Used to support each iteration
stanceDB>()
void Add (TechnologicalInstanceDB element) Connects following axis to leading value
bool Remove (TechnologicalInstanceDB element) Disconnects following axis from leading value
TRUE: Disconnection was succesfully
FALSE: Disconnection was not succesfully

You can use the following read-only attributes:

Attribute Data type Description


Count int Count of leading values
IsReadonly bool TRUE: The container is read-only
FALSE: The container is not read-only
Parent IEngineeringOb‐ Returns the parent of the container.
ject In this case parent means the service SynchronousAxisMas‐
terValues.
this [ id ] { get; } TechnologicalIn‐ Index-based access to leading values
stanceDB

You can use the following attributes to connect a kinematics axis with a leading value:

Attribute Data type Description


SetPointCoupling SW.TechnologicalObjects.Technologica‐ The attribute gets container of connec‐
lInstanceDBAssociation ted leading axis with setpoint coupling.
ActualValueCou‐ SW.TechnologicalObjects.Technologica‐ The attribute gets container of connec‐
pling lInstanceDBAssociation ted leading axis with actual value cou‐
pling.

DelayedCoupling SW.TechnologicalObjects.Technologica‐ The attribute contains all master values


lInstanceDBAssociation that are coupled via delayed values.

Connect conveyor tracking axis of a kinematics with a leading value


An example of the interconnection is included in the topic Connecting synchronous axis with
leading values (Page 635).

Openness: API for automation of engineering workflows


638 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Exporting and importing technology object cam (S7-1500T)

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81).
• A project is open.
See Opening a project (Page 113).
• A S7-1500 PLC is determined in the project.
See Querying PLC and HMI targets (Page 205)
• The technology object exists.

Application
To export or import the data of a technology object cam of typ TO_Cam or TO_Cam_10k you have
to specify the format and which separator should be used. The public API type CamDataSupport
provides the following methods which can be used to export the data of technology object cam.
For more information on export format of cam, Refer function manual Using S7-1500/S7-1500T
Synchronous Operations Functions on chapter Importing / exporting cam.

Method Description
void SaveCamDataBinary(System.IO.FileInfo destinationFile) Exports the data in binary format in the destination file.
void SaveCamDataPointList(System.IO.FileInfo destination‐ Exports the data in format “PointList” in the destination file.
File, CamDataFormatSeparator separator, int samplePoints)
void SaveCamData(System.IO.FileInfo destinationFile, Cam‐ Exports the data in the destination file. You can specify data
DataFormat format, CamDataFormatSeparator separator) format as “MCD”, “SCOUT” or “Pointlist” and separator as “tab”
or “comma”.
If you choose “PointList” 360 interpolation points will be ex‐
ported.
void LoadCamData(System.IO.FileInfo sourceFile, CamData‐ Imports the cam data in the format “MCD”, “SCOUT” or “Point‐
FormatSeparator separator) list” to the project.
void LoadCamDataBinary(System.IO.FileInfo sourceFile) Imports the cam data from a binary file to the project.

You can use the following attributes:

Attribute Data type Description


separator CamDataFormatSepa‐ Allowed values
rator • tab
• comma
samplePoints int Number of interpolation points that should be exported.
format CamDataFormat Allowed values
• MCD
• SCOUT
• Pointlist

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 639
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Attribute Data type Description


destinationFile System.IO.FileInfo Name of destination file. Must not be null. Access rights and enough space
on storage medium must be given. An existing file will be overwritten.
sourceFile System.IO.FileInfo Name of source file. Must not be null. Access rights must be given. Content
must be in specified format.

Program code: Export cam data


Modify the following program code to export cam data:

//An instance of technology object is already available in the program before


private static void ExportCamData(TechnologicalInstanceDB technologyObject,
System.IO.FileInfo destinationFile)
{
//Retrieve service CamDataSupport
CamDataSupport camData = technologyObject.GetService<CamDataSupport>();

//Save cam data in MCD format, using the separator Tab


camData.SaveCamData(destinationFile, CamDataFormat.MCD, CamDataFormatSeparator.Tab);
}

Program code: Import cam data


Modify the following program code to import cam data:

//An instance of technology object is already available in the program before


private static void ImportCamData(TechnologicalInstanceDB technologyObject,
System.IO.FileInfo sourceFile)
{
//Retrieve service CamDataSupport
CamDataSupport camData = technologyObject.GetService<CamDataSupport>();

//Load cam data from source file, using the separator Tab
camData.LoadCamData(sourceFile, CamDataFormatSeparator.Tab);
}

5.12.4.16 PID control

Parameters for PID_Compact, PID_3Step, PID_Temp, CONT_C, CONT_S, TCONT_CP and TCONT_S
You can find a list of all available parameters in the product information “Parameters of
technology objects in TIA Portal Openness“ on the internet (https://
support.industry.siemens.com/cs/ww/en/view/109744932).
For each parameter the following properties are provided:
• Name in configuration (TIA Portal)
• Name in Openness

Openness: API for automation of engineering workflows


640 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

• Data type in Openness


• Default access
• Range of values

Note
In TIA Portal in the Parameter view of the technology object configuration you can find the
column "Name in Openness".

Additional information
You can find additional information in SIMATIC S7-1200/S7-1500 PID control function manual on
the internet (https://support.industry.siemens.com/cs/ww/en/view/108210036).

5.12.4.17 Counting

Parameters for High_Speed_Counter and SSI_Absolute_Encoder


You can find a list of all available parameters in the product information “Parameters of
technology objects in TIA Portal Openness“ on the internet (https://
support.industry.siemens.com/cs/ww/en/view/109744932).
For each parameter the following properties are provided:
• Name in configuration (TIA Portal)
• Name in Openness
• Data type in Openness
• Default access
• Range of values

Additional information
You can find additional information in SIMATIC S7-1500, ET 200MP, ET 200SP Counting,
measurement and position input function manual on the internet (http://
support.automation.siemens.com/WW/view/en/59709820).

5.12.4.18 Easy Motion Control

Parameters for AXIS_REF


You can find a list of all available parameters in the product information “Parameters of
technology objects in TIA Portal Openness“ on the internet (https://
support.industry.siemens.com/cs/ww/en/view/109744932).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 641
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

For each parameter the following properties are provided:


• Name in configuration (TIA Portal)
• Name in Openness
• Data type in Openness
• Default access
• Range of values

Note
In TIA Portal in the Parameter view of the technology object configuration you can find the
column "Name in Openness".

Additional information
You can find additional information for Easy Motion Control in the Information system of STEP 7
(TIA Portal).

5.12.5 Tags and Tag tables

5.12.5.1 Starting the "PLC Tags" editor

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• Instance of the TIA Portal is opened with user interface.

Program code
Modify the following program code to start the corresponding editor for an object reference of
the type PlcTagTable in the TIA Portal instance:

//Opens tagtable in editor "Tags"


private static void OpenTagtableInEditor(PlcSoftware plcSoftware)
{
PlcTagTable plcTagTable = plcSoftware.TagTableGroup.TagTables.Find("MyTagTable");
plcTagTable.ShowInEditor();
}

Openness: API for automation of engineering workflows


642 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Importing configuration data (Page 885)

5.12.5.2 Querying system groups for PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PlcSoftware instance was retrieved from a PLC device item.
See Querying PLC and HMI targets (Page 205)

Program code
Modify the following program code to query the system group for PLC tags:

//Retrieves the plc tag table group from a plc


private PlcTagTableSystemGroup GetControllerTagfolder(PlcSoftware plcSoftware)
{
PlcTagTableSystemGroup plcTagTableSystemGroup = plcSoftware.TagTableGroup;
return plcTagTableSystemGroup;
}

5.12.5.3 Creating PLC tag table

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PlcSoftware instance was retrieved from a PLC device item.
See Querying PLC and HMI targets (Page 205)

Program code
Modify the following program code to create the PLC tag table. It creates a new tag table with
the given name in the composition.

PlcTagTable myTable = plc.TagTableGroup.TagTables.Create("myTable");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 643
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Querying PLC and HMI targets (Page 205)

5.12.5.4 Enumerating user-defined groups for PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A PlcSoftware instance was retrieved from a PLC device item.
See Querying PLC and HMI targets (Page 205)

Application
Subfolders are taken into account recursively for enumeration.

Program code: Enumerating user-defined groups for PLC tags


Modify the following program code to enumerate user-defined groups for PLC tags:

//Enumerates all plc tag table user groups including subgroups


private static void EnumeratePlcTagTableUserGroups(PlcSoftware plcSoftware)
{
foreach (PlcTagTableUserGroup plcTagTableUsergroup in plcSoftware.TagTableGroup.Groups)
{
EnumerateTagTableUserGroups(plcTagTableUsergroup);
}
}
private static void EnumerateTagTableUserGroups(PlcTagTableUserGroup tagTableUsergroup)
{
foreach (PlcTagTableUserGroup plcTagTableUsergroup in tagTableUsergroup.Groups)
{
EnumerateTagTableUserGroups(plcTagTableUsergroup);
// recursion
}
}

Openness: API for automation of engineering workflows


644 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Accessing a user-defined group


Modify the following program code to access a user-defined group for PLC tags:

//Gives individual access to a specific plc tag table user folder


private static void AccessPlcTagTableUserGroupWithFind(PlcSoftware plcSoftware, string
folderToFind)
{
PlcTagTableUserGroupComposition plcTagTableUserGroupComposition =
plcSoftware.TagTableGroup.Groups;
PlcTagTableUserGroup controllerTagUserFolder =
plcTagTableUserGroupComposition.Find(folderToFind);
// The parameter specifies the name of the user folder
}

5.12.5.5 Creating user-defined groups for PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The TIA Portal Openness API interface supports the creation of a user-defined group for PLC tags.

Program code
Modify the following program code to create a user-defined group for PLC tags:

//Creates a plc tag table user group


private static void CreatePlcTagTableUserGroup(PlcSoftware plcSoftware)
{
PlcTagTableSystemGroup systemGroup = plcSoftware.TagTableGroup;
PlcTagTableUserGroupComposition groupComposition = systemGroup.Groups;
PlcTagTableUserGroup myCreatedGroup = groupComposition.Create("MySubGroupName");
// Optional;
// create a subgroup
PlcTagTableUserGroup mySubCreatedGroup =
myCreatedGroup.Groups.Create("MySubSubGroupName");
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 645
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.5.6 Deleting user-defined groups for PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The TIA Portal Openness API interface supports the deletion of a specific user-defined group for
PLC tag tables.

Program code
Modify the following program code to delete a specific user-defined group for PLC tag tables:

private static void DeletePlcTagTableUserGroup(PlcSoftware plcSoftware)


{
PlcTagTableUserGroup group = plcSoftware.TagTableGroup.Groups.Find("MySubGroupName");
if (group != null)
{
group.Delete();
}
}

5.12.5.7 Enumerating PLC tag tables in a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


646 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Enumerating PLC tag tables


Modify the following program code to enumerate all PLC tag tables in system groups or in user-
defined groups:

//Enumerates all plc tag tables in a specific system group or and user group
private static void EnumerateAllPlcTagTablesInFolder(PlcSoftware plcSoftware)
{
PlcTagTableComposition tagTables = plcSoftware.TagTableGroup.TagTables;
// alternatively, PlcTagTableComposition tagTables =
plcSoftware.TagTableGroup.Groups.Find("UserGroup XYZ").TagTables;
foreach (PlcTagTable tagTable in tagTables)
{
// add code here
}
}

Program code: Accessing PLC tag table


Modify the following program code to access the PLC tag table:

//Gives individual access to a specific Plc tag table


private static void AccessToPlcTagTableWithFind(PlcSoftware plcSoftware)
{
PlcTagTableComposition tagTables = plcSoftware.TagTableGroup.TagTables;
// alternatively, PlcTagTableComposition tagTables =
plcSoftware.TagTableGroup.Groups.Find("UserGroup XYZ").TagTables;
PlcTagTable controllerTagTable = tagTables.Find("Tag table XYZ");
// The parameter specifies the name of the tag table
}

5.12.5.8 Querying information from a PLC tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Via PLC tag tables you can access user constants, system constants and tags. The count of the
tag composition of a tag table is equal to the number of tags in that tag table. The PLCTagTable
contains the following navigators, attributes, and actions.
The following attributes are accessed in PLC tag table. 

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 647
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Name Type Type


IsDefault bool Read-only
ModifiedTimeStamp DateTime Read-only
Name string Read-only

The PLCTag table contains the following actions as given below.

Name Return type Description


Delete void Deletes the instance. Throws an
exception if IsDefault is true.
Export void Exports the Simatic ML of a Plc
tag table.
ShowInEditor void Shows the tag table in the Plc tag
table editor.

Program code
Modify the following program code to query the information for a PLC tag table:

private static void AccessPlcConstantsUsingFind(PlcTagTable tagTable)


{
PlcUserConstantComposition plcUserConstants = tagTable.UserConstants;
PlcUserConstant plcUserConstant = plcUserConstants.Find("Constant XYZ");
//PlcSystemConstantComposition plcSystemConstants = tagTable.SystemConstants;
//PlcSystemConstant plcSystemConstant = plcSystemConstants.Find("Constant XYZ");
}
private static void EnumeratePlcTags(PlcTagTable tagTable)
{
PlcTagComposition plcTags = tagTable.Tags;
foreach (PlcTag plcTag in plcTags)
{
string name = plcTag.Name; string typeName = plcTag.DataTypeName;
string logicalAddress = plcTag.LogicalAddress;
}
}
private static void EnumeratePlcTagsUsingFind(PlcTagTable tagTable)
{
PlcTagComposition plcTags = tagTable.Tags;
PlcTag plcTag = plcTags.Find("Constant XYZ");
}

Openness: API for automation of engineering workflows


648 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.5.9 Reading the time of the last changes of a PLC tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The format of the time stamp is UTC.

Program code
Modify the following program code to read the time stamp of a specific PLC tag table:

//Reads Time-Stamp of a plc Tag Table


private static void GetLastModificationDateOfTagtable(PlcSoftware plcSoftware)
{
PlcTagTable plcTagTable = plcSoftware.TagTableGroup.TagTables.Find("MyTagTable");
DateTime modifiedTagTableTimeStamp = plcTagTable.ModifiedTimeStamp;
}

5.12.5.10 Deleting a PLC tag table from a group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 649
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code
Modify the following program code to delete a specific tag table from a group:

//Deletes a PlcTagTable of a group


private static void DeletePlcTagTableInAGroup(PlcSoftware plcSoftware)
{
PlcTagTableSystemGroup group = plcSoftware.TagTableGroup;
PlcTagTable tagtable = group.TagTables.Find("MyTagTable");
if (tagtable!= null)
{
tagtable.Delete();
}
}

5.12.5.11 Enumerating PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code: Enumerating PLC tags in tag tables


Modify the following program code to enumerate all PLC tags in a tag table:

//Enumerates all plc tags in a specific tag table


private static void EnumerateAllPlcTagsInTagTable(PlcSoftware plcSoftware)
{
PlcTagTable tagTable = plcSoftware.TagTableGroup.TagTables.Find("Tagtable XYZ");
foreach (PlcTag tag in tagTable.Tags)
{
// add code here
}
}

5.12.5.12 Accessing PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


650 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
The type PlcTagComposition represents a collection of plc tags.

Program code: Accessing a specific PLC tag


Modify the following program code to access the required PLC tag. You have access to the
following attributes:
• Name (read only)
• Data type name
• Logical address
• Comment
• ExternalAccessible
• ExternalVisible
• ExternalWritable

//Gives individual access to a specific plc tag


private static void AccessPlcTag(PlcTagTable tagTable)
{
PlcTag tag = tagTable.Tags.Find("Tag XYZ");
// The parameter specifies the name of the tag
}

Program code: Creating tags


Modify the following program code:

private static void CreateTagInPLCTagtable(PlcSoftware plcsoftware)


// Create a tag in a tag table with default attributes
{
string tagName = "MyTag";
PlcTagTable table = plcsoftware.TagTableGroup.TagTables.Find("myTagTable");
PlcTagComposition tagComposition = table.Tags;
PlcTag tag = tagComposition.Create(tagName);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 651
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code:

private static void CreateTagInPLCTagtable(PlcSoftware plcsoftware)


// Create a tag of data type bool and logical address not set
{
string tagName = "MyTag";
string dataType = "Bool";
string logicalAddress ="";
PlcTagTable table = plcsoftware.TagTableGroup.TagTables.Find("myTagTable");
PlcTagComposition tagComposition = table.Tags;
PlcTag tag = tagComposition.Create(tagName, dataType, logicalAddress);
}

Program code: Deleting tags


Modify the following program code:

private static void DeleteTagFromPLCTagtable(PlcSoftware plcsoftware)


// Deletes a single tag of a tag table
{
string tagName = "MyTag";
PlcTagTable table = plcsoftware.TagTableGroup.TagTables.Find("myTagTable");
PlcTagComposition tagComposition = table.Tags;
PlcTag tag = tagComposition.Find(tagName);
if (tag != null)
{
tag.Delete();
}
}

5.12.5.13 Accessing PLC constants

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The type PlcUserConstantComposition represents a collection of plc user constants. You
have access to the following attributes:
• Name (read only)
• Data type name
• Value

Openness: API for automation of engineering workflows


652 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The type PlcSystemConstantComposition represents a collection of plc system constants.


You have access to the following attributes:
• Name (read only)
• Data type name (read only)
• Value (read only)

Program code: Creating user constants


Modify the following program code:

private static void CreateUserConstantInPLCTagtable(PlcSoftware plcsoftware)


// Create a user consrant in a tag table
{
string constantName = "MyConstant";
PlcTagTable table = plcsoftware.TagTableGroup.TagTables.Find("myTagTable");
PlcUserConstantComposition userConstantComposition = table.UserConstants;
PlcUserComnstant userConstant = userConstantComposition.Create(constantName);
}

Program code: Deleting user constants


Modify the following program code:

private static void DeleteUserConstantFromPLCTagtable(PlcSoftware plcsoftware)


// Deletes a single user constant of a tag table
{
PlcTagTable table = plcsoftware.TagTableGroup.TagTables.Find("myTagTable");
PlcUserConstantComposition userConstantComposition = table.UserConstants;
PlcUserConstant userConstant = userConstantComposition.Find("MyConstant");
if (userConstant != null)
{
userConstant.Delete();
}
}

Program code: Accessing system contants


Modify the following program code:

//Gives individual access to a specific system constant


private static void AccessSystemConstant(PlcTagTable tagTable)
{
PlcTag systemConstant = tagTable.SystemConstants.Find("Constant XYZ");
// The parameter specifies the name of the tag
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 653
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

See also
Creating user-defined groups for PLC tags (Page 645)
Deleting user-defined groups for PLC tags (Page 646)
Deleting a PLC tag table from a group (Page 649)
Accessing PLC tags (Page 650)
Starting the "PLC Tags" editor (Page 642)
Reading the time of the last changes of a PLC tag table (Page 649)

5.12.6 Functions for software units

5.12.6.1 Working with software unit

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The units are important parts of the PLC's Programming and can be found on the PlcSoftware.
The unit provider is retrieved from PlcSoftware via GetService and the PlcUnitComposition can
be retrieved from it.
You can perform the following elementary operations for units while using TIA Portal Openness:
• Creating units
• Deleting units
• Renaming units

Program code: Creating units


Modify the following program code to create units.

PlcUnitProvider provider = m_Target.GetService<PlcUnitProvider>();


PlcUnitComposition unitComposition = provider.UnitGroup.Units;
//Creating Unit
PlcUnit unit1 = unitComposition.Create("Unit1");

Error will occur if you provide the wrong name, for example starting with whitespace or
containing invalid character or name is too long. A Recoverable Exception will be thrown with

Openness: API for automation of engineering workflows


654 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

the following error message: "The value of attribute 'Name' contains an invalid character at
Position 0."

try
{
PlcUnit unit1 = unitComposition.Create("Unit1");
}
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine(e.Message);
}

Error will occur if you want to create a unit with which a name already exists. A Recoverable
Exception will be thrown with the following message: "Unit with name'Unit1' already exists.

PlcUnit unit1 = unitComposition.Create("Unit1");


...
...
try
{
PlcUnit unit2 = unitComposition.Create("Unit1");
}
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine(e.Message);
}

Program code: Deleting units


Modify the following program code to delete units.

unitProvider.UnitGroup.Units.Find("Unit_2").Delete();

You will encounter NullReferenceException in case of the Find( ) method from above example
code does not provide a reference to a Unit.

Program code: Renaming units


You can set the attributes in several ways. It can be adjusted via value assignment or call of
SetAttribute as well as SetAttributes. The Name property can be validated by GetAttribute or
GetAttributes. To be able to use SetAttribute or GetAttribute the object should be casted to
IEngineeringObject.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 655
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to rename units.

//Set Value
PlcUnit unit1 = unitComposition.Create("Unit1");
unit1.Name = "Unit1_new";
//Using SetAttributes():
PlcUnit unit1 = unitComposition.Create("Unit1");
var attrList = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("Name", "Unit1_new")
};
unit1.SetAttributes(attrList);
//Using SetAttribute()
PlcUnit unit2 = unitComposition.Create("Unit2");
IEngineeringObject unit = (IEngineeringObject)unit2;
unit.SetAttribute("Name", "Unit2_new");

Error will occur if you provide wrong name, for example starting with whitespace, or containing
invalid character. A Recoverable Exception will be thrown with the error message: "The value of
attribute 'Name' contains an invalid character at Position 0."

PlcUnit unit1 = unitComposition.Create("Unit_1");


try                       
{
unit1.Name = "Unit_1";                      
}                      
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine(e.Message);                      
}

Error will occur if you want to rename a unit with a name which already exists. A recoverable
exception will be thrown with the error message: "The property 'Name' has an invalid value:
'Unit1'. A software unit with the same name already exists."

PlcUnit unit1 = unitComposition.Create("Unit1");


PlcUnit unit2 = unitComposition.Create("Unit_2");
try
{
PlcUnit unit2 = unitComposition.Create("Unit1");
}
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine(e.Message);
}

See also
Opening a project (Page 113)

Openness: API for automation of engineering workflows


656 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

5.12.6.2 Accessing software unit

Requirement
• The TIA Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to access the units. The units are important parts of the
PLC's programming. Only a selected set of PLCs are supporting units therefore units are not
modelled statically in the object model so they aren’t browsable directly under the PLC software
container.
The PlcUnitProvider makes units accessible and it is available from the PlcSoftware through
GetService( ) – as it shown in the Program code example below:
The PlcUnitProvider allows the access via the UnitGroup navigator to the PlcUnitSystemGroup
which contains the PlcUnitComposition with the general composition specific possibilities
(iterate, Find, Create, Import etc. for PlcUnits).
The unit's representation (PlcUnit) contains the unit's own specific properties as Openness
attributes.
You can access the below attributes and Methods for Openness unit properties:

Attribute Name Type


Author String
Name String

Method Name Return type


Export void
Delete void
GetAttributes IList<object>
SetAttributes void

On the PlcUnit, You can iterate through the following objects:


• Comment: MultilingualText
• the BlockGroup (PlcBlockSystemGroup)
– unit.BlockGroup
• TagTableGroup (PlcTagTableSystemGroup)
– unit.TagTableGroup
• TypeGroup (PlcTypeSystemGroup)
– unit.TypeGroup

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 657
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Accessing units

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);


PlcUnitProvider unitProvider = plcTarget.GetService<PlcUnitProvider>();
PlcUnit unit = unitProvider.UnitGroup.Units.Find("Unit_2");

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.6.3 Accessing software unit underlying objects

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Opennness to access:
• the Program blocks system group, its contained groups and blocks recursively
• the PLC data types system group, its contained groups and data types recursively
• the PLC tags system group, its contained groups and tag tables recursively

Program code: Accessing program block and block groups


Modify the following program code to access the program block under the current PLC unit by
retrieving the program block composition and iterating through its contained block:

PlcBlockComposition blockComposition = m_PlcUnit.BlockGroup.Blocks;


foreach (PlcBlock block in blockComposition)
{

//usage of block

}

Openness: API for automation of engineering workflows


658 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to access the program block group under the current PLC
unit by retrieving the program block group composition, and iterating through its contained
groups:

PlcBlockUserGroupComposition usergroupComposition = m_PlcUnit.BlockGroup.Groups;


foreach (PlcBlockUserGroup group in usergroupComposition)
{
PlcBlockComposition blockComposition = group.Blocks;
foreach (PlcBlock block in blockComposition)
{

//usage of the block

}
}

Program code: Accessing PLC data types and data type groups
Modify the following program code to access PLC data types under the current PLC unit by
retrieving the PLC data type composition and iterating through its contained data types:

PlcTypeComposition typeComposition = m_PlcUnit.TypeGroup.Types;


foreach (PlcType type in typeComposition)
{

// usage of the type

}

Modify the following program code to access PLC data type group under the current PLC unit by
retrieving the PLC data type composition and iterating through its contained groups:

PlcTypeUserGroupComposition usergroupComposition = m_PlcUnit.TypeGroup.Groups;


foreach (PlcTypeUserGroup group in usergroupComposition)
{
PlcTypeCompostion typeComposition = group.Types;
foreach (PlcType type in typeComposition)
{

// usage of the type

}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 659
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Accessing PLC tag tables and tag table goups
Modify the following program code to access the PLC tag tables under the current PLC unit by
retrieving the PLC tag table composition and iterating through its contained tag tables:

PlcTagTableComposition tagtableComposition = m_PlcUnit.TagTableGroup.TagTables;


foreach (PlcTagTable type in tagtableComposition)
{

// usage of the tag table

}

Modify the following program code to access PLC tag table groups under the current PLC unit by
retrieving the PLC tag table group composition and iterating through its contained groups:

PlcTagTableUserGroupComposition usergroupComposition = m_PlcUnit.TagTableGroup.Groups;


foreach (PlcTagTableUserGroup group in usergroupComposition)
{
PlcTagTableComposition tagtableComposition = group.TagTables;
foreach (PlcTagTable type in tagtableComposition)
{

// usage of the tag table

}
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.6.4 Accessing to existing relations of a unit

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to access all the existing relations of a unit so that you can
read relation properties.

Openness: API for automation of engineering workflows


660 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The following attributes are supported by the unit relation in the Openness:

Attribute name Type description


RelationType UnitRelationType Type of the relation
RelatedObject String Contains the name of the acces‐
sible element

The following ENUM values are provided for the attribute RelationType:
• Software Unit
• Non-Unit DB
• TO DB

Program code: Accessing relations


You can get relations, its relation type and the name of the related object in several ways.
Modify the following program code for getting the relation comosition:

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, 


PLCName);
PlcUnitProvider provider = plcTarget.GetService<PlcUnitProvider>();
//assuming existing units
m_PlcUnit = provider.UnitGroup.Units[0];
PlcUnitRelationComposition unitRelations = m_PlcUnit.Relations;

Modify the following program code for getting relation by indexer:

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);


PlcUnitProvider provider = plcTarget.GetService<PlcUnitProvider>();
m_PlcUnit = provider.UnitGroup.Units[0]; //assuming existing units
PlcUnitRelation unitRelation = m_PlcUnit.Relations[1];

Modify the following program code for getting relations by iterating through them:

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices,PLCName);
PlcUnitProvider provider = plcTarget.GetService<PlcUnitProvider>();
//assuming existing units
m_PlcUnit = provider.UnitGroup.Units[0];
PlcUnitRelationComposition unitRelations = m_PlcUnit.Relations;
foreach (PlcUnitRelation relation in unitRelations)
{
// using ‘relation’
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 661
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code for getting the relation type of a unit by the RelationType
attribute:

PlcSoftware plcTarget = 
GetControllerTargetByPLCName(Session.OpnsProject.Devices,PLCName);
PlcUnitProvider provider = plcTarget.GetService<PlcUnitProvider>();
//assuming existing units
m_PlcUnit = provider.UnitGroup.Units[0];
UnitRelationType unitRelationType = m_PlcUnit.Relations[2].RelationType;

Modify the following program code for getting the name of the related object of a unit by the
RelatedObject attribute:

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices,PLCName);


PlcUnitProvider provider = plcTarget.GetService<PlcUnitProvider>();
//assuming existing units
m_PlcUnit = provider.UnitGroup.Units[0];
string unitRelatedObjectName = m_PlcUnit.Relations[1].RelatedObject;

Modify the following program code for identifying one relation in the collection using Find with
the name of accessible element (RelatedObject):

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);


PlcUnitProvider provider = plcTarget.GetService<PlcUnitProvider>();
//assuming existing units
m_PlcUnit = provider.UnitGroup.Units[0];
PlcUnitRelation relation = m_PlcUnit.Relations.Find(unitRelatedObjectName);

See also
Connecting to the TIA Portal (Page 81)

5.12.6.5 Updating software unit properties

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to update unit properties such as Author and Comment.

Openness: API for automation of engineering workflows


662 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Update unit's author property


Modify the following program code to modify unit's author property.

//Set value
string newAuthor = "Z012345";
unit1.Author = newAuthor;
//Using SetAttributes()
string newAuthor = "Z012345";
var attrList = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("Author", newAuthor)
};
unit1.SetAttributes(attrList));
//Using SetAttribute()
string newAuthor = "Z012345";
IEngineeringObject unit = (IEngineeringObject)unit2;
unit.SetAttribute("Author", newAuthor);

Error Message
Error will occur if you try to use the wrong value, for example starts with space, or contains illegal
characters. An Recoverable Exception will be thrown with the following error message: "The
value of attribute 'Author' contains an invalid character at Position 0."

PlcUnit unit1 = unitComposition.Create("Unit1");                       


try
{    
unit1.Author = " Author";
}
catch (EngineeringTargetInvocationException e)
{   
Console.WriteLine(e.Message);
}

Program code: Update unit's comment property


You cannot set or get the unit 'Comment' property directly as it is a MultilingualText. You can
update the Comment Item's Text Property. The Comment.Item contains the cultures of the TIA
Project. It can be adjusted via value assignment. The project languages are indexed in the
Comment.Item composition, 0 marked as the first default project language. If there are more
languages set, you can iterate on it, otherwise if the culture does not exist, an
EngineeringTargetInvocationException is thrown.

//Setting the default first culture comment Item text:


unit1.Comment.Items[0].Text = "new Comment";
//Setting other culture comment Item Text:
unit1.Comment.Items[1].Text = "neuro Kommentar";

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 663
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Error Message
Error will occur if you try to use the SetAttribute, SetAttributes, GetAttribute, GetAttributes. An
EngineeringNotSupportedException will be thrown with the following error message:
"Comment is not supported by type 'Siemens.Engineering.SW.Units.PlcUnit'."

try
{
((IEngineeringObject)unit1).SetAttribute("Comment", "new comments");
}
catch (EngineeringNotSupportedException e)
{
Console.WriteLine(e.Message);
}

Error will occur if you try to refer a non existing culture. An


EngineeringTargetInvocationException will be thrown with the following error message: "The
argument 'index' (3) is outside the valid value range."

try
{
unit1.Comment.Items[3].Text = "new Comment";
}
catch (EngineeringTargetInvocationException e)
{
Console.WriteLine(e.Message)
}

See also
Connecting to the TIA Portal (Page 81)

5.12.6.6 Publishing software unit object

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get or set the "Access" attribute of the underlying objects
of units so that you can control their accessibilty between units.

Openness: API for automation of engineering workflows


664 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

The following objects are supported in Openness units:


• Program blocks and data blocks - except OBs
• PLC types
The following possible value of the Access attribute represented as enumeration
UnitAccessType:
• Published
• Unpublished

Note
The attribute ’Access’ is only available on objects located under a unit, so if it is going to be set
or get not under PlcUnit related objects a EnginneringNotSupportedException is thrown. In case
of a wrong value (e.g.invalid enum values) EngineeringTargetInvocationException is thrown.

Program code: Configuring the Access attribute of PLC blocks

//Getting attribute value with GetAttribute


...
PlcBlock block = m_PlcUnit.BlockGroup.Find("FB_1");
UnitAccessType currentAccessValue = (UnitAccessType)block.GetAttribute("Access");
...
//Getting attribute value with GetAttributes
...
PlcBlock block = m_PlcUnit.BlockGroup.Block.Find("FB_1");
List<string> attrList = new List<string>();
{
"Access"
};
IList<object> getAttributeValues = block.GetAttributes(attrList));

//Setting attribute value with SetAttribute

PlcBlock block = m_PlcUnit.BlockGroup.Blocks.Find("FB_1");
UnitAccessType newAccessValue = UnitAccessType.Published;
block.SetAttribute("Access", newAccessValue);

//Setting attribute value with SetAttributes

PlcBlock block = m_PlcUnit.BlockGroup.Blocks.Find("FB_1");
UnitAccessType newAccessValue = UnitAccessType.Published;
IList attrList = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("Access", newAccessValue),
};
block.SetAttributes(attrList);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 665
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Configuring the Access attribute of PLC types

//Getting attribute value with GetAttribute



PlcType type = m_PlcUnit.TypeGroup.Types.Find("UDT_1");
UnitAccessType currentAccessValue = (UnitAccessType)type.GetAttribute("Access");

//Getting attribute value with GetAttributes

PlcType type = m_PlcUnit.TypeGroup.Types.Find("UDT_1");
List<string> attrList = new List<string>()
{
"Access"
};
IList<object> getAttributeValues = type.GetAttributes(attrList));

//Setting attribute value with SetAttribute

PlcType type = m_PlcUnit.TypeGroup.Types.Find("UDT_1");
UnitAccessType newAccessValue = UnitAccessType.Published;
type.SetAttribute("Access", newAccessValue);

//Setting attribute value with SetAttributes

PlcType type = m_PlcUnit.TypeGroup.Types.Find("UDT_1");
UnitAccessType newAccessValue = UnitAccessType.Published;
IList attrList = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("Access", newAccessValue),
};
type.SetAttributes(attrList));

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.12.6.7 Adding external sources in units

Requirement
• The TIA Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


666 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness to add an external source under a software units. You can
add source files such as .SCL,. DB, UDT under units.
You can perform the following tasks with external source group under software units while
using Openness API :
• Adding ExternalSourceGroup under units
• Generating blocks/UDTs from an external source under software units
• Exporting source from blocks/UDTs under units

Program code: Adding an external source group


Modify the following program code to add an external source under a software unit:

PlcUnitProvider unitProvider = controllerTarget.GetService<PlcUnitProvider>();


PlcUnit newUnit = unitProvider.UnitGroup.Units.Create("Unit_1");
PlcExternalSource unitExternalSource =
newUnit.ExternalSourceGroup.ExternalSources.CreateFromFile(externalSourceFilename,
GetFilePath(externalSourceFilename));

Program code: Generating blocks/UDT from source


Modify the following program code to generate blocks\UDTs with void return types from an
external source under a software unit:

unitExternalSource.GenerateBlocksFromSource();

Modify the following program code to generate blocks\UDT with collection of blocks get
generated from an external source under a software unit:

// Blocks/UDTs gets generated only if there are no compilation errors


IList<IEngineeringObject> generatedBlocksUnderUnitList =
unitExternalSource.GenerateBlocksFromSource(GenerateBlockOption.None);
// Blocks/UDTs will be generated regardless of any compilation errors
IList<IEngineeringObject> generatedBlocksUnderUnitList =
unitExternalSource.GenerateBlocksFromSource(GenerateBlockOption.KeepOnError);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 667
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Exporting source from blocks/UDTs


Modify the following program code to generate source from blocks under a software unit:

// For blocks
PlcBlock unitPlcBlock = newUnit.BlockGroup.Blocks.Find(generatedBlockName);
// Generate source from blocks with dependencies
newUnit.ExternalSourceGroup.GenerateSource(new[] { unitPlcBlock }, new
FileInfo(outputFileGeneratedPath), GenerateOptions.WithDependencies);
// Generate source from blocks without dependencies
newUnit.ExternalSourceGroup.GenerateSource(new[] { unitPlcBlock }, new
FileInfo(outputFileGeneratedPath), GenerateOptions.None);

Modify the following program code to generate source from UDTs under a software unit:

// For UDTs
PlcType unitPlcUdt = newUnit.TypeGroup.Types.Find(generatedUdtName);
//Generate source from UDTs with dependencies
newUnit.ExternalSourceGroup.GenerateSource(new[] { unitPlcUdt }, new
FileInfo(outputFileGeneratedPath), GenerateOptions.WithDependencies);
//Generate source from UDTs without dependencies
newUnit.ExternalSourceGroup.GenerateSource(new[] { unitPlcUdt }, new
FileInfo(outputFileGeneratedPath), GenerateOptions.None);

Program code: Enumerating external source file group


Modify the following program code to enumerate through the external source file group
composition under the current unit:

PlcUnitProvider unitProvider = controllerTarget.GetService<PlcUnitProvider>();


PlcUnit newUnit = unitProvider.UnitGroup.Units.Find(textBoxAddNewUnit.Text);
PlcExternalSourceComposition unitExtSrcComposition =
newUnit.ExternalSourceGroup.ExternalSources;
foreach (PlcExternalSource unitExtSrc in unitExtSrcComposition)
{
unitExtSrc.GenerateBlocksFromSource(GenerateBlockOption.None);
}

5.12.6.8 Units as mastercopies

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• A unit is created
See Working with software unit (Page 654)

Openness: API for automation of engineering workflows


668 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Application
You can use the TIA Portal Openness to copy units as mastercopies to project library and global
library.
You can perform the following possible tasks with unit as mastercopy while using TIA Portal
Openness:
• Create unit as mastercopy in project library from software units
• Create unit as mastercopy in global library from software units
• Recreate unit from mastercopy of project library to software units in PNV.
• Recreate unit from mastercopy of global library to software units in PNV

Program code
Modify the following program code to create new unit as mastercopy in project library from
software units using MasterCopyComposition:

PlcUnitProvider m_UnitProvider = plc.GetService<PlcUnitProvider>();


PlcUnitComposition m_UnitComposition = m_UnitProvider.UnitGroup.Units;
PlcUnit m_SoftwareUnit1 = unitComposition.Create("Unit_1");//Assuming existing units
IMasterCopySource m_UnitAsMasterCopy = (IMasterCopySource)m_SoftwareUnit1;//Assuming that
m_SoftwareUnit1 is present in the PLC
m_ProjectLibrary.MasterCopyFolder.MasterCopies.Create(m_UnitAsMasterCopy);

Modify the following program code to create unit as mastercopy in global library from software
units:

...
IMasterCopySource m_UnitAsMasterCopy = (IMasterCopySource)m_SoftwareUnit1;//Assuming that
m_SoftwareUnit1 is present in the PLC
m_TiaPortal.GlobalLibraries.Open(libfile, OpenMode.ReadWrite);
GlobalLibrary m_GlobalLibrary = m_TiaPortal.GlobalLibraries[0];
m_GlobalLibrary.MasterCopyFolder.MasterCopies.Create(m_UnitAsMasterCopy)
...

Error will occur if you try to create a new unit in read-only global library. A recoverable exception
will be thrown with the message "Cannot write to read-only libraries".

m_TiaPortal.GlobalLibraries.Open(libfile, OpenMode.ReadOnly);
GlobalLibrary m_GlobalLibrary = m_TiaPortal.GlobalLibraries[0];
try
{
m_GlobalLibrary.MasterCopyFolder.MasterCopies.Create(m_UnitAsMasterCopy);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 669
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to recreate a unit from mastercopy of project library to
software units in PNV:

...
ProjectLibrary m_ProjectLibrary = project.ProjectLibrary;
PlcUnitProvider m_UnitProvider = plc.GetService<PlcUnitProvider>();
PlcUnitComposition m_UnitComposition = m_UnitProvider.UnitGroup.Units;
...
MasterCopy mc_Unit_2 = m_ProjectLibrary.MasterCopyFolder.MasterCopies.Find("Unit_2");
m_UnitComposition.CreateFrom(mc_Unit_2);//Recreate a Unit from Project Library to
SoftwareUnits folder

Modify the following program code to recreate unit from mastercopy of global library to
software units in PNV.

...
GlobalLibrary m_GlobalLibrary = m_TiaPortal.GlobalLibraries[0];
...
mc_Unit_2 = m_GlobalLibrary.MasterCopyFolder.MasterCopies.Find("Unit_2");
m_UnitComposition.CreateFrom(mc_Unit_2);//Recreate a unit from Global Library to
SoftwareUnits folder

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Working with software unit (Page 654)

5.12.6.9 Updating existing relations & create/delete relations

Requirement
• The TIA Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to modify the relations of a PLC units so that you can control
the accessibility of objects existing in other PLC units or outside PLC units.
You can perform the following possible types of modification using TIA Portal Openness:
• Creating new relations
• Deleting existing relations
• Modifying existing relations

Openness: API for automation of engineering workflows


670 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Creating new relations


You can create a new relations by providing the appropriate relation type and the name of the
related object.

private PlcUnitRelation m_SoftwareUnitRelation;


private PlcUnitRelation m_NonUnitDBRelation;
private PlcUnitRelation m_TODBRelation;
...
PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);
PlcUnitProvider plcUnitProvider = plcTarget.GetService<PlcUnitProvider>();
m_PlcUnit = plcUnitProvider.UnitGroup.Units[0]; //assuming existing units

Modify the following program code to create a new relation accessing object in another Plc units:

...
//assuming Plc unit "Unit_2" is already existing in the Plc
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create("Unit_2",
UnitRelationType.SoftwareUnit);
...

Modify the following program code to create a new relation accessing PLC data block outside of
Plc units:

...
//assuming Plc data block "Data_block_1" is already existing in the Plc
m_NonUnitDBRelation = m_PlcUnit.Relations.Create("Data_block_1",
UnitRelationType.NonUnitDB);
...

Modify the following program code to create a new relation accessing a Technological object
outside of Plc units:

...
//assuming Technological object "SpeedAxis_1" is already existing in the Plc
m_TODBRelation = m_PlcUnit.Relations.Create("SpeedAxis_1", UnitRelationType.TODB);
...

Possible Error cases for creating a new relation:


Modify the following program code to create new relation accessing non existing related object:

...
//assuming Plc unit "NonExistingUnit" is not existing in the Plc yet
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create("NonExistingUnit", UnitRelationType.
SoftwareUnit);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 671
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Note
In the above program code, the relation is created and no exception is thrown.

Modify the following program code to create a new relation by specifying a name for the related
object which is not conform with the TIA naming rules:

...
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create(" Unit_2",
UnitRelationType.SoftwareUnit);
...

Note
In the above program code, the relation is not created and a recoverable exception is thrown due
to leading spaces.

Modify the following program code to create a new relation from unit to itself:

...
//assuming m_PlcUnit is assigned to Plc unit "Unit_1"
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create("Unit_1",
UnitRelationType.SoftwareUnit);
...

Modify the following program code to create a new relation which is duplicate of another
already existing relation with the same relation type and related object:

...
//assuming a relation with the same relation type and related object is already existing
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create("Unit_2",
UnitRelationType.SoftwareUnit);
...

Modify the following program code to create a new relation by specifying an empty string for the
name of the related object:

...
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create(string.Empty,
UnitRelationType.SoftwareUnit);
...

Note
In all of the above program codes for error scenarios, the relation is not created and a recoverable
exception is thrown.

Openness: API for automation of engineering workflows


672 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Program code: Delete existing relations


You can create a new relations by providing the appropriate relation type and the name of the
related object.

private PlcUnitRelation m_SoftwareUnitRelation;


private PlcUnitRelation m_NonUnitDBRelation;
private PlcUnitRelation m_TODBRelation;
...
PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);
PlcUnitProvider plcUnitProvider = plcTarget.GetService<PlcUnitProvider>();
m_PlcUnit = plcUnitProvider.UnitGroup.Units[0]; //assuming existing units
m_PlcUnit2 = plcUnitProvider.UnitGroup.Units[1]; //assuming existing units
m_SoftwareUnitRelation = m_PlcUnit.Relations.Create("Unit_2",
UnitRelationType.SoftwareUnit);
m_NonUnitDBRelation = m_PlcUnit.Relations.Create("DB_Global", UnitRelationType.NonUnitDB);
m_TODBRelation = m_PlcUnit.Relations.Create("Axis_TO", UnitRelationType.TODB);

You can delete the relations in several ways.


Modify the following program code to delete the relation accessed by indexer:

...
m_PlcUnit.Relations[0].Delete();
...

Modify the following program code to delete the relation directly:

...
m_SoftwareUnitRelation.Delete();
...

Program code: Modify existing relations


You can modify the relations in several ways:
You can create a new relations by providing the appropriate relation type and the name of the
related object.

private PlcUnitRelation m_Relation;
PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);
PlcUnitProvider plcUnitProvider = plcTarget.GetService<PlcUnitProvider>();
m_PlcUnit = plcUnitProvider.UnitGroup.Units[0];
//assuming existing units
m_PlcUnit2 = plcUnitProvider.UnitGroup.Units[1];
//assuming existing units
m_Relation = m_PlcUnit.Relations.Create("Unit_2", UnitRelationType.SoftwareUnit);
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 673
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to update the name of the related object by assigning a new
value for the RelatedObject attribute directly:

...
m_Relation.RelatedObject = "Unit_3";
...

Modify the following program code to update the name of the related object by assigning a new
value for the RelatedObject attribute through SetAttribute:

...
m_Relation.SetAttribute("RelatedObject", "Unit_4");
...

Modify the following program code to update the name of the related object by assigning a new
value for the RelatedObject attribute through SetAttributes:

...
IList attrList = new List<KeyValuePair<string, object>>();
{
new KeyValuePair<string, object("RelatedObject", "Unit_4")
};
m_Relation.SetAttributes(attrList);
...

Possible error cases for modifying existing relations


Modify the following program code to update a relation to access a non existing related object:

...
//assuming Plc unit "NonExistingUnit" is not existing in the Plc yet
m_Relation.RelatedObject = "NonExistingUnit";
...

Note
In the above program code, the relation is modified and no exception is thrown.

Modify the following program code to update a relation by specifying a name for the related
object which is not confirm with the TIA naming rules:

...
m_Relation.RelatedObject = " Unit_2";
...

Openness: API for automation of engineering workflows


674 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.12 Functions for accessing the data of a PLC device

Modify the following program code to update a relation to access itself:

...
//assuming m_Relation is defined under Plc unit "Unit_1"
m_Relation.RelatedObject = "Unit_1";
...

Note
In the above program code, the relation is not modified and a recoverable exception is thrown.

Modify the following program code to update a relation in a way which would be a duplicate of
another already existing with the same relation type and related object:

...
//assuming a relation with the same relation type and related object is already existing
m_Relation.RelatedObject = "Unit_2";
...

Modify the following program code to update a relation by specifying an empty string for the
name of the related object:

...
m_Relation.RelatedObject = string.Empty;
...

Note
In all of the above program codes for errors scenarios, the relation is not modified and a
recoverable exception is thrown.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 675
TIA Portal Openness API
5.13 Functions for Version Control Interface

5.13 Functions for Version Control Interface

5.13.1 Accessing VCI system group in project

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to navigate to the VCI system group from the project by
accessing a VersionControlInterface from the project as a service. The VersionControlInterface
itself is always a service and will return non-null object.

Program code
Modify the following program code to retrieve the workspace system group from the
VersionControlInterface:

Siemens.Engineering.Project project = tiaPortal.Projects[0];


Siemens.Engineering.VersionControl.VersionControlInterface versionControlInterface =
project.GetService<VersionControlInterface>();
Siemens.Engineering.VersionControl.WorkspaceSystemGroup workspaceSystemGroup =
versionControlInterface.WorkspaceGroup;;

See also
Opening a project (Page 113)
Connecting to the TIA Portal (Page 81)

5.13.2 Enumerating user groups in VCI group

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


676 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

Program code
Modify the following program code to enumerate all VCI workspace user groups in other VCI
workspace groups.

WorkspaceUserGroupComposition userGroupComposition = workspaceGroup.Groups;


foreach (Siemens.Engineering.VersionControl.WorkspaceUserGroup workspaceUserGroup in
userGroupComposition)
{
//...
}

Modify the following program code to access individual workspace user group in other VCI
workspace groups:

Siemens.Engineering.VersionControl.WorkspaceUserGroup workspaceUserGroup =
workspaceGroup.Groups.Find("Some Group Name");

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.3 Creating VCI user group in VCI group

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to create a workspace user group in a workspace group.

Program code
Modify the following program code to create a workspace user group:

VersionControlInterface versionControlInterface =
project.GetService<VersionControlInterface>();
WorkspaceSystemGroup workspaceGroupComposition =
versionControlInterface.WorkspaceGroup.Groups;
WorkspaceUserGroup result = workspaceGroupComposition.Create("NewWorkspaceUserGroup");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 677
TIA Portal Openness API
5.13 Functions for Version Control Interface

Note
To create a new workspace user group by name requires that supplied name should be valid and
the supplied name does not already exist on another workspace user group

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.4 Updating VCI group properties

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to update the properties of workspace user group.
The followiing property is available to update on a workspace group:

Property Name Return Type Description Accessibility


Name System.String The name of the work‐ Read/Write
space user group

Program code
Modify the following program code to update workspace user group name:

var workspaceUserGroup = ...;


workspaceUserGroup.Name = "New_Group_Name";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


678 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

5.13.5 Deleting VCI user group

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to delete workspace user groups. When you are deleting
workspace user groups, all other objects contained in the workspace user group will also get
deleted. This includes other workspace user groups and VCI workspaces.

Program code
Modify the following program code to delete a workspace user group:

WorkspaceUserGroup workspaceUserGroup = ...;


workspaceUserGroup.Delete();

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.6 Enumerating VCI workspaces in VCI group

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 679
TIA Portal Openness API
5.13 Functions for Version Control Interface

Program code
Modify the followng program code to enumerate all VCI workspaces in a VCI group:

WorkspaceComposition workspaceComposition = workspaceSystemGroup.Workspaces;


foreach (Siemens.Engineering.VersionControl.Workspace workspace in workspaceComposition)
{
//...
}

Modify the following program code to find specific workspace by name:

Siemens.Engineering.VersionControl.Workspace workspace =
workspaceUserGroup.Workspaces.Find("SomeWorkspaceName");

See also
Connecting to the TIA Portal (Page 81)

5.13.7 Creating VCI workspace in VCI group

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to create a workspace in a workspace user group.
You can create Siemens.Engineering.VersionControl.Workspace with the create action:
Siemens.Engineering.VersionControl.WorkspaceComposition.Create(strin
g name)

Openness: API for automation of engineering workflows


680 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

Program code
Modify the following program code to create a workspace:

VersionControlInterface versionControlInterface =
project.GetService<VersionControlInterface>();
WorkspaceComposition workspaceComposition =
versionControlInterface.WorkspaceGroup.Workspaces;
Workspace result = workspaceComposition.Create("NewWorkspace");

Note
To create a new workspace by name requires that supplied name should be valid and the name
does not already exist on another workspace user group.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.8 Updating VCI workspace properties

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to update the properties of a VCI workspace.
The following properties are available to update on a workspace:

Property name Return type Description Accessibility


Name System.String The name of the work‐ Read/Write
space.
RootPath System.IO.DirectoryInfo The configured work‐ Read/Write
space path.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 681
TIA Portal Openness API
5.13 Functions for Version Control Interface

Program code: Updating name property


Modify the following program code to update the 'Name' property on workspace:

var workspace = ...;


workspace.Name = "New_Workspace_Name";

Program code: Updating rootpath property


Modify the following program code to configure the workspace path to a rooted directory info.
Setting this value to null will unconfigure the workspaces root path.

var workspace = ...;


workspace.RootPath = new DirectoryInfo(@"D:\Project_WS");

Modify the following program code to unconfigure a workspace:

var workspace = ...;


workspace.RootPath = null;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.9 Deleting VCI workspace

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to delete a workspace. When a workspace is deleted all of
the workspace's mappings get also deleted.

Openness: API for automation of engineering workflows


682 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

Program code
Modify the following program code to delete workspace:

Workspace workspace = ...;


workspace.Delete();

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.10 Enumerating VCI workspace mappings in VCI

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to enumerate all VCI workspace mappings in a workspace:

var workspace = ...;


WorkspaceMappingComposition mappings = workspace.Mappings;
foreach (Siemens.Engineering.VersionControl.WorkspaceMapping workspaceMapping in mappings)
{
//...
}

Modify the following program code to access individual workspace mapping for the specific
engineering object:

var workspace = ...;


IEngineeringObject versionControlSupportedEngineeringObject = ...;
Siemens.Engineering.VersionControl.WorkspaceMapping workspaceMapping =
workspace.Mappings.Find(versionControlSupportedEngineeringObject);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 683
TIA Portal Openness API
5.13 Functions for Version Control Interface

5.13.11 Creating VCI workspace mapping in VCI workspace

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to create a workspace mapping in VCI workspace.
You can create Siemens.Engineering.VersionControl.WorkspaceMapping with the create action
signature:
Siemens.Engineering.VersionControl.WorkspaceMappingComposition.Creat
e(string relativeWorkspacePath, IEngineeringObject
linkedProjectObject)

Program code
Modify the following code to create a workspace mapping:

var workspace = ...;


var plcBlock = ...;
var result = workspace.Mappings.Create(@"\TestCopy\Block_1.xml", plcBlock);

Recoverable Exception will be thrown in case of :


• The linked object is not a valid VCI supported object
• The linked object is already mapped.
• The relative file path contains invalid file characters.
• The relative file path contains parent directory navigation.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


684 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

5.13.12 Updating VCI workspace mapping properties

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Openness Portal to update the properties of a VCI workspace mapping.
The following properties are available on a workspace mapping.

Property name Return type Description Accessibility


RelativeWorkspacePath System.String The relative file path to the Read/write
linked objects representation in
source control.
LinkedProjectObject IEngineeringObject The engineering object compat‐ Read
ible with VCI that is linked to the
file in source control

Program code
Modify the following program code to update the workspace mapping relative file path:

var workspaceMapping = ...;


workspaceMapping.RelativeWorkspacePath = @"\Test\NewBlock_1.xml";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.13.13 Deleting VCI workspace mapping

Requirement
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 685
TIA Portal Openness API
5.13 Functions for Version Control Interface

Principle
You can use the TIA Portal Openness to delete a VCI workspace mapping.

Program code
Modify the following program code to delete a VCI workspace mapping:

WorkspaceMapping workspaceMapping = ...;


workspaceMapping.Delete();

See also
Connecting to the TIA Portal (Page 81)

5.13.14 Synchronizing a workspace mapping

Principle
• The Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to view the status of synchronization workspace mapping.

Program code: Individual Object Synchronization status


You can view status, update status and synchronize status of individual objects you must first
request for
Siemens.Engineering.VersionControl.WorkspaceMapping.IndividualObjectSynchronizationSta
tus from workspace mapping as work

Openness: API for automation of engineering workflows


686 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

It is recommended to perform a null check before invoking the actions on individual object
synchronization service as that mapping may or may not support individual object
synchronization.

var individualObjectSynchronizationStatus =
workpaceMapping.GetService<IndividualObjectSynchronizationStatus>();
if(individualObjectSynchronizationStatus != null);
{
//GetStatus()...
//UpdateStatus()..
//Synchronize()..
}

Program code: Get Status


You can view the synchronization status of inidividual object by using the action
Siemens.Engineering.VersionControl.IndividualObjectSynchronizationStatus.GetStatus()
which returns Siemens.Engineering.VersionControl.IndividualObjectCompareResult.
The IndividualObjectCompareResult object is used to inform about the current sync status.

public class IndividualObjectCompareResult


{
CompareState CompareState { get; }
IndividualObjectCompareDetails {get; }
}

The IndividualObjectCompareDetails flag enum is used to inform you about which part of the
workspace mapping has changed (or both). This value will be None when the
CompareState is Equal. If CompareState is unequal, this enum can have a value of
ProjectObjectChanged or WorkspaceFileChanged or both ProjectObjectChanged,
WorkspaceFileChanged.

[Flags]public enum IndividualObjectCompareDetails


{
None = 0,
ProjectObjectChanged = 1,
WorkspaceFileChanged = 2
}

The CompareState enum is used to inform if an object has any changes.

public enum CompareState


{
Equal,
Unequal,
WorkspaceFileMissing,
Unknown
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 687
TIA Portal Openness API
5.13 Functions for Version Control Interface

Modify the following program code to get the status of a workspace mapping:

var workspaceMapping = ...;


var individualObjectSynchronizationStatus =
workpaceMapping.GetService<IndividualObjectSynchronizationStatus>();
if(individualObjectSynchronizationStatus != null)
{
var compareResult = individualObjectSynchronizationStatus.GetStatus();
//when compareState is unequal
{
if(compareResult.CompareState == CompareState.Unequal)
{
if(compareResult.IndividualObjectCompareDetails ==
IndividualObjectCompareDetails.WorkspaceFileChanged)
{
//Workspace file has changed
}
elseif(compareResult.IndividualObjectCompareDetails ==
(IndividualObjectCompareDetails.ProjectObjectChanged |
IndividualObjectCompareDetails.WorkspaceFileChanged))
{
//Both project object and workspace file has changed
}
}
}

Program code: Updating synchronization status


You can force the system to perform a live comparison between the currently linked project
object and workspace file. This can result in a modification to sync status to reflect the current
state of the system, and can be used to determine the status of a recently linked (but not
synchronized) mapping without modifying either the existing project object or workspace file.
Modify the following program code to update the status of a workspace mapping:

var workspaceMapping = ...;


var individualObjectSynchronizationStatus =
workpaceMapping.GetService<IndividualObjectSynchronizationStatus>();
if(individualObjectSynchronizationStatus != Null)
{
individualObjectSynchronizationStatus.UpdateStatus();
}

Program code: Synchronizing workspace


You can force the system to perform a live comparison between the currently linked project
object and workspace file. This can result in a modification to sync status to reflect the current
state of the system, and can be used to determine the status of a recently linked (but not
synchronized) mapping without modifying either the existing project object or workspace file.

Openness: API for automation of engineering workflows


688 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.13 Functions for Version Control Interface

The SynchronizationMode enum is used to inform the system which direction to perform the
sync:

public enum SynchronizationMode


{
ProjectToWorkspace,
WorkspaceToProject
}

This action will attempt to sync the linked project object to/from the linked workspace file object.
Modify the following program code to synchronize a workspace:

var workspaceMapping = ...;


var individualObjectSynchronizationStatus =
workpaceMapping.GetService<IndividualObjectSynchronizationStatus>();
if(individualObjectSynchronizationStatus != null)
{
individualObjectSynchronizationStatus.Synchronize(SynchronizationMode.ProjectToWorkspace);
}

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 689
TIA Portal Openness API
5.14 Functions support for Multiuser

5.14 Functions support for Multiuser

5.14.1 Creating project server connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to create a new project server connection entry in the TIA
Portal settings.
The following method and parameter can be accessed using TIA Portal Openness:

Return Type Methods Parameters


ProjectServer Create string alias, Protocol protocol,
string hostname, int port

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
Protocol protocol = Protocol.Https;
//Protocol protocol = Protocol.Http;
string hostName = "localhost";
uint port = 16000;
ProjectServer projectServer = tiaPortal.ProjectServers.Create(alias, protocol, hostName,
port);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


690 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

5.14.2 Editing project server connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to edit an existing project server connection in the TIA Portal
settings. You can edit protocol, hostname, and port parameters.
The following method and parameter can be accessed using TIA Portal Openness:

Return Type Methods Parameters


void SetProtocol Protocol protocol
void SetHostName string hostname
void SetPort int port

Note
If alias name has to be modified, then the project server connection entry has to be deleted and
a new connection has to be created.

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
projectServer.SetProtocol(Protocol.Http);
projectServer.SetHostName("RemoteMachineHostName");
projectServer.SetPort(17000);
:

See also
Opening a project (Page 113)
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 691
TIA Portal Openness API
5.14 Functions support for Multiuser

5.14.3 Deleting project server connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to delete the project server connection entry from TIA Portal
settings.
The following method and parameter can be accessed using TIA Portal Openness:

Return Type Methods Parameters


void DeleteConnection -

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
projectServer.DeleteConnection();
:

See also
Opening a project (Page 113)

5.14.4 Getting project server connection from TIA Portal Setting

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


692 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Application
You can use the TIA Portal Openness to access connections to the project server from TIA Portal
Settings. The Openness API will position the connections to the project server as direct navigator
of TiaPortal. Connection to the project server are aggregated using the "ProjectServers"
composition of the TiaPortal.
Each instance of ProjectServer represents project server connection configuration. Using the
instance of ProjectServer retrieved from "ProjectServers" composition, you can comfortably
work with the TIA Project server.
Any functionality which involves Multiuser server interactions without opening a local session
can be invoked using this navigator and ProjectServers will be available all the time.
The local windows user will be used to authenticate with the MU Server.

Program code
The behavior is invoked with the following code

...
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
...

The project server has “ServerName” property, referred to the "alias" assigned as the name for the
project server is used as an identifier.
You can use the below code example to access ProjectServer related properties:

ProjectServer projectServer = ...;


string ServerName = projectServer.ServerName;
string host = projectServer.Host;
int portNumber = projectServer.Port;

For example,if full URL of server is "net.tcp://localhost:9876/" the projectServer.Host returns


"net.tcp://localhost/" and projectServer.Port returns 9876.

5.14.5 Adding a project to server

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 693
TIA Portal Openness API
5.14 Functions support for Multiuser

Application
You can use the TIA Portal Openness to add a single-user project to multiuser server. If the
project that is getting added is already opened, then it will be closed.
The following method and parameter name can be accessed using TIA Portal Openness:

Return type Method name Parameter name


void AddProjectToServer FileInfo projectFileInfo

Note
For all APIs the local windows user who is running the Openness application/script will be used
to authenticate with the MU Server. So please ensure that the user is added to the MU server and
with the required role for the intended operation. If the user is not authenticated then an
exception will be thrown.

Program code
Modify the following program code to add a single user project to multiuser server:

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
FileInfo projectFileInfo = new FileInfo("C:\\Projects\\Project1\\Project1.ap17");
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
projectServer.AddProjectToServer(projectFileInfo);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.6 Getting server projects

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A Project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


694 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Application
You can use the TIA Portal Openness application to get a list of available server projects info on
the project server. You can use this info to perform operations such as:
• Retrieve list of local session info for a specific server project
• Create a local session for a specific server project
The following method and parameter can be accessed using TIA Portal Openness:

Return type Method name


IEnumerable<ServerProjectInfo> GetServerProjects

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects()
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.7 Getting available local sessions

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get a list of avalable session information for a given server
project in the current machine created by the current user.
You can this info to perform further operations such as opening or deleting the local session.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 695
TIA Portal Openness API
5.14 Functions support for Multiuser

The following parameter and method can be accessing using TIA Portal Openness.

Return Type Method name Parameters


IEnumerable<ServerProjectInfo> GetLocalSessions ServerProjectInfo serverProjec‐
tInfo

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
IEnumerable<LocalSessionInfo> localSessionsInfo =
projectServer.GetLocalSessions(serverProjectsInfo[0]);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.8 Creating a local session

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is opening
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to create a local session for a given server project and return
the LocalSessionInfo object.
The type of session Multiuser local session or Exclusive local session can be specified in TIA Portal
Openness. In case the session created is Exclusive local session, then the Server project is
automatically locked.

Openness: API for automation of engineering workflows


696 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

The following method and parameter name can be accessed using TIA Portal Openness:

Return Type Method name Parameters


LocalSessionInfo CreateLocalSession ServerProjectInfo serverProjectInfo,
string localSessionName, DirectoryInfo
localSessionPath, SessionCreationMode
mode

Program code

TiaPortal tiaPortal = new TiaPortal();


string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo, SessionCreationMode.Multiuser);
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo, SessionCreationMode.Exclusive);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.9 Saving a local session

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to save the given session. The session would be saved only
if its of type:
• Engineering session
• Exclusive session
A MultiuserException will be thrown if the session is a server project.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 697
TIA Portal Openness API
5.14 Functions support for Multiuser

The following method can be accessed using TIA Portal Openness:

Return type Method name Parameter


void Save -

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
LocalSession localSession = TiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
//Edit project
localSession.Save();
:

5.14.10 Deleting local session from server

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to delete a given local session. The session will be deleted
from the multiuser server only and the session files in the local disk will not be deleted.
In case the session specified is an Exclusive session then the Server project lock is automatically
removed.
The following method and parameter name can be accessed using the TIA Portal Openness:

Return Type Method name Parameters


void DeleteLocalSessionFromServer ServerProjectInfo serverProjectInfo, Lo‐
calSessionInfo localsessioninfo

Openness: API for automation of engineering workflows


698 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
projectServer.DeleteLocalSessionFromServer(serverProjectInfo, localSessionInfo);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.11 Opening local/exclusive session

Requirement
• The TIA Portal Openness is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to open a multiuser local session or exclusive local session
for a given server project and given local session fileinfo and return the LocalSession object of
type engineering session or exclusive session.
In case the session opened is an Exclusive session the Server project is automatically locked.
The following method name and parameters can be accessed using TIA Portal Openness:

Return Type Method Name Parameters


LocalSession Open FileInfo localSessionPath

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 699
TIA Portal Openness API
5.14 Functions support for Multiuser

Program code
Modify the following program code to open Engineering Session:

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
LocalSession multiuserLocalSession =
tiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
:

Modify the following program code to open Exclusive Session:

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo, SessionCreationMode.Exclusive);
LocalSession exclusiveSession =
tiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.12 Opening server project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


700 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Application
You can use the TIA Portal Openness to open a server project for a given local session fileinfo and
returns the LocalSession object of type server project.
The following parameter and method can be accessed using TIA Portal Openness:

Return type Method name Parameters


LocalSession OpenServerProject FileInfo localSessionPath

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
LocalSession serverProject =
tiaPortal.LocalSessions.OpenServerProject(localSessionInfo.ProjectFileInfo);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.13 Checking marked objects

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 701
TIA Portal Openness API
5.14 Functions support for Multiuser

Application
You can use the TIA Portal Openness to provide information if the given EngineeringObject is
markable. The TIA Portal Openness also provides marking related information like
• If the object is marked by the current user
• If the object marked by other users
• If the object is up to date
You can also use TIA Portal Openness to get the mark state information of an available
EngineeringObject.
The following method and parameter name can be accessed using TIA Portal Openness:

Return type Method name Parameters


MarkStateInfo GetMarkStateInfo IEngineeringObject engineerin‐
gObject

Program code

//Open a local session or a server project


//Add a block or edit an block of type IEngineeringObject
MarkStateInfo markStateInfo = localSession.MarkingService.GetMarkStateInfo(muBlock);
if (markStateInfo.IsMarkable)
{
// The object is markable
// Now we can check the markstate for more information
if (markStateInfo.MarkState.HasFlag(MarkState.IsUptoDate))
{
// You have the latest object
}
if (markStateInfo.MarkState.HasFlag(MarkState.IsMarkedByMe))
{
// You have the marked the object
}
if (markStateInfo.MarkState.HasFlag(MarkState.IsMarkedByOthers))
{
// Some other user has marked the object
}
//Example for Checkin without conflicts
if (markStateInfo.MarkState.HasFlag(MarkState.IsUptoDate) &&
markStateInfo.MarkState.HasFlag(MarkState.IsMarkedByMe) && !
markStateInfo.MarkState.HasFlag(MarkState.IsMarkedByOthers))
{
// You have the latest object, the object is marked by me and no one else has marked the
object
}
}
else
{
// The object is not markable. Open server project and make changes, then commit.
}

Openness: API for automation of engineering workflows


702 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.14 Closing local session

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to close operation on server project or multiuser session or
exclusive session.
It will discard all pending changes.
The following method can be accessed using TIA Portal Openness:

Return type Method name Parameter


void Close -

Program code
Modify the following program code to close server project:

TiaPortal tiaPortal = new TiaPortal();


string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
LocalSession serverProject =
tiaPortal.LocalSessions.OpenServerProject(localSessionInfo.ProjectFileInfo);
serverProject.Close();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 703
TIA Portal Openness API
5.14 Functions support for Multiuser

Modify the following program code to close exclusive session:

TiaPortal tiaPortal = new TiaPortal();


string aliasName = "serverAliasName";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "ProjectServer1";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo, SessionCreationMode.Exclusive);
LocalSession exclusiveSession =
tiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
exclusiveSession.Close();

Modify the following program code to close Engineering Session:

TiaPortal tiaPortal = new TiaPortal();


string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
LocalSession multiuserLocalSession =
tiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
multiuserLocalSession.Close();

5.14.15 Commiting server project changes

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to perform a save operation on changes done in Server
project or exclusive session.
The following method name and parameter can be accessed using TIA Portal Openness:

Return type Method name Parameters


int CloseAndCommit stringComment

Openness: API for automation of engineering workflows


704 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Program code
Modify the following program to save server project changes:

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo);
LocalSession serverProject =
tiaPortal.LocalSessions.OpenServerProject(localSessionInfo.ProjectFileInfo);
int revisionCreated = serverProject.CloseAndCommit(comment: "Comment");
:

Modify the following program code to save Exclusive Session changes:

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo, SessionCreationMode.ExclusiveSession);
LocalSession exclusiveSession =
tiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
int revisionCreated = exclusiveSession.CloseAndCommit(comment: "Comment");
:

See also
Opening a project (Page 113)

5.14.16 Getting lockstate provider

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 705
TIA Portal Openness API
5.14 Functions support for Multiuser

Application
You can use the TIA Portal Openness to return LockStateProvider that can be used to get
information about Server project lock and the lock owner.
The following method and parameter name can be accessed using TIA Portal Openness:

Return Type Method name Parameters


LockStateProvider GetLockStateProvider ServerProjectInfo serverProjectInfo

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
LockStateProvider lockStateProvider =
projectServer.GetLockStateProvider(serverProjectInfo[0]);
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.17 Checking project locked

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to return that server project is locked or not. It gets the real
time value by contacting the server.
The following method name can be accessed using TIA Portal Openness:

Return Type Method name


bool IsProjectLocked

Openness: API for automation of engineering workflows


706 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Program code

:
TiaPortal tiaPortal = new TiaPortal();
string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
LockStateProvider lockStateProvider =
projectServer.GetLockStateProvider(serverProjectInfo[0]);
bool isServerProjectLocked = lockStateProvider.IsProjectLocked();
:

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.18 Getting lock owner

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to return the information about the server project lock
owner as string. If the project is not locked empty string will be returned.
The following method name can be accessed using TIA Portal Openness:

Return type Method name


string GetLockOwner

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 707
TIA Portal Openness API
5.14 Functions support for Multiuser

Program code

TiaPortal tiaPortal = new TiaPortal();


string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
LockStateProvider lockStateProvider =
projectServer.GetLockStateProvider(serverProjectInfo[0]);
string lockOwner= lockStateProvider.GetLockOwner();

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.19 Checking session UptoDate

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Introduction
You can use the TIA Portal Openness to return a session is up-to-date or not.
Th following method name can be accesed using TIA Portal Openness:

Return type Method name


bool IsUptoDate

Openness: API for automation of engineering workflows


708 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.14 Functions support for Multiuser

Program code

TiaPortal tiaPortal = new TiaPortal();


string aliasName = "ProjectServer1";
ProjectServer projectServer =
tiaPortal.ProjectServers.First(a=>a.ServerName.Equals(aliasName));
IEnumerable<ServerProjectInfo> serverProjectInfo = projectServer.GetServerProjects();
string localSessionName = "testLocalSessionName";
DirectoryInfo directoryInfo = new DirectoryInfo("C:\\Sessions");
LocalSessionInfo localSessionInfo = projectServer.CreateLocalSession(serverProjectInfo[0],
localSessionName, directoryInfo, SessionCreationMode.Exclusive);
LocalSession multiuserLocalSession =
tiaPortal.LocalSessions.Open(localSessionInfo.ProjectFileInfo);
bool isUptoDate = multiuserLocalSession.IsUptoDate();

Note
In the above progam code, You have to specify sessionmode either "multiuser" or "exclusive".

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.14.20 Getting markings from local session

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to retrieve all the markings (conflicted, non-conflicted) with
in the local session.
The TIA Portal Openness can be used to retrieve the online/real-time information from the
multiuser server.
The following method can be accessed using TIA Portal Openness:

Method name Return Type


GetMarkings Markings

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 709
TIA Portal Openness API
5.14 Functions support for Multiuser

The following property name can be accessed using TIA Portal Openness:

Custom Type Property name Return Type


Markings AllMarkings MarkingComposition
Markings ConflictedMarkings MarkingComposition
Marking MarkedObject IEngineeringObject
Marking MarkState MarkState

The TIA Portal Openness API does not return markings on objects which got deleted as openness
framework cannot represent deleted objects.

Note
Conflicted markings means markings that are marked by you and others or marked by you and
outdated or marked by you,marked by others and outdated.

Program code

//Open a local session or a server project


//All the non deleted object markings from the session will be retrieved.
Markings markings = localSession.MarkingService.GetMarkings();
MarkingComposition allMarkings = markings.AllMarkings;
foreach (Marking marking in allMarkings)
{
IEngineeringObject markedObject = marking.MarkedObject;
MarkState markState = marking.MarkState;
}
//All the non deleted marked objects which are conflicted.
MarkingComposition conflictedMarkings = markings.ConflictedMarkings;

See also
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


710 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15 Functions for accessing data of the user management

5.15.1 Functions for accessing user, roles and function rights

5.15.1.1 Protecting Project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness application to protect the TIA Portal project. On Calling this
API, project will be protected and a default Admin User created.
The Protection of a TIA Portal Project will fail under given condition:
• Protecting a previously protected project
• Meta configuration do not exists for at-least one UmacDevice in the project
• Validation fails for provided parameters
If the project protection API call fails, then EngineeringTargetInvocationException will be thrown
to you.

Program code

TiaPortal tiaPortal = new TiaPortal();


Project tiaProject = tiaPortal.Projects[0];
tiaProject.ProtectProject("AdminUser", ToSecureSting("Admin123"));

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 711
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.1.2 Engineering Function Rights

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness application to retrieve the following information related to
Engineering function rights:
• Retrieve all Engineering Function Rights present in a TIA Portal Project
• Retrieve a particular Engineering Functions right by Identifier
For Engineering Function Right, Name property value will be based on user interface language.
But Identifier property value will be always constant irrespective of user interface language.
For "Find" API Identier property value should be used.

Program code

tiaProject.ProtectProject("Admin123", ToSecureSting("Admin123"));
UmacConfigurator UmacConfiguratorService = project.GetService<UmacConfigurator>();
//Retrieving Engineering function Rights. Returned list will be empty if called in non-
protected mode
var engineeringFunctionRights = UmacConfiguratorService.EngineeringFunctionRights;
string engineeringFunctionRightIdentifier;
string engineeringFunctionRightName;
//Iterating through Engineering function Rights
foreach (var engineeringFunctionRight in engineeringFunctionRights)
{
engineeringFunctionRightName = engineeringFunctionRight.Name;
engineeringFunctionRightIdentifier = engineeringFunctionRight.Identifier;
}
//Find an Engineering Function Right
var foundEngineeringFunctionRight =
engineeringFunctionRights.Find(engineeringFunctionRightIdentifier);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


712 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.1.3 Device Function Righhts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
In TIA Portal Openness, Device Function rights are of two types:
• System Device Function Rights
• Custom Device Function Rights
You can use the TIA Portal Openness application to retrieve available device function rights:
• Retrieve all Device Function Rights associated to a device instance. (System and Custom)
• Retrieve all Custom Device Function Rights in the project.
• Create a Custom Device Function Right in the project.
• Retrieve a Custom Device Function Right by Identifier

Note
Creating a Custom Device Function Right will result in throwing
EngineeringTargetInvocationException.

Given Below are some scenarios where Creating a Custom Device Function Right might fail:
• Maximum custom device function rights limit is reached and no more new custom device
function rights possible
• Validation fails for given parameters (like special characters or length)
For System Device Function Right, Name property value will be based on UI language. But
Identifier property value will be always constant irrespective of UI language.
For "Find" API Identifier property value should be used.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 713
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code

var umacDevice = device.GetService<UmacDevice>();


// Get available system and custom device function rights in the projectvar
deviceFunctionRightAssociation = umacDevice.AvailableDeviceFunctionRights;
string name;string identifier;
// Iterating through device function rights
foreach(var deviceFunctionRight in deviceFunctionRightAssociation)
{
name = deviceFunctionRight.Name;
identifier = deviceFunctionRight.Identifier;
}
// Retrieve the UmacConfiguratorService from project
UmacConfigurator umacConfiguratorService = project.GetService<UmacConfigurator>();
// Get all custom device function rights in the project
var customDeviceFunctionRightComposition =
umacConfiguratorService.AvailableCustomDeviceFunctionRights;
//create a custom device function right
var customDeviceFunctionRight =
customDeviceFunctionRightComposition.Create("RuntimeRight1", "General", "user defined
runtime right");
// Name and Identifier value for Custom Device Function Right will be the same.
// Iterating through custom device function rights
foreach(var customDeviceFunctionRight in customDeviceFunctionRightComposition)
{
name = customDeviceFunctionRight.Name;
identifier = customDeviceFunctionRight.Identifier;
}
//Find a custom device function right
customDeviceFunctionRight = customDeviceFunctionRightComposition.Find(identifier);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.1.4 System Roles

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


714 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Application
You can perform the following tasks with custom role and device function rights while using TIA
Portal Openness:
• Retrieve all system roles in a project
• Finding a particular system role in a project.
• Retrieve all assigned engineering rights to a given system role.
• Retrieve all assigned system device function rights for system role
For System Roles, Name property value will be based on user interface language. But Identifier
property value will be always constant irrespective of user interface language.
For "Find" API Identifier property value should be used.

Program code

UmacConfigurator umacConfiguratorService = project.GetService<UmacConfigurator>();


var umacDevice = device.GetService<UmacDevice>();
//Retrieve all system role
var systemRoles = umacConfiguratorService.SystemRoles;
//Iterate through the system roles
foreach (var systemRole in systemRoles)
{
string systemRoleName = systemRole.Name;
}
// Find a system role
SystemRole systemRole = systemRoles.Find("SystemRole_01");
//Retrieve assigned System Device Function Rights from system role
IList<SystemDeviceFunctionRight> assignedSystemDeviceFunctionRights =
systemRole.GetAssignedSystemDeviceFunctionRights(umacDevice);
//Retrieve assigned Engineering Function Rights from system role
var engineeringFunctionRights = systemRole.AssignedEngineeringRights;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.1.5 Custom Roles

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 715
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Application
Custom roles are user created roles which are dynamically created during the course of project
life time.
You can perform the following tasks with custom role while using TIA Portal Openness:
• Retrieve all Custom roles in a project.
• Creating a custom role in a project.
• Finding a particular custom role in a project.
• Editing the attributes(name and comment) of a custom role.
• Deleting a custom role in a project.
• Assigning/ Un assigning an EFR to a custom role.
• Assigning/ Un assigning an DFR to a custom role via a device instance.
• Retrieving Assigned Engineering Function Rights to a Custom Role.
• Retrieving Assigned Device Function Rights to a Custom Role
For Custom Role, Identifier property value will be always constant irrespective of user interface
language. For "Find" API Identifier property value should be used.

Openness: API for automation of engineering workflows


716 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code

TiaPortal tiaPortal = new TiaPortal();


Project tiaProject = tiaPortal.Projects[0];
UmacConfigurator UmacConfiguratorService = project.GetService<UmacConfigurator>();
//Retrieve custom roles in project
var customRoles = UmacConfiguratorService.CustomRoles;
// Create a custom role
CustomRole customRole = customRoles.Create("Role_1", "some comment");
//Iterate through custom roles
foreach(customRole in customRoles)
{
string customRoleName = customRole.Name;
string customRoleComment = customRole.Comment;
}
//Find a custom role
customRole = customRoles.Find("CustomRole1");
// Edit custom role
customRole.Name = "CustomRoleNew";
customRole.Comment = "some new comment";
// Retrieve Engineering Function Right. This list will be empty if called in non-protected
mode.
var engineeringFunctionRights = UmacConfiguratorService.EngineeringFunctionRights;
// Find an Engineering Function Right
EngineeringFunctionRight engineeringFunctionRight =
engineeringFunctionRights.Find("EFR_01");
// Assign a EFR to Custom Role
customRole.AssignedEngineeringRights.Add(engineeringFunctionRight);
// Retrieve assigned Engineering Function Rights on a custom role
var engineeringFunctionRights = customRole.AssignedEngineeringRights;
// Remove a EFR from Custom Role
customRole.AssignedEngineeringRights.Remove(engineeringFunctionRight);
// Get the umac device service from openness Device. If service is invoked on non-umac
device then value will be null
var umacDevice = device.GetService<UmacDevice>();
var deviceFunctionRightsAssociation = umacDevice.AvailableDeviceFunctionRights;
var customDeviceFunctionRight = deviceFunctionRightsAssociation.Find("User Right1");
var systemDeviceFunctionRight = deviceFunctionRightsAssociation.Find("SystemDFR_01");
// Assign a custom device function right to custom role
customRole.AssignDeviceFunctionRight(umacDevice, customDeviceFunctionRight);
//Assign a system device function right
customRole.AssignDeviceFunctionRight(umacDevice, systemDeviceFunctionRight);
//Retrieve assigned Device function Rights
var assignedDeviceFunctionRights = customRole.GetAssignedDeviceFunctionRights();
// Unassign a custom device function right from custom role
customRole.UnassignDeviceFunctionRight(umacDevice, customDeviceFunctionRight);
//Unassign a system device function right
customRole.UnassignDeviceFunctionRight(umacDevice, systemDeviceFunctionRight);
// Delete a Custom Role
customRole.Delete();

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 717
TIA Portal Openness API
5.15 Functions for accessing data of the user management

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.1.6 Project Users

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
Project users are users created locally for a project. When a Project is protected by default an
Project user is created and is given ES Administrative role.
You can perform the following tasks with project users while using TIA Portal Openness:
• Retrieve all Project users in a project.
• Create a Project user in a project.
• Find a Project user by name in a project.
• Get the Assigned Roles for a Project user.
• Add/ Remove a role to a Project user.
• Activate/Deactivate project user.
• Indicates whether the Project user is Active

Openness: API for automation of engineering workflows


718 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code

UmacConfigurator UmacConfiguratorService = project.GetService<UmacConfigurator>();


var projectUsers = UmacConfiguratorService.ProjectUsers;
// Create a project user
ProjectUser projectUser = projectUsers.Create("AdminUser",
"AdminUser123#".ToSecureString());
// Indicates whether the user is Active
var isUserActive = projectUser.IsActive;
//Change password of project user
projectUser.SetPassword("NewPassword@123".ToSecureString());
//Change AuthenticationType of projectUser
projectUser.ProjectUserAuthenticationType = AuthenticationType.Radius;
// Iterate through existing project users
foreach(projectUser in projectUsers)
{
string projectUserName = projectUser.Name;
}
// Find a project user
var projectUser = projectUsers.Find("AdminUser");
//Retrieve custom roles in project
var customRoles = UmacConfiguratorService.CustomRoles;
var customRole = customRoles.Find("Role_1");
var systemRole = customRoles.Find("Engineering administrator");
// Deactivate project user
projectUser.Deactivate();
// Add a Custom Role to a deactivated Project User
projectUser.Roles.Add(customRole);
// Add a System Role to a deactivated Project User
projectUser.Roles.Add(systemRole);
// Remove a Custom Role from a deactivated Project User
bool isSuccessfullyRemoved = projectUser.Roles.Remove(customRole);
// Remove a System Role from a deactivated Project User
isSuccessfullyRemoved = projectUser.Roles.Remove(systemRole);
// Activate project user
projectUser.Activate();
// Delete the project user instance
projectUser.Delete();

See also
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 719
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.2 Functions for UMAC Global Users and UMC Server

5.15.2.1 Authentication to connect to a UMC Server

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
In TIA Portal Openness, the UmcServerConfigurator service is introduced to get the list of UMC
Servers. From the UmcServerConfigurator, the list of UMC Servers are obtained through
UmcServers Property. New Event "Authentication" is introduced on the UMC server to connect
to the server.
The service is available in both the modes (protected / unprotected project). When UMC admin
is logged in as an user, then the below authentication event will not be triggered while importing
all umc users / user groups from the umc server. The event will trigger only when the logged user
is other that UMC user having "UMC View" Right at UMC Server. For example, project user, UMC
user who is not having "UMC View" Right at UMC Server.
With TIA Portal Openness V17, only one UMC Server is available and preconfigured.

Program code

var umcServerConfigurator = project.GetService<UmcServerConfigurator>();


UmcServer umcServer = umcServerConfigurator.UmcServer;
umcServer.Authentication += UmcServer_Authentication;

The method UmcServer_Authentication will have Event args like below where you can pass the
UMC admin name and password.

private static void UmcServer_Authentication(object sender, UmcAuthenticationEventArgs e)


{
e.UmacCredentials.Name = "Admin";
Console.WriteLine("Name is set");
e.UmacCredentials.SetPassword(GetSecureString("Admin123"));
Console.WriteLine("Password is set");
}

Openness: API for automation of engineering workflows


720 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.2 Retrieving an UMC User Group from a UMC Server

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to retrieve an UMC User Group from a UMC Server. The
GetUserGroupByName ( ) method is available at UMC server level to get UMC user group of the
connected UMC server.
When the GetUserGroupByName ( ) method is triggered, the event call back triggers for the UMC
Server authentication. Only UMC user having "UMC View" right will be available to retrieve an
UMC user group.

Program code

var umcServerConfigurator = project.GetService<UmcServerConfigurator>();


UmcServer umcServer = umcServerConfigurator.UmcServer;
umcServer.Authentication += UmcServer_Authentication;
string umcUserGroupName = "xxxxxx";
Siemens.Engineering.Umac.UmcUserGroupInfo umcUserGroupsFromUmcServer =
umcServer.GetUserGroupByName(umcUserGroupName);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 721
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.2.3 Retrieving an UMC User from a UMC Server

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to retrieve an UMC user from a UMC server. The
GetUserByName( ) method is used at the UMC server level to get the corresponding UMC user
from UMC server by the UMC username.
When the GetUserByName( ) method is triggered, the event call back triggers for the UMC Server
Authentication. Only Umc user having "UMC View" Right will be able to fetch a UMC user from
the UMC server.

Program code

var umcServerConfigurator = project.GetService<UmcServerConfigurator>();


UmcServer umcServer = umcServerConfigurator.UmcServer;
umcServer.Authentication += UmcServer_Authentication;
string umcUserName = "xxxxxx";
Siemens.Engineering.Umac.UmcUserInfo umcUsersFromUmcServer =
umcServer.GetUserByName(umcUserName);

Note
All UMC exceptions are handled as Siemens.Engineering.TargetInvocation Exception in TIA
Portal Openness.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


722 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.2.4 Adding an UMC User Group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to add an UMC user group to TIA Portal project from an UMC
server.

Program code

var umcServerConfigurator = project.GetService<UmcServerConfigurator>();


var umacConfigurator = project.GetService<UmacConfigurator>();
UmcServer umcServer = umcServerConfigurator.UmcServer;
umcServer.Authentication += UmcServer_Authentication;
string umcUserGroupName = "xxxxxx";
Siemens.Engineering.Umac.UmcUserGroupInfo umcUserGroupInfo =
umcServer.GetUserGroupByName(umcUserGroupName);
//Get the UmcUserGroupComposition.
UmcUserGroupComposition umcUserGroupComposition = umacConfigurator.UmcUserGroups;
//Create the selected UMC UserGroup in to the TIA Portal project
UmcUserGroup umcUserGroup = umcUserGroupComposition.Create(umcUserGroupInfo);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.5 Getting all UMC groups in TIA Portal

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 723
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Application
You can use the TIA Portal Openness to get all UMC user groups added to TIA Portal projects.
When there are no UMC user groups, the TIA Portal Openness application will return empty
collection.

Program code

//Get UmcUserGroups from the Project.


UmcUserGroupComposition umcUserGroupComposition = umacConfigurator.UmcUserGroups;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.6 Adding an UMC User to TIA Portal

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to add an UMC user to TIA Portal project once the UMC users
are retrieved from UMC server.

Program code

var umcServerConfigurator = project.GetService<UmcServerConfigurator>();


var umacConfigurator = project.GetService<UmacConfigurator>();
UmcServer umcServer = umcServerConfigurator.UmcServer;
umcServer.Authentication += UmcServer_Authentication;
string umcUserName ="xxx";
Siemens.Engineering.Umac.UmcUserInfo umcUserInfo = umcServer.GetUmcUserByName(umcUserName);
//Gets the UmcUserComposition
UmcUserComposition umcUserComposition = umacConfigurator.UmcUsers;
//Create the selected UMC user in to the TIA Portal project
UmcUser umcUser = umcUserComposition.Create(umcUserInfo);

Openness: API for automation of engineering workflows


724 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.7 Getting all UMC Users in TIA Portal project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get all the UMC users in TIA Portal.
When there are no UMC users, the TIA Portal Openness application will return empty collection.

Program code

var umacConfigurator = project.GetService<UmacConfigurator>();


UmcUserComposition umcUserComposition = umacConfigurator.UmcUsers;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.8 Finding an UMC User added in TIA Portal

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to find corresponding UMC user from the TIA Portal project.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 725
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code

string UmcUserName ="XXXX";


UmcUserComposition umcUsersList = umacConfigurator.UmcUsers;
UmcUser umcUser = umcUsersList.Find(UmcUserName);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.9 Finding an UMC User group added in TIA Portal project

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to find corresponding UMC User group from the TIA Portal
project.

Program code

//Get UmcUserGroups from the Project.


string UmcUserGroupName ="XXXX";
UmcUserGroupComposition umcUserGroupList = umacConfigurator.UmcUserGroups;
UmcUserGroup umcUserGroup = umcUserGroupList.Find(UmcUserGroupName);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


726 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.2.10 Assigning role to UMC User

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to add the corresponding role to the UMC user added to TIA
Portal project.

Program code

//Assign the System Role.


SystemRole engineeringSystemRole =
umacConfigurationBuilder.SystemRoles.Find(s_SystemRoleName);
umcUser.Roles.Add(engineeringSystemRole);
//Assign the Custom Role.
CustomRole customRole = umacConfigurator.CustomRoles.Create("CustomRole");
umcUser.AssignRole(customRole);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.11 Getting the list of assigned roles of UMC User and UMC User Group.

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to get the list of assigned roles of UM user and UMC user
group.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 727
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code

//Get assigned roles from UmcUserGroup.


string UmcUserGroupName ="XXXX";
UmcUserGroupComposition umcUserGroupList = umacConfigurationBuilder.UmcUserGroups;
UmcUserGroup umcUserGroup = umcUserGroupList.Find(UmcUserGroupName);
RoleAssociation assignedRolesInUmcUserGroup = umcUserGroup.Roles;
//Get assigned roles from UmcUser.
string UmcUserName ="XXXX";
UmcUserComposition umcUserList = umacConfigurationBuilder.UmcUsers;
UmcUser umcUser = umcUserList.Find(UmcUserGroupName);
RoleAssociation assignedRolesInUmcUser = umcUser.Roles;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.12 Assigning role to UMC User Group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to add the corresponding role to the UMC user group added
to TIA Portal project.

Program code

//Assign the System Role.


SystemRole engineeringSystemRole =
umacConfigurationBuilder.SystemRoles.Find(s_SystemRoleName);
umcUserGroup.Roles.Add(engineeringSystemRole);
//Assign the Custom Role.
CustomRole customRole = umacConfigurator.CustomRoles.Create("CustomRole");
umcUserGroup.AssignRole(customRole);

Openness: API for automation of engineering workflows


728 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.13 Removing role from UMC User and UMC User Group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Application to unassign the corresponding role from the UMC user and
UMC user group added to TIA Portal project.

Program code
Modify the following program code to remove role from the UMC user added to TIA Portal
project.

//Remove the System Role.


bool isSuccessfullyRemoved = umcUser.Roles.Remove(engineeringSystemRole);
//Remove the Custom Role
isSuccessfullyRemoved = umcUser.Roles.Remove(customRole);

Modify the following program code to remove role from the UMC user group added to TIA Portal
project.

//Un assign the System Role.


bool isSuccessfullyRemoved = umcUserGroup.Roles.Remove(engineeringSystemRole);
//Un assign the Custom Role.
isSuccessfullyRemoved = umcUserGroup.Roles.Remove(customRole);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 729
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.2.14 Activating/Deactivating UMC User and UMC User Group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal
• A project is open
See Opening a project

Application
You can use the TIA Portal Opennness to activate / deactivate UMC user and UMC user group.

Program code

//Activate UMC User


UmcUser umcUserToActivate = umacConfigurator.UmcUsers.Find("UserNameToActivate");
umcUserToActivate.Activate();
//Deactivate UMC User
UmcUser umcUserToDeactivate = umacConfigurator.UmcUsers.Find("UserNameToDeactivate");
umcUserToDeactivate.Deactivate();
//Activate UMC User Group
UmcUserGroup umcUserGroupToActivate =
umacConfigurator.UmcUserGroups.Find("UserGroupNameToActivate");
umcUserGroupToActivate.Activate();
//Deactivate UMC User Group
UmcUserGroup umcUserGroupToDeactivate =
umacConfigurator.UmcUserGroups.Find("UserGroupNameToDeactivate");
umcUserGroupToDeactivate.Deactivate();

5.15.2.15 Checking state for UMC User and UMC User Group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to retrieve activation state of UMC user and UMC user group.

Openness: API for automation of engineering workflows


730 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code

/Indicates whether the User is Active


UmcUser umcUserToActivate = umacConfigurator.UmcUsers.Find("UserNameToActivate");
var isUserActive = umcUserToActivate.IsActive;
//Indicates whether the Group is Active
UmcUserGroup umcUserGroupToDeactivate =
umacConfigurator.UmcUsers.Find("UserGroupNameToActivate");
var isGroupActive = umcUserGroupToDeactivate.IsActive;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

5.15.2.16 Deleting UMC User and UMC User Group

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to delete UMC user and UMC User Group from TIA Portal
project.

Program code

//Delete user from TIA Portal project.


UmcUser umcUserToDelete = umacConfigurator.UmcUsers.Find("UserNameToDelete");
umcUserToDelete.Delete();
//Delete of user group from TIA Portal project.
UmcUserGroup umcUserGroupToDelete =
umacConfigurator.UmcUserGroups.Find("GroupNameToDelete");
umcUserGroupToDelete.Delete();

See also
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 731
TIA Portal Openness API
5.15 Functions for accessing data of the user management

5.15.2.17 Complete sample code

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


732 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Program code
Below TIA Portal Openness script describes about the complete workflow of Openness APIs for
UMAC global users and UMC server.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 733
TIA Portal Openness API
5.15 Functions for accessing data of the user management

internal class Program


{
static void Main(string[] args)
{
TiaPortal tiaPortal = new TiaPortal();
//Registers for TIA Portal authentication for protected project opening
tiaPortal.Authentication += TiaPortal_Authentication;
Project umacProject = tiaPortal.Projects.Open(new FileInfo("ProtectedProject_Path"));
var umcServerConfigurator = umacProject.GetService<UmcServerConfigurator>();
// Getting UMC servers.
UmcServer umcServer = umcServerConfigurator.UmcServer;
// Register for UMC Server Authentication
umcServer.Authentication += UmcServer_Authentication;
var umacConfigurator = umacProject.GetService<UmacConfigurator>();
// Use case :Import User Group, Add User Group to Tia portal project , Assign & Unassign
Role to UserGroup
// Delete the User group from Tia portal project.
// Retrieve an UMC User Group from UMC Server
const string UmcUserGroupName = "xxxxx";
UmcUserGroupInfo umcUserGroupInfo = umcServer.GetUserGroupByName(UmcUserGroupName);
// Add an UMC User Group into TIA portal Project.
UmcUserGroupComposition umcUserGroupComposition = umacConfigurator.UmcUserGroups;
UmcUserGroup umcUserGroup = umcUserGroupComposition.Create(umcUserGroupInfo);
// Assign and Unassign roles to User Group.
//Assign the System Role.
const string SystemRoleName = "Engineering administrator";
SystemRole engineeringAdministratorSystemRole =
umacConfigurator.SystemRoles.Find(SystemRoleName);
umcUserGroup.AssignRole(engineeringAdministratorSystemRole);
//Assign the Custom Role.
CustomRole customRole = umacConfigurator.CustomRoles.Create("CustomRole");
umcUserGroup.AssignRole(customRole);
//Un assign the System Role.
umcUserGroup.UnassignRole(engineeringAdministratorSystemRole);
//Un assign the Custom Role.
umcUserGroup.UnassignRole(customRole);
//Delete the UMC user group in Tia Portal project.
UmcUserGroup umcUserGroupToDelete = umacConfigurator.UmcUserGroups.Find(UmcUserGroupName);
umcUserGroupToDelete.Delete();
// Use case :Import UMC User , Add UMC User to Tia portal project , Assign & Unassign Roles
to UMC User,
// Delete the UMC User from Tia portal project.
// Import UMC User from UMC Server
const string UmcUserName = "xxxxx";
UmcUserInfo umcUserInfo = umcServer.GetUserByName(UmcUserName);
//Add UMC User to Tia Portal project
UmcUserComposition umcUserComposition = umacConfigurator.UmcUsers;
UmcUser umcUser = umcUserComposition.Create(umcUserInfo);
// Assign & Unassign Roles to UMC User
//Assign the System Role.
const string SystemRoleNameForUser = "NET Radius";
SystemRole systemRoleForUmcUser = umacConfigurator.SystemRoles.Find(SystemRoleNameForUser);
umcUser.AssignRole(systemRoleForUmcUser);
//Assign the Custom Role.

Openness: API for automation of engineering workflows


734 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

CustomRole customRoleNameForUmcUser =
umacConfigurator.CustomRoles.Create("CustomRoleName");
umcUser.AssignRole(customRoleNameForUmcUser);
//Un assign the System Role.
umcUser.UnassignRole(systemRoleForUmcUser);
//Un assign the Custom Role.
umcUser.UnassignRole(customRoleNameForUmcUser);
//Delete the UMC User from Tia Portal project
UmcUser umcUserToDelete = umacConfigurator.UmcUsers.Find(UmcUserName);
umcUserToDelete.Delete();
}
private static void TiaPortal_Authentication(object sender, AuthenticationEventArgs e)
{
e.AuthenticationTypeProvider = AuthenticationTypeProvider.Credentials;
e.UmacCredentials.Type = UmacUserType.Project;
e.UmacCredentials.Name = "Admin";
e.UmacCredentials.SetPassword(GetSecureString("Admin123"));
}
private static void UmcServer_Authentication(object sender, UmcAuthenticationEventArgs e)
{
e.UmcCredentials.Name = "Admin";
e.UmcCredentials.SetPassword(GetSecureString("Admin123"));
}
private static SecureString GetSecureString(string password)
{
SecureString secureString = new SecureString();
foreach (char c in password)
{
secureString.AppendChar(c);
}
return secureString;
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 735
TIA Portal Openness API
5.15 Functions for accessing data of the user management

Openness: API for automation of engineering workflows


736 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

internal class Program


{
static void Main(string[] args)
{
TiaPortal tiaPortal = new TiaPortal();
//Registers for TIA Portal authentication for protected project opening
tiaPortal.Authentication += TiaPortal_Authentication;
Project umacProject = tiaPortal.Projects.Open(new FileInfo("ProtectedProject_Path"));
var umcServerConfigurator = umacProject.GetService<UmcServerConfigurator>();
// Getting UMC servers.
UmcServer umcServer = umcServerConfigurator.UmcServer;
// Register for UMC Server Authentication
umcServer.Authentication += UmcServer_Authentication;
var umacConfigurator = umacProject.GetService<UmacConfigurator>();
// Use case :Import User Group, Add User Group to Tia portal project , Assign & Unassign
Roles to UserGroup ,
// Delete the User group from Tia portal project.
// Retrieve an UMC User Group from UMC Server
const string UmcUserGroupName = "xxxxx";
UmcUserGroupInfo umcUserGroupInfo = umcServer.GetUserGroupByName(UmcUserGroupName);
// Add an UMC User Group into TIA portal Project.
UmcUserGroupComposition umcUserGroupComposition = umacConfigurator.UmcUserGroups;
UmcUserGroup umcUserGroup = umcUserGroupComposition.Create(umcUserGroupInfo);
//Assign the System Role.
umcUserGroup.Roles.Add(engineeringSystemRole);
//Assign the Custom Role.
umcUserGroup.Roles.Add(customRole);
//Un assign the System Role from UserGroup.
bool isSuccessfullyRemoved = umcUserGroup.Roles.Remove(engineeringSystemRole);
//Un assign the Custom Role from UserGroup.
isSuccessfullyRemoved = umcUserGroup.Roles.Remove(customRole);
//Get all users belongs to the UMC UserGroup in the UMC Server
IList<UserInfo> umcUsersBelongstoGroup = = umcUserGroup.GetUsers();
//Get the UmcUserComposition from the project
UmcUserComposition umcUserComposition = umacConfigurator.UmcUsers;
//Itertate through all users belongs to the group and add to the TIA Portal project
foreach (UserInfo umcUserInfo in umcUsersBelongstoGroup)
{
//Create UMC User to TIA Portal project
UmcUser umcUser = umcUserComposition.Create(umcUserInfo);
}
//Get UmcUsers from the Project.
UmcUserComposition umcUserComposition = umacConfigurator.UmcUsers;
//Assign role to UMC Users in TIA Portal project
bool isSuccessfullyRemoved = false;
foreach (UmcUser umcUser in umcUserComposition)
{
//Assign system role to user
umcUser.Roles.Add(engineeringSystemRole);
//Assign custom role to userumcUser.Roles.Add(customRole);
//API for Un assign the System Role.
isSuccessfullyRemoved = umcUser.Roles.Remove(engineeringSystemRole);
//API to Un assign the Custom Role
isSuccessfullyRemoved = umcUser.Roles.Remove(customRole);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 737
TIA Portal Openness API
5.15 Functions for accessing data of the user management

//Deactivate UMC User


UmcUser umcUserToDeactivate = umacConfigurator.UmcUsers.Find("UserNameToDeactivate");
umcUserToDeactivate.Deactivate();
//Deactivate UMC User Group
UmcUserGroup umcUserGroupToDeactivate =
umacConfigurator.UmcUserGroups.Find("UserGroupNameToDeactivate");
umcUserGroupToDeactivate.Deactivate();
//Activate UMC User Group
UmcUserGroup umcUserGroupToActivate =
umacConfigurator.UmcUserGroups.Find("UserGroupNameToActivate");
umcUserGroupToActivate.Activate();
//Activate UMC User
UmcUser umcUserToActivate = umacConfigurator.UmcUsers.Find("UserNameToActivate");
umcUserToActivate.Activate();
//Delete of user from TIA Portal project.
UmcUser umcUserToDelete = umacConfigurator.UmcUsers.Find("UserNameToDelete");
umcUserToDelete.Delete();
//Delete of user group from TIA Portal project.
UmcUserGroup umcUserGroupToDelete =
umacConfigurator.UmcUserGroups.Find("GroupNameToDelete");
umcUserGroupToDelete.Delete();
//Get all the UMC user group the UMC user belongs to in the UMC Server.
IList<UserGroupInfo> userGroups = umcUser.GetAllAssociatedGroups();
}
private static void TiaPortal_Authentication(object sender, AuthenticationEventArgs e)
{
e.AuthenticationTypeProvider = AuthenticationTypeProvider.Credentials;
Console.WriteLine("AuthenticationTypeProvider set successfully.");
e.UmacCredentials.Type = UmacUserType.Project;
Console.WriteLine("User type is set");
e.UmacCredentials.Name = "Admin";
Console.WriteLine("Name is set");
e.UmacCredentials.SetPassword(GetSecureString("Admin123"));
Console.WriteLine("Password is set");
}
private static void UmcServer_Authentication(object sender, UmcAuthenticationEventArgs e)
{
e.UmacCredentials.Name = "Admin";
Console.WriteLine("Name is set");
e.UmacCredentials.SetPassword(GetSecureString("Admin123"));
Console.WriteLine("Password is set");
}
private static SecureString GetSecureString(string password)
{
SecureString secureString = new SecureString();
foreach (char c in password)
{
secureString.AppendChar(c);
}
return secureString;
}
}

Openness: API for automation of engineering workflows


738 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.15 Functions for accessing data of the user management

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 739
TIA Portal Openness API
5.16 Functions on OPC

5.16 Functions on OPC

5.16.1 Configuring OPC UA server secure communication protocol

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Introduction
You can use the TIA Portal Openness application to configure OPC UA server with security policy
"Basic256Sha256" . The security policy Basic256Sha256 needs to be added to the Runtime
Settings. RDP needs to compile the properties in the xml configuration file.
The defaults are Enabled, Sign, and Sign and Encrypt.
In the XML file <Project>\OPC\uaserver\OPCUaServerWinCCPro.xml, you need to set the security
policy and security policies according to ES device configuration.

Openness: API for automation of engineering workflows


740 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.16 Functions on OPC

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 741
TIA Portal Openness API
5.16 Functions on OPC

5.16.2 Setting OPC UA security policy

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
Opening a project (Page 113)
• OPC UA server is activated

Application
You can use the TIA Portal Openness application to set the security policy in OPC UA. You can
implement the security policy as a dynamic attribute of type flagged enum:
OpcUaSecurityPolicies. The security policy is only available in TIA Portal Openness if the OPC UA
server is activated. If the OPC UA server is deactivated, you will encounter
EngineeringNotSupportedException while trying to access the security policy for any other
unavailable attribute.
The below table shows the possible values can be found for security policies:

TIA UI name Enum entry Value Remarks


- NoneSelected 0 Is equivalent to TIA UI
when no checkbox is se‐
lected.
No security OpcUaSecurityPolicies‐ 1
None
Basic128Rsa15 - Sign OpcUaSecurityPoli‐ 2
cies128RSAS
Basic128Rsa15 - Sign & OpcUaSecurityPoli‐ 4
Encrypt cies128RSASE
Basic256 - Sign OpcUaSecurityPoli‐ 8
cies256S
Basic256 - Sign & En‐ OpcUaSecurityPoli‐ 16
crypt cies256SE
Basic256Sha256 - Sign OpcUaSecurityPoli‐ 32
cies256SHAS
Basic256Sha256 - Sign OpcUaSecurityPoli‐ 64
& Encrypt cies256SHASE

Openness: API for automation of engineering workflows


742 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.16 Functions on OPC

Program code
Modify the following program code to set the security policy in OPC UA using TIA Portal
Openness:

DeviceItem UpcUaSubmodule= ...;


object SecurityPolicies = UpcUaSubmodule.GetAttribute("OpcUaSecurityPolicies");
if(SecurityPolicies | OpcUaSecurityPolicies.OpcUaSecurityPolicies256S ==
OpcUaSecurityPolicies.OpcUaSecurityPolicies256S)
{
//Do something
}
UpcUaSubmodule.SetAttribute("OpcUaSecurityPolicies",
OpcUaSecurityPolicies.OpcUaSecurityPolicies256S |
OpcUaSecurityPolicies.OpcUaSecurityPolicies256SHASE);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 743
TIA Portal Openness API
5.17 SiVArc Openness

5.17 SiVArc Openness

5.17.1 Introduction

Introduction
TIA portal openness application allows you to instantiate SiVArc. You must need a client
application to access TIA portal, and through openness feature launch SiVArc services. For more
details on set up, and accessing Openness, see TIA portal user guide.

Setting up the application


To set up a client application, perform the following steps:
1. Create a console application. Add reference of Public API (Siemens.Engineering.dll) available
at _deployed\TIAPV15SP1_11010001\PublicAPI\V15.1\ 936 Siemens.Engineerin.dll or from
installed binaries location PublicAPI\V15.1\ 937 Siemens.Engineerin.dll
2. Add configuration details to the configuration file. For detailed information of configuration
details and steps to access the public API, see TIA openness wiki.
3. To access Sivarc service, use the below mentioned API:
using (TiaPortal tia = new
TiaPortal(TiaPortaMode.WithUserInterface))
{
Project myProject = tia.Projects.Open(new FileInfo(@"C:\Users
\z003exve\Documents\Automation\Project_Demo\Project_Demo.ap15));
//if SiVArc is not installed, user will not be able to access
SiVArc service (compiler error)
Sivarc sivarc =myproject?.GetService<Sivarc>():
if (sivarc !=null)
{
}
}

5.17.2 SiVArc service properties

SiVArc service properties


The table below lists the supported properties and methods for SiVArc:

Property Name Description Data Type


AlarmRules Anchor object for all alarm rule objects AlarmRulesBrowsable
ScreenRules Anchor object for all screen rule objects ScreenRulesBrowsable
TextlistRules Anchor object for all textlist rule objects TextlistRulesBrowsable

Openness: API for automation of engineering workflows


744 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.17 SiVArc Openness

Property Name Description Data Type


TagRules Anchor object for all tag rule objects TagRulesBrowsable
CopyRules Anchor object for all copy rule objects CopyRulesBrowsable
Alarm Rules Enumerate of all immediate first level alarm rules AlarmRuleComposition
Groups Enumerate of all immediate first level alarm rule AlarmRuleGroupComposition
groups
ScreenRules Enumerate of all immediate first level screen rules ScreenRuleComposition
ScreenRu‐ Enumerate of all immediate first level screen rule ScreenRuleGroupComposition
lesGroups groups
TextlistRules Enumerate of all immediate first level textlist TextlistRuleComposition
rules
TextlistGroups Enumerate of all immediate first level textlist rule TextlistRuleGroupComposition
groups
TagRules Enumerate of all immediate first level tag rules TagRuleComposition
TagRulesGroups Enumerate of all immediate first level tag rule TagRuleGroupComposition
groups
CopyRules Enumerate of all immediate first level copy rules CopyRuleComposition
CopyRulesGroups Enumerate of all immediate first level copy rule CopyRuleGroupComposition
groups

Following table lists the AlarmRule and AlarmRuleGroup composition. The same applies to other
SiVArc objects.

Method Name Parameter Description Data Type


Find String- alarm rule /rule‐ Finds the alarm rule/ AlarmRule
group name alarm rule group from
alarm rule/alarm group
collection
CreateFrom MasterCopy – alarm Copy alarm rule/alarm AlarmRule
rule/alarm rule group rule group master copy
master copy from library to project
with default replace op‐
tion
CreateFrom MasterCopy – alarm Copy alarm rule /alarm AlarmRule
rule/alarm rule group rule group master copy
master copy, CreateOp‐ from library to project
tions- Rename/Replace with create option

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 745
TIA Portal Openness API
5.17 SiVArc Openness

5.17.3 Copying rules or groups from library

Requirement
• Launch TIA portal openness application. For more information on connections, see TIA portal
user guide.
• An existing TIA portal project containing screen rule editor, screen rules group and master
copy.

Case 1: When you copy rules/rule groups from master copy to screen rules editor

"The CreateFrom" global library allows rules and rule groups to be copied from the global
library to the SiVarc rule editor. If successful, the API function will return ScreenRule/
ScreenRuleGroup. The following code explains how the rules or rule groups are copied from the
master copy to the SiVArc editor:

By default, the behaviour will be replaced.


Case 2: When you copyrules/rule groups from master copy, the existing rules/rule groups can be
renamed or replaced based on the second parameter input
If rules/rule groups in the master copy are already existing in the SiVArc editor, and if you are
trying to copy them, the rules/rule groups gets renamed. The "CreateOptions" API will create the
rules/rule groups in the SiVArc editor if they are not existing, else they replace the existing rules/
rule groups. If successful, the API function will rename ScreenRule/ScreenRuleGroup. The
following code snippet shows the replacing of rules/rule groups:

Openness: API for automation of engineering workflows


746 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.17 SiVArc Openness

5.17.4 Finding a screen rule and screen rule group

Requirement
• TIA portal openness application connected to TIA portal. For more information on
connections, see TIA portal user guide.
• TIA portal project consisting of screen rules and screen rule groups.

Finding screen rules within screen groups


Case 1:Finding screen rules within screen rules editor.
The API sivarc.ScreenRules.Rules allows you to find the available rules within the SiVArc
screen rule editor as shown below:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 747
TIA Portal Openness API
5.17 SiVArc Openness

Case 2: Finding screen rule groups within screen rules editor.


The API sivarc.ScreenRule.Groups allows you to find the available rules and rule groups
within the SiVArc screen rule editor as shown below:

5.17.5 Deleting rules and rule groups

Requirement
• TIA portal openness application connected to TIA portal. For more information on
connections, see TIA portal user guide.
• TIA project containing screen rules and screen rule groups.

Deleting rules and rule groups


To delete a rule or a rule group, the following API is used:
sivarc.ScreenRules.Rules.Find("Screen rule_1").Delete();
The ScreenRules is an anchor object for all screenrule objects. To perform deletion, it is
mandatory that you find the rule within the rule editor. For more information on finding the
screen rule, refer section Finding a screen rule and screen rule group.
To delete screens from screen group, use the following API:
sivarc.ScreenRules.Rules.Find("Screen rule group_1").Delete();

Openness: API for automation of engineering workflows


748 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.17 SiVArc Openness

5.17.6 UMAC set up for openness

About UMAC
To access UMAC through openness, ensure that you have the UMAC credentials and access
privileges. If you are not a valid UMAC user, the application will return NULL values for all SiVArc
anchor rule objects. For more information on UMAC, refer UMAC topic in SiVArc user guide.

5.17.7 SiVArc generation

Requirement
• Launch TIA portal openness application. For more information on connections, see TIA portal
user guide.
• An existing TIA portal project connected to an HMI device, and PLC configured.

Important points to notice


• Ensure SiVArc license is installed on your PC, else during generation an exception is thrown
- "SiVArc license is missing; it is mandatory to have SiVArc license for modifying data".
• Ensure valid device name is used, else an exception is thrown - "HMI device 'deviceName' not
found”.
• Ensure valid PLC name is called, else an exception is thrown - “PLC device 'plcDeviceName' not
found”.
• Ensure supported device name is called, else an exception is thrown - "HMI device
'deviceName' is not supported”
• Ensure supported PLC name is called, else an exception is thrown - "PLC device
'plcDeviceName' is not supported”
• Ensure you pass valid GenerationOption parameter. If none is passed, SiVArc generation will
happen and by default the TIAP project settings will be used for SiVArc generation
• Ensure you valid PLC name which was not used for generation in the previous generation,
else the system freezes.

GenerationOptions- Enum (Flag)


SiVArc supports Enum options, and you can pass combination of two values in the Generate
API. Following table displays the enum options:

SN Values Description

1 None Nothing is selected, takes default setting for generation

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 749
TIA Portal Openness API
5.17 SiVArc Openness

2 AllTags Generate all tags

3 UsedHmi‐ Generate only relevant (used) tags


Tags
In case when FullGeneration option is not selected, SiVArc will decide inter‐
4 FullGenera‐ nally based on the configuration if it has to perform full generation or delta
tion generation.
When you pass FullGeneration as parameter, SiVArc will be generated
with force full generation.

To generate SiVArc, use the following API:


sivarc.Generate("HMI_1", new List<string> {PLC_1},
GenerateOptions.AllTags | GenerateOptions. FullGeneration);

SiVArcGenerationResult and SivarcFeedbackMessage


SiVArc generation accesses the following properties on successful generation:
• IsGenerationSuccessful - Informs if SiVArc generation is successful.
• WarningCount - Total warning count after SiVArc generation
• ErrorCount - Total error count after SiVArc generation
• Messages - Composition of feedback message

To generate SiVArc result, use the following API:

SiVArc generation accesses the following feedback messages on successful generation:


• Path: Header text of feedback message(Header messages will always have empty description
field)
• DateTime: DateTime of feedback message

Openness: API for automation of engineering workflows


750 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.17 SiVArc Openness

• MessageType: Feedback message type


• Description: Description/Content of Feedback message (Only when Path is empty to ensure
not a header message)
• WarningCount: Warning count for a header message
• ErrorCount: Error count for a header message
• Messages: Composition of feedback message (SivarcFeedbackMessage

You can viewrecursive feedback messages by using the following code snippet:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 751
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

5.18 Functions for SINUMERIK 840D sl

5.18.1 Introduction
Using TIA Portal-Openness, you automate the engineering and control the TIA Portal using a
program that you created yourself.
In this help document, you can find a lot of information and code examples for this program that
you generate yourself. You can also generate and use your own programs for the TIA Portal
"SINUMERIK" application.

Further information
Before you generate your own program for SINUMERIK from the sample codes listed in the
following, please note the general information on Openness, which you can find in this help
under the following keywords:
• Preconditions for using TIA Portal Openness
• Installing TIA Portal Openness
• Access the TIA Portal
• TIA Portal Openness object model
• Programming steps

5.18.2 Type identifier - identifier of the components


Each SINUMERIK component has a unique number, which is designated as type identifier
(TypeIdentifier) . In the Openness program code, you can use the type identifier to clearly
identify and designate a component. For example, the type identifier for SINUMERIK 840D sl
NCU 710.3 PN is "Article No. :6FC5 371-0AA30-0Axx/Vy.z".
The type identifier is displayed when creating a device using the dialog "Add new device" and in
the tabular device overview.
You can copy the type identifier into your Openness application.
The type identifier is expected in Openness as a current parameter when a method is called, e.g.
the CreateWithItem() method.

Activating display of the type identifier in SINUMERIK


1. In the project view, choose "Options > Settings" from the menu.
The "Settings" configuration area opens.
2. In the secondary navigation, select entry "Hardware configuration".
3. Activate option "Activate display of the type identifier for devices and modules".
The type identifier display is now active.

Openness: API for automation of engineering workflows


752 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

5.18.3 Fundamentals

Overview
You can create the following SINUMERIK devices in the TIA Portal Openness:
• NCU
• NX module
• ADI4
To create the SINUMERIK devices, use the CreateWithItem() method of the Devices
Collection.

Note
All integrated subcomponents of a SINUMERIK-NCU - such as PLC, NCK, CP, HMI and SINAMICS
Integrated - are automatically created at the same subordinate level.

Special issue when creating SINUMERIK devices


The names of the subracks correspond to the NCU types and are write protected in the user
interface. You must also use the names of the subracks in the TIA Portal Openness.
Use the following standard names of the subracks for creating a device using a device element
type identifier with the Device CreateWithItem method:

SINUMERIK NCU Subrack standard name


SINUMERIK 840D sl NCU 710.3 PN NCU 710.3 PN
SINUMERIK 840D sl NCU 720.3 PN NCU 720.3 PN
SINUMERIK 840D sl NCU 730.3 PN NCU 730.3 PN
SINUMERIK 840D sl NCU 730.3 PN /319 NCU 730.3 PN /319

Note
Alternatively, you can omit the parameter names. The default name is used if the name is "Null"
or "String.Empty".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 753
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

The following parameters can be used with the CreateWithItem() method:


• default name,
e.g.
project.Devices.CreateWithItem("OrderNumber:6FC5 371-0AA30-0AAB/
V4.8", "NCU 710.3 PN", "TestDevice");
• null,
e.g.
project.Devices.CreateWithItem("OrderNumber:6FC5 371-0AA30-0AAB/
V4.8", null, "TestDevice");
• string.Empty,
e.g.
project.Devices.CreateWithItem("OrderNumber:6FC5 371-0AA30-0AAB/
V4.8", string.Empty, "TestDevice");
Additional information about the call parameters associated with the CreateWithItem()
method is provided in Chapter "Creating a device".

The following table lists the assignment of the devices and their type identifiers:

SINUMERIK NCU Type identifier


SINUMERIK 840D sl NCU 710.3 PN Article No. :6FC5 371-0AA30-0Axx/Vy.z
SINUMERIK 840D sl NCU 720.3 PN Article No. :6FC5 372-0AA30-0Axx/Vy.z
SINUMERIK 840D sl NCU 730.3 PN Article No. :6FC5 373-0AA30-0Axx/Vy.z
SINUMERIK 840D sl NCU 730.3 PN /319 Article No. :6FC5 373-0AA31-0Axx/Vy.z

When creating SINUMERIK devices, place holders in the type identifier are permissible. You can
subsequently replace these placeholders by device-specific characters. If, for example, you enter
type identifier "OrderNumber:6FC5 372-0AA30-0AA0/V4.8", then SINUMERIK 840D sl NCU
720.3 PN is created with firmware version FW4.8.

Classification of the device element


Every device or device element has obligatory attributes, which are read and written to.
Additional information about the attributes that are supported in Openness is provided in
Chapter "Functions on device elements".
The classification attributes of the device element are write protected, and not visible in the user
interface of the TIA Portal.
The classification attributes have the value "DeviceItemClassification":

Value of the classification attribute Description


DeviceItemClassifications.None (0) No classification.
DeviceItemClassifications.CPU (1) The device element is a CPU.
DeviceItemClassifications.HM (2) The device element is a header module.

If you interrogate the value of the device element via the integrated PLC, then for a SINUMERIK
device, this is the value "CPU (1)".

Openness: API for automation of engineering workflows


754 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

In the Openness object model, the following components act as header modules:
• SINAMICS Integrated
• NX module
• ADI4
In all other cases, the value of the classification attribute "DeviceItemClassification" is
"None" (0).

Finding device elements via the "Header module" property


The following example shows how you can find device elements with the "Header module"
property, before configuring a telegram, for example.
You can only read this property, but cannot set it at device elements.

Finding device elements via the "Header module" property


foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.HM)
{
var driveObjectContainer = deviceItem.GetService<DriveObjectContainer>();
// do something
}
}
}

See also
Creating an NX module (Page 759)
Creating an NCU (Page 758)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 755
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

5.18.4 Object model

Overview
The following diagram describes the objects located under "Device" for SINUMERIK 840D sl:

'HYLFH

5DFN 'HYLFH,WHP

&3 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

+0, 'HYLFH,WHP

1&. 'HYLFH,WHP

3/& 'HYLFH,WHP

'3,QWHUIDFH 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

03,'3,QWHUIDFH 'HYLFH,WHP

'3,QWHJUDWHG,QWHUIDFH 'HYLFH,WHP

6,1$0,&6,QWHJUDWHG3UR[\ 'HYLFH,WHP

The following diagram describes the objects located under "Device" for SINUMERIK NX
10.3/15.3:

'HYLFH

5DFN 'HYLFH,WHP

+HDGPRGXOH 'HYLFH,WHP

The following diagram describes the objects located under "Device" for ADI4:

Openness: API for automation of engineering workflows


756 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

'HYLFH

5DFN 'HYLFH,WHP

+HDGPRGXOH 'HYLFH,WHP

$[LVVHSDUDWRU 'HYLFH,WHP

$[LVVHSDUDWRU 'HYLFH,WHP

$[LVVHSDUDWRU 'HYLFH,WHP

$[LVVHSDUDWRU 'HYLFH,WHP

%ODQNPRGXOH 'HYLFH,WHP

%ODQNPRGXOH 'HYLFH,WHP

%ODQNPRGXOH 'HYLFH,WHP

%ODQNPRGXOH 'HYLFH,WHP

%ODQNPRGXOH 'HYLFH,WHP

', 'HYLFH,WHP

'2 'HYLFH,WHP

'ULYH 'HYLFH,WHP

'ULYH 'HYLFH,WHP

'ULYH 'HYLFH,WHP

'ULYH 'HYLFH,WHP

(QFRGHU 'HYLFH,WHP

(QFRGHU 'HYLFH,WHP

(QFRGHU 'HYLFH,WHP

(QFRGHU 'HYLFH,WHP

For more information on TIA Portal Openness object model, see Chapter "TIA Portal Openness
APIl".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 757
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

5.18.5 Code example

5.18.5.1 General
The following code examples describe the basic procedure for various applications. The code is
not necessarily complete or compilable.

5.18.5.2 Executing the first steps in SINUMERIK


• Connect the TIA Portal Openness application with the TIA Portal.
• Open your project.
The following example shows how you can determine which SINUMERIK Toolbox version is
installed.

Determining the SINUMERIK Toolbox version


using Siemens.Engineering;
if (tiaProcess.InstalledSoftware.Any(sw => sw.Name.Equals("SINUMERK Toolbox") &&
sw.Version.Equals("V17")))
{
Console.WriteLine("SINUMERIK Toolbox is available");
}
// "V17" is the current SINUMERIK version started at October 2021.

5.18.5.3 Creating an NCU


You create a SINUMERIK NCU using the CreateWithItem() method of the Devices
Collection. SINUMERIK NCUs are specified using method parameters. The format of the
parameters is described in the following.

Creating an NCU
Parameter format for SINUMERIK NCU:
CreateWithItem(@"OrderNumber:mlfb/
FirmwareVersion/","NameOfTheDevice",positionNumber)
The positionNumber parameter is optional.
The following example shows how you create a SINUMERIK 840D sl NCU 720.3 PN control
system.

Creating a SINUMERIK 840D sl NCU 720.3 PN


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
Project tiaproject= portal.Projects.Open("..."); //The path of the project

Device NCUDevice = tiaproject.Devices.CreateWithItem("@OrderNumber:6FC5


372-0AA30-0AA0/4.8/", "NCU 720.3 PN", string.Empty, "TestDevice");

Openness: API for automation of engineering workflows


758 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

5.18.5.4 Creating an NX module


You create an NX module using the Device CreateWithItem method. You then connect the
NX module to an NCU.
The following type identifiers are used for SINUMERIK NX modules:

SINUMERIK NX module Type identifier


SINUMERIK NX10.3 OrderNumber:6SL3 040-1NC00-0Axx/Vy.z
SINUMERIK NX15.3 OrderNumber:6SL3 040-1NB00-0Axx/Vy.z

The following example shows how you can create a SINUMERIK NX module.

Creating an NX module
project.Devices.CreateWithItem("OrderNumber:6SL3040-1NC00-0AA0/
V5.1", "MyNXDevice", "TestDevice");

Version compatibility
The firmware version of the NX module must match the firmware version of SINAMICS
Integrated - and must be compatible with the firmware version of the NCU.
An NX firmware version that deviates from SINAMICS Integrated cannot be assigned via
Openness.
The following table lists the version compatibility for 840D sl:

NCU firmware (840D sl) SINAMICS Integrated/NX firmware


V4.5 V4.5
V4.7 V4.7
V4.8 V5.1
V4.91 V5.2
V4.92
V4.93
V4.94
V4.95

5.18.5.5 Connecting an NX module with NCU

Connecting an NX module with an NCU


To connect an NX module with an NCU via subnet type "ProfibusIntegrated", the
"NetworkInterface" service must be loaded via the header module of NX.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 759
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

The following example shows how you can load the "NetworkInterface" service.

Loading the NetworkInterface service


foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.HM)
{
var networkInterface = deviceItem.GetService<NetworkInterface>();
// do something
}
}
}

The following example shows how you can connect an NX module with an NCU via
"ProfibusIntegrated":

Connecting an NX module via ProfibusIntegrated


Subnet pbiSubnet = ...;
Node node = networkInterface.Nodes.FirstOrDefault();
node.ConnectToSubnet(pbiSubnet);

The DP address is assigned to the fixed NX in Openness via DRIVE-CLiQ port. Each port label has a
fixed DP-integrated address.
The DP address must be assigned to the NX before connection to the NCU.

5.18.5.6 Activating Safety Integrated

Activating Safety Integrated


With TIA Portal Openness, you can activate Safety Integrated (F-PLC) in the properties of the NCU.

Note
Effects on telegram configuration
The Safety Integrated mode used affects the telegram configuration because telegrams other
than the ones used for inactive Safety Integrated mode are used in Safety Integrated plus (F-PLC)
mode.
However, added or changed telegrams are retained if they are compatible with the newly
selected Safety Integrated mode.
If applicable, after the mode change in the telegram configuration, ensure that any adjustments
are still available.

You activate and deactivate Safety Integrated (F-PLC) with the SafetyModeProvider service.

Note
The PLC must be in offline mode if Safety Integrated (F-PLC) is being activated or deactivated.

Openness: API for automation of engineering workflows


760 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

The following example shows how to call the SafetyModeProvider service:

Calling SafetyModeProvider
...
Siemens.Engineering.HW.Device ncu = ...;
try
{
SafetyModeProvider provider = ncu.GetService<SafetyModeProvider>();
//Perform the safety mode change:
provider.SetSafetyMode(SafetyMode.DbSI);
}
catch( (EngineeringException ex) )
{
// Handle safety mode change failure
}

The following example shows how to call the current Safety Integrated setting on the device:

Calling the safety setting of the device


...
Siemens.Engineering.HW.Device ncu = ...;
try
{
SafetyModeProvider provider = ncu.GetService<SafetyModeProvider>();
//Query the safety mode:
SafetyMode safetyMode = provider.CurrentMode;
}
catch( (EngineeringException ex) )
{
// Handle any failure
}

5.18.5.7 Accessing PLC software

Overview
The following diagram shows the software container and the PLC software in the object model
(Page 767):

'HYLFH

5DFN 'HYLFH,WHP

3/& 'HYLFH,WHP

6RIWZDUH&RQWDLQHU

3OF6RIWZDUH

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 761
TIA Portal Openness API
5.18 Functions for SINUMERIK 840D sl

The following code example shows how to find a PLC, irrespective of its specific implementation
(integrated SINUMERIK PLC, SIMATIC PLC, software PLC in the PC) based on the "CPU" property:

Finding PLCs
Device ncuDevice = ...
DeviceItem plc = GetPlc(ncuDevice.DeviceItems);

...
DeviceItem GetPlc(DeviceItemComposition deviceItems)
{
if (deviceItems.Count == 0)
{
return null;
}
foreach (var deviceItem in deviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.CPU)
return deviceItem;

DeviceItem plc = GetPlc(deviceItem.DeviceItems);


if (plc != null)
return plc;
}

return null;
}  

Find out more about accessing the PLC software container under "Accessing software goals".

Openness: API for automation of engineering workflows


762 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

5.19 Functions for SINUMERIK ONE

5.19.1 Introduction
Using TIA Portal-Openness, you automate the engineering and control the TIA Portal using a
program that you created yourself.
In this help document, you can find a lot of information and code examples for this program that
you generate yourself. You can also generate and use your own programs for the TIA Portal
"SINUMERIK" application.

Further information
Before you generate your own program for SINUMERIK from the sample codes listed in the
following, please note the general information on Openness, which you can find in this help
under the following keywords:
• Preconditions for using TIA Portal Openness
• Installing TIA Portal Openness
• Access the TIA Portal
• TIA Portal Openness object model
• Programming steps

5.19.2 Type identifier designation of the components


Each SINUMERIK component has a unique number, which is designated as type identifier
(TypeIdentifier) . In the Openness program code, you can use the type identifier to clearly
identify and designate a component. For example, the type identifier for SINUMERIK ONE NCU
1750 "Article No.: 6FC5 317-5AA00-0Axx/Vy.z".
The type identifier is displayed when creating a device using the dialog "Add new device" and in
the tabular device overview.
You can copy the type identifier into your Openness application.
The type identifier is expected in Openness as a current parameter when a method is called, e.g.
the CreateWithItem() method.

Activating display of the type identifier in SINUMERIK


1. In the project view, choose "Options > Settings" from the menu.
The "Settings" configuration area opens.
2. In the secondary navigation, select entry "Hardware configuration".
3. Activate option "Activate display of the type identifier for devices and modules".
The type identifier display is now active.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 763
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

5.19.3 Fundamentals
You can create the following SINUMERIK devices in the TIA Portal with Openness:
• NCU
• NX module
• PPU
To create the SINUMERIK devices, use the method CreateWithItem() of the Devices
Collection.

Note
All integrated subcomponents of a SINUMERIK-NCU - such as PLC, NCK, CP, HMI and SINAMICS
Integrated - are automatically created at the same subordinate level.

Special issues when creating SINUMERIK devices


The names of the subracks correspond to the NCU types and are write protected in the user
interface. You must also use the names of the subracks in the TIA Portal Openness. Use the
following standard names of the subracks for creating a device using a device element type
identifier with the Device CreateWithItem method:

SINUMERIK device Standard subrack names


SINUMERIK ONE NCU 1740 NCU 1740
SINUMERIK ONE NCU 1750 NCU 1750
SINUMERIK ONE NCU 1760 NCU 1760
SINUMERIK ONE PPU 1740 PPU 1740

Note
Alternatively, you can omit the parameter names. The standard name is used if the name is "null"
or "String.Empty".

The following parameters can be used with the CreateWithItem() method:


• default name, e.g. project.Devices.CreateWithItem("OrderNumber:6FC5
317-5AA00-0AA0/V6.13", "NCU 1750", "TestDevice");
• null, e.g. project.Devices.CreateWithItem("OrderNumber:6FC5
317-5AA00-0AA0/V6.13", null, "TestDevice");
• string.Empty, e.g. project.Devices.CreateWithItem("OrderNumber:6FC5
317-5AA00-0AA0/V6.13", string.Empty, "TestDevice");
Additional information about the call parameters associated with the CreateWithItem()
method is provided in Chapter "Creating a device".
The following table lists the assignment of the devices and their type identifiers:

SINUMERIK device Type identifier


SINUMERIK ONE NCU 1740 Article No.: 6FC5 317-4AA00-0Axx/Vy.z

Openness: API for automation of engineering workflows


764 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

SINUMERIK ONE NCU 1750 Article No.: 6FC5 317-5AA00-0Axx/Vy.z


SINUMERIK ONE NCU 1760 Article No.: 6FC5 317-6AA00-0Axx/Vy.z
SINUMERIK ONE PPU 1740 Article No.: 6FC5 317-4AA00-1xxx/Vy.z

When creating SINUMERIK devices, place holders in the type identifier are permissible. You can
subsequently replace these placeholders by device-specific characters.

Classification of the device element


Every device or device element has obligatory attributes, which are read and written to.
Additional information about the attributes that are supported in Openness is provided in
Chapter "Functions on device elements".
The classification attributes of the device element are write protected, and not visible in the user
interface of the TIA Portal.
The classification attributes have the value "DeviceItemClassification":

Value of the classification attribute Description


DeviceItemClassifications.None (0) No classification.
DeviceItemClassifications.CPU (1) The device element is a CPU.
DeviceItemClassifications.HM (2) The device element is a header module.

If you interrogate the value of the device element via the integrated PLC, then for a SINUMERIK
device, this is the value "CPU (1)".
In the Openness object model, the following components act as header module:
• SINAMICS Integrated
• NX module
In all other cases, the value of the classification attribute is "DeviceItemClassification" "None" (0).

Finding device elements via the "Header module" property


The following examples show how you can find device elements with the "Header module"
property, for example, before you configure a telegram.
You can only read this property, but cannot set it at device elements.

Finding Sinamics Integrated / NX via the "Header module" property


foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.HM)
{
var driveObjectContainer = deviceItem.GetService<DriveObjectContainer>();
// do something
}
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 765
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

See also
Creating an NCU (Page 787)
Creating an NX module (Page 787)

Openness: API for automation of engineering workflows


766 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

5.19.4 Object model

Overview
The following diagram describes the objects located under "Device" for SINUMERIK ONE:

'HYLFH

5DFN 'HYLFH,WHP

6,1$0,&6,QWHJUDWHG3UR[\ 'HYLFH,WHP

3/& 'HYLFH,WHP

&DUGUHDGHUZULWHU 'HYLFH,WHP

23&8$ 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

'3,QWHUIDFH 'HYLFH,WHP

1&. 'HYLFH,WHP

'3,QWHJUDWHG,QWHUIDFH 'HYLFH,WHP

&3 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

31,(,QWHUIDFH 'HYLFH,WHP

31,(3RUW 'HYLFH,WHP

+0, 'HYLFH,WHP

For more information on the TIA Portal Openness object model, see Chapter "TIA Portal
Openness APIl".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 767
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Available namespaces for telegram configuration


The following namespaces are valid in SINUMERIK Openness for the telegram configuration
interfaces:

Namespace Assembly
Siemens.Engineering.MC.Drive Siemens.Engineering.MC.DriveConfiguration
Configuration (Page 769) in Siemens.Engineering.dll
Siemens.Engineering.MC.Drive Siemens.Engineering.MC.Drives
s (Page 777) in Siemens.Engineering.dll

Note
With the namespace Siemens.Engineering.MC.DriveConfiguration, additional
functions are available, e.g. you can create, delete or reorder drive objects.
In the long term, the namespace Siemens.Engineering.MC.DriveConfiguration
remains. However, the namespace Siemens.Engineering.MC.Drives will still be
supported into the next versions of Openness for compatibility reasons.

The following diagrams describe the objects located under "Device" for SINUMERIK NX 10.3/15.3
(availability of services depends on the namespace).
For new applications, use the namespace Siemens.Engineering.MC.DriveConfiguration (and
thus the DriveObjectCollection service) because the namespace
Siemens.Engineering.MC.Drives (and thus the DriveObjectContainer service) is still supported
for compatibility reasons, but offers less functionality.

'HYLFH

5DFN 'HYLFH,WHP

+HDGPRGXOH 'HYLFH,WHP

'ULYH2EMHFW&ROOHFWLRQ 6HUYLFH

'HYLFH

5DFN 'HYLFH,WHP

+HDGPRGXOH 'HYLFH,WHP

'ULYH2EMHFW&RQWDLQHU 6HUYLFH

Openness: API for automation of engineering workflows


768 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

5.19.5 Reference

5.19.5.1 Namespace Siemens.Engineering.MC.DriveConfiguration

DriveObject

DriveObject
The DriveObject class allows access to the drive object. Using the drive object, the telegram
can be accessed, for example.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the properties of the class:

Name Data type Access Access Description


mode
Telegram TelegramComposi read - Returns a list with the available tele‐
s tion grams of the drive object.
The list can be changed with
the TelegramComposition class.
Parent IEngineeringObj read - Returns the reference to the higher-
ect level class
(DriveObjectCollection
and DriveObjectContainer).
Category read - Returns the reference to the higher-
level class
(DriveObjectCategory)
Name read - Returns the name of the drive object.

The following table describes the methods of the class:

Name Description
GetAttribute Performs read access to an attribute of a drive object
GetAttributes Performs read access to all attributes of a drive object
GetAttributeInfos Performs read access to information on attributes of a drive object
SetAttribute Performs write access to an attribute of a drive object
SetAttributes Performs write access to all attributes of a drive object
Delete Deletes the drive object instance at which the "Delete" is called

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 769
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

DriveObjectCollection

DriveObjectCollection
The DriveObjectCollection is a service of the drive object (DeviceItem) of the current
device (Device).

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the navigators of the DriveObjectCollection:

Name Data type Access Access Description


mode
DriveObj DriveObjectCompo read - Returns a list with the available
ects sition drive objects. The drive objects al‐
low access to the drive parameters
and telegrams.

The following table describes the methods of the class:

Name Description
GetAttribute Performs read access to an attribute of DriveObjectCollection
GetAttributes Performs read access to all attributes of DriveObjectCollection
GetAttributeInfos Performs read access to information on attributes
of DriveObjectCollection
SetAttribute Performs write access to an attribute of DriveObjectCollection
SetAttributes Performs write access to all attributes of DriveObjectCollection

DriveObjectComposition

DriveObjectComposition
The DriveObjectComposition class allows access to available telegrams of a drive object
and contains all of the drive objects of an NCU or NX module.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


770 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following table describes the properties of the class:

Name Data type Access Access Description


mode
Parent IEngineeringObject read - Returns the reference to the
higher-level
class
(DriveObjectContainer)
.
Count read -
IsReadOnly read -

The following table describes the methods of the class:

Name Description
GetEnumerator Facilitates the iteration over the specified set of elements
Contains Determines whether the specified instance is contained in the set of the ele‐
ments.TRUE: The container contains the instance FALSE: The container does
not contain the instance
IndexOf Returns the index in the set of the elements for the queried instance.
Create Creates a DriveObjectComposition class
Find Searches for a DriveObjectComposition class

DriveObjectCategory

DriveObjectCategory
The enum DriveObjectCategory contains predefined categories of the drive objects. Read
access to DriveObjectCategory is possible.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table contains the predefined categories of the drive objects:

Supported drive objects in SINUMERIK DriveObjectCategory


SinumerikDriveAxis SERVO, ENC, HLA, TM41
SinumerikControlUnit CU_I, CU_NX_CX
SinumerikInfeed A_INF, B_INF, S_INF

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 771
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

TelegramComposition

TelegramComposition
The TelegramComposition class facilitates the access to the telegrams of a drive object
(DriveObject (Page 769)). The structure of a telegram can be read out via the Telegram
(Page 773) class.
Changes to telegram objects (e.g. changing the safety telegram) can result in the relevant
telegram object being deleted in the TelegramComposition or a new telegram object being
created. In this case, you must search through the TelegramComposition again to find the
new telegram object (Page 773) again after the change.
If the respective drive object does not support telegrams, the value for
TelegramComposition is returned blank.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the properties of the class:

Name Data type Access Access Description


mode
Parent IEngineeringObject read - Returns the reference to the
higher-level
class (DriveObject).
Count read -
IsReadOnly read -

The following table describes the methods of the class:

Name Description
Create(enum TelegramId Id) Creates a telegram; the type of the telegram corre‐
sponds to the ID.
int IndexOf(TelegramType) Returns the index in the set of the elements for the
queried instance.
bool Contains Determines as to whether the specified instance is
included in the set of elements.
TRUE: The container contains the instance
FALSE: The container does not contain the in‐
stance
IEnumerator GetEnumerator Allows IEnumerator<DriveObject> the itera‐
tion via the given set of the elements

Openness: API for automation of engineering workflows


772 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Telegram

Telegram
The Telegram class allows access to the structure of a telegram from a drive object.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the properties of the class:

Name Data type Access mode Ac‐ Description


cess
Id Int32 read - Returns the ID of the telegram.
Type enum:Tele‐ read - Returns the type of telegram as Enum
gramType TelegramType.
(Page 774)
Addresses AddressCom‐ read - Returns an AdressComposition with
position information on the address.
(Page 775)

The following table describes the methods of the class:

Name Description
GetSize(AddressIoType (Page 776)) Returns the size of the inputs or outputs of the telegram.
CanSetSize (AddressIoType Returns true if the size of the telegram can be changed as
(Page 776), Int32, bool) parameterized.
SetSize Performs write access to the telegram size
Delete Deletes the telegram instance at which "Delete" is called
GetAttribute Performs read access to a telegram attribute
GetAttributes Performs read access to all telegram attributes
GetAttributeInfos Performs read access to information on telegram attributes
SetAttribute Performs write access to a telegram attribute
SetAttributes Performs write access to all telegram attributes

Properties of Safety telegrams


The following table describes the additional properties of the "Telegram" class of the type
"SafetyTelegram".

Name Data type Access Access Description


mode
Failsafe_FSourceAddress UInt32 read Dynamic PROFIsafe source address
Failsafe_FDestinationAddress UInt32 read/ Dynamic PROFIsafe destination address
write

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 773
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Name Data type Access Access Description


mode
Failsafe_FIODBNumber UInt32 read/ Dynamic Safety DB number, write access only possi‐
write ble if the property
"Failsafe_ManualAssignmentFIODB
Number" is assigned the value "1"
Failsafe_FIODBName string read Dynamic Name Safety DB
Failsafe_ManualAssignmentFIODBNu bool read/ Dynamic Setting for manual assignment of the prop‐
mber write erty "Failsafe_FIODBNumber"
Failsafe_FMonitoringtime UInt32 read/ Dynamic Safety monitoring time, write access only
write possible if the property
"Failsafe_ManualAssignmentFMoni
toringtime is set to "true"
Failsafe_ManualAssignmentFMonito bool read/ Dynamic Setting for manual assignment of the prop‐
ringtime write erty "Failsafe_FMonitoringtime"

The additional properties are accessed via GetAttribute and SetAttribute, e.g.
GetAttribute("Failsafe_FSourceAddress"). Uint32 is expected as return value.

TelegramType

TelegramType
The Enum TelegramType contains predefined telegram types.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the enum entries:

Name Description
MainTelegram Main telegram: e.g. telegram 136
SupplementaryTelegram Supplementary telegram: e.g. telegram 701
AdditionalTelegram Additional telegram: free telegram
SafetyTelegram Safety telegram: e.g. telegram 903
ProcessMonitoringTelegram Process monitoring telegram, e.g. telegram 1100

Note
The torque telegram (TorqueTelegram) is not supported, although it is available in the TIA
Portal Openness API in the SINUMERIK context.

Openness: API for automation of engineering workflows


774 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

TelegramPart

TelegramPart
The enum TelegramPart contains the parts of a telegram.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the enum entries:

Name Description
Unknown Unknown part of a telegram
Overall All parts of a telegram in one telegram: BaseTelegram, Exten‐
sion and PIV1) of a telegram
BaseTelegram Main part of a telegram
Extension Telegram extension
PKW Parameter identification value of a telegram
1)
PKW is not available in the SINUMERIK context.

TelegramId

TelegramId
The enum TelegramId contains the telegram numbers that are relevant for communication
between the PLC and the drive. The IDs are defined via the PROFIdrive standard.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll

AddressComposition

AddressComposition
The AddressComposition class represents the address of a telegram.

namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 775
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following table describes the properties of the class:

Name Data type Access Access Description


mode
IoType enum: AddressIoType read - Returns information on the type of
(Page 776) the address.
Context enum: AddressContext read Access on‐ Returns information on the con‐
(Page 777) ly possible text of the address.
via
GetAttri
bute
or
SetAttri
bute
StartAddres Int32 read/ - Returns the start address of the
s write telegram or defines the start ad‐
dress.
Length Int32 read - Returns the length of the telegram.
IndexOf int32 read - Returns the index in the set of the
elements for the queried instance.
Contains bool read - Determines as to whether the
specified instance is included in
the set of elements.
TRUE: The container contains the
instance
FALSE: The container does not
contain the instance
GetEnumerat IEnumerator<DriveO read - Facilitates the iteration over the
or bject> specified set of elements

Note
If you want to navigate back to the telegram via Address.Parent, instead of
namespace Siemens.Engineering.MC.Drives.Telegram,
namespace Siemens.Engineering.MC.DriveConfiguration.Telegram is called.

You can find further information about TIA Portal Openness libraries under "Standard libraries".

AddressIoType

AddressIoType
The Enum AddressIoType contains information on the type of the address.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


776 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following table describes the enum entries:

Name Description
AddressIoType.None The IO type cannot be used
AddressIoType.Input Type is an input address
AddressIoType.Output Type is an output address
AddressIoType.Diagnosis Type is a diagnosis address
AddressIoType.Substitute Type is a substitute address

You can find further information about TIA Portal Openness libraries under "Standard libraries".

AddressContext

AddressContext
The Enum AddressContext contains information on the context of the address.

Namespace: Siemens.Engineering.MC.DriveConfiguration
Assembly: Siemens.Engineering.MC.DriveConfiguration
in Siemens.Engineering.dll
The following table describes the enum entries:

Name Description
AddressContext.None No context has been found for the address
AddressContext.Device Context is a device address
AddressContext.Head Context is a head address

You can find further information about TIA Portal Openness libraries under "Standard libraries".

5.19.5.2 Namespace Siemens.Engineering.MC.Drives

DriveObject

DriveObject
The DriveObject class allows access to the drive object. Using the drive object, the telegram
can be accessed, for example.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 777
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following table describes the properties of the class:

Name Data type Access Access Description


mode
Telegram TelegramCompos read - Returns a list with the available tele‐
s ition grams of the drive object.
The list can be changed with
the TelegramComposition class.
Parent IEngineeringOb read - Returns the reference to the higher-
ject level class
(DriveObjectContainer).

The following table describes the methods of the class:

Name Description
GetAttribute Performs read access to an attribute of a drive object
SetAttribute Performs write access to an attribute of a drive object
GetEnumerator Facilitates the iteration over the specified set of elements

See also
TelegramComposition (Page 779)

DriveObjectContainer

DriveObjectContainer
The DriveObjectContainer is a service of the drive object (DeviceItem) for the current
device (Device).

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the navigators of the DriveObjectContainer:

Name Data type Access Access Description


mode
DriveObj DriveObjectCompo read - Returns a list with the available
ects sition drive objects. The drive objects al‐
low access to the drive parameters
and telegrams.
Parent IEngineeringObje read - Returns the reference to the higher-
ct level class (DeviceItem).

Openness: API for automation of engineering workflows


778 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

DriveObjectComposition

DriveObjectComposition
The DriveObjectComposition class facilitates the access to available telegrams of a drive
object.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll

The following table describes the properties of the class:

Name Data type Access Access Description


mode
IndexOf int32 read - Returns the index in the set of
the elements for the queried
instance.
Contains bool read - Determines as to whether the
specified instance is included
in the set of elements.
TRUE: The container contains
the instance
FALSE: The container does
not contain the instance
GetEnumerator IEnumerator<Dr read - Facilitates the iteration over
iveObject> the specified set of elements

TelegramComposition

TelegramComposition
The TelegramComposition class facilitates the access to the telegrams of a drive object
(DriveObject (Page 777)). The structure of a telegram can be read out via the Telegram
(Page 781) class.
Changes to telegram objects (e.g. changing the safety telegram) can result in the relevant
telegram object being deleted in the TelegramComposition or a new telegram object being
created. In this case, you must search through the TelegramComposition again to find the
new telegram object (Page 781) again after the change.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 779
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following table describes the methods of the class:

Name Description
CanInsertAdditionalTelegram(Int32, Returns true if an extension can be created in
Int32) accordance with the parameterized sizes (input
and output sizes).
InsertAdditionalTelegram(Int32, Int32) Creates an extension for the drive object in ac‐
cordance with the parameterized sizes and re‐
turns true if the extension could be inserted.
In the event of an error,
an
EngineeringTargetInvocationExcepti
on is triggered.
CanInsertSupplementaryTelegram(Int32) Returns true if a supplementary telegram can
be created in accordance with the parameterized
telegram number.
InsertSupplementaryTelegram(Int32) Creates the supplementary telegram with the
parameterized telegram number and
returns true if the telegram could be inserted.
In the event of an error,
an
EngineeringTargetInvocationExcepti
on is triggered.
CanInsertSafetyTelegram(Int32) Returns true if a safety telegram can be gener‐
ated corresponding to the parameterized tele‐
gram number.
InsertSafetyTelegram(Int32) Creates the supplementary telegram with the
parameterized telegram number and
returns true if the telegram could be inserted.
In the event of an error,
an
EngineeringTargetInvocationExcepti
on is triggered.
EraseTelegram(TelegramType) Returns true if the parameterized telegram
could be deleted.
Standard telegrams cannot be deleted.
In the event of an error,
an
EngineeringTargetInvocationExcepti
on is triggered.
Find(TelegramType) Returns the Telegram (Page 781) object if it
could be found via the parameterized telegram
type.
null if the telegram is not found.
Example
Telegram telegram =
telegrams.Find(TelegramType.MainTe
legram);
int IndexOf(TelegramType) Returns the index in the set of the elements for
the queried instance.

Openness: API for automation of engineering workflows


780 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Name Description
Parent Returns the reference to the higher-level class
(DriveObject).
bool Contains Determines as to whether the specified instance
is included in the set of elements.
TRUE: The container contains the instance
FALSE: The container does not contain the in‐
stance
IEnumerator GetEnumerator Facilitates IEnumerator<DriveObject> the
iteration over the specified set of elements

Telegram

Telegram
The Telegram class allows access to the structure of a telegram from a drive object.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the properties of the class:

Name Data type Access mode Ac‐ Description


cess
TelegramNumbe Int32 read - Returns the number of the main tele‐
r gram or specifies the number.
A freely configurable telegram has the
number 999.
Type enum:Tele‐ read - Returns the type of telegram as Enum
gramType TelegramType.
(Page 783)
Addresses AddressCom‐ read - Returns an AdressComposition with
position information on the address.
(Page 784)

The following table describes the methods of the class:

Name Description
CanChangeTelegram(Int32) Returns true if the telegram can be changed to the parame‐
terized standard type.
GetSize(AddressIoType (Page 785)) Returns the size of the inputs or outputs of the telegram.
CanChangeSize(AddressIoType Returns true if the size of the telegram can be changed as
(Page 785), Int32, bool) parameterized. Standard telegrams can only be enlarged.
The retention of the previous telegram address is taken into
account when the option is parameterized with true.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 781
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Name Description
ChangeSize(AddressIoType Returns true if the size of the telegram could be changed as
(Page 785), Int32, bool) parameterized.
The retention of the previous telegram address is taken into
account when the option is parameterized with true.
GetEnumerator Facilitates the iteration over the specified set of elements

Properties of Safety telegrams


The following table describes the additional properties of the "Telegram" class of the type
"SafetyTelegram".

Name Data Access Access Description


type mode
Failsafe_FSourceAddress UInt32 read Access only possi‐ PROFIsafe source ad‐
ble dress
via
GetAttribute
or SetAttribute
Failsafe_FDestinationAddre UInt32 read/ Access only possi‐ PROFIsafe destina‐
ss write ble tion address
via
GetAttribute
or SetAttribute
Failsafe_FIODBNumber UInt32 read/ Access only possi‐ Safety DB number,
write ble write access only pos‐
via sible if the property
GetAttribute "Failsafe_Manual
or SetAttribute AssignmentFIODB
Number" is assigned
the value "1"
Failsafe_FIODBName string read Access only possi‐ Name Safety DB
ble
via
GetAttribute
or SetAttribute
Failsafe_ManualAssignmentF bool read/ Access only possi‐ Setting for manual as‐
IODBNumber write ble signment of the prop‐
via erty
GetAttribute "Failsafe_FIODBN
or SetAttribute umber"

Openness: API for automation of engineering workflows


782 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Name Data Access Access Description


type mode
Failsafe_FMonitoringtime UInt32 read/ Access only possi‐ Safety monitoring
write ble time, write access on‐
via ly possible if the prop‐
GetAttribute erty
or SetAttribute "Failsafe_Manual
AssignmentFMoni
toringtime is set to
"true"
Failsafe_ManualAssignmentF bool read/ Access only possi‐ Setting for manual as‐
Monitoringtime write ble signment of the prop‐
via erty
GetAttribute "Failsafe_FMonit
or SetAttribute oringtime"

The additional properties are accessed via GetAttribute and SetAttribute, e.g.
GetAttribute("Failsafe_FSourceAddress"). Uint32 is expected as return value.

TelegramType

TelegramType
The Enum TelegramType contains predefined telegram types.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the enum entries:

Name Description
MainTelegram Main telegram: e.g. telegram 136
SupplementaryTelegram Supplementary telegram: e.g. telegram 701
AdditionalTelegram Additional telegram: free telegram
SafetyTelegram Safety telegram: e.g. telegram 903

Note
The torque telegram (TorqueTelegram) is not supported, although it is available in the TIA
Portal Openness API in the SINUMERIK context.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 783
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

AddressComposition

AddressComposition
The AddressComposition class represents the address of a telegram.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the properties of the class:

Name Data type Access Access Description


mode
IoType enum: AddressIoType read - Returns information on the type of
(Page 785) the address.
Context enum: AddressContext read Access on‐ Returns information on the con‐
(Page 785) ly possible text of the address.
via
GetAttri
bute
or
SetAttri
bute
StartAddres Int32 read/ - Returns the start address of the
s write telegram or defines the start ad‐
dress.
Length Int32 read - Returns the length of the telegram.
IndexOf int32 read - Returns the index in the set of the
elements for the queried instance.
Contains bool read - Determines as to whether the
specified instance is included in
the set of elements.
TRUE: The container contains the
instance
FALSE: The container does not
contain the instance
GetEnumerat IEnumerator<DriveO read - Facilitates the iteration over the
or bject> specified set of elements

Note
If you want to navigate back to the telegram via Address.Parent, instead of
namespace Siemens.Engineering.MC.Drives.Telegram,
namespace Siemens.Engineering.MC.DriveConfiguration.Telegram is called.

You can find further information about TIA Portal Openness libraries under "Standard libraries".

Openness: API for automation of engineering workflows


784 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

AddressContext

AddressContext
The Enum AddressContext contains information on the context of the address.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the enum entries:

Name Description
AddressContext.None No context has been found for the address
AddressContext.Device Context is a device address
AddressContext.Head Context is a head address

You can find further information about TIA Portal Openness libraries under "Standard libraries".

AddressIoType

AddressIoType
The Enum AddressIoType contains information on the type of the address.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the enum entries:

Name Description
AddressIoType.None The IO type cannot be used
AddressIoType.Input Type is an input address
AddressIoType.Output Type is an output address
AddressIoType.Diagnosis Type is a diagnosis address
AddressIoType.Substitute Type is a substitute address

You can find further information about TIA Portal Openness libraries under "Standard libraries".

5.19.5.3 ArchiveProvider

ArchiveProvider
The ArchiveProvider class is used to generate the PLC archives.

Namespace: Siemens.Engineering.HW.Utilities
Assembly: Siemens.Engineering.HW.Utilities
in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 785
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following table describes the methods of the ArchiveProvider class:

Name Parameter Descrip‐


tion
Archive DeviceItem plc Creates a
FileInfo path PLC ar‐
chive
Siemens.Engineering.MC.Sinumerik.SinumerikA
rchivationMode
String comment (optional)
String author (optional)
Retrieve FileInfo archivePath Retrieves
a created
archive in
the TIA
Portal

Note
If safety is activated, you cannot generate any archive via Openness.

5.19.6 Code example

5.19.6.1 General
The following code examples describe the basic procedure for various applications. The code is
not necessarily complete or compilable.

5.19.6.2 Executing the first steps in SINUMERIK


• Connect the TIA Portal Openness application with the TIA Portal.
• Open your project.
The following example shows how you can determine which SINUMERIK Toolbox version is
installed.

Determining the SINUMERIK Toolbox version


using Siemens.Engineering;
if (tiaProcess.InstalledSoftware.Any(sw => sw.Name.Equals("SINUMERK Toolbox") &&
sw.Version.Equals("V17")))
{
Console.WriteLine("SINUMERIK Toolbox is available");
}
// "V17" is the current SINUMERIK version started at October 2021.

Openness: API for automation of engineering workflows


786 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

5.19.6.3 Creating an NCU


You create a SINUMERIK NCU using the CreateWithItem() method of the Devices
Collection. SINUMERIK NCUs are specified using method parameters. The format of the
parameters is described in the following.

Creating an NCU
Parameter format for SINUMERIK NCU:
CreateWithItem(@"OrderNumber:mlfb/FirmwareVersion/",
"StandardSubrackName", "NameOfTheDevice")
The following example shows how you can create a SINUMERIK ONE NCU 1750 module.

Creating a SINUMERIK ONE NCU 1750 module


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
Project tiaproject= portal.Projects.Open("..."); //The path of the project

Device NCUDevice = tiaproject.Devices.CreateWithItem("@OrderNumber:6FC5


317-5AA00-0AA0/6.13/", "NCU 1750", "TestDevice");

5.19.6.4 Creating an NX module


You create an NX module using the Device CreateWithItem method. You then connect the
NX module to an NCU.
The following type identifiers are used for SINUMERIK NX modules:

SINUMERIK NX module Type identifier


SINUMERIK NX10.3 OrderNumber:6SL3 040-1NC00-0Axx/Vy.z
SINUMERIK NX15.3 OrderNumber:6SL3 040-1NB00-0Axx/Vy.z

The following example shows how you can create a SINUMERIK NX module.

Creating an NX module
project.Devices.CreateWithItem("OrderNumber:6SL3040-1NC00-0AA0/
V5.2", "MyNXDevice", "TestDevice");

Version compatibility
The firmware version of the NX module must match the firmware version of SINAMICS
Integrated - and must be compatible with the firmware version of the NCU.
An NX firmware version that deviates from SINAMICS Integrated cannot be assigned via
Openness.
The following table lists the version compatibility for SINUMERIK ONE:

NCU firmware (SINUMERIK ONE) SINAMICS Integrated/NX firmware


V6.13 V5.2
V6.14
V6.15

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 787
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

5.19.6.5 Connecting an NX module with NCU

Connecting an NX module with an NCU


To connect an NX module with an NCU via subnet type "ProfibusIntegrated", the
"NetworkInterface" service must be loaded via the header module of NX.
The following example shows how you can load the "NetworkInterface" service.

Loading the NetworkInterface service


foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.HM)
{
var networkInterface = deviceItem.GetService<NetworkInterface>();
// do something
}
}
}

The following example shows how you can connect an NX module with an NCU via
"ProfibusIntegrated":

Connecting an NX module via ProfibusIntegrated


Subnet pbiSubnet = ...;
Node node = networkInterface.Nodes.FirstOrDefault();
node.ConnectToSubnet(pbiSubnet);

The DP address is assigned to the fixed NX in Openness via DRIVE-CLiQ port. Each port label has a
fixed DP-integrated address.
The DP address must be assigned to the NX before connection to the NCU.

5.19.6.6 Accessing NCK events

NCK events
According to the SINUMERIK object model (Page 767), the NCK module is a DeviceItem.
With the following attributes of the NCK module, you can access the NCK events and configure
the NCK events in TIA Portal Openness:

Name Data type Access Description


mode
Boolean r/w Activating/deactivating the
HardwareInterruptNckToPlcSignalExch event
angeActive
String r/w Event name
HardwareInterruptNckToPlcSignalExch
angeEventName

Openness: API for automation of engineering workflows


788 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

r/w The OB assigned to the event


HardwareInterruptNckToPlcSignalExch Siemens.Engineering.SW
angeInterrupt .Blocks.OB
Int32 r/w Event priority
HardwareInterruptNckToPlcSignalExch
angePriority

All NCK events are triggered via HardwareInterrupt (hardware interrupt OB). The hardware
interrupt OBs interrupt the cyclical program processing due to a hardware event.
The following example shows how to determine the event name for an NCK module:

Determining the event name for an NCK module


DeviceItem nck = ...;
string eventName =
(string)nck.GetAttribute("HardwareInterruptNckToPlcSignalExchangeEventName");

The following example shows how to set the hardware interrupt:

Setting the hardware interrupt


... DeviceItem nck = ...;
OB ob40 = ... try
{
nck.SetAttribute("HardwareInterruptNckToPlcSignalExchangeInterrupt", ob40);
}
catch( (EngineeringException ex) )
{
// Handle setting failure
}

5.19.6.7 Creating archives

Creating archives for series commissioning


Using TIA Portal Openness, create and export SINUMERIK archives to simplify series
commissioning, for example.

Note
The PLC must be in offline mode while the archives are being created. The safety mode must not
be active.

You create SINUMERIK archives via the TIA Portal project property HwUtilities with the
SinumerikArchiveProvider service.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 789
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following example shows how to call the SinumerikArchiveProvider service:

Calling SinumerikArchiveProvider
Project project = ...;
SinumerikArchiveProvider archiveProvider =
project.HwUtilities.Find("SinumerikArchiveProvider") as SinumerikArchiveProvider;

if (archiveProvider != null)
{
// Work with the provider
}

The following example shows how to create a PLC archive which contains the hardware
information and all of the data blocks:

Creating a PLC archive


...
Siemens.Engineering.HW.DeviceItem plc = ...;

try {
// The file extension is required
string archivePath = string.Format(@"D:\some_path\{0}.dsf", plc.Name);

// Comment and author arguments are optional


archiveProvider.Archive(plc, new FileInfo(archivePath),
SinumerikArchivationMode.HardwareAndAllProgramBlocks);
}
catch (EngineeringTargetInvocationException ex)
{
// Handle archive failure
}

You can use the method as follows:


void Archive(DeviceItem plc, FileInfo path, SinumerikArchivationMode
content, String comment, String author)

Openness: API for automation of engineering workflows


790 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following example shows how to update the software portions of a previously created
archive:

Updating portions of archives


...
Siemens.Engineering.HW.DeviceItem plc_1 = ...;
Siemens.Engineering.HW.DeviceItem plc_1_copy = ...;
try {
// The file extension is required
string archivePath = @"D:\some_path\SinumerikArchive.dsf";

// Create a Sinumerik archive with HardwareAndAllProgramBlocks


archiveProvider.Export(plc_1, new FileInfo(archivePath),
SinumerikArchivationMode.HardwareAndAllProgramBlocks);

// Update the software part in the previously created archive using


UpdateProgramBlocksOfArchive method
archiveProvider.UpdateProgramBlocksOfArchive(plc_1_copy, new FileInfo(archivePath));
}
catch (EngineeringException ex)
{
// Handle export failure
}

5.19.6.8 Activating Safety Integrated

Activating Safety Integrated


With TIA Portal Openness, you can activate Safety Integrated (F-PLC) in the properties of the NCU.

Note
Effects on telegram configuration
The Safety Integrated mode used affects the telegram configuration because telegrams other
than the ones used for inactive Safety Integrated mode are used in Safety Integrated plus (F-PLC)
mode.
However, added or changed telegrams are retained if they are compatible with the newly
selected Safety Integrated mode.
If applicable, after the mode change in the telegram configuration, ensure that any adjustments
are still available.

You activate and deactivate Safety Integrated (F-PLC) with the SafetyModeProvider service.

Note
The PLC must be in offline mode if Safety Integrated (F-PLC) is being activated or deactivated.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 791
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following example shows how to call the SafetyModeProvider service:

Calling SafetyModeProvider
...
Siemens.Engineering.HW.Device ncu = ...;
try
{
SafetyModeProvider provider = ncu.GetService<SafetyModeProvider>();
//Perform the safety mode change:
provider.SetSafetyMode(SafetyMode.DbSI);
}
catch( (EngineeringException ex) )
{
// Handle safety mode change failure
}

The following example shows how to call the current Safety Integrated setting on the device:

Calling the safety setting of the device


...
Siemens.Engineering.HW.Device ncu = ...;
try
{
SafetyModeProvider provider = ncu.GetService<SafetyModeProvider>();
//Query the safety mode:
SafetyMode safetyMode = provider.CurrentMode;
}
catch( (EngineeringException ex) )
{
// Handle any failure
}

5.19.6.9 Accessing PLC software

Overview
The following diagram shows the software container and the PLC software in the object model
(Page 767):

'HYLFH

5DFN 'HYLFH,WHP

3/& 'HYLFH,WHP

6RIWZDUH&RQWDLQHU

3OF6RIWZDUH

Openness: API for automation of engineering workflows


792 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following code example shows how to find a PLC, irrespective of its specific implementation
(integrated SINUMERIK PLC, SIMATIC PLC, software PLC in the PC) based on the "CPU" property:

Finding PLCs
Device ncuDevice = ...
DeviceItem plc = GetPlc(ncuDevice.DeviceItems);

...
DeviceItem GetPlc(DeviceItemComposition deviceItems)
{
if (deviceItems.Count == 0)
{
return null;
}
foreach (var deviceItem in deviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.CPU)
return deviceItem;

DeviceItem plc = GetPlc(deviceItem.DeviceItems);


if (plc != null)
return plc;
}

return null;
}  

Find out more about accessing the PLC software container under "Accessing software goals".

5.19.6.10 Examples for Namespace Siemens.Engineering.MC.DriveConfiguration

Preparing telegrams
The drive communication of a SINUMERIK NCU is realized using telegrams via the SINAMICS
Integrated subcomponent and, if applicable, via additionally connected NX modules.

Note
The SINUMERIK NCU and a SINAMICS Integrated are located at the same level in the TIA Portal
Openness object model, and appear under "DeviceComposition" as two different devices.

Use "DriveObjectCollection" to configure a telegram. "DriveObjectCollection" is a


service of the drive object (device element) of the actual header module (device element).
To start the "DriveObjectCollection" service, navigate to SINAMICS Integrated or to the
header module of the NX module. The hierarchy between devices and device elements is
identical for SINAMICS Integrated and NX modules.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 793
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

The following example shows how to find "DriveObjectCollection" via the "Header
module" property:

Finding DriveObjectCollection via header module

foreach (Device device in project.Devices)


{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.HM)
{
var driveObjectCollection = deviceItem.GetService<DriveObjectCollection>();
// do something
}
}
}

The SINUMERIK NCU contains a SINAMICS Integrated proxy object with references to SINAMICS
Integrated.
To access a SINAMICS Integrated device or an NX module, from the SINUMERIK NCU navigate to
the DP Integrated interface via NCK. Then determine the PROFIBUS master system and navigate
to the connected slave.

Inserting and removing telegrams


The following example indicates how you can insert a telegram. You require a drive object for
access.
You distinguish between the telegram types using their IDs.

Inserting telegrams and accessing telegram attributes


using Siemens.Engineering.MC.DriveConfiguration;

Openness: API for automation of engineering workflows


794 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Inserting telegrams and accessing telegram attributes


TelegramComposition telegrams = drvObj.Telegrams;

//Create telegram
const int tgrmId = 136;
drvObj.Telegrams.CreateTelegram(tgrmId);

//Create safety telegram


const int tgrmId = 30;
drvObj.Telegrams.CreateTelegram(tgrmId);

// Get and set safety telegram attributes


uint watchDogTime =
(uint)safetyTgrm.GetAttribute("Failsafe_FMonitoringtime");

safetyTgrm.SetAttribute("Failsafe_FMonitoringtime", 300);

const int newSafetyTelegramNumber= 902;


if (safetyTgrm.CanChangeTelegram(newSafetyTelegramId)) {
safetyTgrm.TelegramId = newSafetyTelegramId; }

The following example indicates how you can remove a telegram.

Remove telegram
using Siemens.Engineering.MC.DriveConfiguration;
//Delete telegram
const int tgrmId = 136;
drvObj.Telegrams.DeleteTelegram(tgrmId);

Inserting and deleting safety telegrams


The following example shows how to insert a Safety telegram. You require a drive object for
access.

Inserting a Safety telegram and accessing telegram attributes


using Siemens.Engineering.MC.DriveConfiguration;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 795
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Inserting a Safety telegram and accessing telegram attributes


TelegramComposition telegrams = drvObj.Telegrams;

//Add safety telegram


const int tgrmId = 30;
drvObj.Telegrams.Create(tgrmId);

// Get and set safety telegram attributes


uint Failsafe_FDestinationAddress =
(uint)safetyTelegram.GetAttribute("Failsafe_FDestinationAddress");
uint Failsafe_FSourceAddress =
(uint)safetyTelegram.GetAttribute("Failsafe_FSourceAddress");
uint Failsafe_FIODBNumber = (uint)safetyTelegram.GetAttribute("Failsafe_FIODBNumber");
string Failsafe_FIODBName = safetyTelegram.GetAttribute("Failsafe_FIODBName").ToString();
uint Failsafe_FMonitoringtime =
(uint)safetyTelegram.GetAttribute("Failsafe_FMonitoringtime");
uint Failsafe_ManualAssignmentFIODBNumber =
(uint)safetyTelegram.GetAttribute("Failsafe_ManualAssignmentFIODBNumber");
bool Failsafe_ManualAssignmentFMonitoringtime =
(bool)safetyTelegram.GetAttribute("Failsafe_ManualAssignmentFMonitoringtime");

// Set safety telegram attributes


safetyTelegram.SetAttribute("Failsafe_ManualAssignmentFIODBNumber", 1);
safetyTelegram.SetAttribute("Failsafe_ManualAssignmentFMonitoringtime", true);
safetyTelegram.SetAttribute("Failsafe_FIODBNumber", 40000);
safetyTelegram.SetAttribute("Failsafe_FMonitoringtime", 200);
safetyTelegram.SetAttribute("Failsafe_FDestinationAddress", 15);

const int newSafetyTelegramId= 900;


if (safetyTgrm.CanChangeTelegram(newSafetyTelegramId)) {
safetyTgrm.TelegramId = newSafetyTelegramId; }

The following example shows how to delete a safety telegram.

Deleting a safety telegram


using Siemens.Engineering.MC.DriveConfiguration;
//Remove Safety telegram
drvObj.Telegrams.DeleteTelegram(TelegramType.SafetyTelegram);

Extending telegrams
The following example shows how to insert an extension and change the size of a standard
telegram. You require a drive object for access.

Inserting an extension and changing the size of a standard telegram


using Siemens.Engineering.MC.DriveConfiguration;

Openness: API for automation of engineering workflows


796 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Inserting an extension and changing the size of a standard telegram


TelegramComposition telegrams = drvObj.Telegrams;
Telegram telegram = telegrams.Find(TelegramType.MainTelegram);

Console.WriteLine("The Cu has the telegram: " + telegram.TelegramId);


Console.WriteLine("The Setpoint channel-specific size of the telegram is: "
+ telegram.GetOutputSize());

foreach (var address in telegram.Addresses)


{
if (address.IoType == AddressIoType.Output)
{
Console.WriteLine("The Setpoint channel-specific IO start address of
the telegram on the connected PLC is: " + address.StartAddress);
}
else if(address.IoType == AddressIoType.Input)
{
Console.WriteLine("The Actual value channel-specific IO start address
of the telegram on the connected PLC is: " + address.StartAddress);
}
}

// Create an additional telegram


if (drvObj.Telegrams.CreateAdditionalTelegram(2,4))
{
drvObj.Telegrams.CreateAdditionalTelegram(2,4);
}

// Add a 3 word extension to the main telegram


Telegram mainTelegram == drvObj.Telegrams.Find(TelegramType.MainTelegram);
Int32 newSize = mainTelegram.GetSize(AddressIoType.Input) + 3;
if (mainTelegram.CanChangeSize(AddressIoType.Input, newSize, true))
{
mainTelegram.ChangeSize(AddressIoType.Input, newSize, true)
}

5.19.6.11 Examples for Namespace Siemens.Engineering.MC.Drives

Preparing telegrams
The drive communication of a SINUMERIK NCU is realized using telegrams via the SINAMICS
Integrated subcomponent and, if applicable, via additionally connected NX modules.

Note
The SINUMERIK NCU and a SINAMICS Integrated are located at the same level in the TIA Portal
Openness object model, and appear under "DeviceComposition" as two different devices.

Use "DriveObjectContainer" to configure a telegram. "DriveObjectContainer" is a


service of the drive object (device element) of the actual header module (device element).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 797
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

To start the "DriveObjectContainer" service, navigate to SINAMICS Integrated or to the


header module of the NX module. The hierarchy between devices and device elements is
identical for SINAMICS Integrated and NX modules.
The following example shows how to find "DriveObjectContainer" via the "Header module"
property:

Finding DriveObjectContainer via header module

foreach (Device device in project.Devices)


{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.Classification == DeviceItemClassifications.HM)
{
var driveObjectContainer = deviceItem.GetService<DriveObjectContainer>();
// do something
}
}
}

The SINUMERIK NCU contains a SINAMICS Integrated proxy object with references to SINAMICS
Integrated.
To access a SINAMICS Integrated device or an NX module, from the SINUMERIK NCU navigate to
the DP Integrated interface via NCK. Then determine the PROFIBUS master system and navigate
to the connected slave.

Inserting and removing telegrams


The following example indicates how you can insert a telegram. You require a drive object for
access.

Inserting telegrams and accessing telegram attributes


using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


798 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Inserting telegrams and accessing telegram attributes


TelegramComposition telegrams = drvObj.Telegrams;

//Add telegram
const int tgrmNumber = 136;
drvObj.Telegrams.InsertTelegram(tgrmNumber);

//Find telegram
Telegram telegram = drvObj.Telegrams.Find(TelegramType.MainTelegram);

/Add safety telegram


const int tgrmNumber = 30;
drvObj.Telegrams.InsertSafetyTelegram(tgrmNumber);

//Find safety telegram


Telegram safetyTgrm = drvObj.Telegrams.Find(TelegramType.SafetyTelegram);

// Get and set safety telegram attributes


uint watchDogTime =
(uint)safetyTgrm.GetAttribute("Failsafe_FMonitoringtime");

safetyTgrm.SetAttribute("Failsafe_FMonitoringtime", 300);

const int newSafetyTelegramNumber= 902;


if (safetyTgrm.CanChangeTelegram(newSafetyTelegramNumber)) {
safetyTgrm.TelegramNumber = newSafetyTelegramNumber; }

//Add supplementary telegram


const int tgrmNumber = 701;
drvObj.Telegrams.InsertSupplementaryTelegram(tgrmNumber);

Telegram telegram =
drvObj.Telegrams.Find(TelegramType.SupplementaryTelegram);

The following example indicates how you can remove a telegram.

Remove telegram
using Siemens.Engineering.MC.Drives;
//Remove safety telegram
drvObj.Telegrams.EraseTelegram(TelegramType.SafetyTelegram);

//Remove supplementary telegram


drvObj.Telegrams.EraseTelegram(TelegramType.SupplementaryTelegram);

Note
You can change, but not delete, a main telegram (MainTelegram).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 799
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Working with Safety telegrams


The following example shows how to insert a Safety telegram. You require a drive object for
access.

Inserting a Safety telegram and accessing telegram attributes


using Siemens.Engineering.MC.Drives;
TelegramComposition telegrams = drvObj.Telegrams;

//Add safety telegram


const int tgrmNumber = 30;
drvObj.Telegrams.InsertSafetyTelegram(tgrmNumber);

//Find safety telegram


Telegram safetyTgrm = drvObj.Telegrams.Find(TelegramType.SafetyTelegram);

// Get and set safety telegram attributes


uint Failsafe_FDestinationAddress =
(uint)safetyTelegram.GetAttribute("Failsafe_FDestinationAddress");
uint Failsafe_FSourceAddress =
(uint)safetyTelegram.GetAttribute("Failsafe_FSourceAddress");
uint Failsafe_FIODBNumber = (uint)safetyTelegram.GetAttribute("Failsafe_FIODBNumber");
string Failsafe_FIODBName = safetyTelegram.GetAttribute("Failsafe_FIODBName").ToString();
uint Failsafe_FMonitoringtime =
(uint)safetyTelegram.GetAttribute("Failsafe_FMonitoringtime");
uint Failsafe_ManualAssignmentFIODBNumber =
(uint)safetyTelegram.GetAttribute("Failsafe_ManualAssignmentFIODBNumber");
bool Failsafe_ManualAssignmentFMonitoringtime =
(bool)safetyTelegram.GetAttribute("Failsafe_ManualAssignmentFMonitoringtime");

// Set safety telegram attributes


safetyTelegram.SetAttribute("Failsafe_ManualAssignmentFIODBNumber", 1);
safetyTelegram.SetAttribute("Failsafe_ManualAssignmentFMonitoringtime", true);
safetyTelegram.SetAttribute("Failsafe_FIODBNumber", 40000);
safetyTelegram.SetAttribute("Failsafe_FMonitoringtime", 200);
safetyTelegram.SetAttribute("Failsafe_FDestinationAddress", 15);

const int newSafetyTelegramNumber= 900;


if (safetyTgrm.CanChangeTelegram(newSafetyTelegramNumber)) {
safetyTgrm.TelegramNumber = newSafetyTelegramNumber; }

The following example shows how to delete a safety telegram.

Deleting a safety telegram


using Siemens.Engineering.MC.Drives;
//Remove Safety telegram
drvObj.Telegrams.EraseTelegram(TelegramType.SafetyTelegram);

Extending telegrams
The following example shows how to insert an extension and change the size of a standard
telegram. You require a drive object for access.

Inserting an extension and changing the size of a standard telegram


using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


800 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.19 Functions for SINUMERIK ONE

Inserting an extension and changing the size of a standard telegram


TelegramComposition telegrams = drvObj.Telegrams;
Telegram telegram = telegrams.Find(TelegramType.MainTelegram);

Console.WriteLine("The Cu has the telegram: " + telegram.TelegramNumber);


Console.WriteLine("The Setpoint channel-specific size of the telegram is: "
+ telegram.GetOutputSize());

foreach (var address in telegram.Addresses)


{
if (address.IoType == AddressIoType.Output)
{
Console.WriteLine("The Setpoint channel-specific IO start address of
the telegram on the connected PLC is: " + address.StartAddress);
}
else if(address.IoType == AddressIoType.Input)
{
Console.WriteLine("The Actual value channel-specific IO start address
of the telegram on the connected PLC is: " + address.StartAddress);
}
}

// Add an additional telegram


if (drvObj.Telegrams.CanInsertAdditionalTelegram(2,4))
{
drvObj.Telegrams.InsertAdditionalTelegram(2,4);
}

// Add a 3 word extension to the main telegram


Telegram mainTelegram == drvObj.Telegrams.Find(TelegramType.MainTelegram);
Int32 newSize = mainTelegram.GetSize(AddressIoType.Input) + 3;
if (mainTelegram.CanChangeSize(AddressIoType.Input, newSize, true))
{
mainTelegram.ChangeSize(AddressIoType.Input, newSize, true)
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 801
TIA Portal Openness API
5.20 Functions for Startdrive

5.20 Functions for Startdrive

5.20.1 Introduction
Using TIA Portal-Openness, you automate the engineering and control the TIA Portal using a
program that you created yourself.
In this help document, you can find a lot of information and code examples for this program that
you generate yourself. You can also generate and use your own programs for the TIA Portal
"Startdrive" application.
Before you configure your own program for Startdrive from the subsequently listed code
example, please carefully observe the general information relating to Openness, which you can
find under the following keywords in this help document:
• Preconditions for using TIA Portal Openness
• Install TIA Portal Openness
• Access the TIA Portal
• TIA Portal Openness object model
• Programming steps

5.20.2 Security information

5.20.2.1 Encrypted communication with SecureString passwords

Note
SecureString passwords for secure communication
In order to secure communication between Openness API and the TIA Portal when using
Startdrive Openness functions, use passwords which have been encrypted with a SecureString.

Note
Direction of communication
It is only possible to use SecureString passwords when downloading Openness functions to the
TIA Portal and not in the opposite communication direction.

Note
A SecureString object should never be constructed from a String because the sensitive data is
already subject to the memory persistence consequences of the immutable String class. The
best way to construct a SecureString object is from a character-at-a-time unmanaged source,
such as the Console.ReadKey method.

Openness: API for automation of engineering workflows


802 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Note
The API user is responsible for security measures when handling passwords using code.

You can find more information on configuring SecureString passwords in the code examples
download (Page 825) and Creating SecureString passwords (Page 843).

See also
Passwords in TIA Openness (Page 803)

5.20.2.2 Passwords in TIA Openness

Handling passwords in TIA Openness


Password handling in Startdrive Openness is based on TIA Openness.
Please carefully observe the general information relating to passwords in TIA Openness, which
you can find under the following keywords in this help:
• Defining the display password
• Handling PLC passwords linked to blocks
• Password protection for PLCs
• Setting protection levels
• Block protection and unprotection
• Loading hardware, software and files into the PLC device

See also
Encrypted communication with SecureString passwords (Page 802)

5.20.3 TypeIdentifier - identifier of the components


Each version of any Startdrive component comprises a unique number, which is called the
TypeIdentifier . In the Openness program code, you can use these TypeIdentifiers in order to
uniquely identify and name a component.
In Startdrive, the display of the TypeIdentifier is optional, and deactivated as default.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 803
TIA Portal Openness API
5.20 Functions for Startdrive

Activating the display of the TypeIdentifier in Startdrive


1. In the Startdrive project view, select menu "Options > Settings".
The "Settings" configuration area opens.
2. Select "Hardware configuration" in the secondary navigation.
3. Activate the option "Activate display of the Type Identifier for devices and modules".
The display of the TypeIdentifier is now active.

Reading out the TypeIdentifier in Startdrive


In a Startdrive project, the TypeIdentifier can be read out at the following locations when the
display is active:
• For all components (in the inspector window):
• For Control Units (when creating a drive device)

To read out the TypeIdentifier for a component in the inspector window, proceed as follows:
1. In the device view of the Startdrive project, double-click on the required component.
The inspector window opens. The active component version is shown in the list.
2. The associated TypeIdentifiers are listed in the outer right-hand column.
Example: OrderNumber:6SL3131-7TE23-6Axx
Copy this TypeIdentifier to your Openness application.

Proceed as follows to read out the TypeIdentifier for a Control Unit:


1. In the Startdrive project navigation, double click on "Add new device".
The dialog with the same name opens.
2. Select the required control module from the selection.
The TypeIdentifier (under the article number and firmware number) for the corresponding
Control Unit is displayed to the right in the detailed display.
Example: OrderNumber:6SL3040-1MA01-0Axx/V5.2/S120
3. Copy this TypeIdentifier to your Openness application.

Openness: API for automation of engineering workflows


804 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.4 References

5.20.4.1 AddressComposition

AddressComposition
The AddressComposition class represents the address of a telegram.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class AddressComposition

The following table describes the properties of the class:

Name Data type Description


IoType AddressIoType Returns information on the type of the address.
(Page 806)
Context AddressContext Returns information on the context of the address.
(Page 805)
StartAddress Int32 Returns the start address of the telegram or specifies it.
Length Int32 Returns the length of the telegram.

See also
TelegramType (Page 819)

5.20.4.2 AddressContext

AddressContext
The Enum AddressContext contains information on the context of the address.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public enum AddressContext

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 805
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the enum entries:

Name Description
AddressContext.None No context has been found for the address
AddressContext.Device Context is a device address
AddressContext.Head Context is a head address

5.20.4.3 AddressIoType

AddressIoType
The Enum AddressIoType contains information on the type of the address.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public enum AddressIoType

The following table describes the enum entries:

Name Description
AddressIoType.None The IO type cannot be used
AddressIoType.Input Type is an input address
AddressIoType.Output Type is an output address
AddressIoType.Diagnosis Type is a diagnosis address
AddressIoType.Substitute Type is a substitute address

5.20.4.4 Commissioning

Commissioning
The Commissioning class is used for commissioning a drive. It can be applied
to DriveFunctionInterface or OnlineDriveFunctionInterface. If the user uses the
function for a SINAMICS S drive, it returns the return value zero.
The following table describes the methods of the class:

Name Parameter Return value Description


SetSimoGearMlfb string simoGearMlfb bool Sets the SIMOGEAR Article No. of a drive.

See also
Setting the SIMOGEAR article number for G115D drives (Page 845)

Openness: API for automation of engineering workflows


806 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.4.5 ConfigurationEntry

ConfigurationEntry
Class ConfigurationEntry is used to save parameter data, which can be determined from
the ConfigurationEntryCompositions of a motor or encoder configuration.
The following table describes the properties of the class:

Name Data type Description


EnumValueList IDictionary<it, Returns a list with possible values of the enum param‐
string> eter.
MaxValue object Maximum value of the ConfigurationEntry.
MinValue object Minimum value of the ConfigurationEntry.
Name string Name of the ConfigurationEntry.
Number int Numerical representation of the name
for ConfigurationEntry.
Description string Description of the ConfigurationEntry.
Parent IEngineeringObjec Engineering Object model-parent element of this ob‐
t ject.
Unit string Unit of the ConfigurationEntry.
Value object Value of the ConfigurationEntry.

5.20.4.6 DriveDomainFunctions

DriveDomainFunctions
Class DriveDomainFunctions is used to restore the factory settings or the backup of the RAM
content to the ROM.
It can only be applied to an OnlineDriveFunctionInterface object.
For G120 drives, the DriveDomainFunctions object can only be accessed if the Power
Module is connected to the device. Otherwise, null or an exception is returned.
The following table describes the methods of the class:

Name Description
PerformFactoryReset This method is responsible for restoring the factory settings.
PerformRAMtoROMCopyAllDriveObject The date of all drive objects is written from the RAM to the memory card/
hard disk.

The following table describes the properties of the class:

Name Data type Description


Parent IEngineeringObject Engineering Object model-parent element of this object.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 807
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.4.7 DriveObject

DriveObject
The DriveObject class allows access to the drive object. Access to the drive parameters or the
telegram is possible via the drive object, for example.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class DriveObject

The following table describes the properties of the class:

Name Data type Description


Parameters DriveParameter‐ Returns a list with the available parameters of the drive object.
Composition
(Page 811)
Telegrams TelegramComposi‐ Returns a list with the available telegrams of the drive object.
tion (Page 818) The list can be changed with class TelegramComposition.

See also
Determining a drive object (Page 823)

5.20.4.8 DriveObjectActivation

DriveObjectActivation
Class DriveObjectActivation is used to activate the modules or determine the module
status. It can be applied to DriveObjectFunctions from DriveFunctionInterface
or OnlineDriveFunctionInterface.
The following table describes the methods of the class:

Name Description
ChangeActivationState(DriveObjectAc Changes the activation status of the drive object. Returns false if the oper‐
tivationState) ation cannot be completed.
Possible status values:
• Deactivate
• Activate
• DeactivateAndNotPresent

Openness: API for automation of engineering workflows


808 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the properties of the class:

Name Data type Description


ActivationState DriveObjectActivation Returns the actual status value.
State
IsActive Boolean For an active drive object, returns true.

5.20.4.9 DriveObjectContainer

DriveObjectContainer
The DriveObjectContainer is a service of the drive object (DeviceItem) for the current
device (Device).
The following table describes the navigators of the DriveObjectContainer:

Name Data type Description


DriveObjects DriveObjectCom‐ Returns a list with the available drive objects. The drive ob‐
position jects allow access to the drive parameters and telegrams.
(Page 811)

5.20.4.10 DriveObjectTypeHandler

DriveObjectTypeHandler
Class DriveObjectTypeHandler is used to switch over the drive object type for every drive
object and to determine the drive object type - as well as all possible drive object types of the
actual drive object. It can only be applied to DriveFunctionInterface.
The following table describes the methods of the class:

Name Description
ChangeDriveObjectType((target)Drive Changes the actual type of the drive object to a new type that can be
ObjectType) selected.
Returns false if the operation cannot be completed.

The following table describes the properties of the class:

Name Data type Description


PossibleDriveObjectTypes DriveObjectTypeCompos The use of targetDriveObjectType results in an
ition exception on the actual drive object.
CurrentDriveObjectType DriveObjectType Indicates the currently assigned drive object type.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 809
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.4.11 DriveParameter

DriveParameter
The DriveParameter class allows access to a drive parameter. Not all drive parameters are
available for access via Openness.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class DriveParameter

The following table describes the properties of the class:

Name Data type Description


ArrayIndex Int32 Returns the index of an array parameter.
Value range: 0-7FFF
The index is -1 for parameters without array
Example
p108[4].15
par.ArrayIndex produces 4
ArrayLength Int32 Returns the number of array elements.
The index is 0 for parameters without an array
Bits DriveParameter‐ Returns an DriveParameter object for one bit of the pa‐
Composition rameter.
(Page 811) In this way, for example, the value or the name of the bit
parameter can be read from a bit parameter.
Example
DriveParameter param133 =
cu.Parameters.Find(133, 0);
DriveParameter param133Bit1 =
param133.Bits[1];
String paramName = param133Bit1.Name;
EnumValueList IDictionary<i Returns a list with possible values of the enum parameter.
nt, string> For example <1, [1] Quick commissioning>
null, if the parameter is not a parameter of the Enum type.
MaxValue Object Returns the maximum value for the currently selected unit.
MinValue Object Returns the minimum value for the currently selected unit.
Name string Returns the name of the parameter. E.g. "p108[0].2"
ParameterText string Returns the text of the short description for the parameter.
Number Int32 Returns the number of the parameter.
Example
p108[0].2
The return value is 108

Openness: API for automation of engineering workflows


810 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Name Data type Description


Unit string Returns the unit of the parameter as text.
Value Object Returns the offline/online value of the parameter or writes a
value onto the parameter.
If the event of write errors,
an EngineeringTargetInvocationException is trig‐
gered.
Examples
• P2080Bit6.Value = 0;
• P2080Bit6.Value =
cu.Parameters.Find("r19");
BICO source
The parameters of a BICO source can only be read
BICO signal sinks
Possible values are 0, 1 or a DriveParameter object.
A DriveParameter object is returned when the BICO signal
sink is connected to a different parameter.
See also example Reading and writing BICO parameters
(Page 824).

See also
Reading and writing parameters (Page 840)

5.20.4.12 DriveParameterComposition

DriveParameterComposition
The DriveParameterComposition class allows access to parameters of the drive. Not all
drive parameters are approved for access via Openness.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class DriveParameterComposition

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 811
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the methods of the class:

Name Description
Find(string) Returns the DriveParameter (Page 810) object for which a
search is being made via the name.
null if the parameter is not found
Example
Find("P108[1]");
Find(UInt16, Int32) Returns the DriveParameter (Page 810) object for which a
search is being made via the parameter index and array index.
null if the parameter is not found
Examples
• cu.Find(108, 1);
• cu.Find(51, -1);
WriteParameters(IEnumerable<s Writes values in parameters.
tring>, IEnumerable<string>, With the ignoreErrors = true setting, an attempt is
bool) made to write all values in the event of an error and
an EngineeringTargetInvocationException is trig‐
gered at the end.
For SINAMICS G drives, parameter values can only be written
with a configured Power Module (PM).
Example
List<string> names = new List<string>();
List<string> values = new List<string>();
names.add("p300[0])");
values.add("17");
names.add("p5391[0])");
values.add("20");

cu.WriteParameters(names, values, true);

5.20.4.13 EncoderConfiguration

EncoderConfiguration
Class EncoderConfiguration saves data of non-Siemens encoders.
• The user must populate the ConfigurationEntryComposition object.
• Object RequiredConfigurationEntries must also be populated.

Namespace: Siemens.Engineering.MC.Drives
Siemens.Engineering.MC.Drives.DFI
Siemens.Engineering.MC.Drives.Enum
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


812 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the properties of the class:

Name Data type Description


RequiredConfiguration ConfigurationEntr Accessible configuration entries of the motor
Entries yComposition configuration.
Parent IEngineeringObjec Engineering Object model-parent element of
t this object.

5.20.4.14 HardwareProjection
Class HardwareProjection is responsible for commissioning the motor and the encoder. The
object can be found for DriveFunctionInterface
and OnlineDriveFunctionInterface.
For G120 drives, motors and encoders can be configured both online and offline. On the other
hand, for S120 drives, configuration is only possible offline.
For G120 drive devices, the HardwareProjection object can only be accessed if the Power
Module is inserted in the drive device. Otherwise, when calling functions
HardwareProjection, a null or an exception is returned.
For an offline configuration, use the hardware configuration of the
DriveFunctionInterface. For an online configuration, use the hardware configuration of
the OnlineDriveFunctionInterface.

Namespace: Siemens.Engineering.MC.Drives
Siemens.Engineering.MC.Drives.DFI
Siemens.Engineering.MC.Drives.Enums
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the methods of the class:

Name Description
SetMotorType(MotorType type, Sets the motor type at the Control Unit (only for G120).
ushort driveDataSet)
GetCurrentMotorConfiguration( Depending on the data set number of the drive, determines
ushort driveDataSet) the currently existing configuration area.
ProjectMotorConfiguration(Mot Configures the motor configuration of a drive device depend‐
orConfiguration motConfig, ing on the data set number of the drive.
ushort driveDataSet)
SetEncoder(EncoderType type, Sets the encoder at the Control Unit (only for G120).
EncoderInterface
interfaceType,
AbsoluteIncrementalFlag
absIncFlag, RotaryLinearFlag
rotLinFlag, ushort
encDataSet)
GetCurrentEncoderConfiguratio Depending on the data set number of the encoder, deter‐
n(ushort encDataSet) mines the currently existing configuration area.
ProjectEncoderConfiguration(E Configures the motor configuration of a drive device depend‐
ncoderConfiguration ing on the data set number of the encoder.
encConfig, ushort encDataSet)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 813
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the properties of the class:

Name Data type Description


Parent IEngineeringObject Engineering Object model-parent element of
this object.

5.20.4.15 MotorConfiguration

MotorConfiguration
Class MotorConfiguration is responsible for commissioning motors and encoders.

Namespace: Siemens.Engineering.MC.Drives
Siemens.Engineering.MC.Drives.DFI
Siemens.Engineering.MC.Drives.Enums
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll

Response for Siemens motors:


Action SetMotortype must be called to set the motor type. This action comprises the Enum
MotorType and a number, which represents the DriveDatasetNumber.
The following table describes the enums:

Enum name Description


NoMotor 0: No motor
InductionMotor 1: Induction motor
SynchronousMotor 2: Synchronous motor
NoCodeNumber1LE1InductionMoto 10: 1LE1 induction motor (not a code number)
r
NoCodeNumber1LG6InductionMoto 13: 1LG6 induction motor (not a code number)
r
NoCodeNumber1xx1SIMOTICSFDInd 14: 1xx1 SIMOTICS FD induction motor (not a code number)
uctionMotor
NoCodeNumber1LA7InductionMoto 17: 1LA7 induction motor (not a code number)
rNoCodeNumber
MotorSeriesNumber1LA81PQ8Stan 18: 1LA8 / 1PQ8 standard induction motor series
dardInduction
NoCodeNumber1LA9InductionMoto 19: 1LA9 induction motor (not a code number)
r

Response for non-Siemens motors:


Class MotorConfiguration is used to save data of non-Siemens motors. It contains 2 objects
ConfigurationEntryComposition, which, when commissioning, must be populated with
the corresponding motor data. Object RequiredConfigurationEntries must also be
populated. Object OptionalConfigurationEntries does not have to be populated.

Openness: API for automation of engineering workflows


814 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the properties of the class:

Name Data type Description


RequiredConfigurat ConfigurationEntryC Accessible configuration entries of this motor
ionEntries omposition configuration.
OptionalConfigurat ConfigurationEntryC Accessible configuration entries of this motor
ionEntries omposition configuration.
Parent IEngineeringObject Engineering Object model-parent element of
this object.

5.20.4.16 OnlineDriveObject

OnlineDriveObject
The OnlineDriveObject class allows online access to the drive object. Drive parameters can
be accessed via the drive object.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class OnlineDriveObject

The following table describes the properties of the class:

Name Data type Description


Parameters DriveParameter‐ Returns a list with the available parameters of the online drive
Composition object.
(Page 811) null, if the mode is "Offline".
In offline mode, an exception is triggered when a method is
called or for a write access to a parameter.

See also
Determining a drive object (Page 823)
Reading and writing parameters (Page 840)
Reading and writing parameters online (Page 842)

5.20.4.17 OnlineDriveObjectContainer

OnlineDriveObjectContainer
The OnlineDriveObjectContainer is a service of the drive object (DeviceItem) for the
current device (Device).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 815
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the navigators of the OnlineDriveObjectContainer:

Name Data type Description


OnlineDriveObj OnlineDriveOb Returns a list with the available online drive objects (Online‐
ects jectCompositi DriveObject (Page 815)). The drive objects allow access to the
on drive parameters.

5.20.4.18 StartDriveDownloadCheckConfiguration

StartDriveDownloadCheckConfiguration
Class StartDriveDownloadCheckConfiguration is derived from the
class DownloadCheckConfiguration and has the same properties.
Class DownloadCheckConfiguration is described in the standard Openness help.
The class provides the configuration settings via checkboxes from the user.
The following table describes the properties of the class:

Name Data type Description


Checked bool Returns the current setting of the configuration or activates/
deactivates the configuration.

See also
Download (Page 825)

5.20.4.19 SafetyTelegram

SafetyTelegram
Class SafetyTelegram stands for the telegram of the drive object.
Exception EngineeringTargetInvocationException is displayed for errors in the write
attributes.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the properties of the class:

Name Data type Description


TelegramNumbe Int32 Number of the main telegram. Free telegrams are designa‐
r ted with a value of 999.
Type TelegramType Telegram type that is returned as enum "TelegramType".
(Page 819)

Openness: API for automation of engineering workflows


816 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Name Data type Description


Addresses AddressComposition Composition of all addresses of a telegram.
(Page 805)
PKW Telegram Composition of all PKW channels of the telegram.
(Page 817) null - if the telegram does not have a PKW part.

5.20.4.20 Telegram

Telegram
Class Telegram allows access to the structure of a telegram from a drive object.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class Telegram

The following table describes the properties of the class:

Name Data type Description


TelegramNumb Int32 Returns the number of the main telegram or specifies the
er number.
A freely configurable telegram has the number 999.
Type TelegramType Returns the type of telegram as Enum TelegramType.
(Page 819)
Addresses AddressComposi‐ Returns an AdressComposition with information on the
tion (Page 805) address.
PKW Telegram Returns channel PKW as Telegram.
null if the property is not available
A telegram with PKW is telegram 353, for example.

The following table describes the methods of the class:

Name Description
CanChangeTelegram(Int32) Returns true if the telegram can be changed to the parame‐
terized standard type.
GetSize(AddressIoType (Page 806)) Returns the size of the inputs or outputs of the telegram.
CanChangeSize(AddressIoType Returns true if the size of the telegram can be changed as
(Page 806), Int32, bool) parameterized. Standard telegrams can only be enlarged.
The retention of the previous telegram address is taken into
account when the option is parameterized with true.
ChangeSize(AddressIoType Returns true if the size of the telegram could be changed as
(Page 806), Int32, bool) parameterized.
The retention of the previous telegram address is taken into
account when the option is parameterized with true.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 817
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.4.21 TelegramComposition

TelegramComposition
The TelegramComposition class allows access to the telegrams of a drive object. The
structure of a telegram can be read out via class Telegram (Page 817).
Note that referenced objects may become invalid through class TelegramComposition. For
example, object Telegram (Page 817) becomes invalid after the telegram size is changed.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public sealed class TelegramComposition

The following table describes the methods of the class:

Name Description
CanInsertAdditionalTelegr Returns true if an extension can be created in accordance with the
am(Int32, Int32) parameterized sizes (input and output sizes).
CanInsertTorqueTelegram When adding a new torque telegram with an already existing tele‐
(Int32, telegramNumber) gram number, checks whether this is possible.
CanInsertSupplementaryTel Returns true if a supplementary telegram can be created in ac‐
egram(Int32) cordance with the parameterized telegram number.
EraseTelegram(TelegramTyp Deletes a telegram with a known telegram type from the drive ob‐
e) ject.
Returns true if the parameterized telegram could be deleted.
If a torque telegram is used as type, then object "torqueTelegram" is
deleted.
If a Safety Integrated telegram is used as type, then object "safety‐
Telegram" is deleted.
Standard telegrams cannot be deleted.
In the event of an error,
an EngineeringTargetInvocationException is initiated.
Find(TelegramType) Returns the Telegram (Page 817) object if it could be found via the
parameterized telegram type or Safety Integrated telegram type.
null if the telegram is not found.
If a torque telegram is used as type, then object torqueTelegram
is returned, assuming that it exists.
If a Safety Integrated telegram is used as type, then
object safetyTelegram is returned, assuming that it exists.
Example
Telegram telegram =
telegrams.Find(TelegramType.MainTelegram);

Openness: API for automation of engineering workflows


818 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Name Description
InsertAdditionalTelegram( Creates an extension for the drive object in accordance with the
Int32, Int32) parameterized sizes and returns true if the extension could be
inserted.
In the event of an error,
an EngineeringTargetInvocationException is initiated.
InsertTorqueTelegram Adds a new torque telegram with an already existing telegram
(Int32, telegramNumber) number to a drive object.
InsertSafetyTelegram Adds a Safety Integrated telegram with its specified telegram num‐
(Int32, telegramNumber) ber to a drive object.
InsertSupplementaryTelegr Creates the supplementary telegram with the parameterized tele‐
am(Int32) gram number and returns true if the telegram could be inserted.
In the event of an error,
an EngineeringTargetInvocationException is initiated.

5.20.4.22 TelegramType

TelegramType
The Enum TelegramType contains predefined telegram types.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll
The following table describes the syntax of the class:

public enum TelegramType

The following table describes the enum entries:

Name Description
MainTelegram ID of the main telegram
SupplementaryTelegram ID of the supplementary telegram
AdditionalTelegram ID of an extension

5.20.4.23 TorqueTelegram

TorqueTelegram
Class TorqueTelegram stands for the telegram of the drive object.
Exception EngineeringTargetInvocationException is displayed for errors in the write
attributes.

Namespace: Siemens.Engineering.MC.Drives
Assembly: Siemens.Engineering.MC.Drives in Siemens.Engineering.dll

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 819
TIA Portal Openness API
5.20 Functions for Startdrive

The following table describes the properties of the class:

Name Data type Description


TelegramNumbe Int32 Telegram number.
r
Type TelegramType Telegram type that is returned as enum "TelegramType".
(Page 819)
Addresses AddressComposition Composition of all addresses of a telegram.
(Page 805)
PKW Telegram (Page 817) Composition of all PKW channels of the telegram.
null - if the telegram does not have a PKW part.

5.20.5 Code examples

The following code examples describe the basic procedure for various applications. The code is
not necessarily complete or compilable.

5.20.5.1 Determining the activation status


The following examples show how you can determine the activation status for S120 drives,
either offline or online:

Determining the activation status of an S120 drive offline


using Siemens.Engineering.MC.Drives;
DriveFunctionInterface dfi = ...
DriveObjectActivation driveObjectActivation =
dfi.DriveObjectFunctions.DriveObjectActivation;
//driveObjectActivation can be null in case of the actual driveobject does not support
activation.

//change activation state


driveObjectActivation.ChangeActivationState(DriveObjectActivationState.Deactivate);

//get the activation state


DriveObjectActivationState activationState = driveObjectActivation.ActivationState;

//get the Is Active property


bool isActive = driveObjectActivation.IsActive;

Determining the activation status of an S120 drive online


using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


820 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Determining the activation status of an S120 drive online


OnlineDriveFunctionInterface onlinedfi = ...
DriveObjectActivation driveObjectActivation = onlinedfi.DriveObjectActivation;
//driveObjectActivation can be null in case of the actual driveobject does not support
activation in online.

//change activation state


driveObjectActivation.ChangeActivationState(DriveObjectActivationState.Deactivate);

//get the activation state


DriveObjectActivationState activationState = driveObjectActivation.ActivationState;

//get the IsActive property


bool isActive = driveObjectActivation.IsActive;

5.20.5.2 Executing drive functions


The following examples show how you can simply access drive functions, either offline or online:

Executing drive functions offline


using Siemens.Engineering.MC.Drives;
DriveObject driveObject = ...
DriveFunctionInterface dfi = driveObject.GetService<DriveFunctionInterface>();

// dfi can be null in case of the actual driveobject does not support it.

Executing drive functions online


using Siemens.Engineering.MC.Drives;
OnlineDriveObject onlineDriveObject = ...
OnlineDriveFunctionInterface onlineDfi =
onlineDriveObject.GetService<OnlineDriveFunctionInterface>();

// onlineDfi can be null in case of the actual onlineDriveObject


// does not support it or if the device is offline.

5.20.5.3 Creating a drive unit


You can create a drive unit with method CreateWithItem() of collection Devices.
The drive units are specified via parameters of the method. The format of the parameters is
described in the following.

Creating a G120 drive unit


Format of the parameters for a G120:
CreateWithItem(@"OrderNumber: mlfb / FirmwareVersion /",
"NameOfTheDevice", positionNumber)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 821
TIA Portal Openness API
5.20 Functions for Startdrive

The following example shows how to create a G120 drive unit.

Creating a G120 drive unit


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
Project tiaproject= portal.Projects.Open("..."); //The path of the project

Device s120Device =
tiaproject.Devices.CreateWithItem(@"OrderNumber:6SL3246-0BA22-1FA0/4.7.6/"
, "Device_0", null);

Creating a S120, S150, MV, G130, G150 drive unit


Format of the parameters for a S120, S150, MV, G130, G150:
CreateWithItem(@"OrderNumber: mlfb / FirmwareVersion /
AdditionalTypeIdentifier", "NameOfTheDevice", positionNumber)
Possible values for AdditionalTypeIdentifier:
• Empty string (e.g. for G120)
• S120
• S150
• MV
• G130
• G150
The following example shows how to create a S120 drive unit.

Creating an S120 drive unit


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);
Project tiaproject= portal.Projects.Open("..."); //The path of the project

Device s120Device =
tiaproject.Devices.CreateWithItem(@"OrderNumber:6SL3040-1MA01-0Axx/V4.8/
S120", "Device_0", null);

5.20.5.4 Creating a drive component


You can create a drive component for a drive unit with the PlugNew() method of the Device
object.
The following example shows how to create a drive component.

Creating a Motor Module


DeviceItem subModul = sdrDevice.PlugNew(@"OrderNumber:6SL3xxx-xxxxx-xxxx",
"MotorModul", 65535);

Openness: API for automation of engineering workflows


822 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.5.5 Determining a drive object


The following examples show how to determine drive objects offline and online.

Determining an offline drive object


using Siemens.Engineering.MC.Drives;
//G device
Project project = portal.Projects.Open("..."); //Destination folder to
open the project
DeviceItem item = project.Devices[0].Items[0].Items[0];
DriveObject driveObject =
item.GetService<DriveObjectContainer>().DriveObjects[0];

//S device
Project project = portal.Projects.Open("..."); //Destination folder to
open the project
DeviceItem item = project.Devices[0].Items[0];
DriveObject driveObject =
item.GetService<DriveObjectContainer>().DriveObjects[0];

Determining an online drive object


using Siemens.Engineering.MC.Drives;
//G device
Project project = portal.Projects.Open("..."); //Destination folder to
open the project
DeviceItem item = project.Devices[0].Items[0].Items[0];
OnlineDriveObject onlineDriveObject =
item.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];

//S device
Project project = portal.Projects.Open("..."); //Destination folder to
open the project
DeviceItem item = project.Devices[0].Items[0];
OnlineDriveObject onlineDriveObject =
item.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];

5.20.5.6 Determining the drive object type


The following examples shows how you can determine the actual drive object type – and the
types that can be alternatively set.

Determining drive object types


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 823
TIA Portal Openness API
5.20 Functions for Startdrive

Determining drive object types


DriveObject driveObject = ...
DriveFunctionInterface dfi = driveObject.GetService<DriveFunctionInterface>();
DriveObjectTypeHandler driveObjectTypeHandler =
dfi.DriveObjectFunctions.DriveObjectTypeHandler;

// dfi can be null in case of the actual driveobject does not support it.

// driveObjectTypeHandler can be null, if the actual driveObject does not support it.

// Get the possible drive object types on the drive object.


DriveObjectTypeComposition possibleDriveObjectTypes =
driveObjectTypeHandler.PossibleDriveObjectTypes;

// Get the current drive object type on the drive object.


DriveObjectType currentDriveObjectType = driveObjectTypeHandler.CurrentDriveObjectType;

//Call the ChangeDriveObjectType method with the current drive object type.
//The method parameter should be the target drive object type.
driveObjectTypeHandler.ChangeDriveObjectType(possibleDriveObjectTypes[0]);

5.20.5.7 Reading and writing BICO parameters


The following example shows how to read and write values of BICO parameters. You require a
drive object for access.

Reading BICO parameters


using Siemens.Engineering.MC.Drives;
DriveParameter bicoSink= driveObject.Parameters.Find("p681");
if(bicoSink!=null)
{
if(bicoSink.Value is DriveParameter)
{
DriveParamter bicoSourceValue = bicoSink.Value as DriveParameter;
Console.WriteLine("The value of parameter " + bicoSink.Name + ": " +
bicoSource.Name + " " + bicoSource.ParameterText);
}
else if (bicoSink.Value == null)
{
Console.WriteLine("Value contains an invalid connection or the source
parameter is not accessible via Openness");
}
else
{
Console.WriteLine("The value of parameter " + bicoSink.Name + ": " +
bicoSink.Value.ToString());
}
}

Writing BICO parameters


using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


824 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Writing BICO parameters


DriveParameter bicoSource= driveObject.Parameters.Find("r19");
DriveParameter bicoSink = driveObject.Parameters.Find("p738");
if(bicoSource != null)
{
try
{
bicoSink.Value = bicoSource;
}
catch(UserException ex)
{
Console.WriteLine("Write failure :" + ex.Message);
}
}

5.20.5.8 Download
After starting the download, you must adapt and confirm the configuration settings. The
configuration settings are provided as child objects of object DownloadConfiguration – and
there are three different types:
• StartDriveDownloadCheckConfiguration
• DownloadSelectionConfiguration
• DownloadPasswordConfiguration
The following examples show the evaluation of the different types of configuration settings in
the PreDownload Delegate.

Evaluation of the configuration settings after starting the download


using Siemens.Engineering.Download;
using Siemens.Engineering.Online;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 825
TIA Portal Openness API
5.20 Functions for Startdrive

Evaluation of the configuration settings after starting the download


static void PreDownload(DownloadConfiguration configuration)
{
Console.WriteLine(configuration.Message);
StartDriveDownloadCheckConfiguration sdcc = configuration as
StartDriveDownloadCheckConfiguration;
if (sdcc != null)
{
sdcc.Checked = true;
return;
}

DownloadPasswordConfiguration downloadPasswordConfiguration =
configuration as DownloadPasswordConfiguration;

if (downloadPasswordConfiguration != null)
{
SecureString s = new SecureString();
string passwordText = "password";
foreach (var str in passwordText)
{
s.AppendChar(str);
}

downloadPasswordConfiguration.SetPassword(s);
return;
}

DownloadSelectionConfiguration downloadSelectionConfiguration =
configuration as DownloadSelectionConfiguration;

if (downloadSelectionConfiguration != null)
{
downloadSelectionConfiguration.SelectedIndex = 0;
return;
}
}

The following examples show how to download a project to the device.

Download to the S120 device


using Siemens.Engineering.Download;
using Siemens.Engineering.Online;

Openness: API for automation of engineering workflows


826 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Download to the S120 device


try
{
DeviceItem item = ... //device item of the CU (e.g. :
project.Devices[0].Items[0].Items[0])
DownloadProvider downloadProvider = item.GetService<DownloadProvider>();

DownloadConfigurationDelegate pre = PreDownload;


DownloadConfigurationDelegate post = PostDownload;

ConnectionConfiguration connConfiguration =
downloadProvider.Configuration;
ConfigurationMode configurationMode = connConfiguration.Modes.Find("PN/
IE");
ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces[0];
ConfigurationSubnet subnet = pcInterface.Subnets.Find(/*subnet name*/);
IConfiguration configuration = subnet.Addresses.Find(/*IP address of the
device*/);
downloadProvider.Download(configuration, pre, post,
DownloadOptions.Software);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

//configuration handling before download


static void PreDownload(DownloadConfiguration configuration)
{
Console.WriteLine(configuration.Message);
StartDriveDownloadCheckConfiguration dcc = configuration as
StartDriveDownloadCheckConfiguration ;
if (dcc != null)
{
dcc.Checked = true;
}
}

//configuration handling after download


static void PostDownload(DownloadConfiguration configuration)
{
Console.WriteLine(configuration.Message);
}

See also
Encrypted communication with SecureString passwords (Page 802)

5.20.5.9 Editing DRIVE-CLiQ connections


The following example shows how to edit DRIVE-CLiQ connections with Openness.

Editing DRIVE-CLiQ connections


TiaPortal portal = new TiaPortal(TiaPortalMode.WithUserInterface);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 827
TIA Portal Openness API
5.20 Functions for Startdrive

Editing DRIVE-CLiQ connections


Project tiaproject = portal.Projects.Open(new FileInfo(@"C:\Users\testUser
\Documents\Automation\Project109\Project109.ap15")); //The path of the
project

Device device =
tiaproject.Devices.CreateWithItem(@"OrderNumber:6SL3040-1MA01-0Axx/V4.8/
S120", "Device_0", null); //Create the device

DeviceItem subModul = device.PlugNew(@"OrderNumber:6SL3x2x-1xxxx-xxxx",


"", 65535); //Plug a submodul (in this case : Motor modul)

DeviceItem cu = device.DeviceItems[1]; // The CU is always the 1


indexed in the DeviceItems of the Device

DeviceItem subModulDQInterface = subModul.DeviceItems[0]; //We need


the DQ interface from the submodul
DeviceItem cuDQInterface = cu.DeviceItems[3]; //This is the
DQ interface of the CU

NetworkPort subModulDQ =
((IEngineeringServiceProvider)subModulDQInterface.DeviceItems[0]).GetServi
ce<NetworkPort>(); //We need the DriveCliq port of the DQ interface from
the submodul
NetworkPort cuDQ =
((IEngineeringServiceProvider)cuDQInterface.DeviceItems[0]).GetService<Net
workPort>(); //We need the DriveCliq port of the DQ interface
from the CU

cuDQ.DisconnectFromPort(subModulDQ); //Delete the connection between the


two ports (automatically created when plugging a modul)
cuDQ.ConnectToPort(subModulDQ); //Create a new connection

5.20.5.10 Carrying out the first steps in Startdrive


The following example shows how you can localize or generate an active TIA Portal process.

Finding or generating a TIA Portal process


using Siemens.Engineering;
// Get the list of the running TIA Portal processes.
IList<TiaPortalProcess> procs = TiaPortal.GetProcesses();
TiaPortal portal;
// When there is at least one running TIA Portal, we will attach to the first from the list.
if (procs.Count != 0)
{
portal = procs[0].Attach();
}
// When there is no running TIA Portal, we create one.
else
{
portal = new TiaPortal(TiaPortalMode.WithUserInterface);
}

Openness: API for automation of engineering workflows


828 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

The following example shows how you can localize or generate a Startdrive project.

Finding or generating a Startdrive project


using Siemens.Engineering;
Project project;
// When the portal has one project, we save it in a variable.
if (portal.Projects.Count == 1)
{
project = portal.Projects[0];
}
// When there is no existing project, we create one with a specific path, and the actual time
else
{
project = portal.Projects.Create(
new DirectoryInfo(@"C:\Projects\Project_" + DateTime.Now.Ticks),
DateTime.Now.Ticks.ToString());
}

The following example shows how you can determine as to whether a specific Startdrive variant
(package and version) is installed.

Determining whether the required Startdrive version is installed


using Siemens.Engineering;
if (tiaProcess.InstalledSoftware.Any(sw => sw.Name.Equals("SINAMICS Startdrive Advanced")
&& sw.Version.Equals("V15"))) { Console.WriteLine("Startdrive is available");}
// "V15" is the current startdrive version started at December 2017.
// "V15.1" will be the current startdrive version beginning with December 2018.
// "SINAMICS Startdrive Basic" and "SINAMICS Startdrive Advanced" are the 2 possible
startdrive function packages.

5.20.5.11 Defining the encoder type


The following example shows how you can set the encoder type or the encoder data set number
offline.

Setting the encoder type and/or the encoder data set number offline via the hardware configuration
using Siemens.Engineering.MC.Drives
using Siemens.Engineering.MC.Drives.DFI
using Siemens.Engineering.MC.Drives.Enums;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 829
TIA Portal Openness API
5.20 Functions for Startdrive

Setting the encoder type and/or the encoder data set number offline via the hardware configuration
DeviceItem cuDeviceItem = m_Device.DeviceItems[1];
DriveObject cuDriveObject =
cuDeviceItem.GetService<DriveObjectContainer>().DriveObjects[0];

DriveFunctionInterface cuDriveFunctionInterface =
cuDriveObject.GetService<DriveFunctionInterface>();
HardwareProjection hardwareProjection = cuDriveFunctionInterface.HardwareProjection;

// To enable the setting of an EncoderType, the value of p96 should


// be set to 0 (Application class == [0] Expert) if it is present on
// the current G drive.
DriveParameter p96 = cuDriveObject.Parameters.Find("p96");
if (p96 != null)
{
p96.Value = 0;
}

// Setting Encoder 1 on the drive.


// In case of encoders, we have to set several enums to define an
// encoder type. These enums are: EncoderInterface, EncoderType,
// AbsoluteIncrementalFlag, and RotaryLinearFlag.

// There can be a problem, if the given enum combination is not valid.


// In that case, it has to give back a feedback.

hardwareProjection.SetEncoder(
EncoderInterface.Terminal,
EncoderType.HTLTTL,
AbsoluteIncrementalFlag.Incremental,
RotaryLinearFlag.Rotary,
1);

// It is possible to set 2 encoders to a motor, one with encoderNumber == 1


// and the other with encoderNumber == 2

The following example shows how you can set the encoder type or the encoder data set number
using an online connection.

Setting the encoder type and/or the encoder data set number online via the hardware configuration
using Siemens.Engineering.MC.Drives
using Siemens.Engineering.MC.Drives.DFI
using Siemens.Engineering.MC.Drives.Enums;

Openness: API for automation of engineering workflows


830 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Setting the encoder type and/or the encoder data set number online via the hardware configuration
DeviceItem cuDeviceItem = m_Device.DeviceItems[1];
OnlineDriveObject cuOnlineDriveObject =
cuDeviceItem.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];
OnlineDriveFunctionInterface cuDriveFunctionInterface =
cuOnlineDriveObject.GetService<OnlineDriveFunctionInterface>();
HardwareProjection hardwareProjection = cuDriveFunctionInterface.HardwareProjection;

// To enable the setting of an Encoder, the value of p96 should


// be set to 0 (Application class == [0] Expert) if it is present
// the current G drive.
DriveParameter p96 = cuOnlineDriveObject.Parameters.Find("p96");
if (p96 != null)
{
p96.Value = 0;
}

// Setting Encoder 1 on the drive.


// In case of encoders we have to set several enums to define an
// encoder type. These enums are: EncoderInterface, EncoderType,
// AbsoluteIncrementalFlag, and RotaryLinearFlag.

// There can be a problem, if the given enum combination is not valid.


// In that case, it has to give back a feedback.

hardwareProjection.SetEncoder(
EncoderInterface.Terminal,
EncoderType.HTLTTL,
AbsoluteIncrementalFlag.Incremental,
RotaryLinearFlag.Rotary,
1);

// It is possible to set 2 encoders to a motor, one with encoderNumber == 1


// and the other with encoderNumber == 2

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 831
TIA Portal Openness API
5.20 Functions for Startdrive

The following example shows how you can read out the actual encoder configuration from the
drive.

Reading out the encoder configuration


DeviceItem cuDeviceItem = m_Device.DeviceItems[1];
DriveObject cuDriveObject =
cuDeviceItem.GetService<DriveObjectContainer>().DriveObjects[0];
DriveFunctionInterface cuDriveFunctionInterface =
cuDriveObject.GetService<DriveFunctionInterface>();

HardwareProjection encoderProjection = cuDriveFunctionInterface.HardwareProjection;

// Before setting an encoder, p96 should be 0


// (See section "Projecting EncoderConfiguration")

encoderProjection.SetEncoder(
EncoderInterface.Terminal,
EncoderType.HTLTTL,
AbsoluteIncrementalFlag.Incremental,
RotaryLinearFlag.Rotary,
1);

EncoderConfiguration encoderConfiguration =
encoderProjection.GetCurrentEncoderConfiguration(1);

The following example shows how you can configure the actual encoder configuration offline.

Configuring an encoder offline


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;

Openness: API for automation of engineering workflows


832 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Configuring an encoder offline


// Project encoder configuration in Offline state
DeviceItem cuDeviceItem = m_Device.DeviceItems[1];

DriveObject cuDriveObject =
cuDeviceItem.GetService<DriveObjectContainer>().DriveObjects[0];
DriveFunctionInterface cuDriveFunctionInterface =
cuDriveObject.GetService<DriveFunctionInterface>();
HardwareProjection hardwareProjection = cuDriveFunctionInterface.HardwareProjection;

// Before setting an encoder type, p96 should be 0


// (See section "Projecting EncoderConfiguration")

// To Project an EncoderConfiguration, first set e.g. Encoder 1 with .SetEncoder(...).

hardwareProjection.SetEncoder(
EncoderInterface.Terminal,
EncoderType.HTLTTL,
AbsoluteIncrementalFlag.Incremental,
RotaryLinearFlag.Rotary,
1);

// Get the current configuration of Encoder 1.


EncoderConfiguration config = hardwareProjection.GetCurrentEncoderConfiguration(1);

// Fill out Encoder 1's configuration values.


config.RequiredConfigurationEntries.ToList().ForEach(ce =>
{
switch (ce.Name)
{
case "p405.0":
ce.Value = 0;
break;
case "p405.1":
ce.Value = 1;
break;
case "p408":
ce.Value = 1024;
break;
case "p425":
ce.Value = 2048;
break;
default:
break;
}
});

// Project the Encoder 1 configuration to the device.


bool result =
cuDriveFunctionInterface.HardwareProjection.ProjectEncoderConfiguration(config, 1);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 833
TIA Portal Openness API
5.20 Functions for Startdrive

The following example shows how you can configure the actual encoder configuration online.

Configuring an encoder online


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;

Openness: API for automation of engineering workflows


834 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Configuring an encoder online


// Project encoder configuration in Online state
DeviceItem cuDeviceItem = m_Device.DeviceItems[1];
DeviceItem cuDeviceItemForOnline = m_Device.DeviceItems[0];
//You need the rack for going online on G120 Device, which is .DeviceItems[0]

// GoOnline...
// To use these function in Online, you have to use the OnlineDriveFunctionInterface
OnlineDriveObject onlineDriveObject =
cuDeviceItem.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];
OnlineDriveFunctionInterface onlineDfi =
onlineDriveObject.GetService<OnlineDriveFunctionInterface>();
HardwareProjection hardwareProjection = onlineDfi.HardwareProjection;

// Before setting an encoder, p96 should be 0


// (See section "Projecting EncoderConfiguration")

// To Project an EncoderConfiguration, first set e.g. Encoder 1 with .SetEncoder(...).

hardwareProjection.SetEncoder(
EncoderInterface.Terminal,
EncoderType.HTLTTL,
AbsoluteIncrementalFlag.Incremental,
RotaryLinearFlag.Rotary,
1);

// Get the current configuration of Encoder 1.


EncoderConfiguration config = hardwareProjection.GetCurrentEncoderConfiguration(1);

// Fill out Encoder 1's configuration values.


config.RequiredConfigurationEntries.ToList().ForEach(ce =>
{
switch (ce.Name)
{
case "p405.0":
ce.Value = 0;
break;
case "p405.1":
ce.Value = 1;
break;
case "p408":
ce.Value = 1024;
break;
case "p425":
ce.Value = 2048;
break;
default:
break;
}
});

// Project the Encoder 1 configuration to the device.


bool result = onlineDfi.HardwareProjection.ProjectEncoderConfiguration(config, 1);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 835
TIA Portal Openness API
5.20 Functions for Startdrive

The following example shows how you can write the configuration entry to the console.

Write out configuration entry


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
MotorConfiguration motorConfig = hardwareProjection.GetCurrentMotorConfiguration(0);

foreach (var configurationEntry in motorConfig.RequiredConfigurationEntries)


{
Console.WriteLine(configurationEntry.Name);
}
EncoderConfiguration encConfig = hardwareProjection.GetCurrentEncoderConfiguration(1);

foreach (var configurationEntry in encConfig.RequiredConfigurationEntries)


{
Console.WriteLine(configurationEntry.Name);
}

5.20.5.12 Configuring devices


The following example shows how you can configure S120 and G120 drive devices offline.

Configuring S120 and/or G120 drive devices offline


using Siemens.Engineering.MC.Drives
using Siemens.Engineering.MC.Drives.DFI
using Siemens.Engineering.MC.Drives.Enums;
DriveObject driveObject = ...
DriveFunctionInterface dfi = driveObject.GetService<DriveFunctionInterface>();
HardwareProjection hardwareProjection = dfi.HardwareProjection;

// dfi can be null in case of the actual driveobject does not support it.
// hardwareProjection can be null, if the actual driveObject does not support it.
// For example: On G120 drives, you have to use the CU as driveobject. On S120
// drives, you have to use the MotorModul as driveObject.

The following example shows how you can configure G120 drive devices online.

Configuring G120 drive devices online


using Siemens.Engineering.MC.Drives
using Siemens.Engineering.MC.Drives.DFI
using Siemens.Engineering.MC.Drives.Enums;
OnlineDriveObject onlineDriveObject = ...
OnlineDriveFunctionInterface onlineDfi =
onlineDriveObject.GetService<OnlineDriveFunctionInterface>();
HardwareProjection hardwareProjection = onlineDfi.HardwareProjection;

// onlineDfi can be null in case of the actual onlineDriveObject


// does not support it or if the device is offline.
// hardwareProjection can be null, if the actual onlineDriveObject
// does not support it.
// For example: On G120 drives, you have to use the CU as onlineDriveObject. On
// S120 drives, you have to use the MotorModul as onlineDriveObject.

Openness: API for automation of engineering workflows


836 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.5.13 Creating a component for a drive component (S120 only)


You have the option of creating a component below a drive component for the S120.
Also enter a type designation to distinguish between the various encoders. The possible type
designations and restrictions for encoders are described in the table below.
The following example shows how to create a component below a drive component.

Creating a motor and an encoder below a Motor Module


DeviceItem subModul = sdrDevice.PlugNew(@"OrderNumber:6SL3xxx-xxxxx-xxxx",
"MotorModul", 65535);

//Plug a motor to the motor modul


subModul.Container.PlugNew(@"OrderNumber:1PH2092-4WG4x-xxxx",
"Motor_1",65535);

//Plug an encoder to the motor modul


subModul.Container.PlugNew(@"OrderNumber:XExxxxx-xxxxx-xxxx//DRIVE-
CLIQ.202", "Encoder_1",65535);

Type designations for encoders and restrictions


The following restrictions apply when inserting encoders via Openness:
• Only an unspecific Sensor Module can be created for some encoders when inserting via
Openness. In this case, you must configure the specific type of the Sensor Module in the TIA
Portal.
• Maximum two encoders can be inserted for one Motor Module.
The following table lists the available type designations for encoders.

DRIVE-CLiQ Resolver sin/cos SSI sin/cos+SSI HTL/TTL HTL/TTL+SSI EnDat 2.1


DRIVE- Resolver.0 SIN_COS.0 SSI.0 SIN_COS_ HTL_TTL.0 HTL_TTL En‐
CLIQ.202 +_SSI.0 +SSI.0 Dat_2.1.2051
DRIVE- Resolv‐ SIN_COS.200 SSI.3081 SIN_COS_ HTL_TTL.300 HTL_TTL En‐
CLIQ.204 er.1001 1 +_SSI.2081 1 +SSI.3088 Dat_2.1.2052
DRIVE- Resolv‐ SIN_COS.200 SSI.3082 SIN_COS_ HTL_TTL.300 HTL_TTL En‐
CLIQ.212 er.1002 2 +_SSI.2082 2 +SSI.3090 Dat_2.1.2053
DRIVE- Resolv‐ SIN_COS.200 SSI.9999 SIN_COS_ HTL_TTL.300 HTL_TTL En‐
CLIQ.214 er.1003 3 +_SSI.2083 3 +SSI.9999 Dat_2.1.2054
DRIVE- Resolv‐ SIN_COS.200 ‑ SIN_COS_ HTL_TTL.300 ‑ En‐
CLIQ.242 er.1004 4 +_SSI.2084 5 Dat_2.1.2055
DRIVE- Resolv‐ SIN_COS.200 ‑ SIN_COS_ HTL_TTL.300 ‑ En‐
CLIQ.244 er.9999 5 +_SSI.9999 6 Dat_2.1.2151
DRIVE- ‑ SIN_COS.200 ‑ ‑ HTL_TTL.300 ‑ En‐
CLIQ.9999 6 7 Dat_2.1.9999
DRIVE- ‑ SIN_COS.200 ‑ ‑ HTL_TTL.300 ‑ En‐
CLIQ.10100 7 8 Dat_2.1.1010
0
‑ ‑ SIN_COS.200 ‑ ‑ HTL_TTL.300 ‑ ‑
8 9

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 837
TIA Portal Openness API
5.20 Functions for Startdrive

DRIVE-CLiQ Resolver sin/cos SSI sin/cos+SSI HTL/TTL HTL/TTL+SSI EnDat 2.1


‑ ‑ SIN_COS.201 ‑ ‑ HTL_TTL.301 ‑ ‑
0 1
‑ ‑ SIN_COS.201 ‑ ‑ HTL_TTL.302 ‑ ‑
2 0
‑ ‑ SIN_COS.201 ‑ ‑ HTL_TTL.310 ‑ ‑
3 9
‑ ‑ SIN_COS.211 ‑ ‑ HTL_TTL.999 ‑ ‑
0 9
‑ ‑ SIN_COS.211 ‑ ‑ ‑ ‑ ‑
1
‑ ‑ SIN_COS.211 ‑ ‑ ‑ ‑ ‑
2
‑ ‑ SIN_COS.999 ‑ ‑ ‑ ‑ ‑
9

5.20.5.14 Defining the motor type and motor configuration


The following examples show how you can set a motor type for G120 drives via the device
configuration:

Setting the motor type offline via the hardware configuration


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;
//Offline (Only on G120 drives)
DriveFunctionInterface dfi = ...
HardwareProjection hardwareProjection = dfi.HardwareProjection;

// hardwareProjection can be null in case of the actual driveObject


// does not support activation.
// Setting the required MotorType and DriveDataSetNumber on the drive.
// It is only supported on G120 drives.

//First parameter is the MotorType, Second parameter is the DriveDataSetNumber


hardwareProjection.SetMotorType(MotorType.InductionMotor, 0);

// There can be a problem, if the selected MotorType is not available


// on the drive. In that case, it has to give back a feedback.

Setting the motor type online via the hardware configuration


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;

Openness: API for automation of engineering workflows


838 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Setting the motor type online via the hardware configuration


//Online (Only on G120 drives)
OnlineDriveFunctionInterface onlineDfi = ...
HardwareProjection hardwareProjection = onlineDfi.HardwareProjection;

// hardwareProjection can be null in case of the actual


// onlineDriveObject does not support activation.
// Setting the required MotorType and DriveDataSetNumber on
// the drive. It is only supported on G120 drives.

// First parameter is the MotorType, Second parameter is the DriveDataSetNumber


hardwareProjection.SetMotorType(MotorType.InductionMotor, 0);

// There can be a problem, if the selected MotorType is not available on


// the drive. In that case, it has to give back a feedback.

The following examples show how you can read out the motor type for G120 drives from the
drive:

Determining the motor configuration offline


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;
// Offline
// WARNING: You have to set the MotorType on G drives before
// you would like to get the current configuration, otherwise
// you will get an exception/feedback, which informs you that
// there is no motor set.
// On S120 drives, you don't have to do that, but you have to
// plug a motor to motor modul.( later on)

HardwareProjection hardwareProjection = dfi.HardwareProjection;


// Get the current motor configuration
// It needs a datasetnumber, which is currently only supported on G120 drives.
MotorConfiguration motorConfiguration = hardwareProjection.GetCurrentMotorConfiguration(0);

Determining the motor configuration online


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;
// Online
// WARNING: You have to set the MotorType on G drives before
// you would like to get the current configuration, otherwise
// you will get an exception/feedback, which informs you that
// there is no motor set.
// On S120 drives, it is not possible??

HardwareProjection hardwareProjection = onlineDfi.HardwareProjection;


// Get the current motor configuration
// It needs a datasetnumber, which is currently only supported on G120 drives.
MotorConfiguration motorConfiguration = hardwareProjection.GetCurrentMotorConfiguration(0);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 839
TIA Portal Openness API
5.20 Functions for Startdrive

The following example shows how you can create a motor configuration for G120 drives:

Configuring a motor configuration


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;
DeviceItem cuDeviceItem = m_Device.DeviceItems[1];
DriveObject cuDriveObject =
cuDeviceItem.GetService<DriveObjectContainer>().DriveObjects[0];
DriveFunctionInterface cuDriveFunctionInterface =
cuDriveObject.GetService<DriveFunctionInterface>();

HardwareProjection hardwareProjection = cuDriveFunctionInterface.HardwareProjection;


hardwareProjection.SetMotorType(MotorType.InductionMotor, 0);

MotorConfiguration config = hardwareProjection.GetCurrentMotorConfiguration(0);

config.RequiredConfigurationEntries.ToList().ForEach(ce =>
{
switch (ce.Number)
{
case 305:
ce.Value = 20;
break;
case 307:
ce.Value = 30;
break;
case 311:
ce.Value = 200;
break;
case 304:
ce.Value = 450;
break;
case 310:
ce.Value = 50;
break;
case 335:
ce.Value = 1;
break;
default:
break;
}
});
bool result =
cuDriveFunctionInterface.HardwareProjection.ProjectMotorConfiguration(config, 0);

5.20.5.15 Reading and writing parameters


The following example shows how to read and write values of drive parameters. You require a
drive object for access.

Access to parameters
using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


840 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Access to parameters
//Access a parameter via its name
DriveParameter parameter = driveObject.Parameters.Find("p5391[0]");

//Example of reading parameter attributes


if (parameter != null)
{
Console.WriteLine("The Name of the parameter is : " + parameter.Name);
Console.WriteLine("The value of the parameter is : " +
parameter.Value.ToString());
Console.WriteLine("The minvalue of the parameter is : " +
parameter.MinValue);
Console.WriteLine("The MaxValue of the parameter is : " +
parameter.MaxValue);
Console.WriteLine("The Unit of the parameter is : " + parameter.Unit);

//Example for write:


parameter.Value = 60;
}

// Access a parameter via Number and ArrayIndex// Note that


// - arrayless parameters (e.g. p96 on G120) are indexed by -1
// - parameters that consist of only a bit array do not count as
// array parameters, they are indexed by -1 as well and the
// further bit values can be accessed by the 'Bits' property
// of the given parameter (e.g. r2139 on G120). For further
// information about accessing bit parameters see the next
// section of this code snippet

DriveParameter r947_6 = driveObject.Parameters.Find(947, 6); // returns


r947[6]if (r947_6 != null)
{
Console.WriteLine("The Name of the parameter is : " + r947_6.Name);
Console.WriteLine("The value of the parameter is : " +
r947_6.Value.ToString());
}

//Accessing bit values


DriveParameter p2720 = driveObject.Parameters.Find(2720, 0);if (p2720 !=
null)
{
// Note that in general, pXXX.Bits[YYY] is not necessarily equivalent to
pXXX.YYY.
// pXXX.Bits is an array of available bit values in ascending order by
their names
// and not an array of bit values indexed by their names.
// For example: let the available bit values be [pXXX.0, pXXX.2, pXXX.3],
then
// pXXX.Bits[2] == pXXX.3, not pXXX.2

DriveParameter p2720Bit1 = p2720.Bits[1]; // returns p2720[0].1


if (p2720Bit1 != null)
{
Console.WriteLine("The name of the parameter is : " + p2720Bit1.Name);
Console.WriteLine("The value of the second bit of the parameter is : "
+ p2720Bit1.Value.ToString());
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 841
TIA Portal Openness API
5.20 Functions for Startdrive

Access to parameters
}

//Get the enum values of a parameter


DriveParameter r47 = driveObject.Parameters.Find("r47");
foreach (var enumItem in r47.EnumValueList)
{
Console.WriteLine("Enum value: " + enumItem.Key.ToString() + " = " +
enumItem.Value);
}

Extended access to the parameters


In order to obtain reading and writing access to all parameters of a drive object, there is an
additional extended Openness interface. Improper use of the extended parameter access via
openness can lead to damage of the Startdrive project file and prevent commissioning of the
drive. Siemens AG makes this interface available only on request and after consultation. For
more information, contact your regional sales partner (https://www.automation.siemens.com/
aspa_app?ci=yes&lang=en).

5.20.5.16 Reading and writing parameters online


The following example shows how to obtain a list with the available online parameters. You
require an online drive object for access.
The read and write access to individual online parameters from the parameter list is identical to
that in the Reading and writing parameters (Page 840) example.

Access to online parameters


using Siemens.Engineering.MC.Drives;
DeviceItem item = ... //device item of the CU (e.g. :
project.Devices[0].Items[0].Items[0])
OnlineDriveObject onlineDriveObject =
item.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];
if (onlineDriveObject != null)
{
var parameters = onlineDriveObject.Parameters;
}

5.20.5.17 Saving the parameterization


The following example shows how you can determine the parameterization from S120, S210 or
G120 drives.

Determining the parameterization online from the drives


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;

Openness: API for automation of engineering workflows


842 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Determining the parameterization online from the drives


OnlineDriveObject onlineDriveObject =
item.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];
OnlineDriveFunctionInterface onlineDfi =
onlineDriveObject.GetService<OnlineDriveFunctionInterface>();
DriveDomainFunctions driveDomainFunctions = onlineDfi.DriveDomainFunctions;

// onlineDfi can be null in case of the actual onlineDriveObject


// does not support it or if the device is offline.

// driveDomainFunctions can be null, if the actual onlineDriveObject


// does not support it.

// For example: On G120 and S210 drives, you have to use the CU to get the
onlineDriveObject.
// Please, pay attention at S120 drives. Here you can use any module (CU, MotorModul,
lineModul) as onlineDriveObject but preferable the CU, because it will run on CU!

The following example shows how you can copy the parameterization for S120, S210 or G120
drives from RAM to ROM - and therefore retentively save the parameter assignment.

Backing up from RAM to ROM


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;
//In case of G120 device.
DeviceItem cuDeviceItem = m_Device.DeviceItems[1];
OnlineDriveObject cuDriveObject =
cuDeviceItem.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];

//In case of S120 and S210 device you should generally get the CU driveobject.
DeviceItem cuDeviceItem = m_Device.DeviceItems[0];OnlineDriveObject cuDriveObject =
cuDeviceItem.GetService<OnlineDriveObjectContainer>().OnlineDriveObjects[0];

// To use the function, you have to use the OnlineDriveFunctionInterface.


OnlineDriveFunctionInterface cuDriveFunctionInterface =
cuDriveObject.GetService<OnlineDriveFunctionInterface>();
DriveDomainFunctions driveDomainFunctions = cuDriveFunctionInterface.DriveDomainFunctions;

// This function will perform a RAM to ROM copy on all device.


// It is important that the CU should be in online state before you call this function
anyway the program will give an exception.
// This call may take a few moments before be finished.
bool result = DriveDomainFunctions.PerformRAMtoROMCopyAllDriveObject();

5.20.5.18 How to assign a SecureString password


With the SetPassword() method you can assign passwords for secure communication during
downloading. The parameter must be a SecureString.
The following example shows how to assign a SecureString password.

How to assign a SecureString password

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 843
TIA Portal Openness API
5.20 Functions for Startdrive

How to assign a SecureString password


public void SetPassword(DownloadPasswordConfiguration
downloadPasswordConfiguration)
{
if (downloadPasswordConfiguration != null)
{
SecureString s = GetSecureString();
downloadPasswordConfiguration.SetPassword(s);
return;
}
}

private SecureString GetSecureString()


{
SecureString securePwd = new SecureString();
ConsoleKeyInfo key;

Console.Write("Enter password: ");


do
{
key = Console.ReadKey(true);

// Ignore any key out of range.


if (((int)key.Key) >= 65 && ((int)key.Key <= 90))
{
// Append the character to the password.
securePwd.AppendChar(key.KeyChar);
Console.Write("*");
}
// Exit if Enter key is pressed.
} while (key.Key != ConsoleKey.Enter);

return securePwd;

See also
Encrypted communication with SecureString passwords (Page 802)

5.20.5.19 Using Safety Integrated telegrams


The following example shows how you can use Safety Integrated telegrams (e.g. 30) in
Openness.

Using Safety Integrated telegrams


using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


844 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

Using Safety Integrated telegrams


TelegramComposition telegrams = drvObj.Telegrams;

//Add safety telegram


const int tgrmNumber = 30;
drvObj.Telegrams.InsertSafetyTelegram(tgrmNumber);

//Find safety telegram


Telegram safetyTgrm = drvObj.Telegrams.Find(TelegramType.SafetyTelegram);

// Get and set safety telegram attributes


uint watchDogTime = (uint)safetyTgrm.GetAttribute("Failsafe_FMonitoringtime");

safetyTgrm.SetAttribute("Failsafe_FMonitoringtime", 300);

const int newSafetyTelegramNumber= 900;


if (safetyTgrm.CanChangeTelegram(newSafetyTelegramNumber))
{
safetyTgrm.TelegramNumber = newSafetyTelegramNumber;
}

//Remove Safety telegram


drvObj.Telegrams.EraseTelegram(TelegramType.SafetyTelegram);

5.20.5.20 Setting the SIMOGEAR article number for G115D drives


The following example shows how you can set the SIMOGEAR article number for G115D drives.

Setting the SIMOGEAR article number for G115D drives


using Siemens.Engineering.MC.Drives;
Dvar commissioning= dfi.Commissioning;
var commissioning= dfi.Commissioning;
//Commissioning can be null if the actual driveobject does not support the Commissioning
(e.g. SINAMICS S devices).

//Setting the article number of the SimoGear


commissioning.SetSimoGearMlfb("2KJ8001-2EG20-4DG1-D0X");

See also
Commissioning (Page 806)

5.20.5.21 Inserting and extending telegrams


The following example shows how to insert an extension and change the size of a standard
telegram. You require a drive object for access.

Inserting an extension and changing the size of a standard telegram


using Siemens.Engineering.MC.Drives;

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 845
TIA Portal Openness API
5.20 Functions for Startdrive

Inserting an extension and changing the size of a standard telegram


TelegramComposition telegrams = drvObj.Telegrams;
Telegram telegram = telegrams.Find(TelegramType.MainTelegram);

Console.WriteLine("The Cu has the telegram: " + telegram.TelegramNumber);


Console.WriteLine("The Setpoint channel-specific size of the telegram is: "
+ telegram.GetOutputSize());

foreach (var address in telegram.Addresses)


{
if (address.IoType == AddressIoType.Output)
{
Console.WriteLine("The Setpoint channel-specific starting address of
the connected PLC is: " + address.StartAddress);
}
else if(address.IoType == AddressIoType.Input)
{
Console.WriteLine("The Actual value channel-specific starting address
of the connected PLC is: " + address.StartAddress);
}
}

// Add an additional Telegram


if (drvObj.Telegrams.CanInsertAdditionalTelegram(2,4))
{
drvObj.Telegrams.InsertAdditionalTelegram(2,4);
}

// Add a 3 word extension to the main telegram


Telegram mainTelegram == drvObj.Telegrams.Find(TelegramType.MainTelegram);
Int32 newSize = mainTelegram.GetSize(AddressIoType.Input) + 3;
if (mainTelegram.CanChangeSize(AddressIoType.Input, newSize, true))
{
mainTelegram.ChangeSize(AddressIoType.Input, newSize, true)
}

5.20.5.22 Using torque telegrams


The following example shows how you can use torque telegrams (e.g. 750) in Openness.

Using torque telegrams


using Siemens.Engineering.MC.Drives;
const int torqueTelegramNumber = 750;
TelegramComposition telegrams = drvObj.Telegrams;

// Add a new torque telegram


if (drvObj.Telegrams.CanInsertTorqueTelegram(torqueTelegramNumber))
{
drvObj.Telegrams.InsertTorqueTelegram(torqueTelegramNumber);
}

// Find torque telegram


Telegram torqueTelegram = drvObj.Telegrams.Find(TelegramType.TorqueTelegram);

Openness: API for automation of engineering workflows


846 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.20 Functions for Startdrive

5.20.5.23 Restoring factory settings


The following example shows how you can restore the factory settings for S120, S210 or G120
drives.

Restoring factory settings


using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DFI;
using Siemens.Engineering.MC.Drives.Enums;
OnlineDriveObject onlineDriveObject = ...
OnlineDriveFunctionInterface onlineDfi =
onlineDriveObject.GetService<OnlineDriveFunctionInterface>();
DriveDomainFunctions driveDomainFunctions = onlineDfi.DriveDomainFunctions;

// onlineDfi can be null in case of the actual onlineDriveObject


// does not support it or if the device is offline.
// saveParametrization can be null, if the actual onlineDriveObject
// does not support it.
// For example: On G120 and S210 drives, you have to use the CU to get the
onlineDriveObject.
// S120 drives, you can use any modul (CU, MotorModul, lineModul) as onlineDriveObject but
preferable the CU.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 847
TIA Portal Openness API
5.21 Functions for DCC

5.21 Functions for DCC

5.21.1 Introduction
Using TIA Portal-Openness, you automate the engineering and control the TIA Portal using a
program that you created yourself.
In this help document, you can find a lot of information and code examples for this program that
you generate yourself. You can also generate and use your own programs for the TIA Portal "DCC"
application.
Before you generate your own program for DCC from the sample codes listed in the following,
please note the general information on Openness, which you can find in this help under the
following keywords:
• Preconditions for using TIA Portal Openness
• Installing TIA Portal Openness
• Accessing the TIA Portal
• TIA Portal Openness object model
• Programming steps

5.21.2 DCC Openness

Introduction
With TIA Portal Openness V16, you program applications that are automated in TIA Portal
engineering.

Openness functions in conjunction with SINAMICS DCC


The following functions have been implemented in Version V16:
• Import charts (Page 854)
• Export one chart (Page 854) or Export all charts ("Charts" folder) (Page 854)
• Import DCB Extension libraries into the project library (Page 857)
• Find charts based on their names (Page 855)
• Delete a chart from the "Charts" folder (Page 856)
• Optimize the block run sequence in a chart (Page 856)

Openness: API for automation of engineering workflows


848 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

Note
Subcharts
Charts that contain subcharts can be imported using Openness. However, Openness cannot be
used to access subcharts.

Additional information
See TIA information system "Openness: Automate project creation".

5.21.3 DCC Openness object model

Overview
The following diagram describes the DCC Openness object model:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 849
TIA Portal Openness API
5.21 Functions for DCC

5.21.4 References

5.21.4.1 DriveControlChartContainer

DriveParameter
DriveControlChartContainer is a service that represents the DCC chart container under a
DriveObject, so that it can be retrieved from the appropriate DriveObject. The service is not
provided if the DriveObject is not from a supported device.

The following table describes the Navigators of the DriveControlChartContainer:

Name Data type Writable Description


Charts DriveControlChartComposition Read only Reads out the chart layout (composi‐
tion) in the chart container.

5.21.4.2 DriveControlChartComposition

DriveControlChartComposition features
DriveControlChartComposition lists the available charts.

The following table describes the Methods of DriveControlChartComposition:

Name Type of return Parameter Description Exceptions


value
Import DccImportRe‐ string path, Method description: DccImpor‐
sultData DccImportOptions Import charts from a DCC export file. tException
(Page 851) (Page 851) impor‐ Parameter description: (Page
tOptions path: Complete path of the file to be imported. 860)
importOptions: Options used when importing,
see DccImportOptions (Page 851).
Export - string path Method description: DccExpor‐
Exports all charts to a DCC export file. tException
Parameter description: (Page
path: Complete path of the file to be exported. 860)
GetChartSe‐ DriveControl‐ - Reads-out all charts in the container in the order in -
quence Chart which they are run.
(Page 852)
Find DriveControl‐ string name Identifies a chart based on its name in the chart con‐ -
Chart tainer.
(Page 852)

Openness: API for automation of engineering workflows


850 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

See also
DriveControlChartComposition exceptions (Page 860)
DccImportResultData (Page 851)
DriveControlChart (Page 852)
DccImportOptions (Page 851)

5.21.4.3 DccImportOptions

DccImportOptions
These settings are possible when importing charts:
• DccImportOptions.None:
The import has been successfully completed if there is no name conflict. Otherwise
exception DccImportChartWithSameNameAlreadyAvailableException is thrown.
• DccImportOptions.RenameOnConflict:
If there is a chart name conflict, the CFC automatically assigns a name to the newly imported
chart. For example, if a chart with the name CFC_1 already exists on import, then the newly
imported chart is assigned name CFC_2.

See also
DriveControlChartComposition (Page 850)

5.21.4.4 DccImportResultData

DriveParameter
DccImportResultData contains information about the result when importing charts.

The following table describes the attributes of DccImportResultData:

Attribute name Data type Writable Description


RemappedParame‐ IDiction‐ Read only When importing, it is possible that a DCC parameter to be imported
terNumbers ary<UInt16,UInt16> is already available. In this case, the imported parameter is assigned
a new number. This dictionary then contains all of the newly as‐
signed parameters. The key value is the previous parameter num‐
ber as it was exported and the value is the newly created parameter.

See also
DriveControlChartComposition (Page 850)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 851
TIA Portal Openness API
5.21 Functions for DCC

5.21.4.5 DriveControlChart

DriveControlChart Features
DriveControlChart corresponds to a chart within the chart container (Openness does not
support subcharts).
The following table describes the attributes of the DriveControlChart:

Attribute Data type Writable Description


name
Name string Read only Name of the chart.

The following table describes the methods of DriveControlChart:

Name Type of re‐ Parameter Description Exceptions


turn value
Export - string path Method description: DccExportException
Exports only this chart. (Page 859)
Parameter description:
path: Complete path of the file to be exported.
Delete - - Method description: -
Deletes the chart.
OptimizeRunS - - Description method: DccLicenseUnavaila‐
equence Optimizes the run sequence of the chart. CFC pro‐ bleException
vides the optimization mechanism. (Page 859)
Note:
The run sequence can only be optimized if a DCC li‐
cense is available.

See also
DriveControlChart Exceptions (Page 859)
DriveControlChartComposition (Page 850)
Deleting a chart (Page 856)

5.21.4.6 Importing DCB extension library

ImportDCBextensionlibrary
The following table describes the Methods of ImportDCBextensionlibrary:

Name Return val‐ Param‐ Description


ue eter
ImportDcbLibrary - string Method arguments:
path path: The complete path of the DCB Extension library zip file.
Method description:
Imports a DCB Extension library into the project library.

Openness: API for automation of engineering workflows


852 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

5.21.5 Code examples

5.21.5.1 General
The following code examples describe the basic procedure for various applications. The code is
not necessarily complete or compilable.

5.21.5.2 Accessing a DriveControlChartContainer via DriveObject


The following example shows how you can access a DriveControlChartContainer via a drive
object.

Accessing a DriveControlChartContainer
using Siemens.Engineering.MC.Drives;
using Siemens.Engineering.MC.Drives.DCC;
Project project = portal.Projects.Open("..."); //Destination folder to
open the project
DeviceItem item = project.Devices[0].Items[0];
DriveObject
driveObject = item.GetService<DriveObjectContainer>().DriveObjects[0];
DriveControlChartContainer
chartContainer = driveObject.GetService<DriveControlChartContainer>();
//chartContainer can be null in case the DriveObject does not support DCC.

5.21.5.3 Retrieving charts


The following example shows how you can retrieve charts.

Retrieving charts

DriveControlChartComposition charts = chartContainer.Charts;

5.21.5.4 Accessing charts


The following example shows how you can access charts.

Accessing charts

DriveControlChartComposition charts = ...


DriveControlChart firstChart = charts[0];

// or looping...
foreach(DriveControlChart chart in charts)
{
...
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 853
TIA Portal Openness API
5.21 Functions for DCC

5.21.5.5 Importing charts


The following example shows how you can import charts.

Importing charts

try
{
DriveControlChartComposition charts = ...
DccImportResultData result = charts.Import(@"c:\Charts.dcc",
DccImportOptions.None);
}
catch (DccImportException exc)
{
}

See also
DCC Openness (Page 848)

5.21.5.6 Exporting charts


The following example shows how you can export charts.

Exporting charts

try
{
DriveControlChart chart;
...
chart.Export(@"c:\CFC_1.dcc");
}
catch (DccExportException exc)
{
}

See also
DCC Openness (Page 848)

5.21.5.7 Export all charts


The following example shows how you can export all charts.

Exporting all charts

Openness: API for automation of engineering workflows


854 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

Exporting all charts


try
{
charts.Export(@"c:\Charts.dcc");
}
catch (DccExportException exc)
{
}

See also
DCC Openness (Page 848)

5.21.5.8 Retrieving charts in the order in which they are executed


The following example shows how you can retrieve charts in the order in which they are
executed.

Retrieving charts

DriveControlChartComposition charts = ...


IList<DriveControlChart> chartSequence = charts.GetChartSequence();

5.21.5.9 Finding charts based on their names


The following example shows how you can find a chart based on its name.

Finding charts

DriveControlChartComposition charts = ...


DriveControlChart chart = charts.Find("CFC_1");

See also
DCC Openness (Page 848)

5.21.5.10 Displaying an import report


The following example shows how you can display a report associated with the import.

Displaying an import report

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 855
TIA Portal Openness API
5.21 Functions for DCC

Displaying an import report


DccImportResultData importResultData = charts.Import(@"d:\Charts.dcc",
DccImportOptions.None);
IDictionary<ushort, ushort> remappedParameters = importResultData.RemappedP
arameterNumbers;
foreach (KeyValuePair<ushort, ushort> remappedParameter in remappedParamete
rs)
{
System.Console.WriteLine($"ParameterNumber <{remappedParameter.Key}> has
been changed to <{remappedParameter.Value}> during import.");
}

5.21.5.11 Deleting a chart


The following example shows how you can delete charts.

Deleting charts

try
{
DriveControlChart chart;
...
chart.Delete();
}
{
}

See also
DCC Openness (Page 848)
DriveControlChart (Page 852)

5.21.5.12 Optimizing the execution sequence


The following example shows how you can optimize the sequence in which charts are run.

Optimizing the run sequence of charts

try
{
DriveControlChart chart;
...
chart.OptimizeRunSequence();
}
catch (DccLicenseUnavailableException exc)
{
}

Openness: API for automation of engineering workflows


856 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

See also
DCC Openness (Page 848)

5.21.5.13 Importing a DCB Extension library


The following example shows how you can import a DCB Extension library.

Importing a DCB Extension library

try
{
Project myProject;
...

myProject.ProjectLibrary.ImportDcbLibrary(@"c:\GMCV5_1_sinamics5_1_(5.1.15
).zip");
}
catch (DccImportException exc)
{
}

See also
DCC Openness (Page 848)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 857
TIA Portal Openness API
5.21 Functions for DCC

5.21.6 DCC Openness exceptions

5.21.6.1 Exception handling

Exception handling
For applications that could fail because of user error, DCC Openness throws a DCC specific
exception derived from EngineeringTargetInvocationException. These exceptions
are hierarchical, which means that all specific exceptions are derived from the higher-level
exception DccException:

If client does not want to evaluate or distinguish between different error causes, then the
simplest way is to catch the general DccException:

Openness: API for automation of engineering workflows


858 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

try
{
Project myProject;

myProject.ProjectLibrary.ImportDcbLibrary(@"c:\GMCV5_1_sinamics5_1_(5.1.15
).zip");
...
DriveControlChartContainer chartContainer = driveObject.GetService<DriveC
ontrolChartContainer>();
chartContainer.Charts.Import(@"d:\Charts.dcc", DccImportOptions.None);
}
catch (DccException exc)
{
}

If you wish to respond based on the type of error, then catch all relevant exceptions:

try
{
DriveControlChartContainer
chartContainer = driveObject.GetService<DriveControlChartContainer>();
chartContainer.Charts.Import(@"d:\Charts.dcc", DccImportOptions.None);
}
catch (DccImportLibraryIsMissingException missingLibExc)
{
}
catch (DccImportChartWithSameNameAlreadyAvailableException sameNameExc)
{
}
catch (DccImportException exc)
{
}
catch (DccException exc)
{
}

5.21.6.2 DriveControlChart Exceptions

Exceptions
Exceptions that can be thrown when exporting:
• DccExportException:
Is thrown for all export error types.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 859
TIA Portal Openness API
5.21 Functions for DCC

Exceptions that can be thrown when executing the function to optimize the sequence in which
charts are run.
• DccLicenseUnavailableException:
Is thrown if a DCC license is not available. In this case, the function to optimize the run
sequence is not available.

See also
DriveControlChart (Page 852)

5.21.6.3 DriveControlChartComposition exceptions

Exceptions
Exceptions that can be thrown when importing:
• DccImportException:
General import exception, which DCC throws in the case of an import error.
• DccImportBlockCreationException:
Is thrown if a block was not able to be created when being imported.
• DccImportBlockTypeNotFoundException:
Is thrown if a referenced DCB block type was not able to be found in a standard DCBLib or in
an extension library.
• DccImportChartCreationException:
• Is thrown if a chart was not able to be created when being imported.
• DccImportChartWithSameNameAlreadyAvailableException:
Is thrown if a chart with the same name already exists in the chart container and
DccImportOptions.None is used.
• DccImportLibraryIsMissingException:
Is thrown if a referenced DCB Extension library does not exist in the project.
• DccImportFileAlreadyInUseException:
Is thrown if the file being imported is already being used in another process.
• DccImportDcbTypeDifferentVersionAlreadyUsedException:
Is thrown if a DCB type in a different version of the same DCB Extension library is already being
used in the device.

See also
DriveControlChartComposition (Page 850)

Openness: API for automation of engineering workflows


860 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.21 Functions for DCC

5.21.6.4 ImportDcbLibrary Exceptions

Exceptions
Exceptions thrown by ImportDcbLibrary:
• DccImportException:
Is thrown for all import error types.
• DccLibraryImportAlreadyAvailableException:
Is thrown if the same version of the DCB Extension library already exists in the project.
• DccLibraryImportCorruptedStudioLibraryException:
Is thrown if the DCB Extension library zip file is corrupted and cannot be imported.
• DccLibraryImportIntegrityBrokenException:
Is thrown if the zip file of the DCB Extension library is corrupted.
• DccLibraryImportOverallPinLimitExceededException:
Is thrown if the DCB Extension library contains a DCB type that exceeds the maximum
number of pins permitted.
• DccLibraryImportStandardLibraryAlreadyAvailableException:
Is thrown if the DCB Extension library selected for import is the standard DCBLib, and already
exists.
• DccLibraryImportUnsupportedLibraryTypeException:
Is thrown if the selected DCB Extension library is not supported by DCC and SINAMICS drives.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 861
TIA Portal Openness API
5.22 Exceptions

5.22 Exceptions

5.22.1 Handling exceptions

Exceptions when accessing the TIA Portal via TIA Portal Openness APIs
During the execution of an TIA Portal Openness application via the TIA Portal Openness API, all
errors which occur are reported as exceptions. These exceptions contain information that will
help you to correct the errors which have occurred.

Openness: API for automation of engineering workflows


862 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.22 Exceptions

A distinction is made between two types of exceptions:


• Recoverable (Siemens.Engineering.EngineeringException)
You can continue to access the TIA Portal without interruption with this exception.
Alternatively, you can cancel the connection to the TIA Portal.
The EngineeringExceptions include the following types:
– Security-related exceptions (EngineeringSecurityException), for example, in case of
missing access rights.
– Exceptions when accessing objects (EngineeringObjectDisposedException), for example,
when accessing objects which no longer exist.
– Exceptions when accessing attributes (EngineeringNotSupportedException), for
example, when accessing attributes which do not exist.
– General exceptions when calling (EngineeringTargetInvocationException), for example,
error despite valid call of TIA Portal Openness API.
– Exceptions when calling (EngineeringRuntimeException), for example, invalid cast
exception.
– Exceptions when there are not enough resources in associated TIA Portal instance
(EngineeringOutOfMemoryException)
– Exceptions when calling is terminated (EngineeringUserAbortException), for example,
during an import action canceled by user.
– Exceptions thrown during the API call invocated from a client provided delegate
(EngineeringDelegateInvocationException). This exception is derived from
EngineeringTargetInvocationException exception.
The EngineeringExceptions have the following attributes:
– ExceptionMessageData messageData: Contains the reason for which the exception
was thrown.
– ExceptionMessageData detailMessageData: Contains additional information
about the reason. The result is returned as a <IList> .
– String message: Returns the result from MessageData and DetailMessageData.
ExceptionMessageData returns the following information:
– String Text: Contains the reason for which the exception was thrown.
• NonRecoverable (Siemens.Engineering.NonRecoverableException)
This exception closes the TIA Portal and the connection to the TIA Portal is disconnected. You
need to restart the TIA Portal using the TIA Portal Openness application.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 863
TIA Portal Openness API
5.22 Exceptions

Program code
The following example shows the options you have for responding to exceptions:

try
{
...
}

catch(EngineeringSecurityException engineeringSecurityException)
{
Console.WriteLine(engineeringSecurityException);
}

catch(EngineeringObjectDisposedException engineeringObjectDisposedException)
{
Console.WriteLine(engineeringObjectDisposedException.Message);
}

catch(EngineeringNotSupportedException engineeringNotSupportedException)
{
Console.WriteLine(engineeringNotSupportedException.MessageData.Text);
Console.WriteLine();
foreach(ExceptionMessageData detailMessageData in
engineeringNotSupportedException.DetailMessageData)
{
Console.WriteLine(detailMessageData.Text);
}
}

catch (EngineeringTargetInvocationException)
{
throw;
}

catch (EngineeringException)
{
//Do not catch general exceptions
throw;
}

catch(NonRecoverableException nonRecoverableException)
{
Console.WriteLine(nonRecoverableException.Message);
}

Openness: API for automation of engineering workflows


864 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

5.23 F-related Openness

5.23.1 F-related Openness

Requirement
Making changes in the F-Program is only allowed in the Offline mode. In other cases an exception
is thrown.
If an F-Program password has been set, the client needs to be logged in, in order to make
changes in the F-Program. Otherwise, the client is reminded about the need to login to the F-
Program beforehand with an exception.
The TIA Portal Openness application is connected to TIA Portal.
See "Connecting to the TIA Portal (Page 81)".

Openness service
The Openness interface (Siemens.Engineering.dll) has been extended with
the GlobalSettings service (see name area Siemens.Engineering.Safety) which
provides two actions:
• SafetyModificationsPossible(bool safetyModificationsPossible)
• UsernameForFChangeHistory(string userName)
The Openness interface (Siemens.Engineering.dll) has been extended with the
SafetySignatureProvider service which provides three actions:
• SafetySignatureComposition Signatures
• UInt64 SafetySignature.Value
• SafetySignatureType SafetySignature.Type
The Openness interface (Siemens.Engineering.dll) is extended by the service
SafetyAdministration with the following actions and properties in the namespace
Siemens.Engineering.Safety.
• bool IsSafetyOfflineProgramPasswordSet
• void SetSafetyOfflineProgramPassword(SecureString newPassword)
• void RevokeSafetyOfflineProgramPassword(SecureString
currentPassword)
• bool IsLoggedOnToSafetyOfflineProgram
• void LoginToSafetyOfflineProgram(SecureString currentPassword)
• void LogoffFromSafetyOfflineProgram()
The Openness interface (Siemens.Engineering.dll) is extended by the service
SafetyAdministration, which is accessible from a Plc-DeviceItem. The
SafetyAdministration provides the following properties defined in the namespace

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 865
TIA Portal Openness API
5.23 F-related Openness

Siemens.Engineering.Safety. This two properties contain further properties that are listed in
the following section.
• RuntimegroupComposition RuntimeGroups { get; }
• SafetySettings Settings { get; }
The Openness interface (Siemens.Engineering.dll) is extended by the service
SafetyPrintout with the following action in the namespace
Siemens.Engineering.Safety:
• bool Print(SafetyPrintoutFilePrinter filePrinter, FileInfo
fullOutputPath, string documentLayout, SafetyPrintoutOption
documentationOption);

Principle
Get the Safety.GlobalSettings service from the TiaPortal instance:
Engineering.Safety.GlobalSettings globalSettings =
TiaPortal.GetService<Engineering.Safety.GlobalSettings>();

5.23.2 SafetyModificationsPossible

Application
The SafetyModificationsPossible(bool safetyModificationsPossible)
action of the GlobalSettings service is used to prevent changes to the safety program in TIA
Portal.
When the parameter safetyModificationsPossible is true, TIA Portal behaves
according to the current safety settings for the safety program.
If the parameter safetyModificationsPossible is false, all changes to the safety
program are locked, regardless of whether the user has already entered the password for
changing the safety program or not. The system uses feedback messages to provide information
that the current user is not authorized to change the safety program.
If no password has been configured or assigned for the safety program,
safetyModificationsPossible false has no effect. This means the safety program can be
changed. However, the setting up of new passwords is blocked.
The table below shows the parameters required by the method:

Name Type Description


safetyModificationsPossi bool Authorization of changes to the safety pro‐
ble gram

Program code
Prevent changes to the safety program:
globalSettings.SafetyModificationsPossible(false);

Openness: API for automation of engineering workflows


866 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

5.23.3 UsernameForFChangeHistory

Application
The action UsernameForFChangeHistory(string userName) specifies the user name
that is used by TIA Portal for subsequent logging in the F-change history.
The maximum length of the string is limited to 256 characters. Strings which exceed the
maximum length are cut off.
An empty user name (zero or empty string) resets the user name to the default value.
The table below shows the parameters required by the method:

Name Type Description


userName string Preferred user name

Program code
Sets the preferred user name:
globalSettings.UsernameForFChangeHistory("username");

5.23.4 SafetySignatureProvider
The signatures read out give a first indication about changes to F-blocks. For plant acceptance,
continue as described in the section entitled "System acceptance" in the "SIMATIC Safety -
Configuring and Programming" manual.

Application
Signatures: SafetySignatureComposition returns a collection
of SafetySignature objects. Objects of this type have a property
of SafetySignature.Value: UInt64, which return an integer value for the F-signature. In
addition, the property SafetySignature.Type: SafetySignatureType, which returns
the type of the F-signature, encapsulated in the SafetySignature instance.
If the F-signature does not exist or is no longer valid due to a recent change, 0 is returned. This
also applies to blocks without an F-signature (e.g. system blocks).

Program code
Get the SafetySignatureProvider service from the PlcBlock instance.
SafetySignatureProvider signatureProvider =
block.GetService<SafetySignatureProvider>()
If the block is not an F-block or not a block of an F-CPU S7-1200/1500, signatureProvider
returns null.
If there is a non-nullable block, you can query the F-signature with the following code:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 867
TIA Portal Openness API
5.23 F-related Openness

SafetySignature signature =
signatureProvider.Signatures.Find(SafetySignatureType.BlockOfflineSi
gnature);
UInt64 value = signature.value;

5.23.5 SafetyAdministration

5.23.5.1 SafetyAdministration
This features are available for S7-1200/1500 F-CPUs.
A valid Safety license must be installed for actions and setting values. A missing license will result
in an exception. Reading values is possible without a license.

Program code
Obtain the SafetyAdministration service from the PLC DeviceItem instance at hand.
SafetyAdministration safetyAdministration =
deviceItem.GetService<SafetyAdministration>();
// check if the service is not null
if (safetyAdministration != null)
{
// ...
}

5.23.5.2 IsSafetyOfflineProgramPasswordSet

Program code
bool isPasswordSet =
safetyAdministration.IsSafetyOfflineProgramPasswordSet

Application
The property IsSafetyOfflineProgramPasswordSet returns true if the safety program
password is set.

5.23.5.3 SetSafetyOfflineProgramPassword

Program code
if (!safetyAdministration.IsSafetyOfflineProgramPasswordSet)
{
SecureString newPassword = new NetworkCredential("", "new
password").SecurePassword;

Openness: API for automation of engineering workflows


868 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

safetyAdministration.SetSafetyOfflineProgramPassword(newPassword);
}

Application
The action SetSafetyOfflineProgramPassword sets the safety program password if it
isn't set before. After the password is set successfully, the user is not logged ininto the safety
program. The LoginToSafetyOfflineProgram action needs to be called explicitly to
perform a login.
The user gets feedback in the form of an exception in the following cases.
• The given password is invalid (e.g. length equals 0 or is greater than 30)
• The given password is null
• A safety program password is already set
• If the Euchner key or UMAC is in use, manipulating the safety program password via
Openness is not allowed
• The user is not offline
• Safety license is not present

5.23.5.4 RevokeSafetyOfflineProgramPassword

Program code
if (safetyAdministration.IsSafetyOfflineProgramPasswordSet)
{
SecureString password = new NetworkCredential("",
"password").SecurePassword;

safetyAdministration.RevokeSafetyOfflineProgramPassword(password);
}

Application
The action RevokeSafetyOfflineProgramPassword clears the F-Program password if it's
correct.
After the password was revoked successfully, the user can set a valid new F-Program password
with the action SetSafetyOfflineProgramPassword.
The user gets feedback in the form of an exception in the following cases.
• If no password is set, it cannot be revoked
• The given password is null
• If the Euchner key is in use, manipulating the F-Program password via Openness is not
allowed

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 869
TIA Portal Openness API
5.23 F-related Openness

• The user is not offline


• Safety license is not present

5.23.5.5 IsLoggedOnToSafetyOfflineProgram

Program code
bool isLoggedOn =
safetyAdministration.IsLoggedOnToSafetyOfflineProgram

Application
The property IsLoggedOnToSafetyOfflineProgram returns true if a password is set and
the user is logged on.

5.23.5.6 LoginToSafetyOfflineProgram

Program code
if (!safetyAdministration.IsLoggedOnToSafetyOfflineProgram)
{
SecureString password = new NetworkCredential("",
"password").SecurePassword;
safetyAdministration.LoginToSafetyOfflineProgram(password);
}

Application
The action LoginToSafetyOfflineProgram logs-in the user into the safety program if the
passed password is correct. After a successful login changes to the safety program can be
made.
The user gets feedback in the form of an exception in the following cases.
• A safety program password is not set
• The password is null
• The password is wrong
• The Euchner key is in use
• The user is not offline
• Safety license is not present

5.23.5.7 LogoffFromSafetyOfflineProgram

Program code
if (safetyAdministration.IsLoggedOnToSafetyOfflineProgram)

Openness: API for automation of engineering workflows


870 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

{
safetyAdministration.LogoffFromSafetyOfflineProgram();
}

Application
This action LogoffFromSafetyOfflineProgram the user from the safety program. Thus,
it's not possible to make changes to the safety program anymore.
The user gets feedback in the form of an exception in the following cases.
• A safety program password is not set
• The Euchner key is in use
• The user is not offline
• Safety license is not present

5.23.5.8 Runtime Groups

Runtime Groups

Program code
foreach (RuntimeGroup runtimeGroup in
safetyAdministration.RuntimeGroups)
{
// access the properties on the RuntimeGroup object...
}

RuntimeGroup runtimeGroup1 =
safetyAdministration.RuntimeGroups.Find("RTG1");

Application
The property RuntimeGroups returns all runtime groups. Furthermore, one specific runtime
group can be retrieved by using the Find method. The Find method returns null if a runtime
group with the given name does not exist.
The following properties can be accessed from a RuntimeGroup instance at hand.

Runtime group name

Program code
string name = runtimeGroup.Name;

Application
Returns the name of the runtime group.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 871
TIA Portal Openness API
5.23 F-related Openness

FOB Name

Program code
string name = runtimeGroup.FOBName;

Application
Returns the FOB name or null if no FOB is set.

FOB EventClass

Program code
string eventClass = runtimeGroup.FOBEventClass;

Application
Returns the FOB event class or null if no FOB is set.

FOB Number

Program code
Int32 number = (Int32) runtimeGroup.GetAttribute("FOBNumber");
runtimeGroup.SetAttribute("FOBNumber", 123);

Application
Returns and sets the FOB number. If the FOB number is not available, null is returned. If the value
is set and no FOB is available, an exception is thrown.

FOB Cycle Time

Program code
Int32 cycleTime = (Int32) runtimeGroup.GetAttribute("FOBCycleTime");
runtimeGroup.SetAttribute("FOBCycleTime", 100000);

Application
Returns and sets the cycle time of the runtime group. If the value is not available, null is returned.
If the set value is not available or within the valid range, an exception is thrown.

Openness: API for automation of engineering workflows


872 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

FOB Phase shift

Program code
Int32 phaseShift = (Int32)
runtimeGroup.GetAttribute("FOBPhaseShift");
runtimeGroup.SetAttribute("FOBPhaseShift", 120);

Application
Returns and sets the Fail-safe organization block's phase shift of the runtime group. If the value
is not available, null is returned. If the set value is not available or within the valid range, an
exception is thrown.

FOB Priority

Program code
Int32 priority = (Int32) runtimeGroup.GetAttribute("FOBPriority");
runtimeGroup.SetAttribute("FOBPriority", 10);

Application
Returns and sets the Fail-safe organization block's priority of the runtime group. If the value is
not available, null is returned. If the set value is not available or within the valid range, an
exception is thrown.

Main safety block name

Program code
string mainSafetyName = runtimeGroup.MainSafetyBlockName;

Application
Returns the name of the main safety block or null if no block is set.

Main safety block IDB name

Program code
string mainSafetyIDbName = runtimeGroup.MainSafetyBlockIDbName;

Application
Returns the name of the main safety's IDb block or null if no block is set.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 873
TIA Portal Openness API
5.23 F-related Openness

Warn Cycle Time

Program code
Int32 warnCycleTime = runtimeGroup.WarnCycleTime;
runtimeGroup.WarnCycleTime = 110000;

Application
Returns and sets the warn cycle time of the runtime group. If the set value is not within the valid
range, an exception is thrown.

Maximum Cycle Time

Program code
Int32 maximumCycleTime = runtimeGroup.MaximumCycleTime;
runtimeGroup.MaximumCycleTime= 120000;

Application
Returns and sets the maximum cycle time of the runtime group. If the set value is not within the
valid range, an exception is thrown.

F-runtime group information DB

Program code
string infoDbName = runtimeGroup.InfoDbName;

Application
Returns the information DB name of the runtime group.

Pre Processing

Program code
string preProcessingName = runtimeGroup.PreProcessingName;

Application
Returns the name of the pre processing FC or null if no FC is set.

Openness: API for automation of engineering workflows


874 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

PostProcessing

Program code
string postProcessingName = runtimeGroup.PostProcessingName;

Application
Returns the name of the post processing FC or null if no FC is set.

5.23.5.9 Safety settings

Safety settings

Program code
SafetySettings settings = safetyAdministration.Settings;

Application
The property SafetySettings returns a container for the following properties that can be
accessed from the returned instance.

Assignment of block numbers generated by the safety system

Program code
AssignmentOfBlockNumbers blockNumbers =
settings.AssignmentOfBlockNumbers;
ushort fromFBNumber = blockNumbers.FromFB;
ushort toFBNumber = blockNumbers.ToFB;
ushort fromFCNumber = blockNumbers.FromFC;
ushort toFCNumber = blockNumbers.ToFC;
ushort fromDBNumber = blockNumbers.FromDB;
ushort toDBNumber = blockNumbers.ToDB;

BlockNumbersManagementMode mode = blockNumbers.ManagementMode;


if (mode != BlockNumbersManagementMode.FSystemManaged) {
// Set block numbers...
}

Application
Gets or sets the block numbers generated by the safety system. If a number is set and the value
is not within the valid range, an exception is thrown. If a number is set and the management
mode is FSystemManaged, an exception is thrown.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 875
TIA Portal Openness API
5.23 F-related Openness

Safety System Version

Program code
SafetySystemVersion version = settings.SafetySystemVersion;
IList<SafetySystemVersion> versions =
settings.GetApplicableSafetySystemVersions();

settings.SafetySystemVersion = versions.Last();

SafetySystemVersion version1_6 = versions.SingleOrDefault(v =>


v.Value == "V1.6");
if (version1_6 != null) {
settings.SafetySystemVersion = version1_6;
}

Application
Gets or sets the Safety system version of the F-CPU.
With GetApplicableSafetySystemVersions() a list of the applicable Safety system
versions for the corresponding F-CPU can be fetched. The received list is sorted by recency.
With .Last() the latest version is received.
A specific version can also be fetched by selecting an item from the applicable Safety system
version list.

Safety mode can be disabled

Program code
bool safetyModeCanBeDisabled = settings.SafetyModeCanBeDisabled;
settings.SafetyModeCanBeDisabled = true;

Application
Gets or sets whether the Safety mode can be disabled.

Activation of F-change history

Program code
bool activationOfFChangeHistory =
settings.ActivationOfFChangeHistory;
settings.ActivationOfFChangeHistory = true;

Application
Gets or sets the activation of the F-change history.

Openness: API for automation of engineering workflows


876 System Manual, 05/2021, Online documentation
TIA Portal Openness API
5.23 F-related Openness

Enable of consistent upload

Program code
bool consistentUpload = (bool)
settings.GetAttribute("EnableConsistentUploadFromFCpu");
settings.SetAttribute("EnableConsistentUploadFromFCpu", true);

Application
Gets or sets whether the consistent upload from a F-CPU is enabled. This setting is only available
for read and write on specific F-CPUs.

Enable F-Communication ID tag

Program code
bool fCommunicationIdTag = (bool)
settings.GetAttribute("EnableFCommunicationIdTag");
settings.SetAttribute("EnableFCommunicationIdTag", true);

Application
Gets or sets whether the F-Communication ID tag is enabled.
For safety assessment of this information refer to the manual "SIMATIC Safety – Configuring and
Programming".

Create driver instance data blocks without prefix

Program code
bool prefix = settings.CreateDriverInstanceDataBlocksWithoutPrefix;
settings.CreateDriverInstanceDataBlocksWithoutPrefix = true;

Application
Gets or sets whether the names of the F-I/O DBs are created without prefix.

Clean up of system generated objects

Program code
settings.CleanSystemGeneratedObjects();

Application
Cleans up the system generated objects by the compile.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 877
TIA Portal Openness API
5.23 F-related Openness

5.23.6 SafetyPrintout
This feature is available for S7-1200/1500 F-CPUs.

Program code
Obtain the SafetyPrintout service from a DeviceItem instance at hand. Then call
the Print() function on this service. This function returns true on success.
SafetyPrintout printoutService =
deviceItem.GetService<SafetyPrintout>();
if (printoutService != null) {
FileInfo path = new FileInfo(@"C:\safety_printout.pdf");
bool success =
printoutService.Print(SafetyPrintoutFilePrinter.MicrosoftPrintToPdf,
path, "DocuInfo_ISO_A4_Portrait", SafetyPrintoutOption.All)
}

Application
The action Print(...) of the service SafetyPrintout is used to trigger the safety printout
with the given parameters. The given function returns true on a successful printout.
The given path needs to be valid in order to save the printout.
For the printout a given documentLayout (e.g. "DocuInfo_ISO_A4_Portrait") can be set.
Furthermore, a All or Compact safety printout is selectable with the documentationOption
parameter.
Furthermore, the selected digital printer (SafetyPrintoutFilePrinter enum) in the
system is used to create the digital safety printout. The "Microsoft Print to PDF" or "Microsoft XPS
Document Writer" printer can be selected. These printers are available and are activated by
default on Windows 10 ("Microsoft XPS Document Writer" since Windows 7). For the printout to
succeed, the selected printer needs to be activated. If this is not the case, these printers can be
enabled in the Windows feature window by executing the following file after pressing the
Windows + R keys.
optionalfeatures.exe

Openness: API for automation of engineering workflows


878 System Manual, 05/2021, Online documentation
Export/import 6
6.1 Overview

6.1.1 Basic principles of importing/exporting

Introduction
You can export certain configuration data and then re-import the data to the same or a different
project after editing.

Note
There are no obligations or guarantees of any kind associated with using this description to
manually modify and evaluate the source file. Siemens therefore accepts no liability arising from
the use of all or part of this description.

Exportable and importable objects


The following configuration data can also be imported or exported by means of TIA Portal
Openness APIs:

Table 6-1 Projects

Objects Export Import


Project graphics X X

Table 6-2 PLC

Objects Export Import


Blocks X X
Know-how protected blocks X –
Failsafe blocks X X
System blocks X –
PLC tag tables X X
Technology objects X X
PLC tags and constants X X
User data types X X
DBs X -

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 879
Export/import
6.1 Overview

Table 6-3 HMI

Objects Export Import


Screens X X
Screen templates X X
Global screens X X
Pop-up sreens X X
Slide-in screens X X
Scripts X X
Text lists X X
Graphic lists X X
Cycles X X
Connections X X
Tag table X X
Tags X X

Complete export or export of open references


The object types listed above are exported or imported along with all objects if these belong to
the same sub-tree. This rule is also valid for referenced objects of the same sub-tree.
For referenced objects in other sub-trees, however, a complete export or import is not possible.
Instead, "open references" to these objects are exported or imported.
Referenced objects of the same sub-tree are only exported if they belong to the group of
exportable objects. Any dynamizations on objects are treated as objects during the import/
export, and are exported and imported as well.
The export includes all object attributes that were changed during configuration. This applies
regardless of whether the altered attribute will be used or not.
Example: You have configured a graphic IO field with the mode "Input/Output" and selected the
setting "Visible after clicking" for the attribute "Scroll bar type". In the course of configuration,
you have changed the mode to "Two states". The attribute "Scroll bar type" is not available in this
mode. Because the "Scroll bar type" attribute was changed, it is included in the export, even
though the attribute is not used.

Importing open references


You can also import objects with open references (see Importing configuration data
(Page 885)).
If the referenced objects are contained in the target project, the open references are
automatically linked to the object types again. These objects must be available at the same
location and be assigned to the same name as for the export. If the referenced objects are not
contained in the target project the open references can't be resolved. No additional object will
be created to resolve these open references.

Openness: API for automation of engineering workflows


880 System Manual, 05/2021, Online documentation
Export/import
6.1 Overview

Export and import file format


The export and import file format is XML. Only CAx data require AML format. The different
schema definitions for all formats are described in the respective section of this manual:
• XML format for the data of a HMI devices (Page 893)
• XML format for the data of a PLC devices (Page 942)
• AML format for CAx data (Page 1072)

Importing and exporting fonts


Fonts defined on objects are also exported and imported.
When you import fonts that are not included in the project, the standard font is displayed at the
object after the import. However, the imported font is stored in the data management.
If the attributes for a font are not assigned in an import file, the attributes are assigned default
values after the import.

Importing and exporting technology objects


You can find out which technology objects can be exported and imported as of TIA Portal version
V16 you can find in chapter "Overview of technology objects and versions".

Restrictions
The export format is internal and valid exclusively for the current version of TIA Portal Openness.
The export format may change in future versions.
All errors which occur during the import and export are reported as exceptions.
For more information on exceptions, see section Handling exceptions (Page 862).

See also
Field of application for Import/Export (Page 881)
Exporting configuration data (Page 884)

6.1.2 Field of application for Import/Export

Introduction
The Import/Export functionality allows you to export specific objects in a targeted manner.
You can edit the exported data in an external program, or reuse it unchanged in other TIA Portal
projects.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 881
Export/import
6.1 Overview

If you structure the import file correctly, you can also import configuration data created
externally without having to carry out an export first.

Note
If you import externally created configuration data which contain code errors or a wrong
structure this could cause unexpected errors.

Field of application
Exporting and importing data is useful for the following tasks:
• For externally editing configuration data.
• For importing externally-created configuration data, e.g. text lists and tags.
• For distributing specified configuration data to different projects, e.g. a modified process
screen which is to be used in several projects.
• For replicating and adjusting the hardware configuration between the TIA Portal project and
an ECAD program.

See also
Basic principles of importing/exporting (Page 879)

6.1.3 Version Specific Simatic ML Import

Application
As of TIA Portal Openness V14 SP1 the SimaticML import is useable cross-version. You will be
able to import your older export files at least into the next two major versions.
Each version of the Openness API is able to import Simatic ML files from corresponding version
and any supported version from previous release, for example import of Simatic ML file V15,
V15.1 and V16 will be supported in Openness API V17.
The following table shows an example of which Simatic ML version can be imported by a given
Openness API version.

Openness Simatic ML file V15 Simatic ML file Simatic ML V16 Simatic ML V17
API version V15.1
V15 Import supported Import unsuppor‐ Import unsup‐ Import unsupported
ted ported
V15.1 Import supported Import supported Import unsup‐ Import unsupported
ported
V16 Import supported Import supported Import suppor‐ Import unsupported
ted
V17 Import supported Import supported Import suppor‐ Import supported
ted

Openness: API for automation of engineering workflows


882 System Manual, 05/2021, Online documentation
Export/import
6.1 Overview

Note
V14SP1 Siemens.Engineering.dll will not be available as part of TIA Portal Openness V17.

Each version of the Openness API supports export of Simatic ML files. However, the version of the
exported Simatic ML file should match with the version of the TIA Portal rather than that of the
Openness API used.
To support this feature, SimaticML files contains the model version information as shown below:

<?xml version="1.0" encoding="utf-8"?>


<Document>
<Engineering version="V15"/>
<DocumentInfo>
...
</DocumentInfo>
<SW.DataBlock ID="0">
...
</SW.DataBlock>
</Document>

Note
If the version information is not provided in the SimaticML file, the system will use the current
model version.

6.1.4 Editing the XML file

Introduction
Use an XML editor or text editor for editing an XML file for importing configuration data.
If you are making comprehensive changes or are creating custom object structures, we
recommend that you use an XML editor with auto-complete function.

Note
Changing the XML content requires comprehensive knowledge of the structure and validation
rules in XML. Work manually in the XML structure only in exceptional cases in order to avoid
validation errors.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 883
Export/import
6.1 Overview

6.1.5 Exporting configuration data

Introduction
The configuration data of each start object (root) is exported separately to an XML file.
Editing the export file requires an adequate knowledge of XML. Use an XML editor for more
convenient editing.

Example
You have a process screen that contains an IO field. An external tag is configured in the IO field.
An export of the process screen includes the screen and the IO field. The tag and the connection
used by the tag are not exported. Instead, only an open reference is included in the export.

Contents of the export file


Beginning with the start object, all objects of a sub-tree and their attributes are saved to the
export file. All references to objects of different sub-trees are only exported as open references.
The corresponding attributes of the referenced objects in different sub-trees are not written to
the export file.

Note
Export of object types from the library is not supported
You can create objects as a type in the library. Instances of the object type used in the project can
be edited like other objects using the TIA Portal Openness application. When you export objects,
the instances are exported without the type information.
When you re-import these objects into the project, the instances of the object types are
overwritten and the instance is detached from the object type.

The export file does not necessarily contain all the attributes of an object. You define what data
is to be exported:
• ExportOptions.None
This setting exports only the modified data or the data that differs from the default.
The export file also contains all values that are obligatory for the subsequent data import.
• ExportOptions.WithDefaults1
The default values are also exported.
• ExportOptions.WithReadOnly1
The write-protected values are also exported.
1
: You can combine these two options with the following syntax:
Export(path,ExportOptions.WithDefaults |
ExportOptions.WithReadOnly);
The entire contents of the export file are in English. Regardless of this, any project texts
contained are exported and imported in all the languages present.
All configuration data is modeled as XML objects in the export file.

Openness: API for automation of engineering workflows


884 System Manual, 05/2021, Online documentation
Export/import
6.1 Overview

See also
Basic principles of importing/exporting (Page 879)
Exporting blocks (Page 998)

6.1.6 Importing configuration data

Introduction
Configuration data is imported from a previously exported and edited XML file or from an XML
file you have created yourself. The data contained in this file is checked during the import. This
approach prevents the configuration data in the TIA Portal from becoming inconsistent as a
result of the import.

Restrictions
• All root objects in the import file have to be of the same kind, e.g. tag tables, blocks, ...
• If an import file includes several root objects and one of them is not valid, the entire contents
of the import file are not imported.
• When importing texts, the corresponding project languages must have been set up in the
target project in order to exclude import failure. If necessary you can modiy the language
settings via TIA Portal Openness.
• If you specify invalid attributes of an object in the import file that cannot be edited in the
graphical user interface of TIA Portal, the import is canceled.
• Only the area pointers listed in the "separately for each connection" field can be imported or
exported.
• The import of object types from the library is not supported. You can create objects as a type
in the library. Instances of the object type used in the project can be edited like other objects
using the TIA Portal Openness application. When you export objects, the instances are
exported without the type information. When you re-import these objects into the project,
the instances of the object types are overwritten and the instance is detached from the object
type.

Note
Device-dependent value ranges for graphical attributes
If values of graphical attributes exceed the valid value range, these values are reset to the
possible maximum values for the HMI device during import.

Different import behavior


If objects to be imported already exist in the project, control the import behavior using different
program codes. Otherwise, the objects will be created again in the project during the import.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 885
Export/import
6.1 Overview

The following settings for the import behavior are possible:


• ImportOptions.None
By using this setting configuration data will be imported without overwritting.
If an object being imported from an XML file which already exists in the project, the import
is interrupted and an exception will be thrown.
• ImportOptions.Override
By using this setting configuration data will be imported with automatic overwritting.
You can specify that existing objects in the project are overwritten with the import. Relevant
objects are deleted prior to the import and recreated with default values. These defaults are
overwritten with the imported values during the import. If the existing object and the new
object are not in the the same group overwriting can't take place. To avoid naming conflicts
import is canceled and an exception is thrown.

Procedure for importing


If you wish to import an XML file, the data it contains must adhere to certain rules. The contents
of the import file must be well-formed. There must be no syntax errors and no data structure
errors. In the case of comprehensive changes, use an XML editor that checks these criteria prior
to the import.
During the import of the XML file to the TIA Portal, the data it contains is first checked for formal
errors in the XML code. If errors are detected during the check, the import is canceled and the
errors are shown in an exception (see Handling exceptions (Page 862)).

See also
Basic principles of importing/exporting (Page 879)
Importing user data type (Page 1032)

Openness: API for automation of engineering workflows


886 System Manual, 05/2021, Online documentation
Export/import
6.2 Import/export of project data

6.2 Import/export of project data

6.2.1 Project graphics

6.2.1.1 Exporting/importing graphics

Introduction
The export of configuration data from the TIA Portal to the XML file does not include selected
graphics, or graphics referenced by an object. The graphics are saved separately during the
export. In the XML file, the graphics are referenced by a relative path and their file name. A
graphic reference is modeled in the XML file as an object and contains an attribute list and, if
necessary, a link list, just like the other objects.

Exporting graphics
The export of configuration data includes only graphics that were selected directly for export.
The exportable graphics are stored in the TIA Portal for the specific language. If a project is
configured in multiple languages, all the language versions used are exported.
When you export graphics, a new folder is created in the export file folder. The file folder name
is built by concatenating the xml-filename with " files". This folder contains the exported

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 887
Export/import
6.2 Import/export of project data

graphics. If this folder exists already, a new folder is created and supplemented by a consecutive
number.
The graphics are saved in the same file format as in the project. The data format is not changed
or converted, and the resolution and color depth remain unchanged.
The ID "default" is used as the file extension for the language selected as the default language.
If the folder already contains a file of the same name, the file name of the exported graphic is
supplemented by a consecutive number.

Importing graphics
The following requirements apply when importing graphics:
• The graphics must have a file format that is supported by TIA Portal.
• The graphics must be referenced in the XML file by a relative path specification.
Once you have exported a graphic, you can edit it outside TIA Portal using a graphics program
and then re-import it.

See also
Basic principles of importing/exporting (Page 879)

6.2.1.2 Exporting all graphics of a project

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can export either a single graphic or all graphics of the graphics collection of a project in all
languages. An XML file with all project graphic entries concerned is created during the export
and referenced along with the exported graphics. The relevant graphics are saved along with the
XML file to the same directory of the file system.
To allow the exported graphics ("*.jpg", "*.bmp", "*.png", "*.ico", etc.) to be changed, these
graphics are not write-protected.

Openness: API for automation of engineering workflows


888 System Manual, 05/2021, Online documentation
Export/import
6.2 Import/export of project data

Program code: Exporting a graphic


Modify the following program code to export the required graphic:

//Exports all language variants of a single grafic


Project project = …;
MultiLingualGraphicComposition graphicsComposition = project.Graphics;
MultiLingualGraphic graphic = graphicsComposition.Find("graphicName");
graphic.Export(new FileInfo(@"D:\ExportFolder\graphicName.xml"),
ExportOptions.WithDefaults);

Program code: Exporting all graphics


Modify the following program code to export all graphics of a graphics collection:

//Exports all graphics of a graphic library


Project project = …;
MultiLingualGraphicComposition graphicsComposition = project.Graphics;
foreach(MultiLingualGraphic graphic in graphicsComposition)
{
graphic.Export(new FileInfo(string.Format(@"D:\Graphics\{0}.xml", graphic.Name)),
ExportOptions.WithDefaults);
}

6.2.1.3 Importing graphics to a project

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
An XML file is saved along with the language versions of a graphic to a directory of your file
system.
You can reference all graphics in a relative path in the XML file.
You can now import all language versions of a graphic contained in the XML file to the graphics
collection.
You should also observe the Importing configuration data (Page 885).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 889
Export/import
6.2 Import/export of project data

Program code
Modify the following program code to import one or several graphics:

//Import all language variants of a single graphic


Project project = …;
MultiLingualGraphicComposition graphicComposition = project.Graphics;
graphicComposition.Import(new FileInfo(@"D:\Graphics\Graphic1.xml"),
ImportOptions.Override);

6.2.2 Project texts

6.2.2.1 Export of project texts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
In TIA Portal you can find project texts below the "Languages & resources" node of a project.
These texts are exported to a "*.xlsx" file which is used for example for translations. The
limitations of exporting and importing project texts are the same as in the UI. These limitations
include:
• Exported texts can only be imported into the project from where they were exported.
• You can only translate texts to languages that are available in in the project. If necessary you
can add project languages via TIA Portal Openness.
• Only existing texts can be re-imported, if text from the original project has been deleted or
re-created the import for that text will fail.
You have to define the following parameters:

Name Example Description


pah new FileInfo ("D:\Test\Project‐ Path to export file
Text.xlsx")
sourceLanguage new CultureInfo("en-US") Reference language text is to be translated from
targetLanguage new CultureInfo("de-DE") Target language text is to be translated to

Openness: API for automation of engineering workflows


890 System Manual, 05/2021, Online documentation
Export/import
6.2 Import/export of project data

Note
Multilingual texts will be exported together with the parent object to which they belong.
Multilingual texts can not be exported explicitly.

Program code: Export from "Languages & resources" node


The use of the example parameters leads to the following program code to export project texts:

project.ExportProjectTexts(new FileInfo(@"D:\Test\ProjectText.xlsx"), new CultureInfo("en-


US"), new CultureInfo("de-DE"));

XML structure of a exported multilingual text item

6.2.2.2 Import of project texts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 891
Export/import
6.2 Import/export of project data

Application
In TIA Portal you can find project texts below the "Languages & resources" node of a project. You
can import project texts from a ".xlsx" file which is used for example for translations. The
limitations of exporting and importing project texts are the same as in the UI. These limitations
include:
• Exported texts can only be imported into the project from where they were exported.
• You can only import translated texts in languages that are available in project from where
they were exported.
• Only existing texts can be re-imported, if text from the original project has been deleted or
re-created the import for that text will fail.
You have to define the following parameters:

Name Example Description


path new FileInfo(@"D:\Test\Project‐ Path to import file
Text.xlsx")
updateSourceLan‐ true If true, the text of the reference language is updated from the
guage export file.
If false, the text of the reference language is not updated

Note
Multilingual texts will be imported together with the parent object to which they belong.
Multilingual texts can not be imported explicitly.

Program code
The use of the example parameters leads to the following program code to import project texts:

ProjectTextResult result = project.ImportProjectTexts(new FileInfo(@"D:\Test


\ProjectText.xlsx"), true);

The import of the Project Texts returns an object indicating the status of the Import and path to
which the import log is saved. These attributes can be accessed with the following code:

ProjectTextResultState resultState = result.State;


FileInfo logFilePath = result.Path;

Openness: API for automation of engineering workflows


892 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

6.3 Importing/exporting data of an HMI device

6.3.1 Data structure for import/export

6.3.1.1 Structure of an XML file

Introduction
The data in the export file from the import/export is structured with reference to a basic
structure.

Basic structure of an export file


The export file is generated in a XML format.
The XML file starts with a document information. It includes the data of the computer-specific
installation with which the project was exported.
The export file is divided into the following two sections:
• Information about the document
In this section, you can enter your own information about the export in valid XML syntax. The
content is ignored by the import.
For example you can insert a <IntegrityInformation>...</
IntegrityInformation> block, in which you place additional information about the
validation. After the XML file is forwarded, the recipient can use this block before the import
to check whether the XML file has been changed.
• Object
This section contains the elements to be exported.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 893
Export/import
6.3 Importing/exporting data of an HMI device

,QIRUPDWLRQ
DERXWWKH
GRFXPHQW

6FUHHQREMHFW

Openness: API for automation of engineering workflows


894 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Screen objects of an export file


The exported elements are available in additional elements of the XML file.

+PL6FUHHQ6FUHHQ,' ಯಯ!
$WWULEXWH/LVW!
 $FWLYH/D\HU!$FWLYH/D\HU!
$WWULEXWHVRIWKH
 %DFN&RORU!%DFN&RORU!
VFUHHQREMHFW
 1DPH!6FUHHQB1DPH!
$WWULEXWH/LVW!
/LQN/LVW!
/LQNVIURPWKH  7HPSODWH7DUJHW,' ಯ#2SHQ/LQNಯ!
6FUHHQREMHFW
VFUHHQREMHFWWR   1DPH!7HPSODWHB1DPH!
RWKHUREMHFWV  7HPSODWH!
/LQN/LVW!
2EMHFW/LVW!
ORZHUOHYHO 
REMHFWV 2EMHFW/LVW!

+PL6FUHHQ6FUHHQ!

See also
Basic principles of importing/exporting (Page 879)

6.3.1.2 Structure of the data for importing/exporting

Objects
The basic structure is the same for all objects.
Every object in the XML file starts with its type, for example, "Hmi.Screen.Button", and an ID. The
ID is created automatically during export.

Each object apart from the start object also contains an "CompositionName" XML attribute. The
value for this attribute is preset. It is occasionally necessary to specify this attribute, for example,
to change the label when a button is pressed or released.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 895
Export/import
6.3 Importing/exporting data of an HMI device

Attributes
Every object contains attributes that are contained in an "AttributeList" section. Every attribute
is modeled as an XML element, e.g. "BackColor". The value of an attribute is modeled as XML
content, e.g. "204, 204, 204".

For referencing objects, each object contains a "LinkList" section, if necessary. This section
contains links to other objects inside or outside the XML file. Every link is modeled as an XML
element. The designation of a link is defined by the target object in the schema file. Every link
also contains the "TargetID" attribute. When the target object is included in the XML file, the
value of the "TargetID" attribute is the ID of the referenced object preceded by a "#". When the
target object is not included in the XML file, the value of the "TargetID" attribute is "@OpenLink".
The actual reference to the object is modeled as subordinate XML element.

Openness: API for automation of engineering workflows


896 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Relation between objects and XML structure


The figures below show the relation between the exported XML structure and the associated
objects in WinCC.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 897
Export/import
6.3 Importing/exporting data of an HMI device

Figure 6-1 Relation between the WinCC user interface and the XML structure.

Figure 6-2 Relation between the settings in WinCC and the XML structure.

6.3.1.3 Cycles

Exporting cycles

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The TIA Portal Openness API interface supports the export of all cycles of a known HMI device to
an XML file. The generation of the corresponding export file indicates that the export is
complete.

Openness: API for automation of engineering workflows


898 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code
Modify the following program code to export cycles from an HMI device to an XML file:

//Exports cycles from an HMI device


private static void ExportCyclesFromHMITarget(HmiTarget hmitarget)
{
CycleComposition cycles = hmitarget.Cycles;
foreach(Cycle cycle in cycles)
{
cycle.Export(new FileInfo(string.Format(@"C:\Samples\{0}.xml", cycle.Name)),
ExportOptions.WithDefaults);
}
}

Importing cycles

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
When you use ImportOptions.None, you can identify the cycles that have actually been
imported based on the composition number (Composition count). You have access to these
imported cycles.

Note
Standard cycles have attributes that cannot be edited in the user interface. If you specify in the
import file that these attributes should be changed, the import causes a
NonRecoverableException and closes the TIA Portal.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 899
Export/import
6.3 Importing/exporting data of an HMI device

Program code
Modify the following program code to import one or several cycles from an XML file into an HMI
device:

//Imports cycles to an HMI device


private static void ImportCyclesToHMITarget(HmiTarget hmitarget)
{
CycleComposition cycles = hmitarget.Cycles;
string dirPathImport = @"C:\OpennessSamples\Import\";
string cycleImportFileName = "CycleImport.xml";
string fullFilePath = Path.Combine(dirPathImport, cycleImportFileName);

cycles.Import(new FileInfo(fullFilePath), ImportOptions.None);


}

See also
Importing configuration data (Page 885)

6.3.2 Tag tables

6.3.2.1 Exporting HMI tag tables

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
One XML file is exported per HMI tag table. The API supports this export process. The export of
tag tables is also available in subfolders.

Openness: API for automation of engineering workflows


900 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting all HMI tag tables from a specified folder
Modify the following program code to export all HMI tag tables from a specific folder:

//Exports all tag tables from a tag folder


private static void ExportAllTagTablesFromTagFolder(HmiTarget hmitarget)
{
TagSystemFolder folder = hmitarget.TagFolder;
TagTableComposition tables = folder.TagTables;

foreach (TagTable table in tables)


{
FileInfo info = new FileInfo(string.Format(@"C:\OpennessSamples\TagTables\{0}.xml",
table.Name));
table.Export(info, ExportOptions.WithDefaults);
}
}

Program code: Exporting an HMI tag table


Modify the following program code to export an individual HMI tag table:

//Exports a tag table from an HMI device


private static void ExportTagTableFromHMITarget(HmiTarget hmitarget)
{
string tableName = "Tag table XYZ";
TagSystemFolder folder = hmitarget.TagFolder;
TagTableComposition tables = folder.TagTables;
TagTable table = tables.Find(tableName);

if (table != null)
{
FileInfo info = new FileInfo(string.Format(@"C:\OpennessSamples\TagTables\{0}.xml",
table.Name));
table.Export(info, ExportOptions.WithDefaults);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 901
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting all HMI tag tables


Modify the following program code to export all HMI tag tables:

//Exports all tag tables from an HMI device


private static void ExportAllTagTablesFromHMITarget(HmiTarget hmitarget)
{
TagSystemFolder sysFolder = hmitarget.TagFolder;

//First export the tables in underlying user folder


foreach (TagUserFolder userFolder in sysFolder.Folders)
{
ExportUserFolderDeep(userFolder);
}

//then, export all tables in the system folder


ExportTablesInSystemFolder(sysFolder);
}

private static void ExportUserFolderDeep(TagUserFolder rootUserFolder)


{
foreach (TagUserFolder userFolder in rootUserFolder.Folders)
{
ExportUserFolderDeep(userFolder);
}
ExportTablesInUserFolder(rootUserFolder);
}

private static void ExportTablesInUserFolder(TagUserFolder folderToExport)


{
TagTableComposition tables = folderToExport.TagTables;
foreach (TagTable table in tables)
{
string fullFilePath = string.Format(@"C:\OpennessSamples\TagTables\{0}.xml",
table.Name);
table.Export(new FileInfo(fullFilePath), ExportOptions.WithDefaults);
}
}

private static void ExportTablesInSystemFolder(TagSystemFolder folderToExport)


{
TagTableComposition tables = folderToExport.TagTables;
foreach (TagTable table in tables)
{
string fullFilePath = string.Format(@"C:\OpennessSamples\TagTables\{0}.xml",
table.Name);
table.Export(new FileInfo(fullFilePath), ExportOptions.WithDefaults);
}
}

Openness: API for automation of engineering workflows


902 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

6.3.2.2 Importing HMI tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Program code
Modify the following program code to import the HMI tag table of an XML file to a user-defined
folder or to a system folder:

//Imports a single HMI tag table from a XML file


private static void ImportSingleHMITagTable(HmiTarget hmitarget)
{
TagSystemFolder folder = hmitarget.TagFolder;
TagTableComposition tables = folder.TagTables;

FileInfo info = new FileInfo(@"D:\Samples\Import\myExportedTagTable.xml");


tables.Import(info, ImportOptions.Override);
}

Incorrect import of tags


If you use the following symbols in the names of tags or referenced tags, the import of the tags
will be faulty:
• . (period)
• \ (backslash)
Remedy 1:
Before an export, check that the name of the tag or referenced tag to be exported does not
contain a period or backslash.
Remedy 2:
In the import file, exclude the names of tags or referenced tags using quotation marks.
Example
• Tag name with symbol:
<name>Siemens.Simatic.Hmi.Utah.Tag.HmiTag:41000_Options_Time_Date
\DB_SFX0908_HMI1.Actual_Date_Time.Hour</name>
• Tag name with symbol excluded in quotation marks:
<name>"Siemens.Simatic.Hmi.Utah.Tag.HmiTag:41000_Options_Time_Date
\DB_SFX0908_HMI1.Actual_Date_Time.Hour"</name>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 903
Export/import
6.3 Importing/exporting data of an HMI device

6.3.2.3 Exporting an individual tag from an HMI tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following object model object types may possibly exist as sublevel items of an HMI tag and
are taken into account during export:

MultilingualText For Comment, TagValue, DisplayName


TagArrayMemberTag For HMI array elements
TagStructureMember For HMI structure elements
Event For configured events
MultiplexEntry For configured tag multiplexing entries

Program code
Modify the following program code to export an individual tag from an HMI tag table to an XML
file:

//Exports a selected tag from a tag table


private static void ExportSelectedTagFromTagTable(HmiTarget hmitarget)
{
TagSystemFolder tagFolder = hmitarget.TagFolder;
TagTable mytable = tagFolder.TagTables.Find("MyTagTable");

TagComposition containingTags = mytable.Tags;


Tag myTag = containingTags.Find("MyTag");

if (myTag != null)
{
FileInfo info = new FileInfo(string.Format(@"C:\OpennessSamples\Tags\{0}.xml",
myTag.Name));
myTag.Export(info, ExportOptions.WithDefaults);
}
}

Openness: API for automation of engineering workflows


904 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

6.3.2.4 Importing an individual tag into an HMI tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following object model object types may possibly exist as sublevel items of an HMI tag and
are taken into account during import:

MultilingualText For Comment, TagValue, DisplayName


TagArrayMemberTag For HMI array elements
TagStructureMember For HMI structure elements
Event For configured events
MultiplexEntry For configured tag multiplexing entries

Program code
Modify the following program code to import an HMI tag from an XML file into an HMI tag table:

//Imports a tag into a tag table


private static void ImportTagIntoTagTable(HmiTarget hmitarget)
{
TagSystemFolder tagFolder = hmitarget.TagFolder;
TagTable myTable = tagFolder.DefaultTagTable;
TagComposition tagComposition = myTable.Tags;

FileInfo info = new FileInfo(@"D:\Samples\Import\myExportedTag.xml");


tagComposition.Import(info, ImportOptions.Override);
}

6.3.2.5 Special considerations for the export/import of HMI tags

Introduction
Special considerations apply to the export and import of the following HMI tags:
• External HMI tags with integrated connection
• HMI tags with the "UDT" data type

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 905
Export/import
6.3 Importing/exporting data of an HMI device

Similar program codes


The program code for the above-mentioned HMI tags is almost identical to the following
program codes:
• Program code: Exporting HMI tags (Page 904)
• Program code: Importing HMI tags (Page 905)

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Special considerations for the export/import of an external HMI tag with integrated connection
When exporting an external HMI tag with integrated HMI connection, only the link of the HMI
tag to the PLC tag is saved in the export file instead of the PLC tag data.
Before the import, you must ensure that the PLC, the corresponding PLC tags and the integrated
connection to the corresponding PLC exist in the project. If this is not the case, these items must
be created before the import. During the subsequent import of the external HMI tag, the link to
the PLC tag will be activated again.
Names of external HMI tags must be unique across all tag tables of a project. If you do not specify
the suitable tag table for the HMI tag during import, the import is canceled.
Use the following XML structure to import an external HMI tag with integrated connection:

<Hmi.Tag.Tag ID="1" CompositionName="Tags">


<AttributeList>
<Name>MyIntegratedHmiTag_1</Name>
</AttributeList>
<LinkList>
<AcquisitionCycle TargetID="@OpenLink">
<Name>1 s</Name>
</AcquisitionCycle>
<Connection TargetID="@OpenLink">
<Name>HMI_Connection_MP277_300400</Name> <- Must exist in the project
</Connection>
<ControllerTag TargetID="@OpenLink">
<Name>Datablock_1.DBElement1</Name> <- Must exist in the project
</ControllerTag>
</LinkList>
</Hmi.Tag.Tag>

Special considerations for the export/import of an HMI tag of the "UDT" data type
The link is exported to the data type when an HMI tag of the "UDT" data type is exported. Only
versioned data types are supported for import.

Openness: API for automation of engineering workflows


906 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

The data types must be saved in the project library. Data types in the global library are not
supported.
The following rules apply to the import:
• The referenced data type must be contained in the project library.
The import is terminated if the data type is not contained in the project library.
• The referenced data type must be versioned. Versioning is supported as of TIA Portal V13 SP1.
An exception is thrown if the data type is not versioned.
Note
The first data type found is used during the import to resolve the reference.
The following applies here: First, the root directory of the project library is searched, then the
subfolders.

Use the following XML structure to import an HMI tag of the "UDT" data type:

<Hmi.Tag.Tag ID="1" CompositionName="Tags">


...
<LinkList>
<DataType TargetID="@OpenLink">
<Name>HmiUdt_1 V 1.0.0</Name> <- Must exist in the project library
</DataType>
...
</LinkList>
...
</Hmi.Tag.Tag>

6.3.3 VB scripts

6.3.3.1 Exporting VB scripts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
All sublevel user-defined folders are taken into account for the export. A separate XML file is
created for each exported VB script.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 907
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting a VB script


Modify the following program code to export a selected VB script of an HMI device to an XML file:

//Exports a single vbscript of an HMI device


private static void ExportSingleVBScriptOfHMITarget(HmiTarget hmitarget)
{
VBScriptSystemFolder vbScriptFolder = hmitarget.VBScriptFolder;
VBScriptComposition vbScripts = vbScriptFolder.VBScripts;
VBScript vbScript = vbScripts.Find("MyVBScript");

FileInfo info = new FileInfo(string.Format(@"C:\OpennessSamples\Export\Scripts


\{0}.xml", vbScript.Name));
vbScript.Export(info, ExportOptions.None);
}

6.3.3.2 Exporting VB scripts from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A separate XML file is created for each exported VB script.

Program code: Exporting a VB script from a user-defined folder


Modify the following program code to export a VB script from a user-defined folder to an XML file:

//Exports vbscripts of a selected vbscript system folder


private static void ExportVBScriptOfSelectedVBScriptSystemFolder(HmiTarget hmitarget)
{
VBScriptSystemFolder vbScriptFolder = hmitarget.VBScriptFolder;
VBScriptUserFolderComposition vbUserFolders = vbScriptFolder.Folders;
VBScriptUserFolder vbUserFolder = vbUserFolders.Find("MyVBUserFolder");
VBScriptComposition vbScripts = vbUserFolder.VBScripts;

foreach (VBScript script in vbScripts)


{
FileInfo info = new FileInfo(String.Format(@"C:\OpennessSamples\Export\Scripts
\{0}.xml", script.Name));
script.Export(info, ExportOptions.None);
}
}

Openness: API for automation of engineering workflows


908 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting all VB scripts from a system folder


Modify the following program code to export all VB scripts from the system folder:

//Exports all vbscripts by using a foreach loop


private static void ExportAllVBScripts(HmiTarget hmitarget)
{
VBScriptSystemFolder vbScriptFolder = hmitarget.VBScriptFolder;
VBScriptComposition vbScripts = vbScriptFolder.VBScripts;
if (vbScripts == null) return;

foreach (VBScript script in vbScripts)


{
FileInfo info = new FileInfo(string.Format(@"C:\OpennessSamples\Export\Scripts
\{0}.xml", script.Name));
script.Export(info, ExportOptions.None);
}
}

6.3.3.3 Importing VB scripts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
Bulk imports are supported. As an alternative, you can use a program code with a Foreach loop
(Exporting VB scripts (Page 907)).

Program code
Modify the following program code to import a VB script from an XML file into an HMI device:

private static void ImportSingleVBScriptToHMITarget(HmiTarget hmitarget)


{
VBScriptSystemFolder vbScriptFolder = hmitarget.VBScriptFolder;
VBScriptComposition vbScripts = vbScriptFolder.VBScripts;
if (vbScripts 00 null) return;
{
FileInfo info = new FileInfo(@"D:\Samples\Import\VBScript.xml");
vbScripts.Import(info, ImportOptions.None);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 909
Export/import
6.3 Importing/exporting data of an HMI device

6.3.4 Text lists

6.3.4.1 Exporting text lists from an HMI device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The export of text and graphic lists includes all their entries. Text and graphic lists can be
exported separately.
The text lists of an HMI device are exported. A separate XML file is created for each exported text
list.

Program code
Modify the following program code to export text lists from an HMI device:

//Export TextLists
private static void ExportTextLists(HmiTarget hmitarget)
{
TextListComposition text = hmitarget.TextLists;
foreach (TextList textList in text)
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Export\{0}.xml",
textList.Name);
textList.Export(info, ExportOptions.WithDefaults);
}
}

6.3.4.2 Importing a text list into an HMI device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


910 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Application
The API interface supports the import of a text list from an XML file into an HMI device.

Program code
Modify the following program code to import a text list from an XML file into an HMI device:

//Imports a single TextList


private static void ImportSingleTextList(HmiTarget hmitarget)
{
TextListComposition textListComposition = hmitarget.TextLists;
IList<TextList> importedTextLists = textListComposition.Import(new
FileInfo(@"D:\SamplesImport\myTextList.xml"), ImportOptions.Override);
}

6.3.4.3 Advanced XML formats for export/import of text lists

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• Standard export of text lists
See Exporting text lists from an HMI device (Page 910)
• Standard import of text lists
See Importing text lists into an HMI device (Page 910)

Application
A text list may also contain formatted texts. This primarily concerns the following formatting:
• Text formatting
• References to other objects within the text
Pure text formatting within a text list to be exported results in an advanced XML export format.
Object references are characterized as Open Links. The same applies to text lists to be imported
with formatted texts.
Advanced XML export formats may also become considerably more complex. For example, more
than just the object name may be linked in the text list, perhaps by means of an Open Link to a
PLC tag of a different device. In this case, all information must be coded in a string in order to
remove the Open Link.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 911
Export/import
6.3 Importing/exporting data of an HMI device

Openness: API for automation of engineering workflows


912 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

6.3.5 Graphic lists

6.3.5.1 Exporting graphic lists

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The export of text and graphic lists includes all their entries. Text and graphic lists can be
exported separately.
One XML file is created per graphic list. Global graphic objects contained in the graphic lists are
exported as Open Links.

Program code
Modify the following program code to export graphic lists of an HMI device:

//Exports GraphicLists
private static void ExportGraphicLists(HmiTarget hmitarget)
{
GraphicListComposition graphic = hmitarget.GraphicLists;
foreach (GraphicList graphicList in graphic)
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Export\{0}.xml",
graphicList.Name));
graphicList.Export(info, ExportOptions.WithDefaults);
}
}

6.3.5.2 Importing a graphic list

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 913
Export/import
6.3 Importing/exporting data of an HMI device

Application
The API interface supports the import of a graphic list from an XML file into an HMI device.
All referenced graphic objects of the graphic list are included in the import. References to global
graphics are not included. If the referenced global graphics exist in the target project, the
references to the global graphics are restored during the import.

Program code
Modify the following program code to import a graphic list from an XML file into an HMI device:

//Imports a single GraphicList


private static void ImportSingleGraphicList(HmiTarget hmitarget)
{
GraphicListComposition graphicListComposition = hmitarget.GraphicLists;
IList<GraphicList> importedGraphicLists = graphicListComposition.Import(new
FileInfo(@"D:\Samples\Import\myGraphicList.xml"), ImportOptions.Override);
}

6.3.6 Connections

6.3.6.1 Exporting connections

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The API interface supports the export of all connections of an HMI device to an XML file.

Note
Export of integrated connections
Export of integrated connections is not supported.

A separate XML file is created for each exported connection.

Openness: API for automation of engineering workflows


914 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code
Modify the following program code to export all connections of an HMI device to an XML file:

//Exports communication connections from an HMI device


private static void ExportConnectionsFromHMITarget(HmiTarget hmitarget)
{
ConnectionComposition connections = hmitarget.Connections;
foreach(Connection connection in connections)
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Export\{0}.xml",
connection.Name));
connextion.Export(info, ExportOptions.WithDefaults);
}
}

6.3.6.2 Importing connections

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The API interface supports the import of all connections of an HMI device from an XML file into
an HMI device. If you want to import several communication connections, import the
corresponding XML file for each one.

Note
If you import a connection into a project in which an integrated connection has already been
configured, this connection is not overwritten. The import is canceled and an Exception is
thrown.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 915
Export/import
6.3 Importing/exporting data of an HMI device

Program code
Modify the following program code to import an individual connection of an HMI device from an
XML file into an HMI device:

//Imports Communication connections to an HMI device


private static void ImportConnectionsToHMITarget(HmiTarget hmitarget)
{
ConnectionComposition connections = hmitarget.Connections;
IList<Connection> importedConnectionLists = connections.Import(new
FileInfo(@"D:\Samples\Import\myConnectionImport.xml"), ImportOptions.Override);
}

6.3.7 Screens

6.3.7.1 Overview of exportable screen objects

Application
You can export or import the screens below using TIA Portal Openness APIs:

Table 6-4 Supported screens

Object Export/import possible


Screen Yes
Global screen Yes
Screen template Yes
Permanent area Yes
Pop-up screen Yes
Slide-in screen Yes

Openness: API for automation of engineering workflows


916 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

You can export or import the screen objects below using TIA Portal Openness APIs:

Table 6-5 Supported screen objects

Range Object type Export/import possible


Basic objects Line Yes
Polyline Yes
Polygon Yes
Ellipse Yes
Ellipse segment –
Circle segment –
Elliptical arc –
Circular arc –
Circle Yes
Rectangle Yes
Connector –
Text field Yes
Graphic view Yes
Pipe –
Double T-piece –
T-piece –
Pipe elbow –

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 917
Export/import
6.3 Importing/exporting data of an HMI device

Range Object type Export/import possible


Elements I/O field Yes
Graphic I/O field Yes
Editable text field –
List box –
Combo box –
Button Yes
Round button –
Illuminated button Yes
Switch Yes
Symbolic I/O field Yes
Date/time field Yes
Bar Yes
Symbol library Yes
Slider Yes
Scroll bar –
Check box –
Option buttons –
Gauge Yes
Clock Yes
Memory space view –
Function keys (softkeys) Yes
Groups Yes
Faceplate instances Yes

Openness: API for automation of engineering workflows


918 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Range Object type Export/import possible


Controls Screen window –
User view Yes
Print job/script diagnostics –
Camera view –
PDF view –
Recipe view –
Alarm view –
Alarm indicator –
Alarm window –
f(x) trend view –
f(t) trend view –
Table view –
Value table –
HTML Browser –
Media Player –
Channel diagnostics –
WLAN reception –
Zone name –
Zone signal –
Effective range name –
Effective range name (RFID) –
Effective range signal –
Charge condition –
Handwheel –
Help indicator –
Sm@rtClient view –
Status/Force –
Memory space view –
NC subprogram display –
System diagnostic view –
System diagnostic window –

See also
Basic principles of importing/exporting (Page 879)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 919
Export/import
6.3 Importing/exporting data of an HMI device

6.3.7.2 Exporting all screens of an HMI device

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
A different program code is required for exporting all aggregated screens of all user-defined
screen folders of an HMI device.

Program code: Exporting all screens of a device


Modify the following program code to export the screens of a user-defined screen folder of an
HMI device and the screen system folder:

private static void ExportScreensOfDevice(string rootPath, HmiTarget hmitarget)


{
DirectoryInfo info = new DirectoryInfo(rootPath);
info.Create();
//export the ScreenFolder recursive

string screenPath = Path.Combine(rootPath, "Screens");


info = new DirectoryInfo(screenPath);
info.Create();
ExportScreens(screenPath, hmitarget);
}

Program code: Exporting all screens of a user-definded folder


Modify the following program code to export the screens of a user-defined screen folder of an
HMI device and the screen system folder:

private static void ExportScreensOfDevice(HmiTarget hmitarget)


{
ScreenUserFolder folder = hmitarget.ScreenFolder.Folders.Find("MyScreenFolder");
//or ScreenSystemFolder folder = hmitarget.ScreenFolder;
ScreenComposition screens = folder.Screens;
foreach(Screen screen in screens)
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Screens\{0}\{1}.xml",
folder.Name, screen.Name));
screen.Export(info, ExportOptions.WithDefaults);
}
}

Openness: API for automation of engineering workflows


920 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting all screens of a device independent of the user


Modify the following program code to export all screens:

public static void ExportScreens(string screenPath, HmiTarget target)


{
foreach(Screen screen in target.ScreenFolder.Screens)
{
screen.Export(new FileInfo(Path.Combine(screenPath, screen.Name + ".xml")),
ExportOptions.WithDefaults);
}
foreach(ScreenUserFolder subfolder in target.ScreenFolder.Folders)
{
ExportScreenUserFolder(Path.Combine(screenPath, folder.Name), subfolder);
}
}

private static void ExportScreenUserFolder(string screenPath,ScreenUserFolder folder )


{
foreach(Screen screen in folder.Screens)
{
screen.Export(new FileInfo(Path.Combine(screenPath, screen.Name + ".xml")),
ExportOptions.WithDefaults);
}
foreach(ScreenUserFolder subfolder in folder.Folders)
{
ExportScreenUserFolder(Path.Combine(screenPath, subfolder.Name), subfolder);
}
}

6.3.7.3 Exporting a screen from a screen folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 921
Export/import
6.3 Importing/exporting data of an HMI device

Application
The following data of a screen is exported:

Screen Data
Attributes ActiveLayer, BackColor, Height, Width, Name, Number, HelpText
Open links Template
Compositions • Layers
• Animations
All configured animations that are based on Runtime Advanced are exported.
• Events
All configured events that are based on Runtime Advanced are exported.
• Softkeys
All configured softkeys are exported.

The following data is exported for each layer:

Note
By default, the layer name in the TIA Portal is an empty text.
If you do not change the layer name in the TIA Portal, the exported layer name will be an empty
text. In this case, the displayed layer name in the TIA Portal depends on the user interface
language.
If you do change the layer name in the TIA Portal, the modified layer name is displayed in all
relevant languages.

Layer Data
Attributes Name, Index, VisibleES
Compositions ScreenItems (with screen items)

Not included in the export:


• SCADA-specific attributes.
• Layers that do not contain any screen items and whose attributes do not differ from the
default values.

Openness: API for automation of engineering workflows


922 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code
Modify the following program code to export an individual screen from the user folder or from
the system folder of an HMI device:

//Exports a single screen from a screen folder


private static void ExportSingleScreenFromScreenFolder(HmiTarget hmitarget)
{
ScreenUserFolder folder = hmitarget.ScreenFolder.Folders.Find("MyScreenFolder");
//or ScreenSystemFolder folder = hmitarget.ScreenFolder;
ScreenComposition screens = folder.Screens;
Screen screen = screens.Find("Screen_1.xml");
if (screen == null) return;
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Screens\{0}\{1}.xml",
folder.Name, screen.Name));
screen.Export(info, ExportOptions.WithDefaults);
}
}

6.3.7.4 Importing screens to an HMI device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The screens can only be imported to a specific type of HMI device. The HMI device and the device
from which the screens were exported must be of the same device type.
The following data of a screen is imported:

Screen Data
Attributes ActiveLayer, BackColor, Height, Width, Name, Number, HelpText
Open links Templates
Compositions • Layers
• Animations
All animations configurable for screens are imported.
• Events
All events configurable for screens are imported.
• Softkeys
All softkeys configurable for screens are imported.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 923
Export/import
6.3 Importing/exporting data of an HMI device

The following data is imported for each layer:

Note
If you have specified an empty text for the layer name before the import, the displayed layer
name in the TIA Portal after the import depends on the user interface language.
If you have assigned a layer name, the specified layer name is displayed in all relevant languages
after the import.

Layer Data
Attributes Name, Index
Compositions ScreenItems

Restrictions
• The import is canceled and an Exception is thrown if the width and height of a screen do not
correspond to the dimensions of the device. Adaptation of the screen items contained is not
supported. For this reason, certain screen items may be located beyond the screen
boundaries. A compiler warning is output in this case.
• The screen number must be unique for all screens of the device. A screen import is canceled
if a screen with a screen number that was already created in the device is found. If you have
not yet assigned a screen number, a unique number is assigned to the screen during the
import.
• The layout of the screen items within the Z-order must be unique and contiguous for each
layer in the screen. For this reason, after the import of the screen, a consistency check is
performed that repairs the layout, if necessary. This action may lead to modified "tab indexes"
for certain screen items.
You can change the Z-order of the screen items in the XML file manually. The screen item in
first place is at the very end in the Z-order.

Note
You can change the values for width and height of the screen items in the XML file if the attribute
"Fit size to content" is enabled for the screen item.

Note
Import of screen types from the library is not supported
As of WinCC V12 SP1, you can create a screen as type in the library. Instances of the screen type
used in the project can be edited like other screens using the TIA Portal Openness application.
When you export screens, the instances of screen types are exported without the type
information.
When you re-import these screens into the project, the instances of the screen types are
overwritten and the instance is detached from the screen type.

Openness: API for automation of engineering workflows


924 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Importing screens to an HMI device


Modify the following program code to import screens to an HMI device using a For each loop:

//Imports all screens to an HMI device


private static void ImportScreensToHMITarget(HmiTarget hmitarget)
{
FileInfo[] exportedScreens = new FileInfo[] {new FileInfo(@"D:\Samples\Import
\Screen_1.xml"), new FileInfo(@"D:\Samples\Import\Screen_2.xml")};
ScreenUserFolder folder = hmitarget.ScreenFolder.Folders.Find("MyScreenFolder");
foreach (FileInfo screenFileInfo in exportedScreens)
{
folder.Screens.Import(screenFileInfo, ImportOptions.Override);
}
}

Program code: Import to a newly created user folder


Modify the following program code to import a screen to a newly created user folder of an HMI
device:

//Imports a single screen to a new created user folder of an HMI device


private static void ImportSingleScreenToNewFolderOfHMITarget(HmiTarget hmitarget)
{
ScreenUserFolder folder = hmitarget.ScreenFolder.Folders.Create("MyFolder");
folder.Screens.Import(new FileInfo(@"D:\Samples\Import\myScreens.xml"),
ImportOptions.Override);
}

6.3.7.5 Exporting permanent areas

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data of the permanent area is exported:

Permanent area Data


Attributes ActiveLayer, BackColor, Height, Width, Name
Compositions Layers

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 925
Export/import
6.3 Importing/exporting data of an HMI device

The following data is exported for each layer:

Layer Data
Attributes Name, Index
Compositions ScreenItems (with screen items)

Program code
Modify the following program code to export a permanent area of an HMI device to an XML file:

//Exports a permanent area


private static void ExportScreenoverview(HmiTarget hmitarget)
{
ScreenOverview overview = hmitarget.ScreenOverview;
if (overview == null) return;

FileInfo info = new FileInfo(@"D:\Samples\Screens\ExportedOverview.xml");


overview.Export(info, ExportOptions.WithDefaults);
}

6.3.7.6 Importing permanent areas

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data of the permanent area is imported:

Permanent area Data


Attributes ActiveLayer, BackColor, Height, Width, Name, Visible, Number
Compositions Layers

The following data is imported for each layer:

Layer Data
Attributes Name, Index
Compositions ScreenItems (with screen items)

The import is canceled and an Exception is thrown if the width and height of a screen do not
correspond to the dimensions of the device. Adaptation of the included device items (Screen
items) is not supported. For this reason, some device items may be located beyond the screen
boundaries. A compiler warning is output in this case.

Openness: API for automation of engineering workflows


926 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

The layout of the device items must be unique and contiguous in the permanent area. For this
reason, after the import of the permanent area, a consistency check is performed that repairs the
layout, if necessary. This action may lead to modified "tab indexes" for certain device items.

Program code
Modify the following program code to import a permanent area from an XML file into an HMI
device:

//Imports a permanent area


private static void ImportScreenOverview(HmiTarget hmiTarget)
{
FileInfo info = new FileInfo(@"D:\Samples\Screens\ExportedOverview.xml");
hmiTarget.ImportScreenOverview(info, ImportOptions.Override);
}

6.3.7.7 Exporting all screen templates of an HMI device

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
One XML file is created per screen template.
Because bulk exports are not supported, you need to enumerate and export all screen templates
separately. In the course of this action, make sure that the screen template names used conform
to the file naming conventions of your file system.

Program code: Exporting all screen templates of a device


Modify the following program code to export all screen templates from a specific folder:

public static void ExportScreenTemplatesOfDevice(string rootPath ,


ScreenTemplateUserFolder folder)
{
string screenPath = Path.Combine(rootPath, "Screens");
DirectoryInfo info = new DirectoryInfo(screenPath);
info.Create();

//export the ScreenTemplateFolder recursive


ExportScreenTemplates (screenPath, hmitarget);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 927
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting all screen templates of a specific folder


Modify the following program code to export all screen templates:

//Exports all screen templates of a selected folder


private static void ExportScreenTemplates(string templatePath, HmiTarget hmitarget)
{
foreach (ScreenTemplate screen in hmitarget.ScreenTemplateFolder.ScreenTemplates)
{
screen.Export(new FileInfo(Path.Combine(templatePath, screen.Name + ".xml")),
ExportOptions.WithDefaults);
}
foreach (ScreenTemplateUserFolder folder in hmitarget.ScreenTemplateFolder.Folders)
{
ExportScreenTemplates(Path.Combine(templatePath, folder.Name), hmitarget);
}
}

6.3.7.8 Exporting screen templates from a folder

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data of the screen template is exported:

Screen templates Data


Attributes ActiveLayer, BackColor, Height, Width, Name
Compositions • Layers
• Animations
All configured animations are exported. SCADA animations are not exported.
• Softkeys
All configured softkeys are exported.

The following data is exported for each layer:

Layer Data
Attributes Name, Index
Compositions ScreenItems (with screen items)

Openness: API for automation of engineering workflows


928 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting a screen template of a user-defined folder


Modify the following program code to export an individual screen template from the system
folder or from a user-defined folder:

private static void ExportSingleScreenTemplate(string templatePath, HmiTarget hmiTarget)


{
ScreenTemplateUserFolder folder =
hmiTarget.ScreenTemplateFolder.Folders.Find("MyTemplateFolder");
//or ScreenTemplateSystemFolder folder = hmiTarget.ScreenTemplateFolder;
ScreenTemplateComposition templates = folder.ScreenTemplates;
ScreenTemplate template = templates.Find("templateName");
if(template == null) return;

FileInfo info = new FileInfo(string.Format(@"D:\Samples\Templates\{0}\{1}.xml",


folder.Name, template.Name));
template.Export(info, ExportOptions.WithDefaults);
}

Program code: Exporting all screen templates of a user-defined folder


Modify the following program code to export all screen templates from a specific folder:

public static void ExportScreenTemplateUserFolder(string rootPath,


ScreenTemplateUserFolder folder)
{
DirectoryInfo info = new DirectoryInfo(rootPath);
info.Create();

foreach (ScreenTemplate screen in folder.ScreenTemplates)


{
screen.Export(new FileInfo(Path.Combine(info.FullName, screen.Name + ".xml")),
ExportOptions.WithDefaults);
}
foreach (ScreenTemplateUserFolder subfolder in folder.Folders)
{
ExportScreenTemplateUserFolder(Path.Combine(info.FullName, subfolder.Name),
subfolder);
}
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 929
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting all screen templates of a specific folder


Modify the following program code to export all screen templates:

//Exports all screen templates of a selected folder


private static void ExportScreenTemplates(string templatePath, ScreenTemplateUserFolder
folder)
{
foreach (ScreenTemplate screen in folder.ScreenTemplates)
{
screen.Export(new FileInfo(Path.Combine(templatePath, screen.Name + ".xml")),
ExportOptions.WithDefaults);
}
foreach (ScreenTemplateUserFolder subfolder in folders.Folders)
{
ExportScreenTemplates(Path.Combine(templatePath, subfolder.Name), subfolder);
}
}

6.3.7.9 Importing screen templates

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data of a screen template is imported:

Screen template Data


Attributes ActiveLayer, BackColor, Height, Width, Name, SetTabOrderInFront
Compositions • Layers
• Animations
All animations configurable for screens are imported.
• Softkeys
All softkeys configurable for screens are imported.

The following data is imported for each layer:

Layer Data
Attributes Name, Index
Compositions ScreenItems (with screen items)

The import is canceled and an Exception is thrown if the width and height of a screen template
do not correspond to the dimensions of the device. Adaptation of the included screen items is

Openness: API for automation of engineering workflows


930 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

not supported. For this reason, certain screen items may be located beyond the screen
boundaries. A compiler warning is output in this case.
The layout of the screen items must be unique and contiguous in the screen template. For this
reason, after the import of the screen template, a consistency check is performed which repairs
the layout, if necessary. This action may lead to modified "tab indexes" for certain screen items.

Program code: General import


Modify the following program code to import all screen templates to an HMI device using a For
each loop:

//Imports screen templates to an HMI device


private static void ImportScreenTemplatesToHMITarget(HmiTarget hmitarget)
{
ScreenTemplateUserFolder folder =
hmitarget.ScreenTemplateFolder.Folders.Find("MyTemplateFolder");
// or ScreenTemplateSystemFolder folder = hmitarget.ScreenTemplateFolder;
FileInfo[] exportedTemplates = {new FileInfo[] { new FileInfo(@"D:\Samples\Import
\Template_1.xml"), new FileInfo(@"D:\Samples\Import\Template_n.xml") };};
foreach (FileInfo templateFileName in exportedTemplates)
{
folder.ScreenTemplates.Import(templateFileName, ImportOptions.Override);
}
}

Program code: Import into a newly created user folder


Modify the following program code to import a screen template into a newly created user folder
of an HMI device:

//Imports screen templates to a user folder of an HMI device


private static void ImportScreenTemplatesToFolderOfHMITarget(HmiTarget hmitarget)
{
ScreenTemplateUserFolder screenTemplateFolder =
hmitarget.ScreenTemplateFolder.Folders.Find("MyTemplateFolder");
ScreenTemplateUserFolder folder = screenTemplateFolder.Folders.Create("MyNewFolder");
folder.ScreenTemplates.Import(new FileInfo(@"D:\Samples\Import\ScreenTemplate.xml"),
ImportOptions.Override);
}

6.3.7.10 Exporting a pop-up screen

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 931
Export/import
6.3 Importing/exporting data of an HMI device

Application
The following data of the pop-up screen is exported:

Screen templates Data


Attributes ActiveLayer, BackColor, GridColor, Height, Name, ScrollbarBackgroundColor,
ScrollbarForegroundColor, Width
Compositions • Layers
• Events
All configured events are exported.

The following data is exported for each layer:

Layer Data
Attributes Name, Index, VisibleES
Compositions ScreenItems
All exportabe screen objects are exported.

Program code: Exporting a pop-up screen from a folder


Modify the following program code to export an individual pop-up screen from the system folder
or from a user-defined folder:

//Exports a single pop-up screen


private static void ExportSinglePopUpScreen(HmiTarget hmitarget)
{
ScreenPopupUserFolder folder =
hmitarget.ScreenPopupFolder.Folders.Find("MyPopupFolder");
//or ScreenPopupSystemFolder folder = hmitarget.ScreenPopupFolder;
ScreenPopupComposition popups = folder.ScreenPopups;
ScreenPopup popup = popups.Find("popupName");
if(popup == null) return;

FileInfo info = new FileInfo(string.Format(@"D:\Samples\Screens\{0}\{1}.xml",


folder.Name, popup.Name);
popup.Export(info, ExportOptions.WithDefaults);
}

6.3.7.11 Importing a pop-up screen

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


932 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Application
The following data of a pop-up screen is imported:

Screen templates Data


Attributes ActiveLayer, BackColor, GridColor, Height, Name, ScrollbarBackgroundColor,
ScrollbarForegroundColor, Width
Compositions • Layers
• Events
All configured events are exported.

The existence of the following attributes is mandatory for the import:


• Name
• Height
• Width
The following data is imported for each layer:

Layer Data
Attributes Name, Index, VisibleES
Compositions ScreenItems
All importable screen objects are imported.

Restrictions
If a device doesn't support pop-up screens, the import is cancelled and an Exception is thrown.
If the width and height of a pop-up screen do not comply to the following dimensions
restrictions for a device, the import is cancelled and an Exception is thrown:
• Minimum height = 1 pixel
• Minimum width = 1 pixel
• Maximum height = sixfold height of the device's screen
• Maximum width = twofold width of the device's screen
• For devices with runtime version V13 SP1 the maximum height and the maximum width is
equal with th height and width of the device's screen.

Program code: Importing a pop-up screen into a folder


Modify the following program code to import a pop-up screen into the pop-up screen system
folder or to a user-defined folder:

//Imports a pop-up screen to an HMI device


private static void ImportPopupScreenToHMITarget(HmiTarget hmitarget)
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Screens\PopupScreen.xml"));
hmitarget.ScreenPopupFolder.ScreenPopups.Import(info, ImportOptions.None);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 933
Export/import
6.3 Importing/exporting data of an HMI device

6.3.7.12 Exporting a slide-in screen

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data and values of the slide-in screen is exported:

Screen tem‐ Data


plates
Attributes Activate false
ActiveLayer 0
BackColor (182; 182; 182)
GridColor (0; 0; 0)
Dimension 427
The attribute "Dimension" specifies either the width or
height of the slide-in screen, depending on the used slide-in
screen type.
LineColor1 (223; 223; 223)
LineColor2 (32; 32; 32)
OperatableAreaColor (128; 128; 128)
SlideinType Top, Bottom, Left, Right
Slide-in screens do not have a name but a SlideinType.
Visibility FadeOut
Compositions Layers

Note
Slide-in screens do not have a name but a SlideinType.

The following data is exported for each layer:

Layer Data
Áttributes Name,
Index
VisibleES
Compositions ScreenItems All exportabe screen objects are exported.

Openness: API for automation of engineering workflows


934 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Exporting a slide-in screen


Modify the following program code to export an individual slide-in screen from the system
folder:

//Exports a single slide-in screen


private static void ExportSingleSlideinScreen(HmiTarget hmitarget)
{
ScreenSlideinSystemFolder systemFolder = hmitarget.ScreenSlideinFolder;
var screens = systemFolder.ScreenSlideins;
ScreenSlidein slidein = screens.Find(SlideinType.Bottom);
if (slidein == null) return;

FileInfo info = new FileInfo(string.Format(@"D:\Samples\Screens\{0}\{1}.xml"));


slidein.Export(info, ExportOptions.WithDefaults);
}

6.3.7.13 Importing a slide-in screen

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data and values of a slide-in screen is imported:

Screen templates Data


Attributes Activate = false
ActiveLayer = 0
Authorization
BackColor = (182; 182; 182)
Dimension = 427
The attribute "Dimension" specifies either the width or height of the slide-in
screen, depending on which of the two attributes is modifiable for the specified
slide-in type.
GridColor = (0; 0; 0)
LineColor1 = (223; 223; 223)
LineColor2 = (32; 32; 32)
OperateableAreaColor = (128; 128; 128)
SlideinType = Top, Bottom, Left, Right
Visibility = FadeOut
Compositions Layers

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 935
Export/import
6.3 Importing/exporting data of an HMI device

The existence of the following attribute is mandatory for the import:


• SlideinType
The following data is imported for each layer:

Layer Data
Attributes Name, Index, VisibleES
Compositions ScreenItems
All importable screen objects are imported.

Restrictions
• If a device does not support slide-in screens, the import is cancelled and an Exception is
thrown.
• If a slide-in screen is referenced from another element, the slide-in screen must be referenced
via openlink and not via SlideinType, e. g. in system function "ShowSlideinScreen").
The following table shows the mapping of the attribute "SlideinType" with the corresponding
openlink:

SlideinType Openlink Name


Top GraphX_Slidein_Top
Right GraphX_Slidein_Right
Bottom GraphX_Slidein_Bottom
Left GraphX_Slidein_Left

Program code: Importing a slide-in screen into a folder


Modify the following program code to import a slide-in screen to the slide-in screen system
folder:

//Imports a slide-in screen to an HMI device


private static void ImportSlideinScreenToHMITarget(HmiTarget hmitarget)
{
FileInfo info = new FileInfo(@"D:\Samples\Screens\SlideInScreen.xml");
hmitarget.ScreenSlideinFolder.ScreenSlideins.Import(info, ImportOptions.None);
}

6.3.7.14 Exporting a screen with a faceplate instance

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


936 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Application
The following data of a faceplate instance in a screen is exported:

Screen Data
Attributes Left, Top, Width, Height, ObjectName, Resizing, TabIndex, FaceplateTypeName
Interface Attributes All configured interface attributes of a faceplate instance are exported for ex‐
portable screen items.
Compositions • Animations
All movement animations are exported.
Tag animations rely on interface attributes.
• Events
All configured events are exported.

Regard the following specifications for exported attributes of faceplate instance:


• Resizing
The attribute "Resizing" is exported in any case, independent of the export options.
• FaceplateTypeName
The attribute "FaceplateTypeName" identifies the corresponding faceplate type and version,
e. g. "Faceplate_1 V 0.0.2".
Note
Faceplate type in a library folder
If a faceplate type is located within a library folder, the complete path and name is required
to identify the faceplate type. The keyword "@$@" is used to separate folders and/or faceplate
type name, e. g. "Folder_1@$@SubFolder_1@$@Faceplate_1 V 0.0.2".

The following data of inner screen items of a faceplate instance is excluded from the export:

Screen item Attribute


IO-Field Flashing on limit violation
Graphic IO-Field Fit embedded graphic object to screen size

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 937
Export/import
6.3 Importing/exporting data of an HMI device

Program code
Modify the following program code to export an individual screen including a faceplate instance:

//Exports a single screen including a faceplate instance


private static void ExportSingleScreenWithFaceplateInstance(HmiTarget hmitarget)
{
ScreenFolder folder = hmitarget.ScreenFolder.Folders.Find("MyScreenFolder");
ScreenComposition screens = folder.Screens;
Screen screen = screens.Find("ScreenWithFaceplateName");
if (screen == null) return;
{
FileInfo info = new FileInfo(string.Format(@"D:\Samples\Faceplates\{0}\{1}.xml",
folder.Name, screen.Name));
screen.Export(info, ExportOptions.WithDefaults);
}
}

6.3.7.15 Importing a screen with a faceplate instance

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The following data of a faceplate instance in a screen is imported:

Screen Data
Attributes Left, Top, Width, Height, ObjectName, Resizing, TabIndex, FaceplateTypeName
Interface Attributes All configured interface attributes of a faceplate instance are imported for im‐
portable screen items.
Compositions • Animations
All movement animations are imported.
Tag animations rely on interface attributes.
• Events
All configured events are imported.

The existence of the following attributes is mandatory for the import:


• ObjectName
• FaceplateTypeName

Openness: API for automation of engineering workflows


938 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

The following data of inner screen items of a faceplate instance is excluded from the export and
import:

Screen item Attribute


IO-Field Flashing on limit violation
Graphic IO-Field Fit embedded graphic object to screen size

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 939
Export/import
6.3 Importing/exporting data of an HMI device

Restrictions
• Unknown Faceplate, event or interface attribute
If a faceplate type name, an event name or an interface attribute name is specified in the
import file which does not exist in the project, the import is aborted with an Exception.
• Resizing behavior of a faceplate instance
The attribute "Resizing" is imported in any case, independent of the export options.
Examples:
If "Resizing" is set to "KeepRatio", the "Height" attribute is used to calculate the "Width"
attribute value.
– The size of a faceplate type is 100 x 100 pixel. If a faceplate instance is imported with size
300 x 100 pixel and value "FixedSize" is set for the "Resizing" attribute, the import
succeeds and the faceplate size is set to 100 x 100 pixel.
– The size of a faceplate type is 100 x 50 pixel. A faceplate instance is imported with size 100
x 100 pixel and value "KeepRatio" is set for the "Resizing" attribute.The import succeeds
and the faceplate size is set to 200 x 100 pixel.

Note
Sizing behavior of imported faceplate instances
The values of "Resizing" and values of interface attributes can affect the size of the imported
faceplate instance and even the size of the inclosed screen items.
To avoid unrequested changes of the appearance of a faceplate instance, import a faceplate
with the initial size or even without "Width" and "Height" attribute values.

• Deviant interface attribute values


– If you modify attributes for the import, the last applied interface attribute value is
imported.
– If attributes depend on each other, other attribute values can be changed during the
import.
Example: A faceplate includes an I/O field. The attribute "Mode" is connected to an
interface attribute. If you first set the mode to "Output" and then set the attribute "Hidden
input" to true, the value of "Hidden input" is not applied after import. The first
modification set the attribute "Hidden input" to read-only and therefore the value cannot
be applied.
– If a attribute value does not fulfill the restrictions of WinCC, the faceplates type value is
displayed.
Example: The display range of a gauge is set from 10 - 80. The attributes "MaximumValue"
und "MinimumValue" are configured al interface attributes. If you set a minimum value
that exceeds the maximum value, e. g. 100, the faceplate type's value for
"MinimumValue" is displayed after import.
– If an interface attribute is connected with several screen item attributes within the
faceplate type, the interface attribute value at the faceplate instance will display the
applied attribute value of the first connected screen item.
Example: A faceplate includes two gauge objects with deviant maximum values. The
minimum values of both gauges are connected to one single interface attribute.
If you first set a minimum value that is applicable for both gauges, both values are set.
If you set than a value that is only applicable for the second gauge, the value is only set
for the second gauge, but the value of the first gauge is displayed as interface attribute.

Openness: API for automation of engineering workflows


940 System Manual, 05/2021, Online documentation
Export/import
6.3 Importing/exporting data of an HMI device

Program code: Importing screens including a faceplate instance


Modify the following program code to import a screen including a faceplate instance:

//Imports single screen including a faceplate instance


private static void ImportSingleScreenWithFaceplateInstance(HmiTarget hmitarget)
{
FileInfo info = new FileInfo(@"D:\Samples\Screens\ScreenFaceplate.xml");
hmitarget.ScreenFolder.Screens.Import(info, ImportOptions.None);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 941
Export/import
6.4 Importing/exporting data of a PLC device

6.4 Importing/exporting data of a PLC device

6.4.1 Blocks

6.4.1.1 XML structure of the block interface section

Basic principle
The data in the export file from the import/export is structured with reference to a basic
structure. Every import file has to fulfill the basic structural conditions.
The export file includes all edited tags and constants of the interface section of an exported
block. All attributes with "ReadOnly="TRUE""and "Informative="TRUE"" are excluded.
If the information is redundant, it must exactly be identical in the import XML file and the project
data. Otherwise the import will throw a recoverable exception.
The project data can contain more data than the import XML file, e. g. an external type may have
additional members
Only writeable values can be imported via TIA Portal Openness XML.
Depending on the TIA Portal Openness export settings, the export file includes a defined set of
attributes and elements. The XML exported from higher versions of the product is not
compatible during the import operation in lower version of the TIA Portal.

Openness: API for automation of engineering workflows


942 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Basic structure
The interface section of an exported block is covered in the <Interface> element in the
SimaticML of a block. The root object is the <Sections> element, which represents the
interface section of an exported block. The sequence of the following description of elements
represents the required sequence in the input file.

• Section
Section represents a single parameter or local data of a program block
• Member
Member represents the tags or constants used in the program block. Depending of the
datatype of a tag, members can be nested or have further structural sub elements.
In case of the data type "ARRAY" the structural element "Subelement Path" represents e. g.
the index of the components of an array element.
Only those members are exported, which were edited by the user.
• AttributeList
The <AttributeList> includes all defined attributes of a member. Attributes, that are
system defined or assigned by a standard value are not listed in the XML structure.
The member attributes <ReadOnly> and <Informative> are only written to the XML
export file if their value is TRUE.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 943
Export/import
6.4 Importing/exporting data of a PLC device

• StartValue
The element <StartValue> is only written, if the default value of the tag or constant is set
by the user.

• Comment
The element <Comment> is written, if it is set by the user. Comments of a tag or constant are
exported as multilingual text:

Openness: API for automation of engineering workflows


944 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Attributes
• Main attributes
The main attributes are written in the <Member> element in the XML structure.

The following table shows the main attributes of a tag or constant at the block interface
section.

Name Datatype Default Import condition Comment


Name STRING - Required
Datatype ENUM - Required
Version STRING - Optional
Remanence ENUM NonRetain - only written if
not default
Accessibility ENUM Public - pre-defined by
the system
cannot be
changed by the
user
Informative BOOL FALSE -
Members with the flag "Informative" are ignored during import. If the attribute is deleted
or set to FALSE, an exception is thrown.
Note
Remanence settings "Set in IDB"
If the remanence value of a tag or constant is "Set in IDB", the remanence set in the IDB has
to be the same for all other tags and constants with the remanence value "SetInIDB".
The first imported member with "Set in IDB" attribute defines the expected remanence in the
IDB for the following tags and constants with the remanence value "SetInIDB".

• System defined member attributes


Systemdefined member attributes are listed in the element <AttributeList>.
Systemdefined member attributes flagged with the <Informative> and are ignored
during import.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 945
Export/import
6.4 Importing/exporting data of a PLC device

Name Type Default SimaticML Re‐ Comment


adOnly (informa‐
tive)
At string "" FALSE Member shares
offset with anoth‐
er member in this
structure
SetPoint bool FALSE FALSE Member can be
synchronized
with workmemo‐
ry
UserReadOnly bool FALSE TRUE User cannot
change any mem‐
ber attribute (incl.
name)
UserDeletable bool TRUE TRUE Editor does not al‐
low to delete the
member
HmiAccessible bool TRUE FALSE No HMI access, no
structure item
HmiVisible bool TRUE FALSE Filter to reduce
the number of
members shown
in the first place
Offset int - TRUE DB, FB, FC (Temp).
For classic PLCs
and for Plus PLCs
where the rema‐
nence is set to
classic.
PaddedSize int - TRUE DB, FB, FC (Temp).
For classic PLCs
and for Plus PLCs
where the rema‐
nence is set to
classic. Only for ar‐
rays.
HiddenAssign‐ bool FALSE FALSE Hide assignement
ment at call if matches
with Predefine‐
dAssignment
PredefinedAssing‐ string "" FALSE Input for the para‐
ment mter used when
call is placed
ReadOnlyAssign‐ bool FALSE FALSE The user cannot
ment change the prede‐
fined assigne‐
ment at the call
UserVisible bool TRUE TRUE This member is
not shown on the
UI

Openness: API for automation of engineering workflows


946 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Name Type Default SimaticML Re‐ Comment


adOnly (informa‐
tive)
HmiReadOnly bool TRUE TRUE This member is
read only for HMI
CodeReadOnly bool FALSE TRUE -

• User defined attributes


User defined attributes are flagged with <ReadOnly>. Members with this flag are ignored
during import. If the flag is deleted or set to FALSE, an exception is thrown.
Unedited user defined attributes are excluded from the export.

Name Type Default SimaticML Re‐ Comment


adOnly (informa‐
tive)
CFC IBlockAttribute --- FALSE this is a Payload

Datatype "STRUCT"
The components of the datatype "STRUCT" are represented in the XML structure of an import/
export file as nested members:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 947
Export/import
6.4 Importing/exporting data of a PLC device

Datatype "ARRAY" basic type


The components of the basic datatype "ARRAY" are represented in the XML structure of an
import/export file as subelements with the attribute "Path" :

Datatype "ARRAY" of UDT


The components of the datatype "ARRAY" of an UDT are represented in the XML structure of an
import/export file as new <sections> element in a <member> element. The members in the
new section for UDT are within an ARRAY are assigned as subelements with "Path" attribute:

Openness: API for automation of engineering workflows


948 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Datatype "ARRAY" in "ARRAY"


The components of the datatype "ARRAY" in another ARRAY are represented in the XML structure
of an import/export file as subelements with the attribute "Path".
The members within another ARRAY are assigned as subelements with"Path" attribute, if the
component is edited by the user:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 949
Export/import
6.4 Importing/exporting data of a PLC device

PLC data types (UDT)


The XML structure of a PLC data type depends on the TIA Portal Openness export settings.
• ExportOptions.None
Members of PLC data type are only written if the default value of at least one of the
components is set by the user. For these members, only the two additional
attributes "Name" and "Datatype" are written, to identify the member to which
the <StartValue> belongs. Other members and attributes are not written.
• ExportOptions.WithDefaults
The following attributes are always written:
– Name
– Datatype
– ExternalAccessible
– ExternalVisible
– ExternalWritable
– SetPoint
– StartValue
Only written to the XML if it the default value in this type is set by the user. If it only has
been set in the PLC data type, it is not written.
• ExportOptions.ReadOnly
For PLC data types this setting will not lead to meaningful result. In combination with other
settings it will have no influence on the result.

Openness: API for automation of engineering workflows


950 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Overlaid tags
If a tag is overlaid with a new datatype, the members are represented in the XML structure of the
new data type. The following XML structure shows a datatype WORD overlaid by an ARRAY of
BYTE.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 951
Export/import
6.4 Importing/exporting data of a PLC device

Block Interface
All attributes with ReadOnly="TRUE" and Informative="FALSE" are excluded. The XML
structure of a block interface depends on the TIA Portal Openness export settings.
• ExportOptions.None
This setting exports only the modified data or the data that differs from the default.
In case their attribute definition does not specify a default value, the attribute is always
written.
The export file also contains all values that are obligatory for the subsequent data import.
• ExportOptions.WithDefaults
The following attributes are always written
– Name
– Datatype
– HmiAccessible exported as ExternalAccessible
– HmiVisible exported as ExternalVisible
– ExternalWritable
– SetPoint (if applicable)
– Offset (if applicable)
– PaddedSize (if applicable)
All other attributes are only written if their values differ from the default.
The <StartValue> element is only written to the XML if it has been explicitly set.
• ExportOptions.ReadOnly
For block interfaces this setting will not lead to meaningful result. In combination with other
settings it will have no influence on the result.

6.4.1.2 Changes of the object model and XML file format

Introduction
To import a custom created or an edited XML file successfully to the TIA Portal via TIA Portal
Openness, the file must correspond to defined schemas.
The XML files always consist of two major parts:
• Interface
• Compile unit
The schemas they have to correspond to are explained in the following.

Openness: API for automation of engineering workflows


952 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Interface
An interface can contain multiple sections (e. g. Input, InOut, Static): You can find all of these
sections in the schema in the following directory:
• C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas
\SW.InterfaceSections_v3.xsd
• C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas
\SW.Interface.Snapshot .xsd

Compile unit
There are seperate schemas for the compile units of GRAPH, LAD/FBD, STL and SCL blocks. You
can find these schemas in the following directories:
• GRAPH: C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas
\SW.PlcBlocks.Graph_v4.xsd
• LAD/FBD: C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas
\SW.PlcBlocks.LADFBD_v3.xsd
• STL: C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas
\SW.PlcBlocks.STL_v3.xsd
• SCL: C:\Pogram Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas\
SW.PlcBlocks.SCL_v2.xsd

Subschemas
There are the following additional schema definitions used by all compile units:
• Access
• Common

Access
The Access node describes for example:
• local/global members and constant usages
• FB, FC, Instruction calls
• DBs for calls
You can find the access schema in the following directory:
C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*\Schemas
\SW.PlcBlocks.Access_v3.xsd

Common
Common contains the commonly used attributes and elements, for example different types of
comments, texts and tokens.
You can find the common schema in the following directory:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 953
Export/import
6.4 Importing/exporting data of a PLC device

C:\Program Files\Siemens\Automation\Portal V*\PublicAPI\V*.\Schemas\SW.Common_v2.xsd

Note
V* refers to the installed version of TIA Portal.

6.4.1.3 Exporting DBs with snapshots

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to export the DB's with snapshot values as XML and able to
compare the values with different snapshot times. With the compare result, you can manually
adapt single start values within the UI and store for a potential recovery. The schema
“SW.Interface.Snapshot.xsd” will support you to interpret or process the exported XML-file.

Program code
Modify the following program code to export Snapshot Values by using the Snapshot Service:

InterfaceSnapshot interfaceSnapshot = dataBlock.GetService<InterfaceSnapshot>();


interfaceSnapshot.Export(new FileInfo("C:\temp\MyInterfaceSnapshot.xml"),
ExportOptions.ReadOnly);

The Snapshot Service "InterfaceSnapshot" will be provided in the namespace


"Siemens.Engineering.SW.Blocks". The file handling (e.g. if the export directory does not exist;
creating of the export directory; if the export directory is readonly; if the export file already
exists) will be the same as the standard interface openness export. The Snapshot Service will be
supported for Global DBs, Instance DBs and Array DBs.

Note
Export of snapshot values using the Snapshot Service is independent of the standard interface
openness export and therefore will not influence the already existing export of the interface
members. It will not be possible to import the exported XML

Openness: API for automation of engineering workflows


954 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

The snapshot values will be exported as following:

<?xml version="1.0" encoding="utf-8"?>


<Document>
<Engineering version="V15 SP1" />
<DocumentInfo>
...
</DocumentInfo>
<SW.Blocks.InterfaceSnapshot ID="0">
<AttributeList>
<Name>GlobalDB</Name>
<Snapshot ReadOnly="true">
<SnapshotValues>
<Value Path="Static_1" Type="Bool">TRUE</Value>
<Value Path="Static_2[0]" Type="Int">1</Value>
<Value Path="Static_2[1]" Type="Int">2</Value>
<Value Path="Static_2[2]" Type="Int">3</Value>
<Value Path="Static_3" Type="DTL">DTL#1973-01-01-00:00:00</Value>
<Value Path="Static_4.Element_1" Type="Int">7</Value>
<Value Path="Static_4.Element_2[0]" Type="Bool">FALSE</Value>
<Value Path="Static_4.Element_2[1]" Type="Bool">TRUE</Value>
<Value Path="Static_4.Element_2[2]" Type="Bool">TRUE</Value>
<Value Path="Static_4.Element_3.Element_1" Type="Int">5</Value>
<Value Path="Static_4.Element_3.Element_2.Element_1" Type="Bool">TRUE</Value>
<Value Path="Static_4.Element_3.Element_2.Element_2[0]" Type="Int">100</Value>
<Value Path="Static_4.Element_3.Element_2.Element_2[1]" Type="Int">200</Value>
</SnapshotValues></Snapshot>
<SnapshotDate ReadOnly="true">2017-12-06T08:04:11.4590585Z</SnapshotDate>
<StructureModified ReadOnly="true">2017-12-06T08:22:13.3292585Z</StructureModified>
</AttributeList>
</SW.Blocks.InterfaceSnapshot>
</Document>

If a DB does not contain any snapshot values, the content of the exported file would look like as
following:

<SnapshotValues xlmns="http://www.siemens.com/automation/Openness/SW/Interface/Snapshot/
v1"></SnapshotValues>

See also
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 955
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.4 Exporting blocks with know-how protection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Application
The resulting XML file is similar to the export file of a block without know-how protection. With
PlcBlockProtectionProvider, you can unlock a know-how protected block by providing the
password using the Openness API and then export a KHP block with in complete with its code.
A block can be imported and then be protected with a password using the API again.
If the block is exported without unlocking, only the public block interface will be exported.
• TIA Portal block -> Unlock -> Export file without protection
• Import file without protection -> Lock -> TIA Portal block
The attribute list of the block indicates that the relevant block is know-how protected.

Program code
Modify the following program code to export the visible data of a block with know-how
protection to an XML file:

private static void ExportBlock(PlcSoftware plcSoftware)


{
PlcBlock plcBlock = plcSoftware.BlockGroup.Blocks.Find("MyBlock");
plcBlock.Export(new FileInfo(string.Format(@”D:\Samples\{0}.xml”, plcBlock.Name)),
ExportOptions.WithDefaults);
}

6.4.1.5 Export/Import of SCL blocks

SCL statements with export XML tags


The export operation of SCL blocks exports its equivalent XML tags based on the type of SCL
statements. This operation supports the SCL networks of SCL statements in LAD/FBD blocks of
SCL statements. The SCL statements are classified as text elements, operands, expressions,
control, etc. The schema SW.PlcBlocks.SCL_v2.xsd is available to support you to process the SCL
block with export XML tags. The SCL block statements with their corresponding exported XML
tags and attributes are given below.

Openness: API for automation of engineering workflows


956 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

New line
New lines in SCL blocks are represented as NewLine XML tag.
• Contains unsigned Num attribute with default value 1.
• Num attribute does not have value 0.
• Supported only for SCL.

SCL block XML tag


<NewLine Num="2" />

Blank
Blank spaces in SCL blocks are respresented as Blank XML tag.
• Contains unsigned Num attribute with default value 1.
• Num attribute does not have value 0.
• Supported only for SCL.
• Does not support Integer attribute available in other languages of STEP 7.

SCL block XML tag


<Blank Num="2"/>

Identation of SCL block statements


In TIA Portal settings, you can modify the identation of SCL code by accessing Options/Settings/
General/Script/text editiors. The following table defines the type of identation based on the ident
mode.

Ident mode Result


None Import operation adds the spaces as available in
the source files.
Paragraph or Smart Import operation adds the specified ident spaces in
the imported file.

Based on the chosen identation, the imported SCL block XML file are idented.

Comment
Single-line and multi-line comments in SCL blocks are represented as LineComment XML tag.
• Only LineComment tag (for single language comment) is used in SCL.
• Comment tag (for mulitple language comment) is not used in SCL.
• Contains Inserted attribute with default value false
• Inserted="false" indicates "//" single comment in SCL block.
• Inserted="true" indicates "(**)" multi-line comment in SCL block.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 957
Export/import
6.4 Importing/exporting data of a PLC device

• NoClosingBracket="true" indicates comment without closing braces in SCL block. This


attribute is optional and has default value as false.
• XML does not indicate comment hierarchy in SCL block.

SCL block XML tag


// one line comment <LineComment>
<Text>one line comment</Text>
</LineComment>
(* one line comment <LineComment Inserted="true">
second line *) <Text>one linecomment
secondline</Text>
</LineComment>
(* first comment (* second comment <LineComment Inserted=”true”>
*) end first comment *) <Text> first comment (*
second comment *) end first comment</
Text>
</LineComment >
The nested comment is part of outer comment text.
(* comment without closing bracket <LineComment Inserted="true"
NoClosingBracket="true">
<Text> comment without
closing bracket</Text>
</LineComment >

Region
Regions in SCL blocks are represented as Token XML tag.
• Text XML tag represents the region_name.
• The Text attribute of the Token XML tag is case in-sensitive.
• The import operation is case in-sensitive, and the editor displays the keywords as configured
in the TIA Portal settings.
• If the end_region keyword ends with ";" (semi-colon) in SCL block, the symbol ";" is placed in
Text XML tag.

Openness: API for automation of engineering workflows


958 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


region myregion <Token Text="REGION" />
... <Blank />
end_region here is the end of <Text>myregion</Text>
myregion <NewLine />
...
<Token Text="END_REGION" />
<Blank />
<Text>here is the end of myregion</
Text>
<NewLine />
region <Token Text="REGION" />
// here are no blanks <NewLine />
... <LineComment .../>
end_region <Token Text="END_REGION" />
<NewLine />
region <Token Text="REGION" />
... <NewLine />
end_region; ...
<Token Text="END_REGION" />
<Text>;</Text>
<NewLine />

Pragma
Pragma in SCL blocks are represented as Token XML tag. The parameters are represented in
Access XML tag with Scope attribute as LiteralConstant.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 959
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


{PRAGMA_BEGIN 'Param1', 'Param2' <Token Text="{" />
(*parm 2*)} <Token Text="PRAGMA_BEGIN" />
// something else <Blank />
{PRAGMA_END} <Access Scope="LiteralConstant">
<Constant>
<ConstantValue>'Param1'</
ConstantValue>
</Constant>
</Access>
<Token Text="," />
<Blank />
<Access Scope="LiteralConstant">
<Constant>
<ConstantValue>'Param2'</
ConstantValue>
</Constant>
</Access>
<Blank />
<LineComment Inserted="True">
<Text>param 2</Text>
</LineComment>
<Token Text="," />
<Blank />
<Token Text="}" />
<NewLine />
<LineComment>
<Text> something else</Text>
</LineComment>
<NewLine />
<Token Text="{" />
<Token Text="PRAGMA_END" />
<Token Text="}" />

Constants: Literal constants


The constants in SCL blocks are represented by Access XML tag.
• The Scope attribute can have values like LiteralConstant, TypedConstant, LocalConstant, and
GlobalConstant.
• The name of constants preceeded by "#" are ignored in XML.
• The "#" is added during the import operation of XML.
• The value of global constants represented by quotes are ignored in XML.
• The quotes are added during the import operation of XML.

Openness: API for automation of engineering workflows


960 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Type of constant SCL block XML tag


Literal constant: Integer #Out := 10; <Access Scope="LiteralConstant">
<Constant>
<ConstantValue>10</ConstantValue>
<ConstantTypeInformative="true">LINT</
ConstantType>
</Constant>
</Access>
Literal constant: String #myString := 'Hello <Access Scope="LiteralConstant">
world'; <Constant>
<ConstantValue>Hello world</
ConstantValue>

<ConstantTypeInformative="true">STRING</
ConstantType>
</Constant>
</Access>
Literal constant: Typed #Out := int#10; <Access Scope="TypedConstant">
<Constant>
<ConstantValue>int#10</ConstantValue>
</Constant>
</Access>
Format of XML exported in ExportOptions.ReadOnly setting.

<Access Scope="TypedConstant">
<Constant>
<ConstantValue>int#10</ConstantValue>
<StringAttribute Name="Format"
Informative="true">Dec_signed</
StringAttribute>
<StringAttribute Name="FormatFlags"
Informative="true">TypeQualifier</
StringAttribute>
</Constant>
</Access>
Local constant #Out := #mylocal; <Access Scope="LocalConstant">
<Constant Name="mylocal" />
</Access>
Format of XML exported in ExportOptions.ReadOnly setting.

<Access Scope="LocalConstant">
<Constant Name="mylocal">
<ConstantType Informative="true">Int</
ConstantType>
<ConstantValue Informative="true">10</
ConstantValue>
<StringAttribute Name="Format"
Informative="true">Dec_signed</
StringAttribute>
</Constant>
</Access>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 961
Export/import
6.4 Importing/exporting data of a PLC device

Type of constant SCL block XML tag


Global constant #Out := "myglobal"; <Access Scope="GlobalConstant">
<Constant Name="myglobal" />
</Access>
Format of XML exported in ExportOptions.ReadOnly setting.

<Access Scope="GlobalConstant">
<Constant Name="myglobal">
<ConstantType Informative="true">Int</
ConstantType>
<ConstantValue Informative="true">10</
ConstantValue>
<StringAttribute Name="Format"
Informative="true">Dec_signed</
StringAttribute>
</Constant>
</Access>

The address constants are not supported in SCL blocks, and it is ignored in this table.

Variables
The local and global variables in SCL blocks are represented by Access XML tag.
• The Scope attribute has values of LocalVariable and GlobalVariable
• The XML tags for assigning the value 10 is ignored here.

Type of variable SCL block XML tag


Local variable #Out := 10; <Access Scope="LocalVariable">
<Symbol>
<Component Name="Out" />
</Symbol>
</Access>
Global variable "Tag_3":= 10; <Access Scope="GlobalVariable">
<Symbol>
<Component Name="Tag_3" />
</Symbol>
</Access>
Format of XML exported in ExportOptions.ReadOnly setting.

<Access Scope="GlobalVariable">
<Symbol>
<Component Name="Tag_3" />
<Address Area="Memory" Type="Int"
BitOffset="96" Informative="true" />
</Symbol>
</Access>

Expressions
The simple expressions in SCL blocks are represented by Access XML tag. The Scope attribute has
value of LocalVariable for the expressions

Openness: API for automation of engineering workflows


962 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


#a := #b + #c; <Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
</Symbol>
</Access>
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="b" />
</Symbol>
</Access>
<Blank />
<Token text="+" />
<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="c" />
</Symbol>
</Access>
<Token text=";" />

Control structures in SCL blocks


The control statements like IF, CASE, FOR, WHILE, REPEAT, GOTO, EXIT, CONTINE, and RETURN
are represented by Token XML tag.
• The conditional symbols used in SCL block such as >, <, & are represented as escape
sequences (&lt; &gt; &amp) in XML.
• These combination of XML tags are applicable only for SCL blocks. An exception is thrown for
other languages.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 963
Export/import
6.4 Importing/exporting data of a PLC device

Name of the block SCL block XML tag


IF IF #a<#c THEN <Token Text="IF" />
; <Blank />
END_IF; <Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
</Symbol>
</Access>
<Token Text="&lt;" />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="c" />
</Symbol>
</Access>
<Blank />
<Token Text="THEN" />
<NewLine />
<Blank Num="4" />
<Token Text=";" />
<NewLine />
<Token Text="END_IF" />
<Token Text=";" />

Openness: API for automation of engineering workflows


964 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Name of the block SCL block XML tag


CASE CASE #a OF <Tok en Text="CASE" /><Blank />
1 (*test*): // Statement <Access Scope="LocalVariable">
section case 1 <Symbol>
; <Component Name="a" />
2..4: // Statement section </Symbol>
case 2 to 4 </Access>
; <Blank />
ELSE // Statement section <Token Text="OF" />
ELSE <NewLine />
;
END_CASE; <Blank Num="2"/>
<Access Scope="LiteralConstant">
<Constant>
<ConstantValue>1</ConstantValue>
<ConstantType
Informative="true">LINT</ConstantType>
</Constant>
</Access>
<Blank />
<LineComment Inserted=”true”>
<Text>test</Text>
</LineComment >
<Token Text=":" />
<Blank />
<LineComment>
<Text> Statement section case 1</Text>
</LineComment >
<NewLine />

<Blank Num="4"/>
<Token Text=";" />
<NewLine />

<Blank Num="2"/>
<Access Scope="LiteralConstant">
<Constant>
<ConstantValue>2</ConstantValue>
<ConstantType
Informative="true">LINT</ConstantType>
</Constant>
</Access>
<Token Text=".." />
<Blank Num="2"/>
<Access Scope="LiteralConstant">
<Constant>
<ConstantValue>4</ConstantValue>
<ConstantType
Informative="true">LINT</ConstantType>
</Constant>
</Access>
<Blank />
<LineComment>
<Text> Statement section case 2 to 4</Text>
</LineComment >
<NewLine />

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 965
Export/import
6.4 Importing/exporting data of a PLC device

Name of the block SCL block XML tag

<Blank Num="4"/>
<Token Text=";" />
<NewLine />

<Blank Num="2"/>
<Token Text="ELSE" />
<NewLine />

<Blank Num="4"/>
<Token Text=";" />
<NewLine />

<Token Text="END_CASE" />


<Token Text=";" />
FOR FOR #i := #a TO #b DO <Token Text="FOR" />
// Statement section FOR <Blank />
; <Access Scope="LocalVariable">
END_FOR; <Symbol>
<Component Name="i" />
</Symbol>
</Access>
<Blank />
<Token Text=":=" />
<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
</Symbol>
</Access>
<Blank />
<Token Text="TO" />
<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="b" />
</Symbol>
</Access>
<Blank />
<Token Text="DO" />
<NewLine />

<Blank Num="2" />


<LineComment>
<Text> Statement section FOR</Text>
</LineComment >
<NewLine />

<Blank Num="2" />


<Token Text=";" />
<NewLine />

<Token Text="END_FOR" />


<Token Text=";" />

Openness: API for automation of engineering workflows


966 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Name of the block SCL block XML tag


WHILE WHILE #a<#b DO <Token Text="WHILE" />
// Statement section WHILE <Blank />
; <Access Scope="LocalVariable">
END_WHILE; <Symbol>
<Component Name="a" />
</Symbol>
</Access>
<Token Text="&lt;" />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="b" />
</Symbol>
</Access>
<Blank />
<Token Text="DO" />
<NewLine />

<Blank Num="2" />


<LineComment>
<Text> Statement section WHILE</Text>
</LineComment >
<NewLine />

<Blank Num="2" />


<Token Text=";" />
<NewLine />

<Token Text="END_WHILE" />


<Token Text=";" />

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 967
Export/import
6.4 Importing/exporting data of a PLC device

Name of the block SCL block XML tag


REPEAT REPEAT <Token Text="REPEAT" />
// Statement section REPEAT <NewLine />
;
UNTIL #a<#b END_REPEAT; <Blank Num="2" />
<LineComment>
<Text> Statement section REPEAT</Text>
</LineComment >
<NewLine />

<Blank Num="2" />


<Token Text=";" />
<NewLine />

<Token Text="UNTIL" />


<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
</Symbol>
</Access>
<Token Text="&lt;" />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="b" />
</Symbol>
</Access>
<Blank />
<Token Text="END_REPEAT" />
<Token Text=";" />

Openness: API for automation of engineering workflows


968 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Name of the block SCL block XML tag


GOTO here XML example for GOTO label definition
// well
: // this is goto statement <Blank Num="3"/>
<Access Scope="Label">
<Label Name="here">
<NewLine />
<Blank Num="3"/>
<LineComment>
<Text> well</Text>
</LineComment>
<NewLine />
<Token Text=":" />
<Blank />
</Label>
</Access>
<LineComment>
<Text> this is goto statement</Text>
</LineComment>
GOTO (*comment*) here; XML example for GOTO label usage

<Token Text="GOTO" />


<Blank />
<LineComment inserted=”true”>
<Text>comment</Text>
</LineComment>
<Blank />
<Access Scope="Label">
<Label Name="here" />
</Access>
<Token Text=";" />

Referencing attributes
The SCL block referencing attributes are represented by AccessModifier attribute of Component
tag.
• For simple referencing, AccessModifer has value as Reference.
• For array referencing, AccessModifier has value as ReferenceToArray.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 969
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


RefToUDT^(*RefToUDT*).element <Symbol>
<Component Name="RefToUDT"
AccessModifier="Reference" />
<Token Text="^" />
<LineComment Inserted="True">
<Text>RefToUDT</Text>
</LineComment>
<Token Text="." />
<Component Name="element" />
</Symbol>
RefToArrayOfUDT^(*RefToArrayOfUDT*)[#i].ele‐ <Symbol>
ment <Component Name="RefToArrayOfUDT"
AccessModifier="ReferenceToArray" />
<Token Text="^" />
<LineComment Inserted="True">
<Text>RefToArrayOfUDT</Text>
</LineComment>
<Token Text="[" />
<Access Scope=LocalVariable>
<Symbol>
<Component Name="i" />
</Symbol>
</Access>
<Token Text="]" />
</Component>
<Token Text="." />
<Component Name="element" />
</Symbol>

6.4.1.6 Export/Import of structured types of SCL blocks

SCL structured types with export XML tags


In the SCL structured types, you can add blanks, new lines, and comments in the SCL statements.
The SCL strctured statements with its corresponding exported XML tags and attributes are given
below.

Global access
In SCL statements, the global access variables and constants are represented in quotes. The
comments written between the variables and address parts are represented by LineComment
XML tag.

Openness: API for automation of engineering workflows


970 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


"Data_block_1".(*comment <Access Scope="GlobalVariable">
1*)Static_1(*comment 2*).Static_2 <Symbol>
<Component
Name="Data_block_1" />
<Token Text="." />
<LineComment Inserted="True">
<Text>comment 1</Text>
</LineComment>
<Component Name="Static_1" /
>
<LineComment
Inserted="True">
<Text>comment 2</Text>
</LineComment>
<Token Text="." />
<Component Name="Static_2" /
>
</Symbol>
</Access>
"Data_block_1".Static_1 := 10 Format of XML exported in ExportOptions.None
setting.

<Access Scope="GlobalVariable">
<Symbol>
<Component
Name="Data_block_1" />
<Token Text="." />
<Component Name="Static_1" /
>
</Symbol>
</Access>
Format of XML exported in ExportOptions.ReadOn‐
ly setting.

<Access Scope="GlobalVariable">
<Symbol>
<Component
Name="Data_block_1" />
<Token Text="." />
<Component Name="Static_1" /
>
<Address Area="DB"
Type="Word" BlockNumber="1"
BitOffset="0" Informative="true" />
</Symbol>
</Access>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 971
Export/import
6.4 Importing/exporting data of a PLC device

Usage of Quotes and #


The quotes used in the first level describes the type of variable, and used to escape special
characters in SCL statements. When quotes are used in first level, it defines the variable as global
variable. If the quotes are used after #, they represent the escape sequence of special characters
like #, and spaces.
• To represent the differential usage, XML file uses BooleanAttributes tag with Name attribute.
The Name contain values such as HasQuotes and HasHash.
• To define structure in scope attribute, # is defined.
• These values are applicable only for SCL.
• The default values for these tags were FALSE, but the values never gets exported in
ExportOptions.WithDefaults settings too.

SCL block XML tag


"a".#b."c".#"d" <Access Scope="GlobalVariable">
<Symbol>
<Component Name="a" />
<Token Text="." />
<Component Name="b">
<BooleanAttribute
Name=”HasHash”>TRUE</
BooleanAttribute>
</Component>
<Token Text="." />
<Component Name="c">
<BooleanAttribute
Name=”HasQuotes”>TRUE</
BooleanAttribute>
</Component>
<Token Text="." />
<Component Name="d">
<BooleanAttribute
Name=”HasQuotes”>TRUE</
BooleanAttribute>
<BooleanAttribute
Name=”HasHash”>TRUE</
BooleanAttribute>
</Component>
</Symbol>
<Access />

Array
SCL allows to add comment within the array indexes around "[" and "]". To mark the existence of
array, XML file uses AccessModifier attribute in Component tag.
• If Accessmodifier contains the value Array, then a child tag Access is mandatoy to indicate the
index variable of the array.
• The default value for AccessModifier is None.

Openness: API for automation of engineering workflows


972 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


#a.b[#i+#j,#k+#l].c <Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
<Token Text="." />
<Component Name="b"
AccessModifier="Array" />
<Token Text="[" />
<Access Scope=LocalVariable>
<Symbol>
<Component Name="i" />
</Symbol>
</Access>
<Token Text="+" />
<Access Scope=LocalVariable>
<Symbol>
<Component Name="j" />
</Symbol>
</Access>
<Token Text="," />
<Access Scope=LocalVariable>
<Symbol>
<Component Name="k" />
</Symbol>
</Access>
<Token Text="+" />
<Access Scope=LocalVariable>
<Symbol>
<Component Name="l" />
</Symbol>
</Access>
<Token Text="]" />
</Component>
<Token Text="." />
<Component Name="c" />
</Symbol>
</Access>

Absolute Access
SCL allows different types of access such as absolute, absolute offset, mixed (database and
member variable), slice, peripheral, and direct type. The absolute access specifiers are
represented by Address tag in XML.
• The % character of the DB is not written in XML. It is created automatically during the import.
• Blanks are allowed between the address parts

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 973
Export/import
6.4 Importing/exporting data of a PLC device

SCL Block XML Tag


%DB20 . DBW10 <Access Scope="Address">
<Symbol>
<Address Area="DB"
BlockNumber="20" />
<Blank />
<Token Text="." />
<Blank />
<Address Area="DB"
BitOffset="80" Type="Word"/>
</Symbol>
</Access>
%DB20.DBX10.3 := true; The following XML is valid for all langages except
SCL.

<Access Scope="Address">
<Address Area="DB" BlockNumber="20"
BitOffset="83" Type="Bool" />
</Access>

The following XML is valid for SCL.

<Access Scope="Address">
<Symbol>
<Address Area="DB"
BlockNumber="20" />
<Token Text="." />
<Address Area="DB"
BitOffset="83" Type="Bool"/>
</Symbol>
</Access>

Absolute offset
In STL, AbsoluteOffset tag represents the absolute offset access. In SCL, Address tag is used for
absolute access.

SCL Block XML Tag


#Input_DB_ANY.%DBX2.3 := TRUE; <Access Scope="LocalVariable">
<Symbol>
<Component Name="Input_DB_ANY" /
>
<Token Name="." />
<Address BitOffset="19"
Type="Bool" />
</Symbol>
</Access>

Openness: API for automation of engineering workflows


974 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Slicing
In SCL, the SliceAccessModifier attribute is not supported and the slicing is represented by Token
tag.

SCL Block XML Tag


"tag_1"(*1*).(*2*)member(*3*).(*4*) <Access Scope="GlobalVariable">
%x1 <Symbol>
<Component Name="tag_1" />
<LineComment Inserted="True">
<Text>1</Text>
</LineComment>
<Token Text="." />
<LineComment Inserted="True">
<Text>2</Text>
</LineComment>
<Component Name="member"/>
<LineComment Inserted="True">
<Text>3</Text>
</LineComment>
<Token Text="." />
<LineComment Inserted="True">
<Text>4</Text>
</LineComment>
<Token Text="%x1" />
</Symbol>
</Access>

Peripheral access
The peripheral access is represented by Token tag.

SCL Block XML Tag


"tag_1"(*1*).(*2*)member:P <Access Scope="GlobalVariable">
<Symbol>
<Component Name="tag_1" />
<LineComment Inserted="True">
<Text>1</Text>
</LineComment>
<Token Text="." />
<LineComment Inserted="True">
<Text>2</Text>
</LineComment>
<Component Name="member"/>
<Token Text=":P" />
</Symbol>
</Access>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 975
Export/import
6.4 Importing/exporting data of a PLC device

Direct type access


The TypeOf and TypeOfDB instructions are handled either with system type or user defined type.
The types are represented in Access tag with Scope attribute containing values of SystemType
and UserType.

SCL Block XML Tag


Example for system type <Token text="=" />
if TypeOf( #inVariant ) = </Blank>
TO_SpeedAxis then … end_if <Access Scope="SystemType">
<DataType>TO_SpeedAxis</DataType>
</Access>
Example for user defined type <Token text="=" />
if TypeOf( #inVariant ) = </Blank>
"aUserDefinedType" then … end_if <Access Scope="UserType">
<DataType>aUserDefinedType</
DataType>
</Access>

6.4.1.7 Export/Import of SCL call blocks

SCL call blocks with export XML tags


SCL call paramaters are respresented by Parameter tag in XML. The informative attribute is used
to represent the non-assigned FB parameters and return values such as timestamp, flag
information, etc. The XML format follows the same arbitrary order followed in the SCL block.
An example for block call is given below.

Openness: API for automation of engineering workflows


976 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 977
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


#Callee_Instance(Input_1 := 5); Format of XML exported in ExportOptions.None
setting

<Access Scope="Call">
<CallInfo BlockType="FB">
<Instance
Scope="LocalVariable">
<Component
Name="Callee_Instance" />
</Instance>
<Token text="(" />
<Parameter Name="Input_1">
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="LiteralConstant">
<Constant>
<ConstantType>Int</
ConstantType>
<ConstantValue>5</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Token text=")" />
</CallInfo>
</Access>
<Token text=";" />
Format of XML exported in ExportOptions.ReadOn‐
ly setting

<Access Scope="Call">
<CallInfo BlockType="FB">
<IntegerAttribute
Name="BlockNumber"
Informative="true">1</
IntegerAttribute>
<DateAttribute
Name="ParameterModifiedTS"
Informative="true">2016-10-24T08:27:
34</DateAttribute>
<Instance
Scope="LocalVariable">
<Component
Name="Callee_Instance" />
</Instance>
<Token text="(" />
<Parameter Name="Input_1">
<StringAttribute
Name="InterfaceFlags"
Informative="true">S7_Visible</
StringAttribute>
<Blank />
<Token text=":=" />

Openness: API for automation of engineering workflows


978 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


<Blank />
<Access Scope="LiteralConstant">
<Constant>
<ConstantType>Int</
ConstantType>
<ConstantValue>5</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Token text=")" />
</CallInfo>
</Access>
<Token text=";" />

Unconnected parameters example


The FB has 4 paramters where a, b, c, and d. b and d are not connected.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 979
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


"Block_4_DB"(a:=TRUE,c:=TRUE); <Access Scope="Call">
<CallInfo Name="Block_4"
BlockType="FB">
<Instance
Scope="GlobalVariable">
<Component Name="Block_4_DB" /
>
</Instance>
<Token text="(" />
<Parameter Name="a">
<Token text=":=" />
<Access
Scope="LiteralConstant">
<Constant>
<ConstantType>Bool</
ConstantType>
<ConstantValue>TRUE</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Token text="," />
<Parameter Name="b"
Informative="true"/>
<Parameter Name="c" >
<Token text=":=" />
<Access
Scope="LiteralConstant">
<Constant>
<ConstantType>Bool</
ConstantType>
<ConstantValue>True</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Parameter Name="d"
Informative="true"/>
<Token text=")" />
</CallInfo>
</Access>

One parameter example


SCL block allows you to omit the parameter name. This parameter is represented as
NamelessParameter tag. The NamelessParameter tag has no attributes and it is applicable only
for SCL.

Openness: API for automation of engineering workflows


980 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


"Block_4_DB"(TRUE); <Access Scope="Call">
<CallInfo Name="Block_4"
BlockType="FB">
<Instance
Scope="GlobalVariable">
<Component Name="Block_4_DB" /
>
</Instance>
<Token text="(" />
<NamelessParameter>
<Access
Scope="LiteralConstant">
<Constant>
<ConstantType>Bool</
ConstantType>
<ConstantValue>TRUE</
ConstantValue>
</Constant>
</Access>
</NamelessParameter>
<Token text=")" />
</CallInfo>
</Access>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 981
Export/import
6.4 Importing/exporting data of a PLC device

Expression as actual parameter

SCL block XML tag


#Callee_Instance(Input_1 := #a+3); <Access Scope="Call">
<CallInfo BlockType="FB">
<Instance
Scope="LocalVariable">
<Component
Name="Callee_Instance" />
</Instance>
<Token text="(" />
<Parameter Name="Input_1">
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
</Symbol >
</Access>
<Token text="+" />
<Access
Scope="LiteralConstant">
<Constant>
<ConstantType>Int</
ConstantType>
<ConstantValue>3</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Token text=")" />
</CallInfo>
</Access>
<Token text=";" />

Openness: API for automation of engineering workflows


982 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Expression as actual parameter without formal paramter

SCL block XML tag


#Callee_Instance(#a+3); <Access Scope="Call">
<CallInfo BlockType="FB">
<Instance Scope="LocalVariable">
<Component
Name="Callee_Instance" />
</Instance>
<Token text="(" />
<NamelessParameter>
<Access Scope="LocalVariable">
<Symbol>
<Component Name="a" />
</Symbol >
</Access>
<Token text="+" />
<Access
Scope="LiteralConstant">
<Constant>
<ConstantType>Int</
ConstantType>
<ConstantValue>3</
ConstantValue>
</Constant>
</Access>
</NamelessParameter>
<Token text=")" />
</CallInfo>
</Access>
<Token text=";" />

Function call

SCL block XML tag


#myInt := "MyFunction"(Param_1 := 1, <Access Scope="LocalVariable">
Param_2 := 15, Param_3 := TRUE); <Symbol>
<Component Name="myInt" />
</Symbol>
</Access>
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="Call">
<CallInfo Name="MyFunction"
BlockType="FC">
<Token text="(" />
<Parameter Name="Param_1">
...

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 983
Export/import
6.4 Importing/exporting data of a PLC device

Absolute call
In SCL, the call can be initiated using absolute address of the DB. Due to absolute address, the
Name attriubute of CallInfo node is empty.
A recoverable exception is thrown by the import of
• An "Address" node is available, with valid value of Name attribute.
• Non-existence of Address node with no valid value of Name attribute.

SCL block XML tag


%DB20(...); <Access Scope="Call">
<CallInfo Name="" BlockType="FB">
<Instance
Scope="GlobalVariable">
<Address Area="DB"
BlockNumber="20" />
</Instance>
<Token text="(" />
<Parameter>

</Parameter>
<Token text=")" />
</CallInfo>
</Access>

Instruction
The instruction in SCL block is checked in system library during the import operation, and the
instruction versions are not exported in export operation.
The general instruction type is given below.

Openness: API for automation of engineering workflows


984 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 985
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


#myInt := ATTACH(OB_NR := 1, Format of XML exported in ExportOptions.ReadOn‐
EVENT := 15, ADD := TRUE); ly setting

<Access Scope="LocalVariable">
<Symbol>
<Component Name="myInt" />
</Symbol>
</Access>
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="Call">
<Instruction Name="ATTACH">
<Token text="(" />
<Parameter Name="OB_NR">
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="LiteralConstant">
<Constant>
<ConstantType>OB_ATT</
ConstantType>
<ConstantValue>1</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Token text="," />
<Blank />
<Parameter Name="EVENT">
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="LiteralConstant">
<Constant>
<ConstantType>EVENT_ATT</
ConstantType>
<ConstantValue>15</
ConstantValue>
</Constant>
</Access>
</Parameter>
<Token text="," />
<Blank />
<Parameter Name="ADD">
<Blank />
<Token text=":=" />
<Blank />
<Access Scope="LiteralConstant">
<Constant>
<ConstantType>Bool</
ConstantType>
<ConstantValue>TRUE</
ConstantValue>

Openness: API for automation of engineering workflows


986 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


</Constant>
</Access>
</Parameter>
<Parameter Name="RET_VAL"
Informative="true" />
<Token text=")" />
</Instruction>
</Access>
<Token text=";" />

Instruction with template


When the template parameter is complements the instruction name, the export of the template
parameter is necessary. If a "TemplateValue" tag with attribute Type="Type" follows the
Instruction tag, the import operation concatenates the template value to the instruction name.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 987
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


"tag_4" := MIN_DINT( IN1:="Tag_1", <Access Scope="GlobalVariable">
IN2:="Tag_2", IN3:="Tag_3" ); <Symbol>
<Component Name="Tag_4" />
</Symbol>
</Access>
...
<Access Scope="Call">
<Instruction Name="MIN">
<TemplateValue
Name="value_type" Type="Type">DInt</
TemplateValue>
...
<Parameter Name="IN1">
...
<Access Scope="GlobalVariable">
<Symbol>
<Component Name="Tag_1" />
</Symbol>
</Access>
</Parameter>
...
<Parameter Name="IN2">...
<Access Scope="GlobalVariable">
<Symbol>
<Component Name="Tag_2" />
</Symbol>
</Access>
</Parameter>
...
<Parameter Name="IN3">
...
<Access Scope="GlobalVariable">
<Symbol>
<Component Name="Tag_3" />
</Symbol>
</Access>
</Parameter>
...
</Instruction>
</Access>
...

Conversion
For conversion functions, the real instruction name and its template values are not exported.
Instead, the name used in the SCL block is exported.

Openness: API for automation of engineering workflows


988 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


#output_1 := <Access Scope="LocalVariable">
TIME_TO_S5TIME(#input_1); <Symbol>
<Component Name="output_1" />
</Symbol>
</Access>
...
<Access Scope="Call">
<Instruction
Name="TIME_TO_S5TIME">
<Token text="(" />
<NamelessParameter>
<Access Scope="LocalVariable">
<Symbol>
<Component Name="input_1" /
>
</Symbol>
</Access>
</NamelessParameter>
<Token text=")" />
</Instruction>
</Access>
...

Instruction with instance


The instance and instruction are separated by blanks. Blanks are optional, and they can
represented by new lines and comments. The instruction TON is represented by Name attribute
of Instruction tag.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 989
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


IEC_Timer_0_DB . TON (IN:="Tag_1", <Access Scope="GlobalAccess">
PT:="Tag_2"); <Symbol>
<Component
Name="IEC_Timer_0_DB" />
</Symbol >
</Access>
<Blank />
<Token text="." />
<Blank />
<Access Scope="Call">
<Instruction Name="TON">
<Blank />
<Token text="(" />
<Parameter Name="IN">
<Access Scope="GlobalVariable">
<Symbol>
<Component Name="Tag_1" />
</Symbol>
</Access>
</Parameter>
...
<Token text=")" />
</Instruction>
</Access>
<Token text=";" />

Alarm constant
The alarm constants are only used in S7 400 PLCs, and the exported XML is similar to other
languages.

Openness: API for automation of engineering workflows


990 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

SCL block XML tag


"Block_1_DB"(16#0000_0001); Format of XML exported in
ExportOptions.None setting

<Access Scope="Call">
<CallInfo Name="Block_1"
BlockType="FB">
<Instance Scope="GlobalVariable">
<Component Name="Block_1_DB" />
</Instance>
<NamelessParameter>
<Access Scope="AlarmConstant">
<Constant>
<ConstantType>C_Alarm_8</
ConstantType>

<ConstantValue>16#0000_0001</
ConstantValue>
</Constant>
</Access>
</NamelessParameter >
</CallInfo>
</Access>
Format of XML exported in ExportOptions.ReadOn‐
ly setting

<Access Scope="Call">
<CallInfo Name="Block_1"
BlockType="FB">
<Instance Scope="GlobalVariable">
<Component Name="Block_1_DB" />
</Instance>
<NamelessParameter>
<Access Scope="AlarmConstant" >
<Constant>
<ConstantValue>16#00000001</
ConstantValue>
<ConstantType>C_Alarm</
ConstantType>
<StringAttribute
Name="Format"
Informative="true">Hex</
StringAttribute>
</Constant>
</Access>
</NamelessParameter>
</CallInfo>
</Access>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 991
Export/import
6.4 Importing/exporting data of a PLC device

ENO (Enable Output)


To support the ENO construct in SCL block, an attribute named "Scope" with value
"PredefinedVariable" is used in the "Access" tag. It also contains the "PredefinedVariable" tag as
child of the Access tag.
• The "PredefinedVariable" tag has one mandatory "Name" attribute.
• The scope "PredefinedVariable" and the tag "PredefinedVariable" are only allowed for SCL.

SCL block XML tag


Call(…, ENO => ENO); <Access Scope="Call">
<CallInfo BlockType="FC">
<Token text="(" />

<Token text="," />
<Blank />
<Parameter Name="ENO">
<Blank />
<Token text="=>" />
<Blank />
<Access
Scope="PredefinedVariable">
<PredefinedVariable
Name="ENO" />
</Access>
</Parameter>
<Token text=")" />
</CallInfo>
</Access>
<Token text=";" />
IF ENO = #c THEN … <Token text="IF" />
<Blank />
<Access Scope="PredefinedVariable">
<PredefinedVariable Name="ENO" />
</Access>
<Blank />
<Token Text="=" />
<Blank />
<Access Scope="LocalVariable">
<Symbol>
<Component Name="c" />
</Symbol>
</Access>
<Blank />
<Token Text="THEN" />

Openness: API for automation of engineering workflows


992 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.8 Export/Import multilingual comments in SCL

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
It is possible in TIA Portal Openness to support import and export multilingual comments in SCL
editor by the following ways:
• During SCL export in Openness, all the multilingual comments with its translation, according
to enabled project languages, are exported into the same openness xml file.
• During SCL import in Openness, all the multilingual comments with its translation, according
to enabled project languages, shall be imported back from the openness xml file. It shall be
reflected in the project text area. The language gets enabled in if the language is not enabled
in the project during import.
• After import, it shall be verified that all multilingual comment in SCL editor is liked to the
appropriate comments in the project text.

Example
The following figure shows an example of Multilingual comment in SCL Editor:

The following figure shows an example for export of multilingual comment in openness XML file:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 993
Export/import
6.4 Importing/exporting data of a PLC device

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.9 Exporting failsafe blocks

Exporting failsafe blocks


It is now possible to import and export the Failsafe blocks, but F-system blocks cannot be
exported.

Importing failsafe blocks


Consistent F-blocks can be exported and re-imported. They will be created as F-blocks.
It will be imported as standard block if you remove the prefixes "F_" from the value of all
attributes "ProgrammingLanguage".

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)
Exporting blocks (Page 998)
Exporting blocks with know-how protection (Page 956)

6.4.1.10 Exporting system blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The project contains a system block.
• The system block is not a F-block
• PLC is not online.

Openness: API for automation of engineering workflows


994 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Application
Only visible system blocks will be available in the blocks composition, e.g. no SFBs or SFCs. The
resulting XML file is similar to the export file of a block.

Program code
Modify the following program code to export the visible data of a block to an XML file:

//Exports system blocks


private static void ExportSystemBlocks(PlcSoftware plcsoftware)
{
PlcSystemBlockGroup sbSystemGroup = plcsoftware.BlockGroup.SystemBlockGroups[0];
foreach (PlcSystemBlockGroup group in sbSystemGroup.Groups)
{
foreach (PlcBlock block in group.Blocks)
{
block.Export(new FileInfo(string.Format(@”D:\Samples\{0}.xml”, block.Name)),
ExportOptions.WithDefaults);
}
}
}

6.4.1.11 Exporting GRAPH blocks with multi-language text

XML structure of GRAPH blocks with multi-language text


The export XML for GRAPH blocks contains the translated step names and transition names of
the GRAPH. These translated multi-language text are represented as StepName and
TransitionName elements under the parent element Step and Transition respectivelty. These
elements contain one MultiLanguageText element for each supported language. The texts for
the languages which are not set explicitly are not exported. If no translation is made, the
StepName and TransitionName elements are not exported. The StepName and TransitionName
elements are optional. The TIA Portal Openness XML import operation throws a recoverable
exception for the graph versions < V5.0.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 995
Export/import
6.4 Importing/exporting data of a PLC device

Example for StepName element

<Steps>
<Step Number="1" Init="true" Name="Step1" MaximumStepTime="T#10S" WarningTime="T#7S">
<StepName>
<MultiLanguageText Lang="de-DE">stepDE</MultiLanguageText>
<MultiLanguageText Lang="en-US">stepEN</MultiLanguageText>
<MultiLanguageText Lang="it-CH">stepIT</MultiLanguageText>
</StepName>
..
</Step>
..
</Steps>

Example for TransitionName element

<Transitions>
<Transition IsMissing="false" Name="Trans1" Number="1" ProgrammingLanguage="LAD">
<TransitionName>
<MultiLanguageText Lang="de-DE">transDE</MultiLanguageText>
<MultiLanguageText Lang="en-US">transEN</MultiLanguageText>
<MultiLanguageText Lang="it-CH">transIT</MultiLanguageText>
</TransitionName>
..
</Transition>
..
</Transitions>

6.4.1.12 Importing block

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Openness: API for automation of engineering workflows


996 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Application
The TIA Portal Openness API supports the import of blocks with "LAD", "FBD", "GRAPH", "SCL" or
"STL" programming languages from an XML file. The following block types are supported:
• Function blocks (FB)
• Functions (FC)
• Organization blocks (OB)
• Global data blocks (DB)

Note
Importing optimized data blocks
Optimized data blocks are only supported by CPUs as of S7-1200. If you import optimized data
blocks into S7-300 or S7-400, an exception is thrown and the import fails.

Response to importing
The following rules apply when importing a block:
• The XML file can contain less data than the block in the project, e.g., fewer parameters.
• Redundant information, such as call information, must be identical in the project and in the
XML file. Otherwise, an exception is thrown.
• The data in the XML file may be "inconsistent" regarding their ability to be compiled in the TIA
Portal.
• Attributes with the attributes "ReadOnly=True" and "Informative=True" are not imported.
• Missing instance DBs are not created automatically.
• If no block number is specified in the xml file, the block number is assigned automatically.
• If the block is not existing in the project and no version information is specified in the xml
file, the version "0.1" is assigned.

Program code
Modify the following program code:

//Import blocks
private static void ImportBlocks(PlcSoftware plcSoftware)
{
PlcBlockGroup blockGroup = plcSoftware.BlockGroup;
IList<PlcBlock> blocks = blockGroup.Blocks.Import(new FileInfo(@"D:\Blocks
\myBlock.xml"), ImportOptions.Override);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 997
Export/import
6.4 Importing/exporting data of a PLC device

Modify the following program code:

//Import system blocks


private static void ImportSystemBlocks(PlcSoftware plcSoftware)
{
PlcBlockSystemGroup systemblockGroup = plcSoftware.BlockGroup;
IList<PlcBlock> blocks = systemblockGroup.Blocks.Import(new FileInfo(@"D:\Blocks
\myBlock.xml"), ImportOptions.Override);
}

6.4.1.13 Exporting blocks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Application
The API interface supports exporting consistent blocks and user data types to an XML file.
The XML file receives the name of the block. The following block types are supported:
• Function blocks (FB)
• Functions (FC)
• Organization blocks (OB)
• Global data blocks (DB)
The following programming languages are supported:
• STL
• FBD
• LAD
• GRAPH
• SCL

Attributes applicable for all blocks


The following attributes are exported in all blocks with the selected ExportOptions
(see Exporting configuration data (Page 884)). Attributes in bold typeface are always exported.
Additional information is available in the TIA Portal information system under "Overview of block
attributes".

Openness: API for automation of engineering workflows


998 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Attribute Type Default value ReadOnly


AutoNumber Bool true false
CodeModifiedDate DateTime - true
CompileDate DateTime - true
CreationDate DateTime - true
HeaderAuthor String "" false
HeaderFamily String "" false
HeaderName String "" false
HeaderVersion String "0.1" false
Interface String empty interface false
InterfaceModifiedDate DateTime - true
IsConsistent Bool - true
IsKnowHowProtected 1
Bool false true
IsWriteProtected Bool false true
MemoryLayout enum MemoryLayout - false
ModifiedDate DateTime - true
Name String - false
Number Int32 next available number false
ParameterModified DateTime - true
PLCSimAdvancedSupport Bool false true
ProgrammingLanguage enum ProgrammingLan‐ - false
guage
StructureModified DateTime - true
1
The IsKnowHowProtected attribute is applicable for UDT too.

Note
There are certain conditions where MemoryLayout attribute can be readonly.

Dynamic accessible general attribributes


The following attributes which can be read only in some conditions:

Attribute ReadOnly condition


AutoNumber All KnowHowProtected blocks, All Classic OBs; Plus OBs: DiagnosticErrorInterrupt, IOAccessError, Program‐
mingError, PullOrPlugOfModules, RackOrStationFailure, Status, TimeErrorInterrupt, Update
HeaderVersion System- and KnowHowProtected DBs; ArrayDBs that originated from system library
HeaderName
HeaderFamily
HeaderAuthor
MemoryLay‐ Classic blocks, System Know how protected blocks, ArrayDBs, IDBofFBs, Graph blocks
out

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 999
Export/import
6.4 Importing/exporting data of a PLC device

Attributes applicable for ArrayDB block


The following attributes are exported for ArrayDB block with the selected ExportOptions.

Attribute Type Default value ReadOnly


ArrayDataType String - true
ArrayLimitUpperBound Int32 - true

Attributes applicable for DB block


The following attributes are exported in DB block with the selected ExportOptions.

Attribute Type Default value ReadOnly


IsOnlyStoredInLoadMemory Bool false false
IsPLCDB Bool false false
IsWriteProtectedInAS Bool false false

Attributes applicable for FB block


The following attributes are exported for FB blocks with the selected ExportOptions.

Attribute Type Default value ReadOnly


AssignedProDiagFB String - -
ISMultiInstanceCapable Bool - true
Supervisions String no supervisions true for IDB of FB and false for
FB

Attributes applicable for DB and FB blocks


The following attributes are exported in DB and FB block with the selected ExportOptions.

Attribute Type Default value ReadOnly


IsIECCheckEnabled Bool false false
IsRetainMemResEnabled 1
Bool false false
MemoryReserve Unsigned 0 false
RetainMemoryReserve 2
Unsigned 0 false
2
If the "IsRetainMemResEnabled" attribute's value is "false", and the "RetainMemoryReserve" attribute is not equal to "0", an
exception is thrown.

Openness: API for automation of engineering workflows


1000 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Attributes applicable for FB, DB and IDB blocks


The following attributes are exported in FB, DB, and IDB blocks with the
selected ExportOptions.

Attribute Type Default value ReadOnly


DownloadWithoutReinit Bool false true

Attributes applicable for FB and FC blocks


The following attributes are exported for FB and FC block with the selected ExportOptions.

Attribute Type Default value ReadOnly


LibraryType String - true
LibraryTypeVersionGuid String - true

Attributes applicable for FB and FC (STL) blocks


The following attributes are exported for FB and FC (STL) block with the
selected ExportOptions.

Attribute Type Default value ReadOnly


ParameterPassing Bool false false

Attributes applicable for FB, FC and instance DB of an FB block


The following attributes are exported for FB, FC and instance DB of an FB block with the
selected ExportOptions.

Attribute Type Default value ReadOnly


UDABlockProperties String "" false
UDAEnableTagReadback Bool false false

Attributes applicable for instance DB of FB and UDT


The following attributes are exported for instance DB of FB and UDT block with the
selected ExportOptions.

Attribute Type Default value ReadOnly


InstanceOfName String "" false
InstanceOfNumber Unsigned Short - true
InstanceOfType enum BlockType - true

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1001
Export/import
6.4 Importing/exporting data of a PLC device

Attribute Type Default value ReadOnly


OfSystemLibElement String "" false
OfSystemLibVersion String "" false

Attributes applicable for OB block


The following attributes are exported in OB block for specific Plus PLCs with the
selected ExportOptions.

Attribute Type Default value ReadOnly


ApplicationCycle Single - true
AutomaticMinimum Bool - true
ConstantName String - true
CycleTimeDistributedIO Single - true
CyclicApplicationCycleTime Single - true
CyclicTime Int32 100000 true
DataExchangeMode OBDataExchangeMode Cyclic true
DelayTime Double - true
DistributedIOName String - true
DistributedIONumber Int32 - true
EnableTimeError Bool - true
EventClass String - true
EventsToBeQueued Int32 - true
EventThresholdForTimeError Int32 - true
Execution OBExecution Never true
Factor Single - true
PhaseOffset Int32 0 true
PriorityNumber Int32 - true
ProcessImagePartNumber UInt32 - true
ReportEvents Bool - true
SecondaryType 3
String - false
StartDate DateTime 1/1/2012 true
SynchronousApplicationCy‐ Single - true
cleTime
TimeMode OBTimeMode System true
TimeOfDay DateTime 12:00 AM true
TransformationDBNumber UInt16 0xffff true
3
When exporting an OB, the "SecondaryType" is additionally set based on the OB number. The assignment is checked during
import. If the assignment is incorrect, an exception of type "Recoverable" is thrown.

Attributes applicable for FB, FC and OB blocks


The following attributes are exported for FB, FC and OB block with the
selected ExportOptions.

Openness: API for automation of engineering workflows


1002 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Attribute Type Default value ReadOnly


HandleErrorsWithinBlock Bool false true

Attributes applicable for FB, FC and UDT blocks


The following attributes are exported for FB, FC and UDT block with the
selected ExportOptions.

Attribute Type Default value ReadOnly


LibraryConformanceStatus String - false

Attributes applicable for GRAPH block


The following attributes are exported for GRAPH block with the selected ExportOptions.

Attribute Type Default value ReadOnly


AcknowledgeErrorsRequired Bool true false
CreateMinimizedDB Bool false false
ExtensionBlockName String - -
GraphVersion String - false
InitialValuesAcquisition String - -
LanguageInNetworks String - false
LockOperatingMode Bool false false
PermanentILProcessingIn‐ Bool false false
MANMode
SkipSteps Bool false false

Attributes applicable for GRAPH FB block


The following attributes are exported for GRAPH FB block with the selected ExportOptions.

Attribute Type Default value ReadOnly


WithAlarmHandling Bool true false

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1003
Export/import
6.4 Importing/exporting data of a PLC device

Attributes applicable for SCL block


The following attributes are exported for SCL blocks with the selected ExportOptions. These
attribues are exported based on the type of PLCs.

Attribute Type Default value ReadOnly


CheckArrayLimits Bool false false
ExtendedStatus Bool false false
DBAccessibleFromOPCUA Bool true false

Attributes applicable for GRAPH, SCL, and LAD/FBD blocks


The following attributes are exported for GRAPH, SCL, and LAD/FBD blocks with the
selected ExportOptions.

Attribute Type Default value ReadOnly


SetENOAutomatically Bool - false

Attributes applicable for program blocks (except OB), DB, and UDT blocks
The following attributes are exported for program blocks (except OB), DB, and UDT blocks under
a unit with the selected ExportOptions.

Attribute Type Default value ReadOnly


Access UnitAccessType Unpublished false

For Import behavior for the attribute 'Access'

Imported under unit Imported not under unit Imported not under unit
(without SWImportOp‐ (with SWImportOptions.Ig‐
tions.IgnoreUnitAttributes) noreUnitAttributes)
XML exported from under unit 'Access' used and set RecoverableException is 'Access' ignored
thrown
XML exported from not under 'Access' gets its default value 'Access' doesn't exist 'Access' doesn't exist
unit

Openness: API for automation of engineering workflows


1004 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Program code
Modify the following program code to export a block without know-how protection to an XML
file:

//Exports a regular block


private static void ExportRegularBlock(PlcSoftware plcSoftware)
{
PlcBlock plcBlock = plcSoftware.BlockGroup.Blocks.Find("MyBlock");
plcBlock.Export(new FileInfo(string.Format(@”D:\Samples\{0}.xml”, plcBlock.Name)),
ExportOptions.WithDefaults);
}

6.4.1.14 Importing blocks/UDT with open reference

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is not online

Application
Using Openness API, you can use a new import mode for STEP7 objects to import blocks and
UDTs even if a related object is missing.
The Openness interface supports the new import mode for the following conditions:

Import of Object reference


UDT UDT
DB (global) UDT
IDBofUDT UDT
IDBofFB FB
ArrayDB Array of UDT
FB UDT (interface), Multi-instance
FC UDT (Interface)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1005
Export/import
6.4 Importing/exporting data of a PLC device

Program code
You can use the new mode by a new overload of the respective Import method. The new
overload has an additional parameter which accepts a value of the new flagged enum
SWImportOptions. To allow the import, you can use
SWImportOptions.IgnoreMissingReferencedObject, even if the referenced object is missing.

Flagged Enum SWImportOptions


{
None = 0,
IgnoreStructuralChanges = 1,
IgnoreMissingReferencedObjects = 2
}
... // All kinds of blocks
PlcBlockComposition.Import(file, ImportOptions.None,
SWImportOptions.IgnoreMissingReferencedObject);
...
... // UDTs
PlcTypeComposition.Import(file, ImportOptions.None,
SWImportOptions.IgnoreMissingReferencedObject);
...

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.15 Importing blocks/UDT for structural change object

Requirement

• The TIA Portal Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is not online

Application
Using Openness API, you can import blocks and UDTs even if instance data is lost because of a
structural change of related objects.
The Openness interface supports the new import mode for the following conditions:

Import of Object references


Tag UDT
UDT UDT

Openness: API for automation of engineering workflows


1006 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Import of Object references


DB (global) UDT
IDBofUDT UDT
IDBofFB FB
ArrayDB Array of UDT
FB UDT (interface), Multi-instance
FC UDT (Interface)

Program code
You can use new mode by a new overload of the respective Import method. The new overload
has an additional parameter which accepts a value of the new flagged enum SWImportOptions.
To allow the import althoughthere are structural change and maybe a data loss using
"SWImportOptions.IgnoreStructuralChanges".

Flagged Enum SWImportOptions


{
None = 0,
IgnoreStructuralChanges = 1,
IgnoreMissingReferencedObjects = 2
}
...
// All kinds of blocks
PlcBlockComposition.Import(file, ImportOptions.None,
SWImportOptions.IgnoreStructuralChanges);
...
...
// UDTs
PlcTypeComposition.Import(file, ImportOptions.None,
SWImportOptions.IgnoreStructuralChanges);
...

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1007
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.16 Export/Import of unit specific publishing attribute of blocks and types

Requirement
• The TIA Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
The 'Access' attribute exists only for blocks, plc types, and tag tables located under a unit.
therefore the exported XML will contain it. The exported XML of the same block, type, or tag
table located in non-unit environment won't contain it.
The general Openness XML import rules won't allow importing XMLs containing unknown/
undefined attributes. Because of this rule the exported XMLs originated from object in a unit
environment cannot be imported in a non-unit environment. This would be a huge limitation in
the usage therefore a following extension is defined.
The import () method has an overload to pass three parameters. The following are the these
parameters:

Parameter Return type Description


path String Specifies the path to the
Simatic ML file to be im‐
ported
importOptions enum: Siemens.Engineering.ImportOptions Specifies the general im‐
port option(s) to be used
during import.
swImportOptions enum: Siemens.Engineering.SW.SWImportOptions Specifies the import op‐
tion(s) specific to Step7 to
be used during import.

The enum type Siemens.Engineering.SW.SWImportOptions will be extended with the following


new import option:
• IgnoreUnitAttributes: specifies that the import process shouldn’t be aborted in case of unit
related attributes are present in the XML and the import is performed in a non-unit
environment.
The 'IgnoreUnitAttributes' is only taken into consideration when the XML
• Is exported from a unit
• contains the 'Access' attribute
• Is imported into non-unit environment
If the exported XML doesn’t contain the ‘Access’ Openness attribute and / or it is imported into
a unit the new import option won’t be considered by the import logic at all.

Openness: API for automation of engineering workflows


1008 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Program code:

PlcSoftware plcTarget = GetControllerTargetByPLCName(Session.OpnsProject.Devices, PLCName);


PlcUnitProvider plcUnitProvider = plcTarget.GetService<PlcUnitProvider>();
PlcSoftware plcSoftware = plcTarget.GetService<SoftwareContainer>() as PlcSoftware;
PlcUnit plcUnit1 = plcUnitProvider.UnitGroup.Units[0];
//assuming Unit_1 is already existing
PlcUnit plcUnit2 = plcUnitProvider.UnitGroup.Units[1];
//assuming Unit_2 is already existing
PlcBlock block1 = plcUnit1.BlockGroup.Blocks.Find("Block_1");
//assuming Block_1 is already existing under Unit_1
PlcBlock block2 = plcUnit2.BlockGroup.Blocks.Find("Block_2");
//assuming Block_2 is already existing under Unit_2
PlcBlock block3 = plcSoftware.BlockGroup.Blocks.Find("Block_3");
//assuming Block_3 is already existing under the PLC

Program code: Object exported from a unit and imported into a unit
The examples below are demonstrating the behavior of the new import option by using blocks,
the same applies for plc types and tag tables as well.
Modify the following program code to export a block with ‘Access’ attribute set to value
‘Unpublished’ (default value) with ExportOptions.WithDefaults and import with
SWImportOptions.None:

block1.SetAttribute("Access", UnitAccessType.Unpublished);
block1.Export(new FileInfo("somepath"), ExportOptions.WithDefaults);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.None);

Modify the following program code to export a block with ‘Access’ attribute set to value
‘Unpublished’ (default value) with ExportOptions.WithDefaults and import with
SWImportOptions.IgnoreUnitAttributes:

block1.SetAttribute("Access", UnitAccessType.Unpublished);
block1.Export(new FileInfo("somepath"), ExportOptions.WithDefaults);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.IgnoreUnitAttributes);

Modify the following program code to export a block with 'Access' attribute set to value
'Published' with ExportOptions.None and import with SWImportOptions.None:

block1.SetAttribute("Access", UnitAccessType.Published);
block1.Export(new FileInfo("somepath"), ExportOptions.None);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.None);

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1009
Export/import
6.4 Importing/exporting data of a PLC device

Modify the following program code to export a block with 'Access' attribute set to value
'Published' with ExportOptions.None and import with SWImportOptions.IgnoreUnitAttributes:

block1.SetAttribute("Access", UnitAccessType.Published);
block1.Export(new FileInfo("somepath"), ExportOptions.None);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.IgnoreUnitAttributes);

Note
In all of the above program codes, No exception is thrown, and import succeeds.

Program code: Object exported from a unit and imported into non-unit environment
Modify the following program code to export a block with 'Access' attribute set to value
'Unpublished' (default value) with ExportOptions.WithDefaults and import with
SWImportOptions.None:

block1.SetAttribute("Access", UnitAccessType.Unpublished);
block1.Export(new FileInfo("somepath"), ExportOptions.WithDefaults);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.None);

Note
In the above program code, Import does not succeed and a Recoverable Exception is thrown,

Modify the following program code to export a block with ‘Access’ attribute set to value
‘Unpublished’ (default value) with ExportOptions.WithDefaults and import with
SWImportOptions.IgnoreUnitAttributes:

block1.SetAttribute("Access", UnitAccessType.Unpublished);
block1.Export(new FileInfo("somepath"), ExportOptions.WithDefaults);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.IgnoreUnitAttributes);

Note
In the above program code, import succeed and No exception is thrown.

Openness: API for automation of engineering workflows


1010 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Modify the following program code to export a block with 'Access' attribute set to value
'Published' with ExportOptions.None and import with SWImportOptions.None:

block1.SetAttribute("Access", UnitAccessType.Published);
block1.Export(new FileInfo(„somepath"), ExportOptions.None);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.None);

Note
In the above program code, Import succeed and a Recoverable exception is thrown.

Modify the following program code to export a block with ‘Access’ attribute set to value
‘Published’ with ExportOptions.None and import with SWImportOptions.IgnoreUnitAttributes:

block1.SetAttribute("Access", UnitAccessType.Published);
block1.Export(new FileInfo(„somepath"), ExportOptions.None);
block1.Delete();
plcUnit2.BlockGroup.Blocks.Import(new FileInfo("somepath"), ImportOptions.None,
SWImportOptions.IgnoreUnitAttributes);

Note
In the above program code, No exception is thrown and import succeed.

Object exported from non-unit environment into a unit


The exported XML doesn’t contain the ‘Access’ Openness attribute and when importing it gets
the default value ‘Unpublished’.

Object exported from non-unit environment into non-unit environment


The exported XML doesn't contain the 'Access' Openness attribute and when importing it
nothing happens.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1011
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.17 Creating Instance DB

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is opening
See Opening a Project (Page 113)

Application
You can use the TIA Portal Openness to create instance DB for programming languages such as
SCL, LAD, FBD, STL, Graph, and CEM.

Program code: Creating Instance DB for SCL, LAD, FBD, STL, Graph, & CEM block
Modify the following program code to create Instance DB of SCL block:

plc.BlockGroup.Blocks.CreateInstanceDB("ConveyerDB", true, 5, "Conveyer_SCL_Block");

Modify the following program code to create Instance DB of LAD block:

plc.BlockGroup.Blocks.CreateInstanceDB("RelayDB", true, 6, "Relay_LAD_Block");

Modify the following program code to create Instance DB of FBD block:

plc.BlockGroup.Blocks.CreateInstanceDB("SensorDB", true, 6, "Sensor_FBD_Block);

Modify the following program code to create Instance DB of STL block:

plc.BlockGroup.Blocks.CreateInstanceDB("ReadIODB", true, 6, "ReadIO_STL_Block");

Modify the following program code to create Instance DB of Graph block:

plc.BlockGroup.Blocks.CreateInstanceDB("ConveyerDB", true, 6, "Conveyer_Graph_Block");

Modify the following program code to create Instance DB of CEM block:

plc.BlockGroup.Blocks.CreateInstanceDB("RelayDB", true, 6, "Relay_CEM_Block");

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1012 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.18 Accessing DB value parameter without export

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• You have opened a project via a TIA Portal Openness application
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to read/write the start value of a member in all kinds of DB's
using two ways:
• Indexed access of members in the DB
• Finding the member using the member name
You can access the following properties name in DB using TIA Portal Openness:

Property name Data type Access Read/Write


Name String Read
StartValue Object Read/Write

You can use the following method name to access the properties of a member in DB:
• public Member Find(string Name)

Program code
Modify the following program code to read start value from DB:

PlcBlockInterface bi = dbbblock.Interface;
MemberComposition members = bi.Members;
Member member = members.Find("Room_Temperature");
object startValue = member.StartValue;
//Normal get attribute should be possible as usual
startValue = member.GetAttribute("StartValue");
//Array
initialSpeedvar = members.Find("Motor.InitialSpeed[0]");
object motorInitialSpeed = initialSpeedvar.StartValue;
//UDT-struct
axisSpeedvar = members.Find("FillingStation.Conveyer.AxisSpeed");
object axisSpeed = axisSpeedvar.StartValue;
axisSpeed = axisSpeedvar.GetAttribute("StartValue");
//Struct
initialSpeedvar = paramF.Find("DischargeValve.FlowMeter.InitialSpeed[0]");
object initialSpeed = initialSpeedvar.StartValue;
initialSpeed = initialSpeedvar.GetAttribute("StartValue");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1013
Export/import
6.4 Importing/exporting data of a PLC device

Modify the program code to write start value to DB:

PlcBlockInterface bi = dbbblock.Interface;
MemberComposition members = bi.Members
Member member = members.Find("Room_Temperature");
member.StartValue = 10.2;
//Normal set attribute should be possible as usual
member.SetAttribute("StartValue", 20.3);
//Array
initialSpeedvar = members.Find("Motor.InitialSpeed[0]");
initialSpeedvar.StartValue = 36;
initialSpeedvar.SetAttribute("StartValue", 56);
//UDT-struct
axisSpeedvar = members.Find("FillingStation.Conveyer.AxisSpeed");
object axisSpeed = axisSpeedvar.StartValue;
axisSpeed.SetAttribute("StartValue", 40.5);
initialSpeedvar = paramF.Find("DischargeValve.FlowMeter.InitialSpeed[0]");
object initialSpeed = initialSpeedvar.StartValue;
initialSpeed.SetAttribute("StartValue", 12);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.19 Export/Import of Plc Alarm TextLists

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use TIA Portal Openness to export/import Plc alarm text lists. The format of the Export/
Import is XLSX.

Excel file structure


The generated XLSX file consists two sheets, one for the text lists and one for the entries. The
created file will receive a custom property named FileContent with value "Alarm text lists". If this
property is missing or invalid (contains no or different value), the import will be denied.
The data is linked together between the two sheets. The TextListEntry.Parent refers to the
TextList.Name

Openness: API for automation of engineering workflows


1014 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Results
The TextListXlsxResult object contains information about the result of the export or import. It
contains a FileInfo named LogFilePath, which points to the logfile of the finished process. The
State (which is of type TextListXlsxResultState) will show the final state of the process, which can
be OK, Warning or Error. If the result is Error, the process failed, if it is Warning, the process
partially succeeded.

Engineering object model


The Engineering Object Model definition of the newly introduced PlcAlarmTextListProvider type
It is accessible both under a PlcUnit and PlcSoftware Engineering object

Export
Two API methods are provided for the export. If all text lists of a PLC/SW Unit in all activated
project languages is to be exported, the only required parameter is the 'path' that defines the
location where the result XLSX file has to be located after the successful export.

FileInfo fileInfo = new FileInfo(Path.Combine(Environment.CurrentDirectory,


$"{xlsxName}.xlsx"));
PlcAlarmTextListProvider textListProvider = GetTextListProvider(unitName);
textListProvider.ExportToXlsx(fileInfo);

If not all text lists of a PLC/SW Unit has to be exported or the languages - in which the text lists
have to be exported - should be filtered, another method is also available in the API, where the
list of text list names identify the text lists to be exported, and the list of Languages identify the
languages in which the text lists have to be exported.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1015
Export/import
6.4 Importing/exporting data of a PLC device

A sample usage of the ExportToXlsx action:

Openness: API for automation of engineering workflows


1016 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

private void ExportPlcOrUnit(


string stationName,
string plcName,
string xlsxName,
string[] textListNames,
string[] cultureCodes,
string unitName = null)
{
LanguageSettings languageSettings = Project.LanguageSettings;
LanguageComposition supportedLanguages = languageSettings.Languages;
IEnumerable<Language> cultureInfos = null;
if (cultureCodes != null)
{
cultureInfos = cultureCodes.Select(i =>
supportedLanguages.Find(CultureInfo.GetCultureInfo(i)));
}
FileInfo fileInfo = new FileInfo(Path.Combine(Environment.CurrentDirectory,
$"{xlsxName}.xlsx"));
PlcAlarmTextListProvider textListProvider = GetTextListProvider(stationName, plcName,
unitName);
TextListXlsxResult result = null;
string exceptionMessage = string.Empty;
ExceptionMessageData? userExceptionMessageData = null;
try
{
result = textListProvider.ExportToXlsx(fileInfo, textListNames, cultureInfos);
}
catch (EngineeringTargetInvocationException e)
{
exceptionMessage = e.ToString();
userExceptionMessageData = e.DetailMessageData.FirstOrDefault();
}
}
private PlcAlarmTextListProvider GetTextListProvider(string stationName, string plcName,
string unitName = null)
{
DeviceComposition devices = Project.Devices;
Device device = devices.Where(station => station.Name == stationName).FirstOrDefault();
if (device == null)
{
throw new InvalidOperationException($"The requested '{stationName}' station is not found");
}
PlcSoftware plcTarget = (PlcSoftware)FindSoftwareTarget(device, plcName);
if (plcTarget == null)
{
throw new InvalidOperationException($"The requested '{plcName}' PLC SW is not found")
}
if (unitName != null)
{
PlcUnitProvider unitProvider = plcTarget.GetService<PlcUnitProvider>();
PlcUnit unit = unitProvider.UnitGroup.Units.Where(unit => unit.Name ==
unitName).FirstOrDefault();
if (unit == null)
{
throw new InvalidOperationException($"The requested '{unitName}' unit is not found");

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1017
Export/import
6.4 Importing/exporting data of a PLC device

}
return unit.GetService<PlcAlarmTextListProvider>();
}
return plcTarget.GetService<PlcAlarmTextListProvider>();
}

Error Handling:
• If the given language is not activated as a project language a UserException is expected to be
thrown. For example, "Required language 'Konkani (India)' cannot be exported, because it is
not used culture in this project. Valid languages are 'German (Germany)', 'English (United
States)'"
• If there is no user text list exist, a UserException will be thrown (TextListNotFoundException)
with the following message: "There is no text list on the following item: <PLCName>."
• If a given text list name does not exist, or exists but not a user text list, a UserException is
expected to be thrown. Such as
"Text list User_1 is not found at PLC_1."
"Text list SYSTEM_SDiag_CmpCpuName cannot be exported, because it is not user text list."

Import
The following action is present at the PLCAlarmTextListProvider class for import. With the
importOptions parameter it can be clarified if the import should override existing text lists or not.
If the importOptions is set to ImportOptions.None and during the import an already existing text
list should be updated, a UserException is expected to be thrown. If the importOptions
parameter is set to ImportOptions.Override, then the already existing text lists will be updated
during the import.
Existing text lists are identified by their name. New data (text list, entry) will be appended.
Existing text list will not be deleted if there is not any corresponding data in the import file,
however if the Excel file contains text list entries for an already existing text list, the already
existing entries will be removed, and the entries given in the Excel file will be imported to the TIA
project for that specific text list (No merge for text list entries).
If invalid entries exist in the file, the text list containing the invalid entry will not be imported.
(Examples for invalid entries: overlap, inconsistent with the containing text list data type.). Texts
will be imported only in languages, which are active in the project. If the file contains more
languages than the project, texts in extra languages will not be imported and a warning will be
logged. If the project contains more languages than the file, texts which have no corresponding
data in the file will remain untouched (or empty, if import inserts new text lists or ranges).
No import can be done into a read-only project. A UserException is expected in case the user tries
to import into a read-only project.
Import is a complex process, so several kinds of errors can occur. If the error is not critical, the
import will be finished and the method returns with a TextListXlsxResult object that contains the
path to the log file (that contains the messages that are generated during the import), and has
a State of TextListXlsxResultState.Warning.
If the error is critical a UserException is expected to be thrown that contains the details about the
error.

Openness: API for automation of engineering workflows


1018 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

If the error is fatal, a NonRecoverableException is expected to be thrown.


A sample usage of the ImportFromXlsx action:

private void ImportPlcOrUnit(


string xlsxName,
string unitName = null
)
{
FileInfo fileInfo = new FileInfo(Path.Combine(System.Environment.CurrentDirectory,
$"{xlsxName}.xlsx"));
PlcAlarmTextListProvider textListProvider = GetTextListProvider(unitName);
TextListXlsxResult result = null;
string exceptionMessage = string.Empty;
ExceptionMessageData? userExceptionMessageData = null;
//Import
try
{
result = textListProvider.ImportFromXlsx(fileInfo, ImportOptions.Override);
}
catch (EngineeringTargetInvocationException e)
{
exceptionMessage = e.ToString();
userExceptionMessageData = e.DetailMessageData.FirstOrDefault();
}
if (result == null)
{
Console.WriteLine($@"Error is occurred during the import process:
'{userExceptionMessageData}'");
return;
}
Console.WriteLine($@"The import is finished with '{result.State}'. The log file is
available at '{result.LogFilePath.FullName}'");
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1019
Export/import
6.4 Importing/exporting data of a PLC device

The log-file is stored in the 'Logs' folder of the TIA project.

<?xml version="1.0" standalone="no"?>


<?xml-stylesheet type='text/xsl' href='MassDataHandlerLogFile.xsl'?>
<LogFile
titleName="PLCAlarmTextLists_InvalidLanguage.xlsx__2019.06.07_13.46.45.070__Import_Log.xml
" projectName="D:\TIA\dev\WM5_WinCC_HW_Work\binaries\Debug\x64\Tests
\Siemens.Simatic.AlarmServices.Integration.Test.Openness\TextListXlsxFiles
\PLCAlarmTextLists_InvalidLanguage.xlsx" typeText="Type" messageText="Message"
timeText="Time">
<LogEntry type="Warning" dateTime="3:46:45 PM">
<Message>The language ID in column 'Comment [abcd-EF]' is missing or is invalid (sheet
'TextList'). The texts in this language are not imported.</Message>
</LogEntry>
<LogEntry type="Warning" dateTime="3:46:45 PM">
<Message>The language ID in column 'Text [abcd-EF]' is missing or is invalid (sheet
'TextListEntry'). The texts in this language are not imported.
</Message>
</LogEntry>
<LogEntry type="Information" dateTime="3:46:45 PM">
<Message>Import completed: 2 text lists with 9 entries.</Message>
</LogEntry>
</LogFile>

Note
• XLSX files generated during Export by TIA Portal V16 should have FileVersion custom
property specified with value 1.
• XLSX files generated during Export by TIA Portal V16 should have FileContent custom
property specified with value Alarm text lists.
• Log file is generated during Import at the TIA project's Logs folder

6.4.1.20 Export/Import of Alarm classes

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to export/import Alarm classes.
The format of the Export/Import is XML. However, XML is not provided to the TIA user as the
result of export, but is archived and used with .DAT extension.
Using TIA Portal Openness, you have the possibility to choose between the .XML extension or the
archived .DAT extension as the result of the export, or as the input of the import.

Openness: API for automation of engineering workflows


1020 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

XML file structure


The generated XML file contains all information of the controller alarm classes present in the
project.
The display name and the short name is stored in all activated project languages.

<?xml version="1.0" encoding="utf-8"?>


<AlarmServiceGlobalSettingsData SchemaVersion="2.0" ProjectName="Project1572"
CreationDate="2020-03-12T08:55:13Z">
<ProjectCulture Name="en-US" />
<ProjectCulture Name="de-DE" />
<AlarmClass Name="Acknowledgement">
<DisplayName Culture="de-DE">DE - A</DisplayName>
<DisplayName Culture="en-US">EN - A</DisplayName>
<DisplayName>A</DisplayName>
<ShortName Culture="de-DE">DE - A</ShortName>
<ShortName Culture="en-US">EN - A</ShortName>
<ShortName>A</ShortName>
<GlobalId>33</GlobalId>
</AlarmClass>
<AlarmClass Name="No Acknowledgement">
<DisplayName Culture="de-DE">DE - NA</DisplayName>
<DisplayName Culture="en-US">EN - NA</DisplayName>
<DisplayName>NA</DisplayName>
<ShortName Culture="de-DE">DE - NA</ShortName>
<ShortName Culture="en-US">EN - NA</ShortName>
<ShortName>NA</ShortName>
<GlobalId>34</GlobalId>
</AlarmClass>
<AlarmClass Name="User alarm class">
<DisplayName Culture="de-DE">DE - User alarm class</DisplayName>
<DisplayName Culture="en-US">EN - User alarm class</DisplayName>
<DisplayName>User alarm class</DisplayName>
<Acknowledgement>true</Acknowledgement>
<Priority>0</Priority>
<ShortName Culture="de-DE">DE - User alarm class</ShortName>
<ShortName Culture="en-US">EN - User alarm class</ShortName><ShortName />
<GlobalId>35</GlobalId>
</AlarmClass></AlarmServiceGlobalSettingsData>

Results
The AlarmClassExportImportResult object will contain an Information about the result of the
export or import. It contains an AlarmClassExportImportResultMessageComposition navigator
named Messages, which points to the messages generated during the export/import process.
The State (which is of type AlarmClassExportImportResultState) will show the final state of the
process, which can be Success, Warning or Error. If the result is Error, the process failed, if it is
Warning, the process succeeded.

Engineering Object Model


The Engineering object model definition of the newly introduced AlarmClassDataProvider type.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1021
Export/import
6.4 Importing/exporting data of a PLC device

It is accessible under the ProjectBase Engineering object.

Export
The following action is present at the AlarmClassDataProvider class for Export:
The export action has one parameter: path.
With the path parameter the file path can be given where the result of the export is to be placed.
The type of the parameter is FileInfo.
The result of the action is an AlarmClassExportImportResult object. It contains the count of
errors, warnings and the state of the export result (Success, Warning or Error).
It also has a Messages composition property, that contains the messages generated during the
export together with the state (Success, Error or Warning).
A sample usage of the Export action:

FileInfo fileInfo = new FileInfo(@"D:\AlarmClasses.XML");


AlarmClassDataProvider provider = Project.GetService<AlarmClassDataProvider>();
if (fileInfo.Exists)
{
fileInfo.Delete();
}
AlarmClassExportImportResult result;
result = provider.Export(fileInfo);
Assert.AreEqual(AlarmClassExportImportResultState.Success, result.State);
Assert.AreEqual(0, result.ErrorCount);
Assert.AreEqual(0, result.WarningCount);
AlarmClassExportImportResultMessageComposition messages = result.Messages;
Assert.AreEqual(1, messages.Count);
Assert.AreEqual($"Export of Alarm class settings file '{fileInfo.FullName}' was
successful.", messages.FirstOrDefault().Message);
Assert.AreEqual(AlarmClassExportImportResultState.Success,
messages.FirstOrDefault().State);
Assert.IsTrue(File.Exists(fileInfo.FullName), "Exported file does not exist.");
fileInfo.Delete();

Error Handling:
• If the overall state of the export process is Error a UserException is raised, and the list of error
messages is stored in the exception itself.
From client side an EngineeringTargetInvocationException exception can be caught, where the
DetailMessageData property contains the error messages.
• Possible errors:
– IO error during the export process

Import
The import action is similar to the export action.

Openness: API for automation of engineering workflows


1022 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

A sample of usage of the Import action:

FileInfo fileInfo = new FileInfo(@"D:\AlarmClasses.dat");


AlarmClassDataProvider provider = Project.GetService<AlarmClassDataProvider>();
AlarmClassExportImportResult result;
result = provider.Import(fileInfo);
Assert.AreEqual(AlarmClassExportImportResultState.Success, result.State);
Assert.AreEqual(0, result.ErrorCount);
Assert.AreEqual(0, result.WarningCount);
AlarmClassExportImportResultMessageComposition messages = result.Messages;
Assert.AreEqual(1, messages.Count);
Assert.AreEqual($"Import of Alarm class settings file '{fileInfo.FullName}' was
successful.", messages.FirstOrDefault().Message);
Assert.AreEqual(AlarmClassExportImportResultState.Success,
messages.FirstOrDefault().State);

Error handling:
• If the overall state of the export process is Error a UserException is raised, and the list of error
messages is stored in the exception itself.
From client side an EngineeringTargetInvocationException exception can be caught, where the
DetailMessageData property contains the error messages
• Possible errors
– File to be imported has invalid file extension
– File to be imported missing file extension
– With the import the count of alarm classes would exceed the maximum allowed number
of alarm classes in the project
– The file to be imported uses not the correct schema version (Only version 1.0 and 2.0 is
supported)
– No overlapping between the activated project languages and the languages given in the
import file
– No language is defined
– IO error during the export process

Note
• XML files generated during Export with TIA Portal V17 shall have
AlarmServiceGlobalSettingsData XML root element with SchemaVersion="2.0".
• It shall be supported to import XML files generated during Export with TIA Portal V16.

See also
Opening a project (Page 113)
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1023
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.21 Export/Import of global supervision for ProDiag-FB

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 113)
• A project is open
See Opening a project (Page 81)

Introduction
You can use the TIA Portal Openness to support export/import of global supervisions of ProDiag
block.. This functionality is supported by service provider mechanism and the same service
provider is used by the block under Plc and software unit to perform export and import
operations.
On perfoming export\import you shall be communicated with proper result state or with proper
user exceptions.
The following method can be used to export and import global supervisions of ProDiag block:

Method Description

ExportSupervisionsToXlsx(FileInfo Export the supervisions tags including settings in the TIA portal
path) supported format and generates the results of the export

ImportSupervisionsFromXlsx(FileInfo
path, ImportOptions importOptions) Import supervision tags with supported import options
ImportSupervisionSettings‐ Import supervision settings which are placed in exported file
FromXlsx(FileInfo path,ImportOptions along with supervised tags
importOptions)

The following properties are available under SupervisionXlsxResult:

Property Name Data Type Access


LogFilePath System.IO.FileInfo Read
State SupervisionXlsxResult Read

The SupervisionXlsxResultState has the following enum values:

ENUM Values
SupervisionXlsxResultState Success
Failure

Openness: API for automation of engineering workflows


1024 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Program code
Modify the following program code to export global supervisions of ProDiag block:

// File Path for the export


Filelnfo fileInfo = new FileInfo(@"C:\Users\z003jwfc\Desktop\Supervisions_Openness.Xlsx");
//SW is nothing but PlcSoftware / PlcUnit.
var proDiagBlock = (FB)SW.BlockGroup.Blocks.Find("Blockl");
SupervisionProvider supervisionProvider = proDiagBlock.GetService<SupervisionProvider>();
SupervisionXlsxResult result = supervisionProvider.ExportSupervisionsToXlsx(fileInfo);

Modify the following program code to import global supervisions of ProDiag block:

// File Path for the import


Filelnfo fileInfo = new FileInfo(@"C:\Users\z003jwfc\Desktop\SupervisionsOpenness.Xlsx");
//SW is nothing but PlcSoftware / PlcUnit.
var proDiagBlock = (FB)SW.BlockGroup.Blocks.Find("Blockl");
SupervisionProvider supervisionProvider = proDiagBlock.GetService<SupervisionProvider>();
//import supervisions
SupervisionXlsxResult result = supervisionProvider.ImportSupervisionsFromX1sx(fileInfo,
ImportOptions.None);
SupervisionXlsxResult result = supervisionProvider.ImportSupervisionsFromX1sx(fileInfo,
ImportOptions.Override);
//import supervision settings
SupervisionXlsxResult result =
supervisionProvider.ImportSupervisionSettingsFromX1sx(fileInfo, ImportOptions.None);
SupervisionXlsxResult result =
supervisionProvider.ImportSupervisionSettingsFromX1sx(fileInfo, ImportOptions.Override);

6.4.1.22 Export/import of ProDiag supervisions from Global overview editor

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• Opening a project
See Opening a Project (Page 113)

Introduction
You can use the TIA Portal Openness to support export\import of global supervisions available
under Plc or under Unit. The functionality is supported by service provider mechanism and the
same service provider is used mainly by both Plc and software unit to perform export and import
operations. On performing export\import, you shall be communicated with proper result or with
exceptions.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1025
Export/import
6.4 Importing/exporting data of a PLC device

The following method can be used to export and import global supervisions:

Method Description

ExportSupervisionsToXlsx(FileInfo Export the supervisions tags including settings in the TIA portal
path) supported format and generates the results of the export

ImportSupervisionsFromXlsx(FileInfo
path, ImportOptions importOptions) Import supervision tags with supported import options
ImportSupervisionSettings‐ Import supervision settings which are placed in exported file
FromXlsx(FileInfo path,ImportOptions along with supervised tags
importOptions)

The following properties are available under SupervisionXlsxResult:

Property name Data type Access


LogFilePath System.IO.FileInfo Read
State SupervisionXlsxResult Read

The SupervisionXlsxResultState has the following ENUM values:

ENUM Values
SupervisionXlsxResultState Success
Failure

Program code
Modify the following program code to export global supervisions:

//File Path for the export


FileInfo fileInfo = new FileInfo(@"C:\Users\z003jwfc\Desktop\Supervisions_Openness.Xlsx");
//SW is nothing but PlcSoftware / PlcUnit.
SupervisionProvider supervisionProvider = SW.GetService<SupervisionProvider>();
SupervisionXlsxResult result = supervisionProvider.ExportSupervisionsToXlsx(fileInfo);

Openness: API for automation of engineering workflows


1026 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Modify the following program code to import global supervisions:

//File Path for the import.


FileInfo fileInfo = new FileInfo(@"C:\Users\z003jwfc\Desktop\Supervisions_Openness.Xlsx");
//SW is nothing but PlcSoftware / PlcUnit.
Supervision Provider supervisionProvider = SW.GetService<SupervisionProvider>();
//import supervisions
SupervisionXlsxResult result = supervisionProvider.ImportSupervisionsFromXlsx(fileInfo,
ImportOptions.None);
SupervisionXlsxResult result = supervisionProvider.ImportSupervisionsFromXlsx(fileInfo,
ImportOptions.Override);
//import supervision settings
SupervisionXlsxResult result =
supervisionProvider.ImportSupervisionsSettingsFromXlsx(fileInfo, ImportOptions.None);
SupervisionXlsxResult result =
supervisionProvider.ImportSupervisionsSettingsFromXlsx(fileInfo, ImportOptions.Override);

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.23 Export/Import of settings for ProDiag supervisions

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Introduction
You can use the TIA Portal Openness to support export/import of supervision settings.
The following properties are available under SupervisionSettingsExportImportResult:

Property Name Data Type Access


State SupervisionSettingExportImportResult‐ Read
State
ErrorCount Int32 Read
WarningCount Int32 Read
Message String Read

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1027
Export/import
6.4 Importing/exporting data of a PLC device

The ENUM SupervisionSettingExportImportResultState has following value:

ENUM Value
SupervisionSettingExportImportResultState Success
ErrorRollback

Program code
Modify the following program code to export supervision settings:

// MyProject obtains SupervisionSettingsProvider


SupervisionSettingsProvider settingsProvider =
MyProject.GetService<SupervisionSettingsProvider>();
// Import file path defined
FileInfo exportFile = new FileInfo(@"D:\Temp\ProDiagSettings.dat");
// Stores result after import
SupervisionSettingsExportImportResult exportResult = settingsProvider.Export(exportFile);
// Result state after import
SupervisionSettingsExportImportResultState resultState = exportResult.State;
// Total error count of result messages
int totalErrorCount = exportResult.ErrorCount;
// Composition of result messages
SupervisionSettingsExportImportResultMessageComposition exportMessageList =
exportResult.Messages;
// Count of result messages
exportMessageList.Count;
// Read out specific message text from each message
exportMessageList [0].Message;
// Output: "Export of file 'D:\temp\SupervisionSettings.dat' with the ProDiag supervision
settings was successful.";

Openness: API for automation of engineering workflows


1028 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Modify the following program code to import supervision settings:

// MyProject obtains SupervisionSettingsProvider


SupervisionSettingsProvider settingsProvider =
MyProject.GetService<SupervisionSettingsProvider>();
// Import file path defined
FileInfo importFile = new FileInfo(@"D:\Temp\ProDiagSettings.dat");
// Stores result after import
SupervisionSettingsExportImportResult importResult = settingsProvider.Import(importFile);
// Result state after import
SupervisionSettingsExportImportResultState resultState = importResult.State;
// Total error count of result messages
int totalErrorCount = importResult.ErrorCount;
// Composition of result messages
SupervisionSettingsExportImportResultMessageComposition importMessageList =
importResult.Messages;
// Count of result messages
importMessageList.Count;
// Read out specific message text from each message
importMessageList[0].Message;
// Output: "Import of the file 'D:\temp\SupervisionSettings.dat' with the ProDiag
supervision settings was successful.";

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.24 Export/Import Watch & Force Table

Requirement:
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• You have opened a project with your TIA Portal Openness application.
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to export Watch Table and Force Table from TIA Portal to
SIMATIC ML and import the Watch Table and Force Table from SIMATIC ML.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1029
Export/import
6.4 Importing/exporting data of a PLC device

Program code: Export Watch Table and Force Table


Modify the following program code to export Watch Table:

SoftwareContainer softwareContainer =
((IEngineeringServiceProvider)item).GetService<SoftwareContainer>();
PlcSoftware plcSoftware = softwareContainer.Software as PlcSoftware;
PlcWatchTableComposition exportWatchTables =
plcSoftware.PlcWatchAndForceTableGroup.WatchTables;
PlcWatchTable watchTable = exportWatchTables.Find(watchTableName);
if(watchTable != null)
{
watchTable.Export((FileInfo) fileInfo, ExportOptions.None);
}

Note
Export options in Watch Table should be set (None, WithDefaults, WithReadOnly,
WithDefaultsAndReadOnly.). A WatchTable has only one published property i.e. the name. The
name is published for read.

Modify the following program code to export Force Table:

SoftwareContainer softwareContainer =
((IEngineeringServiceProvider)item).GetService<SoftwareContainer>();
PlcSoftware plcSoftware = softwareContainer.Software as PlcSoftware;
PlcForceTableComposition exportForceTables =
plcSoftware.PlcWatchAndForceTableGroup.ForceTables;
PlcForceTable forceTable = exportForceTables[0];
forceTable.Export((FileInfo) fileInfo, ExportOptions.None);

Note
There is only one ForceTable in every situation, and it has a read-only name.

Program code: Import Watch Table and Force Table


Modify the following program code to import Watch Table:

SoftwareContainer softwareContainer =
((IEngineeringServiceProvider)item).GetService<SoftwareContainer>();
PlcSoftware plcSoftware = softwareContainer.Software as PlcSoftware;
PlcWatchTableComposition importWatchTables =
plcSoftware.PlcWatchAndForceTableGroup.WatchTables;
IList<PlcWatchTable> WatchTables = importWatchTables.Import((FileInfo)fileInfo,
ImportOptions.None);

Openness: API for automation of engineering workflows


1030 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Note
The imported WatchTable will be added to the list of WatchTables. Import options in Watch Table
should be set to the required one (None, Override).

ForceTables can be imported in a similar way, but it is only allowed to have one ForceTable. If you
use the None option instead of Override and a (non-empty) ForceTable already exists, then the
import will fail with the following RecoverableException: Only one ForceTable is allowed to be
imported. Please use Override importOption to overwrite the existing one.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.25 Exporting user data type

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online

Program code
Modify the following program code to export an user data type to an XML file:

//Exports a user defined type


private static void ExportUserDefinedType(PlcSoftware plcSoftware)
{
string udtname = "udt name XYZ";
PlcTypeComposition types = plcSoftware.TypeGroup.Types;
PlcType udt = types.Find(udtname);
udt.Export(new FileInfo(string.Format(@"C:\OpennessSamples\udts\{0}.xml", udt.Name)),
ExportOptions.WithDefaults);
}

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1031
Export/import
6.4 Importing/exporting data of a PLC device

6.4.1.26 Importing user data type

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
Connecting to the TIA Portal (Page 81)
• A project is open.
Opening a project (Page 113)
• PLC is not online.

Application
The API interface supports the importing of user data types from an XML file.

Import file syntax


The following code example shows an excerpt from an import file of a user-defined data type:

<Section Name="Input">
<Member Name="Input1" Datatype=quot;myudt1&quot;>
<Sections>
<Section Name="None">
<Member Name="MyUDT1Member1" Datatype="bool"/>
<Member Name="MyUDT1Member2" Datatype=&quot;myudt1&quot;>
<Sections...

Note
Syntax for user-defined data types of elements
An exception is thrown if the user-defined data type of an element in the import file for user data
types has incorrect syntax.
Make sure that user-defined data types are noted with &quot;.

Program code
Modify the following program code to import a user data type:

//Imports user data type


private static void ImportUserDataType(PlcSoftware plcSoftware)
{
FileInfo fullFilePath = new FileInfo(@"C:\OpennessSamples\Import\ExportedPlcType.xml");
PlcTypeComposition types = plcSoftware.TypeGroup.Types;
IList<PlcType> importedTypes = types.Import(fullFilePath, ImportOptions.Override);
}

Openness: API for automation of engineering workflows


1032 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

See also
Importing configuration data (Page 885)

6.4.1.27 Export of data in OPC UA XML format

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online

Application
You can use the TIA Portal Openness to export PLC data as OPC UA XML file. As input parameter
for the action you need an absolute directory path, where the xml file will be saved.

Program code
Modify the following program code to export PLC data as OPC UA XML file:

//Export PLC data as OPC UA XML file


private static void OpcUaExport(Project project, DeviceItem plc)
{
OpcUaExportProvider opcUaExportProvider = project.HwUtilities.Find("OPCUAExportProvider")
as OpcUaExportProvider;
if (opcUaExportProvider == null) return;
opcUaExportProvider.Export(plc, new FileInfo(string.Format(@"D:\OPC UA export files
\{0}.xml", plc.Name)));
}

6.4.1.28 Export/Import of UDT & DB

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1033
Export/import
6.4 Importing/exporting data of a PLC device

Application
You can use the TIA Portal Openness to define a supervision for bool members inside UDT and
assign prodiagFB for UDT instances in global data while creating the global Datablock. You
should be able to provide and fetch this supervison information through TIA Portal Openness
export and import respectively.

Openness: API for automation of engineering workflows


1034 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

XML structure of exported/imported UDT


Use the below XML structure to export a element of boolean variable for which you have
defined a supervision:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1035
Export/import
6.4 Importing/exporting data of a PLC device

<?xml version="1.0" encoding="utf-8"?>


<Document>
<Engineering version="V17" />
<DocumentInfo>
<Created>2020-06-08T20:10:12.6308242Z</Created>
<ExportSetting>None</ExportSetting>
<InstalledProducts>
<Product>
<DisplayName>Totally Integrated Automation Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<OptionPackage>
<DisplayName>TIA Portal Openness</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</OptionPackage>
<OptionPackage>
<DisplayName>TIA Portal Version Control Interface</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</OptionPackage>
<Product>
<DisplayName>Feature Cycle 3 TIA Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>STEP 7 Professional</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<OptionPackage>
<DisplayName>SIMATIC Energy Suite</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</OptionPackage>
<OptionPackage>
<DisplayName>STEP 7 Safety</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</OptionPackage>
<Product>
<DisplayName>WinCC Professional</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
</InstalledProducts>
</DocumentInfo>
<SW.Types.PlcStruct ID="0">
<AttributeList>
<Interface><Sections>
<Section Name="None">
<Member Name="Element_1" Datatype="Bool" />
</Section>
</Sections>
</Interface>
<Name>User_data_type_1</Name>
<Supervisions><PLCDataTypeSupervisions>
<PLCDataTypeSupervision Number="1" Type="Operand">
<SupervisedOperand Name="#Element_1" />
<SupervisedStatus>false</SupervisedStatus>
<DelayOperand Name="T#0ms" />

Openness: API for automation of engineering workflows


1036 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

<Conditions>
<Condition>
<ConditionOperand Number="1" Name="" />
<TriggeringStatus>true</TriggeringStatus>
</Condition>
<Condition>
<ConditionOperand Number="2" Name="" />
<TriggeringStatus>true</TriggeringStatus>
</Condition>
<Condition>
<ConditionOperand Number="3" Name="" />
<TriggeringStatus>true</TriggeringStatus>
</Condition>
</Conditions>
<CategoryNumber>1</CategoryNumber>
<SubCategory1Number>0</SubCategory1Number>
<SubCategory2Number>0</SubCategory2Number>
</PLCDataTypeSupervision></PLCDataTypeSupervisions></Supervisions>
</AttributeList>
<ObjectList>
<MultilingualText ID="1" CompositionName="Comment">
<ObjectList>
<MultilingualTextItem ID="2" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
<MultilingualText ID="3" CompositionName="Title">
<ObjectList>
<MultilingualTextItem ID="4" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
</ObjectList>
</SW.Types.PlcStruct>
</Document>

When you want to import a UDT and assign the supervision for the bool variable, the above-
mentioned XML tags can be used. However, you cannot set the supervision information to a bool
variable through openness after import.

Note
Supervision is only applicable for bool variables for UDT, when you attempt to import or export
the "PLCDataTypeSupervisions" tags for any non-boolean members in UDT then no exception is
thrown.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1037
Export/import
6.4 Importing/exporting data of a PLC device

XML structure of exported /imported DB


Use the following XML structure to export a member of UDT instance irrespective of whether the
UDT has supervision or not and an array of struct which has UDT instance as its member:

Openness: API for automation of engineering workflows


1038 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

<?xml version="1.0" encoding="utf-8"?>


<Document>
<Engineering version="V17" />
<DocumentInfo>
<Created>2020-06-09T16:01:18.494539Z</Created>
<ExportSetting>None</ExportSetting>
<InstalledProducts>
<Product>
<DisplayName>Totally Integrated Automation Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>Feature Cycle 1 TIA Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>Feature Cycle 3 TIA Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>STEP 7 Professional</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<OptionPackage>
<DisplayName>STEP 7 Safety</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</OptionPackage>
</InstalledProducts>
</DocumentInfo>
<SW.Blocks.GlobalDB ID="0">
<AttributeList>
<Interface><Sections>
<Section Name="Static">
<Member Name="Static_1" Datatype="Udt_With_Supervision"><AttributeList><BooleanAttribute
Name="SetPoint" SystemDefined="true">true</BooleanAttribute></
AttributeList><AssignedProDiagFB>Default_SupervisionFB</AssignedProDiagFB></Member>
<Member Name="Static_2" Datatype="Array[0..1] of Struct">
<Member Name="Static_1"
Datatype="&quot;Udt_With_Supervision&quot;"><AttributeList><BooleanAttribute
Name="SetPoint" SystemDefined="true">true</BooleanAttribute></AttributeList><Subelement
Path="0"><AssignedProDiagFB>Default_SupervisionFB</AssignedProDiagFB></
Subelement><Subelement Path="1"><AssignedProDiagFB>Default_SupervisionFB</
AssignedProDiagFB></Subelement></Member>
</Member>
</Section>
</Sections></Interface>
<MemoryLayout>Optimized</MemoryLayout>
<MemoryReserve>100</MemoryReserve>
<Name>Data_block_5</Name>
<Number>16</Number>
<ProgrammingLanguage>DB</ProgrammingLanguage>
</AttributeList>
<ObjectList>
<MultilingualText ID="1" CompositionName="Comment">

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1039
Export/import
6.4 Importing/exporting data of a PLC device

<ObjectList>
<MultilingualTextItem ID="2" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
<MultilingualText ID="3" CompositionName="Title">
<ObjectList>
<MultilingualTextItem ID="4" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
</ObjectList>
</SW.Blocks.GlobalDB>
</Document>

Note
It is valid to have assignedProDiagFB attribute only for UDT instance. It is not possible to export
any invalid data as it should be compile clean so you don’t get any exception during export. You
will encounter the not supported exception , if you try to import the "AssignedProDiagFB" tag for
non UDT instances inside global DB or any other member in any block.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.4.1.29 Export/Import of Array & Instance DB

Quintessence
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to export and import the Array DB and instance DB of UDT
instances so that the information about assigned proDiagFB sould be exported appropriately.

Openness: API for automation of engineering workflows


1040 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Similarly, the same attribute should be supported for Openness user during import as well so
that you would be able to assign the possible proDiagFB for Array DB and instance DB of UDT.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1041
Export/import
6.4 Importing/exporting data of a PLC device

XML structure of the exported Array DB


Use the following XML structure to export Array DB of UDT which gets assigned with ProdiagFB
"Default_SupervisionFB":

Openness: API for automation of engineering workflows


1042 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

<?xml version="1.0" encoding="utf-8"?>


<Document>
<Engineering version="V17" />
<DocumentInfo>
<Created>2020-06-09T16:06:07.7850963Z</Created>
<ExportSetting>None</ExportSetting>
<InstalledProducts>
<Product>
<DisplayName>Totally Integrated Automation Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>Feature Cycle 1 TIA Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>Feature Cycle 3 TIA Portal</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<Product>
<DisplayName>STEP 7 Professional</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</Product>
<OptionPackage>
<DisplayName>STEP 7 Safety</DisplayName>
<DisplayVersion>V17</DisplayVersion>
</OptionPackage>
</InstalledProducts>
</DocumentInfo>
<SW.Blocks.ArrayDB ID="0">
<AttributeList>
<Interface><Sections>
<Section Name="None">
<Member Name="Data_block_6" Datatype="Array[0..1] of &quot;Udt_With_Supervision&quot;">
<Comment>
<MultiLanguageText Lang="en-US">comment of Data_block_6</MultiLanguageText>
</Comment>
<Sections>
<Section Name="None">
<Member Name="Element_1" Datatype="Bool">
<Subelement Path="0">
<Comment>
<MultiLanguageText Lang="en-US">comment of Element_1</MultiLanguageText>
</Comment>
</Subelement>
<Subelement Path="1">
<Comment>
<MultiLanguageText Lang="en-US">comment of Element_1</MultiLanguageText>
</Comment>
</Subelement>
</Member>
</Section>
</Sections>
<Subelement Path="0">
<Comment>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1043
Export/import
6.4 Importing/exporting data of a PLC device

<MultiLanguageText Lang="en-US">comment of Data_block_6[0]</MultiLanguageText>


</Comment>
<AssignedProDiagFB>Default_SupervisionFB</AssignedProDiagFB>
</Subelement>
<Subelement Path="1">
<Comment>
<MultiLanguageText Lang="en-US">comment of Data_block_6[1]</MultiLanguageText>
</Comment>
<AssignedProDiagFB>Default_SupervisionFB</AssignedProDiagFB>
</Subelement>
</Member>
</Section>
</Sections></Interface>
<Name>Data_block_6</Name>
<Number>17</Number>
<ProgrammingLanguage>DB</ProgrammingLanguage>
</AttributeList>
<ObjectList>
<MultilingualText ID="1" CompositionName="Comment">
<ObjectList>
<MultilingualTextItem ID="2" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
<MultilingualText ID="3" CompositionName="Title">
<ObjectList>
<MultilingualTextItem ID="4" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
</ObjectList>
</SW.Blocks.ArrayDB>
</Document>

Note
It is valid to have assignedProDiagFB only for Array DB of UDT, it is not possible to export any
invalid data so you don’t get any exception during export.
When you try to import the "AssignedProDiagFB" tag for any other ArrayDB which is not of UDT
then you will encounter the not supported exception and this is not supported for System
defined Datatype as well though they have bool variable or not.

Openness: API for automation of engineering workflows


1044 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Exported XML structure of Instance DB


Use the following XML structure to export instance DB of UDT which gets assigned with
ProdiagFB "Default_SupervisionFB":

...
<SW.Blocks.InstanceDB ID="0">
<AttributeList>
<AssignedProDiagFB>Default_SupervisionDB</AssignedProDiagFB>
<InstanceOfName>User_data_type_4</InstanceOfName>
<InstanceOfType>UDT</InstanceOfType>
<Interface>
<Sections>
<Section Name="Static">
<Member Name="Element_1" Datatype="Bool" />
</Section>
</Sections>
</Interface>
<MemoryLayout>Optimized</MemoryLayout>
<Name>Data_block_9</Name>
<Number>19</Number>
<ProgrammingLanguage>DB</ProgrammingLanguage>
</AttributeList>
<ObjectList>
<MultilingualText ID="1" CompositionName="Comment">
<ObjectList>
<MultilingualTextItem ID="2" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
<MultilingualText ID="3" CompositionName="Title">
<ObjectList>
<MultilingualTextItem ID="4" CompositionName="Items">
<AttributeList>
<Culture>en-US</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
</ObjectList>
</SW.Blocks.InstanceDB>
</Document>
...

Note
The appropriate "Not Supported attribute" exception should be thrown to you, If you try to set
the assignedProDiagFB to instance DB.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1045
Export/import
6.4 Importing/exporting data of a PLC device

See also
Opening a project (Page 113)

6.4.2 Technology objects

6.4.2.1 Overview of technology objects and versions

Technology objects
The following table shows the available technology objects for import and export.

CPU Technology Technology object Version of CPU FW


technology
object
S7-1200 Motion Control TO_PositioningAxis ≥ V7.0 ≥ V4.4
TO_CommandTable
PID Control PID_Compact V2.3 ≥ V4.2
PID_3Step V2.3
PID_Temp V1.1
S7-1500 Motion Control TO_SpeedAxis ≥ V5.0 ≥ V2.8
TO_PositioningAxis
TO_ExternalEncoder
TO_SynchronousAxis
TO_OutputCam
TO_CamTrack
TO_MeasuringInput
TO_Cam (S7-1500T)
TO_Kinematics (S7-1500T)
TO_LeadingAxisProxy
(S7-1500T)
TO_Cam_10k (S7-1500T) ≥ V6.0 ≥ V2.9
Counting and High_Speed_Counter ≥ V4.1 any
measurement SSI_Absolute_Encoder ≥ V3.1
PID Control PID_Compact ≥ V2.3 ≥ V2.0
PID_3Step V2.3
PID_Temp V1.1
CONT_C
CONT_S
TCONT_CP
TCONT_S

Openness: API for automation of engineering workflows


1046 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

CPU Technology Technology object Version of CPU FW


technology
object
S7-300/400 PID Control CONT_C V1.1 Any
CONT_S
TCONT_CP
TCONT_S
TUN_EC
TUN_ES
PID_CP V2.0
PID_ES
EMC AXIS_REF V2.0

6.4.2.2 XML structure of the block interface section

Basic principle
The data in the XML file from the import/export is structured with reference to an openness XML
file format. Every import file must fulfill the structural conditions.
The export file includes all edited tags and constants of the interface section of an exported
technology object. The project data can contain more data than the import XML file, e.g.
external references. These must be exported separately. Only writeable values can be imported
via TIA Portal Openness XML.
Depending on the TIA Portal Openness export settings, the export file includes a defined set of
attributes and elements. Export files from higher versions of the TIA Portal are not compatible
with lower versions of the TIA Portal and could not be imported in those. SimaticML files
exported with the latest TechObject version are also supported for the newer ones.

Openness XML file format


The export file is generated in an XML format. The export file includes all edited tags and
constants of the interface section of an exported block. The sequence of the following
description of elements represents the required sequence in the input file.

Attributes
The SimaticML format is largely taken over from the export/import format of user blocks.
Particularly important are the following additional attributes:
• OfSystemLibElement
• OfSystemLibVersion
• Interface
The attribute OfSystemLibVersion contains the version of the TO, and the attribute
OfSystemLibElement contains the type of the TO.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1047
Export/import
6.4 Importing/exporting data of a PLC device

The attribute Interface contains all members of the TO DB including the structure elements
and versions.

Figure 6-3 Example for TO_SpeedAxis for S7-1500

Technology data that are not stored in the DB itself are stored in an additional attribute
ParameterData.

Openness: API for automation of engineering workflows


1048 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

6.4.2.3 Exporting technology objects

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• A project contains TO to be exported.
• PLC is not online.

Application
The TIA Portal Openness API supports the export of all technology objects listed in the
table Overview of technology objects and versions (Page 1046) to an XML file. You can only
export consistent technology objects. HWCN or TagTable are not exported with the technology
object, but must be exported separately. You check the consistency of a technology object using
the IsConsistent attribute. This flag can be set by successfully compiling of the respective
technology object. The generation of the corresponding export file indicates that the export is
completed.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1049
Export/import
6.4 Importing/exporting data of a PLC device

Exceptions
• When you try to export an inconsistent technology object an exception is thrown.
• When you try to export the technology object that not supports the export functionality an
exception is thrown. This exception is also thrown in case of older technology object versions
that not support export.
• When you try to export the technology object while you are in online mode an exception is
thrown.

Additional parameters
Most parameters of Motion Control technology objects are directly mapped to data block tags,
but there are also some additional parameters that do not map directly to data blocks. See
also Specific attributes for TO_PositioningAxis and TO_CommandTable (Page 1052), Specific
attributes for Axis and Encoder technology objects (Page 1055), Specific attributes for
OutputCam, CamTrack and MeasuringInput technology objects (Page 1058).

Program code
void Export(FileInfo path, ExportOptions options);
The path parameter describes the path and file name of the export file that should be created.
The parameter (ExportOptions options) specifies options for the export (Page 884).

Attributes Description
ExportOptions.None Exports only modified parameters.
ExportOptions.WithDefaults This option exports the parameters that have their default value. The de‐
fault value itself is not exported. The same behavior is defined also for the
TO specific parts of the XML export. The respective default values that are
exported are defined for each TO type.
ExportOptions.WithReadOnly This option exports additional informative attributes and values. During
import, read only values are not written back to the DB. The respective
read only values that are exported are defined for each TO type.
ExportOptions.WithDefaults | ExportOptions.With‐ Combination of the two options above.
ReadOnly

Modify the following program code to find and export a technology object to an XML file:

// Find a specific technology object by its name and export this


private static void ExportTechnologicalObject(FileInfo path, ExportOptions options,
PlcSoftware plcSoftware, String nameOfTO)
{
// Find by name
TechnologicalInstanceDBComposition technologicalObjects = plcSoftware.TechnologicalObje
ctGroup.TechnologicalObjects;
TechnologicalInstanceDB technologicalObject = technologicalObjects.Find(nameOfTO);
// Export TO
technologicalObject.Export(path, options);
}

Openness: API for automation of engineering workflows


1050 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Modify the following program code to export a technology object OutputCam to an XML file:

// Export OutputCam
private static void ExportTechnologicalObject(FileInfo path, ExportOptions options,
PlcSoftware plcSoftware, String nameOfTO)
{
//Retrieve service OutputCamMeasuringInputContainer
OutputCamMeasuringInputContainer container =
technologyObject.GetService<OutputCamMeasuringInputContainer>();
//Get access to TO_OutputCam container
TechnologicalInstanceDBComposition outputcamCamtrackContainer = container.OutputCams;
//Find technology object TO_OutputCam
TechnologicalInstanceDB outputCam = outputcamCamtrackContainer.Find("OutputCamName");
// Export
outputCam.Export(path, options);
}

6.4.2.4 Importing technology objects

Requirements

• The TIA Portal Openness application is connected to the TIA Portal.


See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is not online.

Application
The TIA Portal Openness API supports the import of technology objects from an XML file.

Exceptions
If the import data contains parameters that are not defined for the respective TO type, an
EngineeringTargetInvocationException is thrown.
If the value of a parameter has a wrong format and cannot be converted to the type of the
parameter, an EngineeringTargetInvocationException is thrown. The Import will be succeeded
but an error will be produced on compile.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1051
Export/import
6.4 Importing/exporting data of a PLC device

Open connection
In TIA Portal, open connections are created when a tag that is connected to a TO is deleted. The
further behavior of open connections is identical to the behavior of open connections created
by deleting a connected tag. If the partner TO is missing during the import, an open connection
will be established in this case. This also applies to TO types that can not be used for certain
connections.

Program code
IList<SW.TechnologicalObjects.TechnologicalInstanceDB>
Import(FileInfo path, ImportOptions options);
Modify the following program code to import one or several technology objects from an XML
file. For more information about the ImportOptions see Importing configuration data
(Page 885).

// Import technology objects


private static void Import(FileInfo path, ImportOptions options, PlcSoftware plcSoftware)
{
// Create technological instance
TechnologicalInstanceDBComposition technologicalObjects =
plcSoftware.TechnologicalObjectGroup.TechnologicalObjects;

// Import TO
technologicalObjects.Import(path, options);
}

6.4.2.5 S7-1200 Motion Control

Specific attributes for TO_PositioningAxis and TO_CommandTable

Application
The API supports the export and import of technology objects.
Parameters of TO_PositioningAxis and TO_CommandTable that are data block members are
exported in the "Interface" section of the export file. Additional parameters are exported in the
"ParameterData" section of the export file. The next chapter shows all additional parameters.
You can find a list of all available variables in SIMATIC STEP 7 S7-1200 Motion Control function
manual on the internet (https://support.industry.siemens.com/cs/ww/en/view/109754206).

Note
The data type information is only exported for parameters that are part of the "Interface" section.

Openness: API for automation of engineering workflows


1052 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Additional parameters TO_PositioningAxis


The following additional parameters are not directly mapped to DB members and will be
exported in section ParameterData depending on the ExportOption:

Parameter Name Possible Values


_Actor.Interface.PTO Pulse generator data:
0: Pulse_1
1: Pulse_2
2: Pulse_3
3: Pulse_4
_Actor.Interface.EnableDriveOutput Tag name of the connected device address
_Actor.Interface.DriveReadyInput Tag name of the connected device address
_Actor.Interface.DataConnection 0: Drive
1: DB
_Actor.Interface.DataBlock See the functional view for possible values
_Actor.Interface.Analog See the functional view for possible values
_Actor.Interface.ProfiDriveIn Tag name of the connected device address
_Actor.Interface.ProfiDriveOut Tag name of the connected device address
_Actor.DataAdaptionOffline TRUE or FALSE
_Sensor[1].Interface.ProfiDriveIn Tag name of the connected device address
_Sensor[1].Interface.ProfiDriveOut Tag name of the connected device address
_ Sensor[1].Interface.EncoderConnection 4: HSC
7: Encoder on PROFINET/PROFIBUS
_Sensor[1].DataAdaptionOffline TRUE or FALSE
_Sensor[1].Interface.DataConnection 0: Encoder
1: DB
_ Sensor[1].Interface.HSC HSC number:
0: HSC_1
1: HSC_2
2: HSC_3
3: HSC_4
_ Sensor[1].Interface.DataBlock See the functional view for possible values
_ Sensor[1].PassiveHoming.DigitalInput Tag name of the connected device address
_ Sensor[1].ActiveHoming.DigitalInput Tag name of the connected device address
_PositionLimits_HW.MinSwitch Tag name of the connected device address
_PositionLimits_HW.MaxSwitch Tag name of the connected device address

Additional parameters TO_CommandTable


The following additional parameters are not directly mapped to DB members:

Parameter name Possible values


_WarningsEnable TRUE or FALSE
_UseAxisParametersFrom "Sample axis", Name of axis

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1053
Export/import
6.4 Importing/exporting data of a PLC device

External references

External references at the TO_PositioningAxis


The TO editor of TO_PositioningAxis displays information that is not stored in the TO DB. This
external information is therefore not part of the TO export/import and must be exported/
imported or treated separately. For the TO_PositioningAxis these are the following data:
• TagTable
The tags used by the axis (assignment between symbolic name and address) are stored in the
tag table and must be provided to the TO. One possibility to do this is the separate export/
import of the TagTable.
• HW Config
Some information is stored in HW Config e.g. The device configuration of the drive/encoder,
the settings of a pulse generator and settings of High Speed Counters.
In HW Config not all parameters can be exported/imported. TO relevant parameters of HW
Config can be set over the TO openness parameter API: See Writing parameters of technology
object (Page 609).

Hardware configuration settings


The Openness import does not specify hardware configuration settings. The following
parameters have to be set over TO openness parameter API directly if they have not previously
been set in the hardware configuration.

In case of PTO-Axis:
An explicit set of _Actor.Interface.PTO has be done over TO openness parameter API to connect
the TO to the PTO-Output.
The following parameters can be set via Openness API:
• _Actor.Interface.PTO_OutputA
• _Actor.Interface.PTO_OutputBEnable
• _Actor.Interface.PTO_OutputB
• _Actor.Interface.PTO_SignalType
If Homing- or Position Limit inputs are used in PTO-Axis, activation of EdgeDetection will be done
with setting of following parameters over TO openness parameter API:
• _Sensor[1].ActiveHoming.DigitalInput
• _Sensor[1].PassiveHoming.DigitalInput
• _PositionLimits_HW.MaxSwitch
• _PositionLimits_HW.MinSwitch

In case of Analog/ProfiDrive:
An explicit set of following parameters has to be done over TO openness parameter API to
activate the PIP to OB-Servo:
• _Actor.Interface.ProfiDriveOutName
• _Actor.Interface.ProfiDriveInName

Openness: API for automation of engineering workflows


1054 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

• _Sensor[1].Interface.ProfiDriveOutName
• _Sensor[1].Interface.ProfiDriveInName

In case of HSC is used for encoder connection:


An explicit set of _Sensor[1].Interface.HSC has to be done over TO Openness parameter API to
connect the TO to the HSC and activate the HSC in Hardware Configuration.
The following parameters can be set over Openness API:
• _ Sensor[1].Interface.HSC_OperatingMode
• _ Sensor[1].Interface.HSC_InputA
• _ Sensor[1].Interface.HSC_InputB

6.4.2.6 S7-1500 Motion Control

Specific attributes for Axis and Encoder technology objects

Application
The API supports the import and export of technology objects. The following section describes
the specific attributes.

Export TO_SpeedAxis, TO_PositioningAxis, TO_SynchronousAxis and TO_ExternalEncoder


For the TO types TO_SpeedAxis, TO_PositioningAxis, TO_SynchronousAxis and
TO_ExternalEncoder, the EOM attribute ParameterData contains the Parameters as described in
the following tables. Parameters corresponding to TO DB members have the data type and the
default value as defined in the TO DB.

Name TO_SpeedAxis TO_PositioningAxis / TO_Synchro‐ TO_ExternalEncoder


nousAxis
VirtualAxis.Mode X X -
Actor.Type X X -
Actor.Interface.EnableDri‐ X X -
veOutput
Actor.Interface.DriveReadyIn‐ X X -
put
Actor.Interface.EnableTor‐ X X -
queData
Sensor[n].Existent1) - X -
Sensor[n].Interface.Number 1)
- X -
Sensor[n].Type1) - X -
Sensor.Interface.Number - - X

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1055
Export/import
6.4 Importing/exporting data of a PLC device

Sensor.Type - - X
CrossPlcSynchronousOpera‐ - X X
tion.Interface[n].EnableLea‐
dingValueOutput2)

Parameters for TO_SpeedAxis, TO_PositioningAxis, TO_SynchronousAxis and TO_ExternalEncoder corresponding to TO DB


members
1) S7-1500 PLC: n=1; S7-1500T PLC: 1≤n≤4
2) V5.0 n=1; ≥V6.0 1≤n≤8

The Parameters listed in the following Table correspond to "additional


TechnologicalParameters". These Parameters have the same data type in SimaticML as the
respective TechnologicalParameters in the Openness API.

Name Default Value TO_SpeedAxis TO_Positionin‐ TO_ExternalEncoder


gAxis / TO_Syn‐
chronousAxis
_Properties.MotionType 0 - X X

_Properties.UseHighResolution‐ false - X X
PositionValues
_CrossPlcSynchronousOpera‐ true - X X
tion.ActivateLocalLeadingValue‐
DelayTimeCalculation
_Units.LengthUnit 1013 (mm) - X X
_Units.VelocityUnit 1062 (mm/s) 1083 (1/mm) X X
_Units.TorqueUnit 1126 (Nm) X X -
_Units.ForceUnit 1120 (N) - X -
_Actor.Interface.Telegram 0 X X -

_Sensor[n].Interface.Telegram1) 0 - X -

_Sensor.Interface.Telegram 0 - - X

_Actor.DataAdaptionOffline false X X -

_Sensor[n].DataAdaptionOff‐ false - X -
line1)
_Sensor.DataAdaptionOffline false - - X

Parameters for TO_SpeedAxis, TO_PositioningAxis, TO_SynchronousAxis and TO_ExternalEncoder corresponding to additional


TechnologicalParameters.
1) S7-1500 PLC: n=1; S7-1500T PLC: 1≤n≤4

Openness: API for automation of engineering workflows


1056 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

In contrast, the additional TechnologicalParameters that reference tags in the Openness API are
treated differently in SimaticML. The affected Parameters are shown in the following Table. In the
Openness API, they have the data type SW.Tags.PlcTag, but in SimaticML, the name of the
connected tag is exported.

Name TO_SpeedAxis TO_PositioningAxis / TO_ExternalEn‐


TO_SynchronousAxis coder
_Actor.Interface.EnableDriveOutputAddress X X -
_Actor.Interface.DriveReadyInputAddress X X -
_Sensor[n].ActiveHoming.DigitalInputAd‐ - X -
dress1)
_Sensor[n].PassiveHoming.DigitalInputAd‐ - X -
dress1)
_PositionLimits_HW.MinSwitchAddress - X -
_PositionLimits_HW.MaxSwitchAddress - X -
_CrossPlcOperation.Interface[n].Address‐ - X X
Out2)
_Sensor.PassiveHoming.DigitalInputAddress - - X

Parameters for TO_SpeedAxis, TO_PositioningAxis, TO_SynchronousAxis and TO_ExternalEncoder corresponding to additional


Technological parameters that reference tags.
1) S7-1500 PLC: n=1; S7-1500T PLC: 1≤n≤4
2) V5.0 n=1; ≥V6.0 1≤n≤8

XML element Connection


XML element connection describes a connection of a TO interface. The names and values of the
attributes listed below correspond to the parameter names and values of the particular
AxisEncoderHardwareConnectionInterface.

• Required Attribute "Interface"


– Possible values:

Value TO_SpeedAxis TO_PositioningAxis / TO_Synchro‐ TO_ExternalEncoder


nousAxis
Actor X X -
Sensor - - X
Sensor[n] 1)
- X -
Torque X X -
1) S7-1500 PLC: n=1; S7-1500T PLC: 1≤n≤4
• Optional Attributes InputAddress and OutputAddress
– The attribute must either be present together or not be used at all
– The possible values are bit addresses (as in API)
– The attribute describes connections to DeviceItems and Channels

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1057
Export/import
6.4 Importing/exporting data of a PLC device

• Optional Attribute ConnectOption


– May only be used together with InputAddress and OutputAddress
– The attribute corresponds to method parameter of same name at
AxisEncoderHardwareConnectionInterface.Connect
– The attribute has the possible values Default and AllowAllModules
• Optional Attribute SensorIndexInActorTelegram
– The attribute is used for connections to sensor part in actor telegram
– The rules are the same as defined for the according API attribute
• Optional Attribute PathToDBMember
– The attribute has the same possible values as for parameter of corresponding method
– Describes a connection to a DB member
• Optional Attribute OutputTag
– The value is name of connected PlcTag
– The attribute describes a connection to an analog tag

Connect TO_SynchronousAxis with leading values


You connect TO_SynchronousAxis with leading values via the service
SynchronousAxisMasterValues, see Connecting synchronous axis with leading values
(Page 635).

Specific attributes for OutputCam, CamTrack and MeasuringInput technology objects

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The API supports the import and export of technology objects. The following section describes
the specific attributes.

Export TO_OutputCam, TO_CamTrack and TO_MeasuringInput


For the TO types TO_OutputCam, TO_CamTrack and TO_MeasuringInput the EOM attribute
ParameterData contains the Parameters as described in the following tables. Parameters
corresponding to TO DB members have the data type and the default value as defined in the TO
DB.

Openness: API for automation of engineering workflows


1058 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

The attribute ParameterData contains the following parameters for TO_OutputCam and
TO_MeasuringInput:

Name TO_OutputCam TO_MeasuringInput


Interface.LogicOperation X -
Parameter.MeasuringInputType - X

Parameters for TO_OutputCam and TO_MeasuringInput corresponding to TO DB members


TO_CamTrack does not have any elements in the attribute ParameterData. The Parameter
"_AssociatedObject" is not used in the export.

XML element "Connection"

Value Description TO_OutputCam TO_CamTrack TO_MeasuringInput


Interface Single possible value: OutputCam X - X
OutputAddress • The value is bit address X X -
• It describes a connection to a chan‐
nel
OutputTag • The value is name of connected X X -
PlcTag
• It describes a connection to an ana‐
log tag
InputAddress • The value is bit address - - X
• It describes a connection to a Devi‐
ceItem or a channel

Specific attributes for Cam technology objects

Application
The API supports the import and export of technology objects. The following section describes
the specific attributes.

Export TO_Cam or TO_CAM_10k


For the TO type TO_Cam or TO_CAM_10k the EOM attribute ParameterData contains the
parameters as described in the following tables. Parameters corresponding to TO DB parameters
have the data type and the default value as defined in the TO DB.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1059
Export/import
6.4 Importing/exporting data of a PLC device

XML elements

XML element Description


ParameterData The attribute ParameterData contains the parameters as described
below.
ProfileData The XML element ProfileData is a single child element of Parame‐
ters inside the EOM attribute ParameterData.
Top level extension element, contains the XML element General‐
Configuration followed by the XML element Elements.
GeneralConfiguration The element GeneralConfiguration describes the general configu‐
ration that is valid for the complete cam profile.
Additionally, the following optional attributes are used:
• Attribute StandardContinuity
Possible values are Position, Velocity, Acceleration (default val‐
ue) and Jerk
• Attribute StandardOptimizationGoal
Possible values are None (default value), Velocity, Accelera‐
tion, Jerk and DynamicMoment
• Attribute InterpolationMode
Possible values are Linear, CubicSpline (default value) and Be‐
zierSpline
• Attribute BoundaryConditions
Possible values are NoConstraint (default value) and FirstDeri‐
vative
DesignLeadingRange Describes the leading value range of the curve definition.
The following two optional attributes with datatype xsd:float are
used:
• Attribute Start
Default value is 0
• Attribute End
Default value is 360
The value of Start must be less than the value of End.
DesignFollowingRange The element describes the following value range of the curve def‐
inition.
• Attribute Start
Default value is -1
• Attribute End
Default value is 1

Openness: API for automation of engineering workflows


1060 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

XML element Description


Elements The element contains the list of cam profile elements. A cam pro‐
file element is described by an XML element, and it can be either a
Point or a segment type.
Possible segment types are:
• Line
• Polynomial
• VDITransition
• Sine
• InverseSine
• PointGroup
All segment types share the two common required XML attributes
StartX and EndX of type xsd:float. These attributes contain the X
coordinate at the start respectively the end of the segment.
Point The element describes a single point.The following attributes are
used, all of them have the datatype xsd:float and default value 0:
• Required Attribute X
• Required Attribute Y
• Optional Attribute Velocity
• Optional Attribute Acceleration
• Optional Attribute Jerk
Line Describes a Line segment. The following attributes are used, all of
them have the datatype xsd:float and default value 0:
• Optional Attribute StartY
Contains the Y coordinate at the start of the line
• Optional Attribute EndY
Contains the Y coordinate at the end of the line
• Optional Attribute Gradient
Contains the gradient of the line
Two of these three optional attributes must be present in the ex‐
port.XML
Polynomial The element describes a Polynomial segment. The XML element
Polynomial has the sub elements TrigonometricValues, Coeffi‐
cients and Constraints.TrigonometricValues can be used optional‐
ly, but either Coefficients or Constraints need to be present.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1061
Export/import
6.4 Importing/exporting data of a PLC device

XML element Description


TrigonometricValues The element TrigonometricValues can be optionally used as sub
element of Polynomial.
It has the following attributes with datatype xsd:float:
• Optional Attribute Amplitude
Default value is 1
• Optional Attribute StartPhase
Default value is 0
• Optional Attribute EndPhase
Default value is 6.2831853071795862
• Optional Attribute Frequency
Default value is 1
• Optional Attribute PeriodLength
Default value is 1
Two of the attributes StartPhase, EndPhase, Frequency and Peri‐
odLength must be used. Additionally, at least StartPhase or End‐
Phase needs to be present.
Coefficients The element Coefficients can be optionally used as sub element of
Polynomial.It has the optional attributes C0, C1, C2, C3, C4, C5 and
C6. Each of them has the datatype xsd:float and the default value
0.
Constraints This element can be optionally used as sub element of Polynomial.
It has the following attributes with datatype xsd:float and default
value 0:
Optional Attribute LeftValue
Optional Attribute RightValue
Optional Attribute LeftVelocity
Optional Attribute RightVelocity
Optional Attribute LeftAcceleration
Optional Attribute RightAcceleration
Optional Attribute LeftJerk
Optional Attribute RightJerk
Optional Attribute Lambda
Additionally, it has the optional attribute LambdaMode which sup‐
ports the values Relative and Absolute (default value).
VDITransition The element describes a VDI transition segment.
It has the optional attributes LeftContinuity and RightContinuity
which can have the values AsProfile (default value), Position, Ve‐
locity, Acceleration and Jerk.
Additionally, the optional attribute OptimizationGoal with the pos‐
sible values AsProfile (default value), None, Velocity, Acceleration,
Jerk and DynamicMoment can be used.

Openness: API for automation of engineering workflows


1062 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

XML element Description


InverseSine The element describes an InverseSine segment. It has the follow‐
ing optional attributes:
• InterpolationPointCount
• MaxFollowingValueTolerance
• MathStartX
• MathEndX
• Minimum
• Maximum
• Inversed
Sine Describes a Sine segment. The Sine element has the following at‐
tributes:
• Amplitude
• StartPhase
• EndPhase
• Frequency
• PeriodLength
• Inclination
• StartOffset
• EndOffset
PointGroup The element describes a PointGroup segment that contains several
Points. The PointGroup element has the following optional attrib‐
utes:
• ApproximationDataPoints
• ApproximationTolerance
• LeadingValueMode
• FollowingValueMode
• ApproximationMode

Specific attributes for Kinematics technology objects

Application
The API supports the import and export of technology objects. The following section describes
the specific attributes.

Export TO_Kinematics
For the TO type TO_Kinematics the EOM attribute ParameterData contains the following
parameters.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1063
Export/import
6.4 Importing/exporting data of a PLC device

The following parameters corresponding to TO DB parameters have the data type and the
default value as defined in the TO DB:
• Kinematics.TypeOfKinematics
• MotionQueue.MaxNumberOfCommands
The following parameters have the same data type in SimaticML as the respective
TechnologicalParameters in the Openness API:
• _X_Minimum
• _X_Maximum
• _Y_Minimum
• _Y_Maximum
• _Z_Minimum
• _Z_Maximum
• _A3_Maximum

XML elements

XML element Description


AdditionalData The element contains up to four KinematicsAxis elements, fol‐
lowed by a ConveyorTrackingLeadingValues element.
KinematicsAxis The element describes a connected kinematics axis. This XML ele‐
ment has the following attributes:
• Required Attribute Index
Possible values are 1 to 4
The index values denote the index of the connected axis at the
TO_Kinematics, and thus they need to be unique.
• Required Attribute Ref
Denotes the name of the connected TO
• Required attribute Type
Contains the associated TO type (version independent)
ConveyorTrackingLeadingValues The element contains elements for SetPointCoupling followed by
elements for ActualValueCoupling, DelayedCoupling.
SetPointCoupling The element describes a connected leading value TO that is cou‐
pled via setpoint values. It has the following attributes:
• Required Attribute Ref
Denotes the name of the connected TO
• Required attribute Type
Contains the associated TO type (version independent)
ActualValueCoupling The element describes a connected leading value TO that is cou‐
pled via actual values. The same attributes as at SetPointCoupling
elements are used.
DelayedCoupling The element describes a connected leading value TO that is cou‐
pled via actual values. The same attributes as at SetPointCoupling
elements are used.

Openness: API for automation of engineering workflows


1064 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Specific attributes for LeadingAxisProxy technology objects

Application
The API supports the import and export of technology objects. The following section describes
the specific attributes.

Export TO_LeadingAxisProxy
For the TO type TO_LeadingAxisProxy the EOM attribute ParameterData contains additional
parameters _Interface.AddressIn. The additional TechnologicalParameter references a tag. Here
the same rules apply as described inSpecific attributes for Axis and Encoder technology objects
(Page 1055).

6.4.2.7 PID control

Specific attributes for PID_Compact


The API interface supports the export and import of technology objects. You can find a list of all
available parameters in the product information "Parameters of technology objects in TIA Portal
Openness" on the internet (https://support.industry.siemens.com/cs/ww/en/view/109744932).

Export
For the TO type PID_Compact all parameters correspond to TO DB members and have the data
type and the default value as defined in the TO DB. The EOM attribute ParameterData is empty.

Import
The following parameters for PID_Compact are not part of the import:
• PhysicalUnit
• PhysicalQuantity
• _Config.OutputSelect
• _Retain.CtrlParams.SetByUser
These parameters will have the default value after the import.

Note
Remake the associated settings manually after an import of a PID_Compact export file. This can
be done by using the function Writing parameters (Page 609).

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1065
Export/import
6.4 Importing/exporting data of a PLC device

Specific attributes for PID_3Step and PID_Temp


The API interface supports the export and import of technology objects. You can find a list of all
available parameters in the product information "Parameters of technology objects in TIA Portal
Openness" on the internet (https://support.industry.siemens.com/cs/ww/en/view/109744932).

Export
For the TO types PID_3Step and PID_Temp all parameters correspond to TO DB members and
have the data type and the default value as defined in the TO DB. The EOM
attribute ParameterData is empty.

Import
The following parameters for PID_3Step and PID_Temp are not part of the import:
• PhysicalUnit
• PhysicalQuantity
These parameters will have the default value after the import. If you want to modify them you
have to use the function Writing parameters (Page 609).

Note
Remake the associated settings manually after an import of a PID_3Step or PID_Temp export file.

6.4.2.8 Counting

The API interface supports the export and import of technology objects. You can find a list of all
available parameters in the product information "Parameters of technology objects in TIA Portal
Openness" on the internet (https://support.industry.siemens.com/cs/ww/en/view/109744932).
For the TO types High_Speed_Counter and SSI_Absolute_Encoder all parameters correspond to
TO DB members and have the data type and the default value as defined in the TO DB. The EOM
attribute ParameterData is empty.

6.4.2.9 Easy Motion Control

The API interface supports the export and import of technology objects. You can find a list of all
available parameters in the product information "Parameters of technology objects in TIA Portal
Openness" on the internet (https://support.industry.siemens.com/cs/ww/en/view/109744932).
For the TO type AXIS_REF all parameters correspond to TO DB members and have the data type
and the default value as defined in the TO DB. The EOM attribute ParameterData is empty.

Openness: API for automation of engineering workflows


1066 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

6.4.3 Tag tables

6.4.3.1 Exporting PLC tag tables

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
One XML file is exported per PLC tag table.
The TIA Portal Openness API supports the export of all PLC tag tables from the system group and
its subgroups.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1067
Export/import
6.4 Importing/exporting data of a PLC device

Program code
Modify the following program code to export all PLC tag tables from the system group and its
subgroups:

private static void ExportAllTagTables(PlcSoftware plcSoftware)


{
PlcTagTableSystemGroup plcTagTableSystemGroup = plcSoftware.TagTableGroup;
// Export all tables in the system group
ExportTagTables(plcTagTableSystemGroup.TagTables);
// Export the tables in underlying user groups
foreach(PlcTagTableUserGroup userGroup in plcTagTableSystemGroup.Groups)
{
ExportUserGroupDeep(userGroup);
}
}

private static void ExportTagTables(PlcTagTableComposition tagTables)


{
foreach(PlcTagTable table in tagTables)
{
table.Export(new FileInfo(string.Format(@”D:\Samples\{0}.xml”, table.Name)),
ExportOptions.WithDefaults);
}
}

private static void ExportUserGroupDeep(PlcTagTableUserGroup group)


{
ExportTagTables(group.TagTables);
foreach(PlcTagTableUserGroup userGroup in group.Groups)
{
ExportUserGroupDeep(userGroup);
}
}

See also
Exporting configuration data (Page 884)

6.4.3.2 Importing PLC tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


1068 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Program code
Modify the following program code to import PLC tag tables or a folder structure with PLC tag
tables from an XML file into the system group or a user-defined group:

//Imports tag tables to the tag system group


private static void ImportTagTable(PlcSoftware plcSoftware)
{
PlcTagTableSystemGroup plcTagTableSystemGroup = plcSoftware.TagTableGroup;
PlcTagTableComposition tagTables = plcTagTableSystemGroup.TagTables;
tagTables.Import(new FileInfo(@"D:\Samples\myTagTable.xml"), ImportOptions.Override);
// Or, to import into a subfolder:
// plcTagTableSystemGroup.Groups.Find("SubGroup").TagTables.Import(new
FileInfo(@"D:\Samples\myTagTable.xml"), ImportOptions.Override);
}

See also
Notes on performance of TIA Portal Openness (Page 112)

6.4.3.3 Exporting an individual tag or constant from a PLC tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
The API interface supports the export of a tag or constant from a PLC tag table to an XML file.
Make sure that the tag table names used conform to the file naming conventions of your file
system.
The comment of a tag or constant is only exported if at least one language is set for the
comment. If the comment is not set for all project languages, this comment is only exported for
the set project languages.

Note
PLC system constants
PLC system constants are excluded from export and import.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1069
Export/import
6.4 Importing/exporting data of a PLC device

Program code
Modify the following program code to export a specific tag or constant from a PLC tag table to
an XML file:

//Exports a single tag or constant of a controller tag table


private static void ExportTag(PlcSoftware plcSoftware, string tagName)
{
PlcTagTableSystemGroup plcTagTableSystemGroup = plcSoftware.TagTableGroup;
PlcTag tag = plcTagTableSystemGroup.TagTables[0].Tags.Find(tagName);
if(tag 0= null) return;

tag.Export(new FileInfo(string.Format(@”D:\Samples\{0}.xml”, tag.Name)),


ExportOptions.WithDefaults);
}

private static void ExportUserConstant(PlcSoftware plcSoftware, string userConstantName)


{
PlcTagTableSystemGroup plcTagTableSystemGroup = plcSoftware.TagTableGroup;
PlcUserConstant plcConstant =
plcTagTableSystemGroup.TagTables[0].UserConstants.Find(userConstantName);
if(plcConstant== null) return;

plcConstant.Export(new FileInfo(string.Format(@”D:\Samples\{0}.xml”,
plcConstant.Name)), ExportOptions.WithDefaults);
}

See also
Exporting configuration data (Page 884)
Notes on performance of TIA Portal Openness (Page 112)

6.4.3.4 Importing an individual tag or constant into a PLC tag table

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
You can import either tags or constants in an import call.

Openness: API for automation of engineering workflows


1070 System Manual, 05/2021, Online documentation
Export/import
6.4 Importing/exporting data of a PLC device

Note
Constants can oly beimported as user constants.

Program code
Modify the following program code to import tag groups or individual tags and constants from
an XML file:

//Imports tags into a plc tag table


private static void ImportTag(PlcSoftware plcSoftware, string tagtableName)
{
PlcTagTableSystemGroup plcTagTableSystemgroup = plcSoftware.TagTableGroup;
PlcTagTable tagTable = plcTagTableSystemgroup.TagTables.Find(tagtableName);
if(tagTable == null) return;

tagTable.Tags.Import(new FileInfo(@"D:\Samples\myTags.xml"), ImportOptions.Override);


}

//Imports constants into a plc tag table


private static void ImportConstant(PlcSoftware plcSoftware, string tagtableName)
{
PlcTagTableSystemGroup plcTagTableSystemgroup = plcSoftware.TagTableGroup;
PlcTagTable tagTable = plcTagTableSystemgroup.TagTables.Find(tagtableName);
if(tagTable == null) return;

tagTable.UserConstants.Import(new FileInfo(@"D:\Samples\myConstants.xml"),
ImportOptions.Override);
}

See also
Exporting configuration data (Page 884)
Notes on performance of TIA Portal Openness (Page 112)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1071
Export/import
6.5 Importing/exporting hardware data

6.5 Importing/exporting hardware data

6.5.1 AML file format

Introduction
AutomationML is a neutral data format based on XML for the storage and exchange of plant
engineering information, which is provided as open standard. Goal of AutomationML is to
interconnect the heterogeneous tool landscape of modern engineering tools in their different
disciplines, e.g. mechanical plant engineering, electrical design, HMI, PLC, robot control.
The class model used for the export and import of CAx data is based on the following AML
standards:
• Whitepaper AutomationML Part 1 – AutomationML Architecture, October 2014
• Whitepaper AutomationML Part 2 –AutomationML Role Libraries, October 2014
• Whitepaper AutomationML Part 4 –AutomationML Logic, May 2010
• Whitepaper AutomationML– AutomationML Communication, September 2014
• Whitepaper AutomationML– AutomationML and eCl@ss Integration, November 2015
• Application Recommendations: Automation Project Configuration - AR_001E Version 1.0.0,
Mai.2017

Schema
The AutomationML data exchange model is described by the CAEX schema Version 2.15. You
can download this file from the homepage of AutomationML e.V. (https://
www.automationml.org/o.red.c/dateien.html)

6.5.2 Pruned AML

Introduction
Pruning is the act of optimizing the content by removing certain things which are not necessarily
to be provided. In case of external tools like EPLAN , the auto created sub module information
within a hardware configuration has no significance with respect to EPLAN. Hence, these tools
generate an AML file by removing the auto created sub module information from the hardware
configuration. This file is called as pruned AML.

Generation of pruned AML


Generation of a Pruned AML is based on the following rules in order.
1. If a device item is pluggable, it shall not be pruned.
2. If a device item is of type "interface" or "port", it shall not be pruned.

Openness: API for automation of engineering workflows


1072 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

3. If a device item is built-in and is at rack level, it shall not be pruned


4. AddressObjects of type "diagnosis" are not relevant for the prune algorithm.
5. Address objects linked with the auto created sub modules shall be provided under the
immediate parent (which shall be a non-auto created sub module).
6. Address objects shall be included in the same sequence as returned by TIA Portal Openness.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1073
Export/import
6.5 Importing/exporting hardware data

6.5.3 Overview of the objects and parameters of the CAx import/export

Export/Import objects and attributes


The following figure shows the exportable objects with their attributes and dependencies of the
CAx Import/Export.

Openness: API for automation of engineering workflows


1074 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

$XWRPDWLRQ3URMHFW

3URMHFW1DPH
3URMHFW0DQXIDFWXUHU
3URMHFW6LJQ
3URMHFW5HYLVLRQ
3URMHFW,QIRUPDWLRQ

6XEQHW 'HYLFH 'HYLFH8VHU)ROGHU

1DPH 1DPH 1DPH


7\SH 7\SH,GHQWLILHU
&RPPHQW

'HYLFH,WHP

1DPH
7\SH1DPH 7DJ7DEOH 7DJ8VHU)ROGHU
'HYLFH,WHP7\SH
3RVLWLRQ1XPEHU 1DPH 1DPH
%XLOW,Q $VVLJQ7R'HIDXOW
7\SH,GHQWLILHU
)LUPZDUH9HUVLRQ
3ODQW'HVLJQDWLRQ,(&
/RFDWLRQ,GHQWLILHU,(&
&RPPHQW
$GGUHVV>Q@6WDUW$GGUHVV/HQJWK,27\SH

&KDQQHO 7DJ

7\SH 1DPH
,R7\SH 'DWD7\SH
1XPEHU /RJLFDO$GGUHVV
/HQJWK &RPPHQW
&RPPXQLFDWLRQ,QWHUIDFH

/DEHO

1RGH ,R6\VWHP &RPPXQLFDWLRQ3RUW

7\SH 1XPEHU /DEHO


1HWZRUN$GGUHVV 1DPH

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1075
Export/import
6.5 Importing/exporting hardware data

6.5.4 Structure of the CAx data for importing/exporting

Basic structure of an export file


The data in the export file from the import/export is structured with reference to a basic
structure. The export file is generated in an AML format.
The AML file starts with a document information. The file includes the data of the computer-
specific installation of the exported project.
It shall be possible in TIA Portal Openness V16 onwards to support export and import AML files
with a new version of "AR APC V1.1.0".
TIA Portal V16 can import AML files with "AR APC V1.0.0" and "AR APC V1.1.0".
AML files generated by TIA Portal older versions like V14 SP1, V15, V15.1 should still export and
import AML files "AR APC V1.0.0".
From TIA Portal V17 onwards, CAx shall export/import the AML file in accordance to the latest
version of AR APC 1.2.0 recommendation document
The content of the AML file will not undergo any change with respect to AR APC 1.2.0 and shall
still host the same hardware configuration content as the AR APC 1.1.0 version of TIA Portal
The export file comprises the following two sections:
• Additional information
The <WriterHeader> includes information about the export or import process. The import
ignores the content of the <AdditionalInformation> section.
For example you can insert a <AdditionalInformation>...</
AdditionalInformation> block, in which you place additional information about the
validation. After the AML file is forwarded, the recipient can use this block before the import to
check whether the AML file has been changed.
Below XML depicts the AML file with latest AR APC recommendation corresponding to TIA Portal
V17 version in AdditionalInformation section
• Additional Information

Note
CAx shall perform export and import of AR APC version in AML file in accordance to the installed
version of TIA Portal.

Openness: API for automation of engineering workflows


1076 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

• Instance hierarchy
This section contains the hierarchical sequence of the exported internal elements.

Internal elements

All objects inside the instance hierarchy of the AML file are InternalElements. The internal
element AutomationProject contains all internal elements of all role classes. Every internal
element supports a set of attributes.
The attribute <TypeIdentifier> identifies every object type of a hardware object that is
creatable via TIA Portal Openness.

Note
Auto-created objects
Auto-created objects can only be created by other objects. They do not have properties or a type-
identifier. They are included in the exported file, but you cannot trigger the export of a specific
autocreated object.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1077
Export/import
6.5 Importing/exporting hardware data

At the end of the AML-element of an internal element, the following are defined:
• Role class
The SupportedRoleClass element defines the object type of the internal element. The
object type is defined in the role class library that maps the standard AML to the object model
of TIA Portal Openness and TIA Portal.

• Internal link
The element InternalLink defines the communication partners of a connection.

Openness: API for automation of engineering workflows


1078 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Attributes
Attributes are assigned to internal elements as follows:

Handling modes for attributes


The handling of attributes is defined for every attribute indiviually as follows:
• Ignored
The attribute will be ignored during import and is not present in the export file.
• Mandatory
The attribute has to be present in an import file and may not be deleted in the export file.
• Optional
If this attribute is missing in the import file, the default value for the attribute is specified. This
attribute is missing in an export file if it is not applicable for an object, e. g. not all modules
have a FirmwareVersion.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1079
Export/import
6.5 Importing/exporting hardware data

• Export-only
The attribute value is determined by the TIA Portal internally, e. g. the type name of a device
item. If it is present in an import file, it will be ignored by the TIA Portal during import.
• Import-only
The attribute can influence the import behavior. If the attribute is missing in an import file,
the behavior will correlate to the standard value for the attribute.

See also
AML type identifiers (Page 1080)

6.5.5 AML type identifiers

Internal elements
The TypeIdentifier string consists of several parts:
• <TypeIdentifierType>:<Identifier>
The following values for TypeIdentifierType are possible:
• OrderNumber used to specify pyhsical modules
• GSD used to specify GSD/GSDML based devices
• System used to specify systems and generic devices

Type identifier type: OrderNumber


OrderNumber is the common type identifier for all modules present in the hardware catalog,
excluding GSD. AML type identifier are not always equal to TIA Portal Openness type identifier.
AML type identifier do not have a FirmwareVersion info. The information about firmware
versions is handled in a separate AML attribute "FirmwareVersion".

Openness: API for automation of engineering workflows


1080 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

The format for this TypeIdentifierType is as following:


• <OrderNumber>
Example: OrderNumber:3RK1 200-0CE00-0AA2
Note
Wildcards in order numbers
There are a few modules in the hardware catalog which use "wildcard" characters in their
order number to represent a certain cluster of real hardware, e. g. the different lengths of
S7-300 racks.
In this case the specific OrderNumber and the "wildcard"-OrderNumber can both be used
to create an instance of the hardware object. However, you cannot generically use wildcards
at any position. Example: An S7-300 rack can be created in the following ways:
OrderNumber:6ES7 390-1***0-0AA0
or
OrderNumber:6ES7 390-1AE80-0AA0
Regard that you cannot use the following structure for instance:
OrderNumber:6ES7 390-1AE80-0A*0
The return value of reading the type identifier is always the order number from the hardware
catalog.
Example: Reading OrderNumber:6ES7 390-1AE80-0AA0
returns OrderNumber:6ES7 390-1***0-0AA0

Type identifier type: GSD


The type identifier for GSD and GSDML based devices is TypeIdentifier =
GSD:<Identifier>
The identifier is composed by the following elements
• GsdName: name of the GSD or GSDML in uppercase letters
• GsdType: One of the following:
– D: Device
– R: Rack
– DAP: HeadModule
– M: Module
– SM: Submodule
• GsdId: ID of the GSD or GSDML

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1081
Export/import
6.5 Importing/exporting hardware data

The following formats for the type identifier are supported of the CAx import/export:
• GSD.<GsdName>/<GsdType>
Examples:
GSD:SIEM8139.GSD/DAP
GSD:GSDML-V2.31-SIEMENS-SINAMICS_DCP-20140313.XML/D
• <GsdName>/<GsdType>/<GsdId>
Examples:
GSD:SIEM8139.GSD/M/4
GSD:GSDML-V2.31-SIEMENS-SINAMICS_G110M-20140704.XML/M/IDM_DRIVE_47

Type identifier type: System


System. is the identifier for objects that cannot be determined by any other identifier. The
formats for this TypeIdentifierType are as following:
• <SystemTypeIdentifier>
Examples:
System:Device.S7300
System:Subnet.Ethernet
• <SystemTypeIdentifier>/<AdditionalTypeIdentifier>
The AdditionalTypeIdentifier is necessary in case the SystemTypeIdentifier is
not unique.
The SystemTypeIdentifier has a prefix for certain object types:
Subnet.
Device.
Rack.
Example: System:Rack.S71600/Large
A rack with an ordner number is identified via the OrderNumber identifier.

Openness: API for automation of engineering workflows


1082 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Displaying type identifiers in TIA Portal


If you need to know a type identifier you inquire it in TIA Portal as follows:
1. Enable the setting "Enable display of the type identifier for devices and modules" in "Options
> Settings > Hardware configuration > Display of the type identifier".
2. Open the editor "Devices & networks".
3. Select a device in the Catalog.
The type identifier is displayed in the viewlet "Information"

6.5.6 Export/Import of base unit Information via AML

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline

Application
In TIA Portal, you can export and import base unit information from and to TIA Portal so as to
facililate the information exchange with other tools like EPLAN.
There are two types of base units supported during export and import in TIA Portal project:
• Single base unit
• Double base unit

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1083
Export/import
6.5 Importing/exporting hardware data

Export of base unit


For example, a module configured with base unit information in TIA Portal, CAx shall export base
unit information as a 'sub-module' under a module in the AML file.
The base unit submodule shall always be exported with:
• PositionNumber: 0
• DeviceItemType: Accessory
• BuiltIn: False
• TypeIdentifier: "The typeId of the Baseunit"
• ID: Always randomly generated GUID

Export of single base unit


The below example shows an AML file for DI module configured with a single base unit in TIA
Portal

<InternalElement ID="6f76c890-5c5d-41c4-9ade-96543b0222ac" Name="DI 8x24VDC ST_1">


...
<InternalElement ID="69233c1f-7ef7-4999-8e84-691d0ff3a210" Name="BaseUnit">
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>Accessory</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 193-6BP00-0DA0</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
...

Export of double base unit


The below example shows an AML file for two DI modules configured with double base unit in
TIA Portal. For example, first module shall be configured with base unit having prefix 'IX300' and
second shall be configured with same double base unit having prefix 'IX301'.

Openness: API for automation of engineering workflows


1084 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

During export, only first module which is configured with base unit having IX300 suffix shall be
exported with a base unit sub-module in the AML file. The second module, the one configured
with IX301 shall not be injected with any Sub-module under it.

<InternalElement ID="6f76c890-5c5d-41c4-9ade-96543b0222ac" Name="DI 8x24VDC ST_1">


...
<InternalElement ID="3a1bee8a-12d0-4ec4-849c-333d45113d9c" Name="BaseUnit">
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>Accessory</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 193-6BP60-0DA0</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
...
<InternalElement ID="5f843491-b053-4dc8-b879-9ac327ee2a7e" Name="DI 8x24VDC ST_2">
...
<InternalElement ID="55c30280-6f8a-4c37-9b2d-41bb90941258" Name="DI 8x24VDC ST_2">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value> </Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
...

Import of base unit


It shall be possible to import a module configured with a base unit sub-module in an AML file.
During import of base unit,
• GUID, PositionNumber, BuiltIn, and DeviceItem has no relevance, and hence it is not
displayed in TIA Portal
• If any unintended module has base unit sub-module in AML file, Openness shallnot return
"BaseUnit" attribute for it. Hence, CAx shall display a proper warning for it in the log file.
• CAx shall not verify for 'correctness' of base unit MLFB in AML file (except using it to identify
whether it is single or double BU). CAx shall try to set the MLFB of base unit through
Openness. In case of an error from Openness a proper error will be displayed.
• Import of previous version AML file with/without any BaseUnit information should be
successful by importing information into TIA Portal.

Import of single base unit


During single base unit import, only the module carrying the base unit submodule in the AML
file shall be imported with base unit information in TIA Portal.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1085
Export/import
6.5 Importing/exporting hardware data

Single BaseUnit shall be identified from the TypeIdentifier in AML file with a specific pattern as
below:
OrderNumber:xxxx 193-6[B|U|T]xYx-xxxx where value of Y (11th Position) can be in the range
of 0 to 5.
Import of double base unit:
During double base unit import, two modules(adjacent) shall be displayed with base unit
information in TIA Portal. The first module configured with double base unit submodule in AML
file shall be imported with a double base unit by appending suffix '|X300' to base unit MLFB. The
second module, the one not having any base unit sub-module under it shall be imported with
same double base unit by appending suffix '|X301' to base unit MLFB. Double BaseUnit shall be
identified from the TypeIdentifier in AML file with a specific pattern as below:
OrderNumber:xxxx 193-6[B|U|T]x6x-xxxx

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.7 Export/Import AML with extension rack connection

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
In TIA Portal, you can export the devices with multiple racks having extension rack connection
to an AML file and also import it back to get the same device configuration created back in the
TIA Portal project.

Openness: API for automation of engineering workflows


1086 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Example: Device with multiple racks having extension rack connections

AML structure
In TIA Portal, extension rack connections between multiple racks are modeled under sender and
receiver modules (both are DeviceItem objects) directly. However as per AR APC
recommendation, these connections to be modeled as Port-to-Port connection under a
CommunicationPort. A dummy CommunicationInterface having dummy CommunicationPort
objects shall be added under IM modul to make inline with the recommendation.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1087
Export/import
6.5 Importing/exporting hardware data

The following sample shows a partial element structure of the exported AML file for above device
configuration:

Openness: API for automation of engineering workflows


1088 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<InternalElement ID="1ddb8d5c-d6cc-42c9-b1d8-621219b139f6" Name="RackExtension">


<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ExtensionRack</Value>
</Attribute>
...
<InternalElement ID="f25e531a-1793-4896-ade5-a87bd98de06e" Name="IM 46x SenderPort_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="9a824a06-89b9-4ba8-bee0-83c89b1f5e53"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
...
<InternalElement ID="d841278f-558a-41ab-9f03-91eeb454dc6b" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ExtensionRack</Value>
</Attribute>
...
<InternalElement ID="2e1ff3b2-8a3e-4d5b-a95c-3ed027287db9" Name="IM 46x ReceiverPort_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="98460c75-a05d-4c23-8f88-33878ccd79c5"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="7615a32e-09dc-4171-88ed-118026357bae" Name="IM 46x SenderPort_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X2</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1089
Export/import
6.5 Importing/exporting hardware data

<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">


<Value>true</Value>
</Attribute>
<ExternalInterface ID="846093a9-6473-4946-acf4-95a7813924df"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
...
<InternalElement ID="f4eb31c6-41d4-4a6e-ac33-de9c054a8c74" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ExtensionRack</Value>
</Attribute>
...
<InternalElement ID="c11d2227-91db-41ae-9d94-d822e3ab9c7a" Name="IM 46x ReceiverPort_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="a9b2cce1-7078-4347-b5f2-428da1ad5326"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
...
<InternalLink Name="Link To Port_1" RefPartnerSideA="f25e531a-1793-4896-ade5-
a87bd98de06e:CommunicationPortInterface" RefPartnerSideB="2e1ff3b2-8a3e-4d5b-
a95c-3ed027287db9:CommunicationPortInterface" />
<InternalLink Name="Link To Port_2"
RefPartnerSideA="7615a32e-09dc-4171-88ed-118026357bae:CommunicationPortInterface"
RefPartnerSideB="c11d2227-91db-41ae-9d94-d822e3ab9c7a:CommunicationPortInterface" />

Openness: API for automation of engineering workflows


1090 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Note
The extension rack interface shall be exported only when extension rack connections are
present. Also, the number of dummy ports added under ExtensionRack dummy interface is
based on ports participating in extension rack connection at module level. In above example, the
"IM 460-0_1" module supports two ports (IM 46x SenderPort_1 and IM 46x SenderPort_2).
However, only one port is configured with connection in TIA Portal. Hence, the exported AML
file shall contain only one port under extension rack interface.

Extension rack connection


The XML representation of extension rack connections between multiple racks shall be done
using format shown below.

ExternalInterface-
<ExternalInterface> internal element shall be added under <CommunicationPort> internal
element which participates in the connection

<InternalElement ID="[IM Module Unique ID]" Name="[IM Module Name]">


...
<InternalElement ID="[Dummy Interface Unique ID]" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ExtensionRack</Value>
</Attribute>
...
<InternalElement ID="[Dummy Port Unique ID]" Name="[IM Module Sender/Receiver Name]">
...
<ExternalInterface ID="[External Interface Unique ID]" Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="[Dummy Port Unique ID]" Name="[IM Module Sender/Receiver Name]">
...
<ExternalInterface ID="[External Interface Unique ID]" Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1091
Export/import
6.5 Importing/exporting hardware data

Internal link
Extension racks connections are represented using <InternalLink> tags. The <InternalLink> tags
shall be added under common parent of multiple racks (i.e., Device). Internal link name shall be
unique across the common parent.

<InternalLink Name="Link To [Internal link Name]" RefPartnerSideA="[Communication Port


UniqueID]:[Communication Port External Interface Name]" RefPartnerSideB="[Communication
Port UniqueID]:[Communication Port External Interface Name]" />

6.5.8 Connection handling for extension racks

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
You can use the TIA Portal Openness to fetch, add, and remove extension rack connections so
that you can make use of TIA Portal Openness to implement extension rack connection support
during CAx export/import.

Program code

ImConnection imConnection = portDeviceItem.GetService<ImConnection>();


imConnection.Connect(partnerport);
imConnection.Disconnect();
imConnection.GetPartnerPort();
var imConnectionOwner = imConnection.OwnedBy;

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1092 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.9 Export of CAx data

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
In TIA Portal you can export your configuration in the device&networks editor to an AML file. This
function is based on TIA Portal Openness and enables you to export hardware data from project
or device level.
TIA Portal Openness provides the following ways to export CAx data:
• Export function
The export function is accessed via CaxProvider service. To get the CaxProvider service
invoke the GetService method at Project object.
• Command line interface
You execute the "Siemens.Automation.Cax.AmiHost.exe" located in "C:\Program Files
\Siemens\Automation\Portal V..\Bin\" by passing specific command line arguments.
With TIA Portal V17 user interface, It shall be possible to perform CAx export and import
operation in multiuser environment. If a Server project is opened alongside the local session,
then Export and Import will happen for Server Project. For exporting and importing local session,
the Server project needs to be closed.
Furthermore, for purpose of single device export as CAx, device context menu shall have menu
entry for performing Export for a Server project in case it is open. In this case the context menu
shall not appear for local Session. For a single device export as CAx, the context menu shall be
available for a local session only when user closes Server project view.
It shall also be possible in TIA Portal Openness V17 to perform CAx export and import operation
in multi user environment. For multiuser project (local session and server project) to participate
in exchange via AML, a new API for export is used. The new Export API takes 'ProjectBase' as an
argument. You can now use Export API to export both single and multiuser project.

Note
This Command line interface is applicable only for single user project. Multi user projects (local
session and server project) are not yet supported via Command line.

As of TIA Portal OpennessV17, CAx export/import functionality through UI, API or Command line
will no longer check:
• Windows Group for Openness 'Siemens TIA Openness' is present
• Windows User is a member of 'Siemens TIA Openness' Group

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1093
Export/import
6.5 Importing/exporting hardware data

Note
For invoking CAx APIs in a client application, you have to make sure that either the application
is signed with proper Openness certificate, or Openness 'Siemens TIA Openness' Group is
present and the user is a member of the group.

Export and Import restrictions for CAx


CAx does not support the export and import of
• HMI devices except push button panels and key panels
• Drives
CAx does not support the export and import of the following Scalance device items:
• 6AV2 104-0xxxx-xxxx
• 6AV2 155-xxxxx-xxxx
• 6ES7 XXX-XXXXX-XXXX
• 6ES7 370-0AA01-0AA0
• 6ES7 451-3AL00-0AE0
• 6GK5 414-3FC00-2AA2
• 6GK5 414-3FC10-2AA2
• 6GK5 495-8BA00-8AA2
• 6GK5 496-4MA00-8AA2
• 6GK5 602-0BA00-2AA3
• 6GK5 602-0BA10-2AA3
• 6GK5 612-0BA00-2AA3
• 6GK5 612-0BA10-2AA3
• 6GK5 613-0BA00-2AA3
• 6GK5 623-0BA10-2AA3
• 6GK5 627-2BA10-2AA3
• System:Device.Scalance/S627
• System:IPIProxy.Device
• System:IPIProxy.Rack
• System:Rack.Scalance/X200BA-Y V4.2
• OrderNumber:6ES7 611-4SB00-0YB7
• OrderNumber:6ES7 611-4FB00-0YB7
• OrderNumber:6ES7 677-1DD00-0BB0
• OrderNumber:6ES7 677-1DD10-0BB0

Openness: API for automation of engineering workflows


1094 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

• OrderNumber:6ES7 677-1FD00-0FB0
• OrderNumber:6ES7 677-1FD10-0FB0

Note
From TIA Portal Openness V17 onwards, Normalized format of TypeIdentifier of above
mentioned device items can also be considered for exclusion.

Program code: Access the CaxProvider service


Modify the following program code to access the CaxProvider service:

//For Single Project


ProjectBase project = tiaPortal.Projects.Open(...);
//Or
//for LocalSession of a Multiuser Project
MultiuserProject project = tiaPortal.LocalSessions.Open(...).Project;
//Or
//for Server Project of a Multiuser Project
MultiuserProject project = tiaPortal.LocalSessions.OpenServerProject(...).Project;
Or
//Single user Project
Project project = tiaPortal.Projects.Open(...);
CaxProvider caxProvider = project.GetService<CaxProvider>();
if(caxProvider != null)
{
// Perform CAx export and import operation
}

CAx export at project level


To export CAx data at project level, use the Export method with the following parameters in TIA
Portal V14 onwards:

Name Type Example Description


ProjectToExport Project tiaPortal.Projects[0] Project object to Export
ExportFilePath FileInfo new FileInfo(@"D:\Temp Full Export file path of AML file
\ProjectExport.aml")
LogFilePath FileInfo new FileInfo(@"D:\Temp Full file path of Log file
\ProjectExport_Log.log")

To export CAx data at project level, use the Export method with the following parameters in TIA
Portal V17 onwards:

Name Type Description


ProjectToExport ProjectBase Single or Multiuser Project object to Export
ExportFilePath FileInfo Full Export file path of AML file
LogFilePath FileInfo Full file path of Log file

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1095
Export/import
6.5 Importing/exporting hardware data

Return Type

Type Description
bool True, if CAx Export operation completed without
errors; otherwise False

Modify the following program code to export CAx data at project level:

caxProvider.Export(project, new FileInfo(@"D:\Temp\ProjectExport.aml"),


new FileInfo(@"D:\Temp\ProjectExport_Log.log"));

CAx export at device level


To export CAx data at device level, use the Export method with the following parameters:

Name Type Example Description


DeviceToEx‐ Device project.Devices[0] Device object to Export
port
ExportFile‐ FileInfo new FileInfo(@"D:\Temp\Project‐ Full Export file path of AML file
Path Export.aml")
LogFilePath FileInfo new FileInfo(@"D:\Temp\Project‐ Full file path of Log file
Export_Log.log")

Return Type

Type Description
bool True, if CAx Export operation completed without
errors; otherwise False

Modify the following program code to export CAx data at project level:

caxProvider.Export(device, new FileInfo(@"D:\Temp\DeviceExport.aml"), new


FileInfo(@"D:\Temp\DeviceExport_Log.log"));

CAx export via command line


To export CAx data via command line, use "Siemens.Automation.Cax.AmiHost.exe" with the
following parameters:

Parameter Example Description


-p -p "D:\Temp\MyProject.ap*" Specifies a full path name to an existing
TIA Portal project.
-d -d "S7300/ET200M station_1" Optional paramter. If no device is speic‐
fied export will take place at project lev‐
el.
Specifies the name of the device or sta‐
tion inside the specified TIA project, that
needs to be exported.

Openness: API for automation of engineering workflows


1096 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Parameter Example Description


-m -m "AML" Specifies the export/import mode (for‐
mat for export/import):
"AML" exports in AML format
-e -e "D:\Import" Specifies full path of AML file to be ex‐
-e "D:\Import\CAx_Export.aml" ported. The project name will be used as
exported file name if only a path is speci‐
fied.

Modify the following program code to o export CAx data at project level via the command line:

//please adapt the path and the extension apx to the installed version of
TIA Portal
Siemens.Automation.Cax.AmiHost.exe -p "D:\Temp\MyProject.apx" -m "AML" -e
"D:\Import\CAx_Export.aml"

Modify the following program code to o export CAx data at device level via the command line:

//please adapt the path and the extension apx to the installed version of
TIA Portal
Siemens.Automation.Cax.AmiHost.exe -p "D:\Temp\MyProject.apx" -d "S7300/
ET200M station_1" -m "AML" -e "D:\Import\CAx_Export.aml"

6.5.10 Import of CAx data

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Application
In TIA Portal you can import your configuration in the device&networks editor from an AML file.
This function enables you to import hardware data from project or device level.
TIA Portal Openness provides the following ways to export CAx data:
• Import function
The import function is accessed via CaxProvider service. To get the CaxProvider service
invoke the GetService method at Project object.
• Command line
You execute the "Siemens.Automation.Cax.AmiHost.exe" located in "C:\Program Files
\Siemens\Automation\Portal V..\Bin\" by passing specific command line arguments:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1097
Export/import
6.5 Importing/exporting hardware data

Program code: Access the CaxProvider service


Modify the following program code:

//Access the CaxProvider service


Project project = tiaPortal.Projects.Open(...);
CaxProvider caxProvider = project.GetService<CaxProvider>();

if(caxProvider != null)

{
// Perform Cax export and import operation
}

CAx import
To import CAx data into a TIA Portal project, you use the Import method with the following
parameters:

Name Example Description


ImportFilePath new FileInfo(@"D:\Temp\ProjectEx‐ Full import file path of AML file
port.aml")
LogFilePath new FileInfo(@"D:\Temp\ProjectEx‐ Full file path of log file
port_Log.log")
ImportOptions CaxImportOptions.MoveToParkingLot Conflict resolution strategies in case of im‐
CaxImportOptions.RetainTiaDevice porting into an already existing non empty
project.
CaxImportOptions.OverwriteTiaDevice

Modify the following program code to import CAx data:

caxProvider.Import(new FileInfo(@"D:\Temp\ProjectImport.aml"), new


FileInfo(@"D:\Temp\ProjectImport_Log.log"),
CaxImportOptions.MoveToParkingLot);

The following CaxImportOptions are provided:

Import option Description


MoveToParkingLot Retain name conflicting device/s in the project and import those out of CAx into a
parkinglot folder
RetainTiaDevice Retain name conflicting device/s in the project and do not import those out of CAx
OverwriteTiaDe‐ Overwrite name conflicting device/s in the project by the ones out of CAx
vice

Openness: API for automation of engineering workflows


1098 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

CAx import via command line


To import CAx data via command line, use "Siemens.Automation.Cax.AmiHost.exe" with the
following parameters:

Parameter Example Description


-p -p "D:\Temp\MyProject.ap*" Specifies a full path name to an existing
TIA Portal project.
-m -m "AML" Specifies the export/import mode (for‐
mat for export/import):
"AML" exports in AML format
-i -i "D:\Import\CAx_Export.aml" Specifies full path of the AML file to be
imported.
-c -c "ParkingLot" Specifies differnt strategies if there is a
conflict in the device name according to
import options.

Modify the following program code to o import CAx data via the command line:

//please adapt the path and the extension apx to the installed version of
TIA Portal
Siemens.Automation.Cax.AmiHost.exe -p "D:\Temp\MyProject.apx" -m "AML" -i
"D:\Import\CAx_Export.aml"

The following import options are provided:

Import option Description


ParkingLot Retain name conflicting device/s in the project and import those out of CAx into a
parkinglot folder
RetainTia Retain name conflicting device/s in the project and do not import those out of CAx
OverwriteTia Overwrite name conflicting device/s in the project by the ones out of CAx

6.5.11 Export/Import of sub modules

Requirements
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is offline

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1099
Export/import
6.5 Importing/exporting hardware data

Application
You can have round trip exchange of sub modules data between the TIA Portal and other
engineering tools, e.g. CAD tool like EPLAN by keeping a common hierarchy for sub modules
inside AML file during export and import. For example, the sub modules like Bus Adapters shall
have different internal hierarchy in TIA Portal than in other applications (e.g., CAD tools like
EPLAN).

AML structure of the export file


You can export sub modules data from TIA Portal hierarchy to AML file hierarchy.

Openness: API for automation of engineering workflows


1100 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

The following example depicts the partial AML file structure that shall be generated during the
export of Bus Adapter as sub module from TIA Portal .

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1101
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8"?>


<CAEXFile FileName="Project4.aml" SchemaVersion="2.15"
xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
<AdditionalInformation>
<WriterHeader>
<WriterName>Totally Integrated Automation Portal</WriterName>
<WriterID>1d4fcebb-1ad6-4881-b01d-bca335d94a46:V1.0</WriterID>
<WriterVendor>Siemens AG</WriterVendor>
<WriterVendorURL>www.siemens.com</WriterVendorURL>
<WriterVersion>15</WriterVersion>
<WriterRelease>1500.0100.0.0</WriterRelease>
<LastWritingDateTime>2018-05-03T11:23:10.3011329Z</LastWritingDateTime>
</WriterHeader>
</AdditionalInformation>
<AdditionalInformation AutomationMLVersion="2.0" />
<AdditionalInformation DocumentVersions="Recommendations">
<Document DocumentIdentifier="AR APC" Version="1.1.0" />
</AdditionalInformation>
<InstanceHierarchy Name="APC Sample Instance Hierarchy">
<InternalElement ID="6cd7f80f-e049-4958-ba67-630481805bf0" Name="Project4">
<Attribute Name="ProjectManufacturer" AttributeDataType="xs:string" />
<Attribute Name="ProjectSign" AttributeDataType="xs:string" />
<Attribute Name="ProjectRevision" AttributeDataType="xs:string" />
<Attribute Name="ProjectInformation" AttributeDataType="xs:string" />
<InternalElement ID="b27045c4-9cb3-4b8d-916b-85f8100d1602" Name="Ungrouped devices">
<InternalElement ID="3f770698-940d-49c2-9f77-06fc458e1340" Name="ET 200SP station_1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.ET200SP</Value>
</Attribute>
<InternalElement ID="6f52fbab-a221-4d54-9368-84c392ca7fec" Name="Rack_0">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>Rack</Value>
...
<InternalElement ID="f7445c0b-1c52-4a84-915f-2c8bee13af70" Name="BA 2xRJ45">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>BA 2xRJ45</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>127</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 193-6AR00-0AA0</Value>
</Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string">
<Value>V0.0</Value>
</Attribute>
<InternalElement ID="40f8bbce-35d3-4d65-907a-bece3e0144e0" Name="PROFINET interface">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">

Openness: API for automation of engineering workflows


1102 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<InternalElement ID="8fb775eb-96c6-48d6-af8a-96ba72418830" Name="IE1">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value>
</Attribute>
<Attribute Name="NetworkAddress" AttributeDataType="xs:string">
<Value>192.168.0.1</Value>
</Attribute>
<Attribute Name="SubnetMask" AttributeDataType="xs:string">
<Value>255.255.255.0</Value>
</Attribute>
<Attribute Name="IpProtocolSelection" AttributeDataType="xs:string">
<Value>Project</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/Node" />
</InternalElement>
<InternalElement ID="f28a3d93-d821-4556-9df1-a45f0e4ff6a6" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P1 R</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="ad6a0faa-3b70-4528-8c54-8183018b6714" Name="Port_2">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P2 R</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
...

Note
CAx shall perform export and import of AR APC version in AML file in accordance to the installed
version of TIA Portal.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1103
Export/import
6.5 Importing/exporting hardware data

Import sub modules


You can import sub modules from an AML files, which is generated from above export.

Note
• The export hierarchy change behavior shall be applicable only in versions V15.1 onwards
• The hierarchy in AML file shall not influence/affect the TIA Portal internal hierarchy after
Import.
• The AML files created using older TIA Portal versions shall also be imported without any
failure.
• This hierarchy change/transformation behavior is applicable for both built-in and non built-in
sub modules.

Multiple sub modules under same Interface


There are some scenarios where multiple sub modules shall exist under a same interface. For ex:
IO Device : IM 155-6 PN/3 HF 6ES7 155-6AU30-0CN0/V4.2. This head module has two non built-
in Bus Adapters under a same interface. In such case, it shall be possible to export mentioned Bus
Adapters from TIA Portal hierarchy to required AML file hierarchy. In this example from TIA Portal
hierarchy, 'PROFINET interface' has two Bus Adapters, three ports and one node. Here, Port_1
and Port_2 logically belongs to BA 2xRJ45 and Port_3 logically belongs to BA 2xRJ45_1 though
all the three ports are aggregated under one interface.
During Export:
• AML file should be exported with Label and Type attribute supported for secondary interface
• Only first sub module shall get 'original' interface along with its connection relevant
information. Here, BA 2xRJ45 gets original interface along with node 'IE1', 'Port_1' and
'Port_2'.
• Rest of the sub modules shall get a 'duplicate' interface with ports which logically belongs to
the sub module. Here, BA 2xRJ45_1 shall get a 'duplicate' interface and Port_3.
• If the head module is connected to a subnet/Iosystem, the relevant link information(like
ExternalInterface links) shall be exported only as part of first sub module (ExternalInterface
link related to Subnet under 'Node' and ExternalInterface link related to IoSystem under
'Interface') .
• The link information pertaining to topology connection, shall be part of respective 'Port'.
During import:
• It shall be possible to import multiple sub modules from an AML file which is generated out
of above mentioned export.
• It shall be possible that EPLAN generated AML file shall have node information inside
secondary interface

Openness: API for automation of engineering workflows


1104 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

• Node details, which is duplicate of primary interface node are handled as mentioned below:
– Node Attributes: Overwrites node attribute details which set during Primary interface
processing
– Subnet Connection: Silently skipped if it is already connected otherwise connection shall
be established
• If the AML file contains IoSystem connection details on secondary interface, then
– Connection shall be skipped if already connected and user shall be notified with proper
error message in InfoTab.
– Connection shall be established if it is not connected.
The following configuration shows IO device configuration with master-slave and topology
connections.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1105
Export/import
6.5 Importing/exporting hardware data

The below example shows a partial AML file that shall be generated during export for the above
configuration:

Openness: API for automation of engineering workflows


1106 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8"?>


<CAEXFile FileName="MultipleBA_01.aml" SchemaVersion="2.15"
xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
<AdditionalInformation>
<WriterHeader>
<WriterName>Totally Integrated Automation Portal</WriterName>
<WriterID>1d4fcebb-1ad6-4881-b01d-bca335d94a46:V1.0</WriterID>
<WriterVendor>Siemens AG</WriterVendor>
<WriterVendorURL>www.siemens.com</WriterVendorURL>
<WriterVersion>15</WriterVersion>
<WriterRelease>1501.0000.0.0</WriterRelease>
<LastWritingDateTime>2018-05-17T09:36:46.9230179Z</LastWritingDateTime>
</WriterHeader>
</AdditionalInformation>
<AdditionalInformation AutomationMLVersion="2.0" />
<AdditionalInformation DocumentVersions="Recommendations">
<Document DocumentIdentifier="AR APC" Version="1.1.0" />
</AdditionalInformation>
<InstanceHierarchy Name="APC Sample Instance Hierarchy">
<InternalElement ID="e005c094-1b0a-42c4-92a0-67c981508c1a" Name="Project45">
<Attribute Name="ProjectManufacturer" AttributeDataType="xs:string" />
<Attribute Name="ProjectSign" AttributeDataType="xs:string" />
<Attribute Name="ProjectRevision" AttributeDataType="xs:string" />
<Attribute Name="ProjectInformation" AttributeDataType="xs:string" />
<InternalElement ID="2782e61d-8c27-46cb-93ea-6b804157ae60" Name="PN/IE_1">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value>
</Attribute>
<ExternalInterface ID="2d901881-a2bf-4fe7-915f-b2542b346988" Name="LogicalEndPoint_Subnet"
RefBaseClassPath="CommunicationInterfaceClassLib/LogicalEndPoint" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Subnet" />
...
<InternalElement ID="dc5cf410-2516-4b0b-ad1a-c43117d8c9b3" Name="BA 2xRJ45">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>BA 2xRJ45</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>127</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 193-6AR00-0AA0</Value>
</Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string">
<Value>V0.0</Value>
</Attribute>
<InternalElement ID="f04874a8-2d35-47c4-93ae-d6fdc2668479" Name="PROFINET interface">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1107
Export/import
6.5 Importing/exporting hardware data

</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="81a7d9df-99b8-4eca-8e72-404b22bd05e7"
Name="LogicalEndPoint_Interface" RefBaseClassPath="CommunicationInterfaceClassLib/
LogicalEndPoint" />
<InternalElement ID="83eb7d69-8cd5-4217-a07a-0c656d215ec7" Name="IE1">
...

Devices with sub module and integrated port at Interface level


There are some device configuration where a module can support an integrated port as well as
extended ports(For ex: via sub module i.e., Bus Adapter). For ex: ET200SP CPU: CPU 1510SP-1
PN/6ES7 510-1DJ00-0AB0/V1.8. This CPU module supports three ports (two ports via Bus
Adapter and one integrated port) under a same interface.
In this example from TIA Portal hierarchy, 'PROFINET interface' has Bus adapter, three ports and
one node. Here, Port_1 and Port_2 logically belongs to BA 2xRJ45 and Port_3 logically belongs
to PROFINET interface though all the three ports are aggregated under one interface.
During export:
• The sub module shall get 'original' interface along with its connection relevant information.
Here, BA 2xRJ45 gets original interface along with 'IE1', 'Port_1' and 'Port_2'. And head
module shall have the 'duplicate' interface (having Type-'Ethernet') with only integrated port
'Port_3' in it.
• In case sub module (BA 2xRJ45) is not plugged, then PROFINET interface at head module
level shall be considered as 'original' interface and shall have 'IE1' and 'Port_3'.
• If the head module is connected to a Subnet/IoSystem, then relevant link information (like
ExternalInterface links) shall be exported only as part of 'original' interface (ExternalInterface
link related to Subnet under 'Node' and ExternalInterface link related to IoSystem under
'Interface').
• The link information pertaining to topology connection, shall be part of respective 'Port'.
During import:
• It shall be possible to import modules with interface having sub module and integrated port
under it from an AML file which is generated out of the above-mentioned export.
• Handling redundant information (Node, IoSystem and links) under 'duplicate' interface shall
be handled in a same way as 'Multiple sub modules under same interface' scenario.
The following configuration shows modules with master-slave and topology connections.

Openness: API for automation of engineering workflows


1108 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1109
Export/import
6.5 Importing/exporting hardware data

The AML file that shall be generated during export for the above configuration is depicted below:

Openness: API for automation of engineering workflows


1110 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8"?>


<CAEXFile FileName="Project_BusAdapter_Demo.aml" SchemaVersion="2.15"
xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
...
<AdditionalInformation AutomationMLVersion="2.0" />
<AdditionalInformation DocumentVersions="Recommendations">
<Document DocumentIdentifier="AR APC" Version="1.2.0" />
</AdditionalInformation>
<InternalElement ID="12b43940-cea6-476a-886c-11ebaa518256" Name="BA 2xRJ45">
...
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 193-6AR00-0AA0</Value>
</Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string">
<Value>V0.0</Value>
</Attribute>
<InternalElement ID="8f8a4cdb-8f4b-4e72-8c92-b8fa1cc3bf70" Name="PROFINET interface_1">
...
<InternalElement ID="7a9938c3-ccc0-4d28-be35-333a343f3613" Name="E1">
...
<ExternalInterface ID="3d9f7f55-723f-4c5d-a2e7-ffe1ec3b9167" Name="LogicalEndPoint_Node"
RefBaseClassPath="CommunicationInterfaceClassLib/LogicalEndPoint" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/Node" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationEthernetRoleClassLib/
NodeEthernet" /</InternalElement>
<InternalElement ID="3c4085cb-7565-4673-8de1-c5624c4c08dc" Name="PROFINET IO-System">
<Attribute Name="Number" AttributeDataType="xs:int">
<Value>100</Value>
</Attribute>
<ExternalInterface ID="7fb6129f-95c4-4d2c-aab5-702937198e80"
Name="LogicalEndPoint_IoSystem" RefBaseClassPath="CommunicationInterfaceClassLib/
LogicalEndPoint" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
IoSystem" />
</InternalElement>
<InternalElement ID="1f1d3e8d-55da-4355-b87e-7feb58d86143" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P1 R</Value>
</Attribute>
...
<ExternalInterface ID="850e3f32-985f-4432-b627-26e2775a69cc"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="11731ed5-7922-41c9-b179-a5ae029cc10d" Name="Port_2">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P2 R</Value>
</Attribute>
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" /> </InternalElement>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1111
Export/import
6.5 Importing/exporting hardware data

<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="7be36254-5ed6-4a6f-9e7b-90be8b35e595" Name="PROFINET interface_1">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value>
</Attribute>
...
<InternalElement ID="61ac6187-8a5d-4f98-ae91-b809c0a3a15d" Name="Port_3">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P3</Value>
</Attribute>
...
<ExternalInterface ID="425f5a5d-84e2-40c6-928f-e1aab73a8b86"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>

Pruned AML
Pruning is an act of optimizing the content by removing certain things which are not necessary
to be provided. For information on Pruned AML, (Refer Pruned AML (Page 1072)).
There might be some scenarios where sub module configuration hierarchy is not same in TIA
Portal and CAD tools (like EPALN) due to pruned sub modules. In such scenarios, TIA Portal shall
support import of both pruned and unpruned AML files.

Note
• TIA Portal shall always export unpruned AML file.
• TIA Portal shall always import both pruned and unpruned AML file

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1112 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.12 Export/Import AML file in UMAC environment

Introduction
With TIA Portal V17, it shall be possible to perform CAx export and import operations on a UMAC
protected project.
CAx operations on protected project is based on the below mentioned functions rights:
• Project with read and write access
• Modify project via Openness API

Export
CAx export operation is not restricted. So, it shall be possible to perform export operations on
protected project irrespective of the above mentioned users function rights.

Import
CAx import operation is restricted. When a user has above mentioned access rights then import
shall be successful, otherwise missing function rights error message shall be displayed in TIA
Portal user interface or Function rights not found exception shall be thrown for CAx API.

User function rights and CAx operation


Below table depicts the users function rights and their allowed CAx operations:

Users Function Rights CAx Operations


Project with read and Modify project via Export Import
write access Openness API
Project Administrator X X X X
Project read-only user - X X -
User without Openness X - X -
access
Read-only user without - - X -
Openness access

Note
• From TIA Portal V17 onwards, it shall be possible to perform CAx Export operation on read-
only project.

To perform Export and Import on UMAC protected project using CAx API, project needs to be
opened in UMAC protected environment. see Opening a Project (Page 113)via API for opening
project in UMAC protected environment.

See also
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1113
Export/import
6.5 Importing/exporting hardware data

6.5.13 Export/Import AML file with normalized type identifier

Introduction
In TIA Portal, there are different notations for order numbers inside type identifiers. In order to
allow import and export of these different notations of order numbers to integrate with other
tools, Tolerant handling of Order Numbers in Automation AML files is now possible.
In order to export TypeIdentifier format of TIA Portal V16 and below, a new setting has been
added:

If this checkbox "With TypeIdentifier format from V16 and below" is checked, TypeIdentifier value
in AML will be exported in old format, e.g. OrderNumber:6ES7 516-3AN00-0AB0.
If this checkbox is unchecked, TypeIdentifier value in AML will be exported with Order number's
wildcard characters denoted by "*" and blanks will be removed, e.g.
OrderNumber:6ES7590-1***0-0AA0.
During the import arbitrary wild card characters and blanks are accepted as part of the order
number of a TypeIdentifier.

6.5.14 Export/import AML file with custom attributes in GSD/GSDML

Introduction
Custom attributes in general allow the exchange of data which are specific for a certain device
or module and not covered by an AutomationML based specification. Currently in TIA Portal
custom attributes are only supported for GSD/GSDML based modules. Only additional data of
the module itself can be exchanged by custom attributes but not additional data at ports,
interfaces, nodes, etc.
Custom attributes are defined in the AR APC V1.2 as an unordered list of name value pairs. The
AML structure is given here:

<Attribute Name="CustomAttributes">
<RefSemantic CorrespondingAttributePath="ListType" />
<Attribute Name="AttributeName1" AttributeDataType="xs:string">
<Value>AttributeValue1</Value>
</Attribute>
<Attribute Name="AttributeName2" AttributeDataType="xs:string">
<Value>AttributeValue2</Value>
</Attribute>
</Attribute>

Openness: API for automation of engineering workflows


1114 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

To allow a correct identification of a custom attribute in the TIA Portal, the name of the custom
attribute must conform to the following definitions:
A custom attribute named consists of three parts <name>, <attribute_location>,
<value_location>.
• <name> is a string containing only alphanumeric letters, numbers , "_" and ".". Usually the
‘name’ is the attribute name found in GSD/GSDML file. It is an optional part for attributes in
parameter dataset otherwise mandatory.
• <attribute_location> defines the device item where the attribute is located. This is required
to identify the location of the attribute if it is not located directly at the module. It has the
form #<subslotnumber>#<subsubslotnumber>. That means, if the attribute is located at the
module the <attribute_location> is empty, if it is located at a Sub Module it is
"#<subslotnumber>" and in case of a location at a sub sub module the value is
"#<subslotnumber>#<subsubslotnumber>".
• <value location> defines how to access an attribute at its device item. In case the value is
part of a parameter data set, it is identified by the following quintuple:
– DatasetNumber: The number of the data set at the device item.
– ByteOffset: The position in bytes (starting with 0) where the value begins within the
parameter data set.
– Length: The overall length of the data set in bytes.
– BitOffset: The position in bits (starting with 0) where the value begins within its start byte
(see ByteOffset).
– BitLength: The complete length of the value in bit
Overall example for custom attributes:

<Attribute name = "CustomAttribute">


<RefSemantic CorrespondingAttributePath="ListType"/>
<Attribute Name="IDTP_No_Unit_DIAG#0-1-0-2-7-1" AttributeDataType="xs:string">
<Value>1<Value>
</Attribute>
<Attribute Name="IDTP_LANG#0-1-1-2-0-4" AttributeDataType="xs:string">
<Value>89<Value>
<Attribute Name="IDTP_D_FREEZE#0-1-1-2-7-1" AttributeDataType="xs:string">
<Value>1<Value>
</Attribute>
</Attribute>

In some (rare) cases the attribute is explicitly modelled (not part of parameter data set) in the
GSD/GSDML. Then the value is accessed via attribute name.

Note
On export TIA Portal always exports the complete data sets to allow partner applications full
access of the contained data

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1115
Export/import
6.5 Importing/exporting hardware data

<Attribute name = "CustomAttribute">


<RefSemantic CorrespondingAttributePath="ListType"/>
<Attribute Name="PrmData#0-1-0-2-0-16" AttributeDataType="xs:string">
<Value>128, 0<Value>
</Attribute>
</Attribute>

Export/import an AML file with custom attributes


With TIA Portal Openness V17, it shall be possible to exchange Parameter Data of GSD/GSDML
modules via CAx export and import. In AML file this Parameter Data shall be represented as
Custom Attributes.

Export
Below snippet shows the format in which PrmData shall be expected in the AML file if it is found
over a pluggable module.

...
<InternalElement ID="049f1260-7c97-458e-84bd-12682f943f19" Name="Slave_1">
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string"> <Value>GSD:SI018098.GSD/
DAP</Value>
</Attribute>
<Attribute Name="CustomAttributes">
<RefSemantic CorrespondingAttributePath="ListType" />
<Attribute Name="PrmData-0-0-39-0-312" AttributeDataType="xs:string">
<Value>39,129,0,0,28,0,128,15,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,15,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255</
Value>
</Attribute>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>

Openness: API for automation of engineering workflows


1116 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Below snippet shows the format in which PrmData in case where it is available over a built-in
submodule in tia portal, but in the AML file it is given at the pluggable parent.

<InternalElement ID="8fb83cae-ae30-45d2-9d4c-6db1154af02d" Name="IE-AS-i-LINK">


...
<Attribute Name="CustomAttributes">
<RefSemantic CorrespondingAttributePath="ListType" />
<Attribute Name="PrmData#0-130-0-4-0-32" AttributeDataType="xs:string">
<Value>0,0,131,0</Value>
</Attribute>
</Attribute>
<InternalElement ID="574a55bb-1209-4672-86bd-01ee9085eaf6" Name="DAP 1">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
...

• In the above snippet custom attribute name "PrmData#0-130-0-4-0-32" has the following
meaning:
– PrmData#0: Name of the attribute and position number of the submodule containing it
– 130: Dataset number
– 0: Byte Offset
– 4: Dataset length in bytes
– 0: Bit Offset
– 32: Bit length
• Custom attributes in AML file shall never appear on any built-in modules expect for built-in
modules directly placed under the Rack.
• In case of a GSD/GSDML built-in module that has PrmData , the custom attribute shall be
exported over the immediate pluggable parent or a built-in parent directly under rack,
whichever is appropriate.
• In case of prunned files(files exported from E-plan) the built-in submodule which is the actual
owner of the custom attribute shall not be present in the AML file.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1117
Export/import
6.5 Importing/exporting hardware data

Import
CAx shall support import of PrmData custom attributes over GSD/GSDML modules in the
following cases:
• If a pluggable GSD/GSDML module has been provided with custom attributes.
• If the file has the built-in submodule prunned and the custom attributes are provided over the
appropriate pluggable parent module.
• If the file is not prunned, it has the built-in submodules and the custom attributes are
provided over the appropriate pluggable parent module
Custom attributes provided as individual attributes and not as full PrmDataset shall also be
supported with CAx import. This kind of a format is expected from Eplan exported files.
Below snippet shows such a sample.

<InternalElement ID="1cf85c26-cc2a-4413-b91b-e4b55e183762" Name="Slave_1">


...
<Attribute Name="CustomAttributes">
<RefSemantic CorrespondingAttributePath="ListType" />
<Attribute Name="PSR-0-4-26-0-1" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="C4F-0-4-26-1-1" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="GPC-0-4-26-2-1" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="SFC-0-4-26-3-1" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="ACC-0-4-26-4-1" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="CMV3.1-0-4-26-5-1" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="MUPR-0-5-26-0-32" AttributeDataType="xs:string">
<Value>0,0,31,64</Value>
</Attribute>
<Attribute Name="TMR-0-9-26-0-32" AttributeDataType="xs:string">
<Value>7,255,225,236</Value>
</Attribute>
<Attribute Name="TSOLF-0-13-26-0-8" AttributeDataType="xs:string">
<Value>100</Value>
</Attribute>
<Attribute Name="PP-0-25-26-0-8" AttributeDataType="xs:string">
<Value>2</Value>
</Attribute>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
...

Openness: API for automation of engineering workflows


1118 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

In the example above all the individual custom attributes pertain to Data set number 0. But they
try to alter the value of different byte(s) and bit(s).
• CAx import shall support both Integer and Hex formats(e.g 0x67) for the value of a custom
attribute, but only one format at a time for any given attribute.

Export/import an AML file with Non PRM Data custom attributes


With TIA Portal V17 it shall be possible to exchange all attributes of GSD/GSDML modules that
have read-write access via CAx export and import. In AML file these attributes shall be
represented as Custom Attributes.

Export
CAx export shall ignore all such attributes that are read-only in TIA Portal, the custom attribute
section in a TIA Portal exported AML file shall contain attributes that are writable.
Below snippet shows the format in which custom attributes shall be expected in the AML file if
it is found over a pluggable module.

...
<InternalElement ID="806532c8-109a-42c6-82e9-84e8ba308aad" Name="cp1604">
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="CustomAttributes">
<RefSemantic CorrespondingAttributePath="ListType" />
<Attribute Name="Author" AttributeDataType="xs:string">
<Value>AuthorValue</Value>
</Attribute>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1119
Export/import
6.5 Importing/exporting hardware data

Below snippet shows the format in which custom attribute shall be exported in case where it is
available over a built-in submodule in TIA Portal, but in the AML file it is given at the pluggable
parent.

...
<InternalElement ID="806532c8-109a-42c6-82e9-84e8ba308aad" Name="cp1604">
...
<Attribute Name="CustomAttributes">
<RefSemantic CorrespondingAttributePath="ListType" />
<Attribute Name="Failsafe_FIODBNumber#0" AttributeDataType="xs:string">
<Value>0</Value>
</Attribute>
<Attribute Name="Failsafe_FParameterSignatureIndividualParameters#0"
AttributeDataType="xs:string">
<Value>5</Value>
</Attribute>
</Attribute>
<InternalElement ID="6b94abcd-3fe4-4800-9e18-ea7810d7afed" Name="PS_8Byte">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>

In the snippet above #0 signifies the position number of the built-in child item to which the
attribute really belongs to.
CAx export shall ignore all attributes that are already being exported as part of the applicable AR
APC version recommendation.
CAx shall not export custom attributes over interfaces and ports and any submodule under
them. The only exception being PrmData.

Import
CAx shall support import of custom attributes over GSD/GSDML modules in the following cases:
• If a pluggable GSD/GSDML module has been provided with custom attributes.
• If the file has the built-in submodule pruned and the custom attributes are provided over the
appropriate pluggable parent module.
• If the file is not pruned, it has the built-in sub modules and the custom attributes are provided
over the appropriate pluggable parent module.
CAx import shall ignore all custom attributes over interfaces and ports and any submodule under
them with appropriate warning. The only exception being PrmData.
CAx import shall ignore all attributes with appropriate warning that are already being imported
as part of the applicable AR APC version recommendation.

Openness: API for automation of engineering workflows


1120 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.15 Import CAx data without logical address

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)

Application
In TIA Portal, you can use CAx import to configure connection between channel and tag without
having the start address of an I/O module and/or logical address of tag specified in the AML file.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1121
Export/import
6.5 Importing/exporting hardware data

The following AML file example depicts the XML that shall be generated without start address
and logical address attributes.

Openness: API for automation of engineering workflows


1122 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8"?><CAEXFile FileName="TagsExport.aml"


SchemaVersion="2.15" xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
...
<InstanceHierarchy Name="APC Sample Instance Hierarchy">
<InternalElement ID="fff25423-fe9e-4334-9331-4cec118e06f7" Name="Project1">
...
<InternalElement ID="59c0b48b-aa6c-45c3-8dc8-bba5367bd4fb" Name="S7300/ET200M station_1">
...
<InternalElement ID="1b7b2b24-243b-4348-831e-bc46bc35957f" Name="Rail_0">
...
<InternalElement ID="974ca791-ad8d-482b-be80-2cf4e8dcedaf" Name="PLC_1">
...
<InternalElement ID="9564bcc2-8ea0-4be7-a950-5c55b34e474a" Name="Default tag table">
<ExternalInterface ID="7fd969e6-c2c9-45a8-b573-68833df327f5" Name="Tag_1"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/Tag">
<Attribute Name="DataType" AttributeDataType="xs:string">
<Value>Bool</Value>
</Attribute>
</ExternalInterface>
<ExternalInterface ID="33899862-86c1-4171-832a-1136b6e59b9d" Name="Tag_2"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/Tag">
<Attribute Name="DataType" AttributeDataType="xs:string">
<Value>Byte</Value>
</Attribute>
</ExternalInterface>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
TagTable" />
</InternalElement>
...
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>8</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<Attribute Name="Address">
<RefSemantic CorrespondingAttributePath="OrderedListType" />
<Attribute Name="1">
<Attribute Name="StartAddress" AttributeDataType="xs:int">
<Value>832</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>128</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">
<Value>Input</Value>
</Attribute>
</Attribute>
<Attribute Name="2">
<Attribute Name="StartAddress" AttributeDataType="xs:int">
<Value>832</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>128</Value>
</Attribute>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1123
Export/import
6.5 Importing/exporting hardware data

<Attribute Name="IoType" AttributeDataType="xs:string">


<Value>Output</Value>
</Attribute>
</Attribute>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="29e0bb63-0050-46e3-968a-fcecf4eb050a" Name="DI 16x24VDC_1">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>DI16 x 24VDC</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>4</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 321-1BH02-0AA0</Value>
</Attribute>
<Attribute Name="Address">
<RefSemantic CorrespondingAttributePath="OrderedListType" />
<Attribute Name="1">
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>16</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">
<Value>Input</Value>
</Attribute>
</Attribute>
</Attribute>
<ExternalInterface ID="175dc9c9-f9a3-4b10-b43e-68dfc14811fc" Name="Channel_DI_0"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/Channel">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Digital</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">
<Value>Input</Value>
</Attribute>
<Attribute Name="Number" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
</ExternalInterface>
<ExternalInterface ID="23e99053-906c-4548-9bd2-e975cacf01b2" Name="Channel_DI_1"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/Channel">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Digital</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">

Openness: API for automation of engineering workflows


1124 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<Value>Input</Value>
</Attribute>
<Attribute Name="Number" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
</ExternalInterface>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
<InternalLink Name="Link To Tag_1" RefPartnerSideA="29e0bb63-0050-46e3-968a-
fcecf4eb050a:Channel_DI_0" RefPartnerSideB="9564bcc2-8ea0-4be7-a950-5c55b34e474a:Tag_1" />
<InternalLink Name="Link To Tag_2" RefPartnerSideA="29e0bb63-0050-46e3-968a-
fcecf4eb050a:Channel_DI_0" RefPartnerSideB="9564bcc2-8ea0-4be7-a950-5c55b34e474a:Tag_2" />
<InternalLink Name="Link To Tag_3" RefPartnerSideA="29e0bb63-0050-46e3-968a-
fcecf4eb050a:Channel_DI_1" RefPartnerSideB="9564bcc2-8ea0-4be7-a950-5c55b34e474a:Tag_2" />
<InternalLink Name="Link To Tag_4" RefPartnerSideA="29e0bb63-0050-46e3-968a-
fcecf4eb050a:Channel_DI_2" RefPartnerSideB="9564bcc2-8ea0-4be7-a950-5c55b34e474a:Tag_2" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
AutomationProject" />
</InternalElement>
</InstanceHierarchy>
</CAEXFile>

Tag with Bool datatype (%I0.0)


For the above AML file example, upon import the Logical Address for tag is calculated by using
the following algorithm:
Logical Address = ChannelIoType + ByteAddress + BitAddress

Name Description
ChannelIoType Input (I) or Ouput (Q)
ByteAddress ByteAddress shall be calculated as specified below :
StartAddress of the I/O Module * 8 + BitOffsetAddress of the I/O Module + (Chan‐
nelNumber * ChannelLength) / 8
BitAddress BitAddress shall be calculated as specified below:
(BitOffsetAddress of the I/O Module + (ChannelNumber * ChannelLength)) % 8

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1125
Export/import
6.5 Importing/exporting hardware data

Note
• In cases where a tag spans across more than one modules: The algorithm above gives
multiple byte addresses based on the start address of modules and an array of bit addresses
per byte address, corresponding to each channel number. Then the algorithm shall select the
lowest byte address and the lowest among the bit address array corresponding to this byte,
for calculating the logical address of the tag. Once the logical address is assigned to the tag,
the spanning is automatically taken care by the TIA Portal during import
• In TIA Portal, only few device configuration (for example ASI modules) supports Bit Offset
address attribute. For modules which does not support BitOffset address attribute, default
value "0" will be considered for above mentioned calculation.

Following are the list of tag data types which supports Bit address in TIA Portal:

Tag data types Bit address value


Bool 0 to 7
LReal Highest and lowest bit number values is 0 in TIA
LWord Portal.
LInt
ULInt
LTime
LDT
LTime_Of_Day

During CAx import, If a boolean tag is configured to a channel type, then logical address
calculation includes bit offset address. The logical address along with bit offset shall be updated
as the tag's logical address in TIA Portal UI.

Tag with other datatypes which supports Bit Offset Address


In case of tag channel configured between two different datatypes where a channel of type bool
is mapped to a tag of type LDT which spans across multiple channels, then logical address
calculation includes bit offset address for calculating logical address for Tag of "LDT" datatype
and the tag logical address will be updated in TIA Portal UI with an error if the bit address value
is other than "0" and tag channel configuration shall not happen.
You must make sure that tag-channel configuration is happening between similar datatypes.

Tag with with other datatypes (%IB0)


Logical Address = ChannelIoType + TagDataType + ByteAddress

Name Description
ChannelIoType Input (I) or Ouput (Q)
TagDataType TagDataType is an abbreviation of the tag type.
Example: W for word and B for Byte
ByteAddress ByteAddress shall be calculated as specified below :
StartAddress of the I/O Module + ( ChannelNumber * ChannelLength) / 8

Openness: API for automation of engineering workflows


1126 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

The algorithm explained above is used to calculate the Logical Address of a tag accurately in case
of
• Length of the datatype specified in the tag should be equal to the length of the channel it is
mapped to.
• For example, If a tag of datatype "Byte" is mapped to an Analog channel which is of length
2Bytes: upon import of AMl file which doesnot have Logical Address of the tag specified; The
tag in TIA portal shall always be mapped to the first byte of the channel irrespective of which
byte it was originally mapped to.

Note
• In cases where a tag spans across more than one modules: The algorithm above gives
multiple byte addresses based on the Start Address of the modules. Then the algorithm shall
select the lowest byte address for calculating the logical address of the tag. Once the logical
address having the lowest byte address is assigned to the tag, the spanning is automatically
taken care by the portal during import. If the StartAddress attribute for the I/O Module is not
provided in the AML file, the default value is assigned by TIA portal and same shall be used
for the above calculation.
• If the StartAddress attribute for the I/O Module is not provided in the AML file, the default
value is assigned by TIA portal and same shall be used for the above calculation.

Upon successful completion of import the following tag configuration shall be created in TIA
Portal for the example above.

The channels shall be configured to the tags as depicted below.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1127
Export/import
6.5 Importing/exporting hardware data

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.16 Exceptions during import and export of CAx data

Exception due to non-availability of TIA Openness


CAx implementation is based on TIA Openness Public API's. Openness Public API's are available
only when user has installed Openness optional pack during TIA Portal installation. Hence, there
is a need to check whether Openness is available before performing any CAx related
functionalities. (Refere Installing TIA Portal Openness (Page 36))
Whenever user triggers a CAx Export or CAx Import actions from TIA Portal UI, a check is
performed to see availability of TIA Openness in the system. If TIA Openness is not found to be
installed, user will be displayed a TIA Portal message dialog with following error message dialog.

While performing the CAx operation through command-line, the following error diaglog
displays during the non-availablity of TIA Openness.

Openness: API for automation of engineering workflows


1128 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Figure 6-4 OpennessNotInstalled-Commandline

6.5.17 Round trip exchange of devices and modules

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
You can exchange configuration data between the TIA Portal and other engineering tools, e. g.
an electrical planning tool like EPLAN or the TIA selection tool. For the identification of the
imported and exported devices, a global unique identifier, the AML GUID, is used.
During the round trips, the AML GUID is kept stable for physical assets like devices and device
items which are not built-in e.g. CPUs or modules, but not for virtual assets like tags, channels, ...
During the first export from the TIA Portal, the AML GUID for a device or a no built-in device item
is randomly generated, but kept stable afterwards.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1129
Export/import
6.5 Importing/exporting hardware data

(QJLQHHULQJ7RRO $0/ILOH 7,$3RUWDO

([SRUW 3/& ,PSRUW


3/&
*8,' *8,'
*8,' *8,' *8,'
3/&

If you export a device from an engineering tool into an empty TIA Portal project, the AML GUID
is added to the comment of the hardware object. If in the TIA Portal at "Tools > Settings > CAx
> Import settings" the correspondig setting is enabled the AML GUID is added in the current
editing language. The round trip process supports only one editing language to store the AML
GUIDs. When importing or exporting data, always use the editing language with which you
started the round trip.
For all following imports or exports, the AML GUID stays the same for this hardware object.
Changes to the hardware object are resumed.
Within a TIA Portal project object names have to be unique. The import of a device or a device
item into a TIA Portal project where a certain object with the same name already exists would
lead to a naming conflict. During the import you have the possibility to move the objects with
naming conflicts to the user defined parking lot. The name of the imported Object will be
extended with "_CAX".
During CAx export of the GUI

$0/ILOH 7,$3RUWDO
3DUNLQJORW

3/& ,PSRUW
*8,' *8,' *8,'
*8,'
3/& 3/&B&$;

To support AML roundtrip for previous project version, during project upgrade AML GUIDs are
now stored in "CustomIdentity" (App ID) instead of "Comment" part of device/deviceitem. The
AML GUIDs of device/deviceItem are expected to be unique and could be stored in any editing
language. So during project upgrade, all the comment editing languages are considered to get
the unique AML GUID. As the AML GUID of device/deviceItem is unique, but when a new GUID
with matching [AR_APC:ID:*] regex is added to comment in any editing language then the first
GUID which is picked from the editing languages is considered as the AML GUID for that device/
deviceItem.
Once the AML GUID's in the comment are moved to CustomIdentity, the device/deviceItem
comment is updated by removing the [AR_APC:ID:*] as shown in the image below
If the comment contains multiple [AR_APC:ID:*] section then the first GUID which matches the
pattern is set to CustomIdentity repository and the same is removed from comment. Rest of the
text is considered as comments.

Openness: API for automation of engineering workflows


1130 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Note
Copying an imported device
If you copy a device or a device item possessing an AML GUID you have to delete the AML GUID
in the comment of the copied object. Otherwise, devices or device items with identical AML
GUID exists in your project and lead to an invalid AML file.

Import settings
1. Define the parking lot folder name under "Options > Settings > CAx > Settings for conflict
resolution".
The parking lot folder is used to store objects with naming conflicts.
2. Activate "Options > Settings > CAx > Import settings > Save GUIDs during import".
During Import:
• The GUIDs of a physical asset shall be stored as part of its CustomIdentity section
• While importing an AML file, the GUIDs are stored as part of CustomIdentity

Note
Valid AML GUID
If you edit an AML GUID before the import, the AML GUID becomes invalid and then CAx import
operation shall be aborted and corresponding information shall be logged.

Note
Exceeding length of a comment
If the appending of the AML GUID the comment exceeds its maximum limit of 500 characters,
the user comment value will be trimmed to 500 characters. A corresponding information will be
logged.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1131
Export/import
6.5 Importing/exporting hardware data

Export
During export:
• GUID to be exported shall be fetched from CustomIdentity for the key AR_APC:ID.
• If the GUID is not available as part of CustomIdentity then the Multi user GUID shall be fetched
and exported as the AML GUID
• If above 2 steps fail to provide the GUID of a physical asset then a new random GUID shall be
generated by the export process and shall be treated as the AML GUID for physical assets.

AML structure
The generated ID is exported to AML file as depicted in the following code snippet:
<InternalElement ID="23aeefd0-ce05-4116-a644-e33d43901eaf"
Name="PLC_1"

6.5.18 Import AML ignoring unknown artifacts

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• The PLC is offline

Application
It shall be possible to import an AML file containing unknown artifacts into TIA Portal where the
unknown artifacts are ignored and only relevant information consumed. Unknown artifacts
contains un-neccessary information that are not relevant for TIA Portal during CAx import
operations. The possible unknown artifacts can be an attributes, sub attributes, internal
elements and external interfaces.
Below are the two possible reactions encountering an unknown artifact during import
operations:
• The unknown artifact is "known" but meaningless to TIA Portal and can be silently ignored
• The unknown artifact is "unknown" and will be ignored but reported by a warning

Whitelist - classification of known/unknown artifacts


A special meta xml file "Automation-Cax-WhiteList.xml" is used to decide whether an unknown
artifact is known or unknown to TIA Portal. You can consider artifacts which are inside
AutomationProject. Hence, meta will also support configuring artifacts within
AutomationProject boundary.

Openness: API for automation of engineering workflows


1132 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Below are the role class types available for configuring unknown artifacts to be ignored

Whitelist Item Description


ItemType Represents type of role class. The possible values for ItemType are as below:
• AutomationProjectConfigurationRoleClassLib/AutomationProject
• AutomationProjectConfigurationRoleClassLib/Device
• AutomationProjectConfigurationRoleClassLib/DeviceItem
• AutomationProjectConfigurationRoleClassLib/DeviceUserFolder
• AutomationProjectConfigurationRoleClassLib/Subnet
• AutomationProjectConfigurationRoleClassLib/CommunicationInterface
• AutomationProjectConfigurationRoleClassLib/CommunicationPort
• AutomationProjectConfigurationRoleClassLib/Node
• AutomationProjectConfigurationRoleClassLib/IoSystem
• AutomationProjectConfigurationRoleClassLib/TagTable
• AutomationProjectConfigurationRoleClassLib/TagUserFolder
• AutomationProjectConfigurationInterfaceClassLib/Channel
• AutomationProjectConfigurationInterfaceClassLib/Tag
Name Represents name of unknown attribute/subattribute

Whitelist file structure


The following example depicts the whitelist meta file for attributes:

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright @ Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
...
<WhiteListItem ItemType="AutomationProjectConfigurationRoleClassLib/DeviceItem">
<AttributeList>
<Attribute Name="UnknownAttribute" /> <!--This is how an attribute as white list item is
configured-->
</AttributeList>
</WhiteListItem>
...
...
</WhiteList>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1133
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright @ Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
<WhiteListItem ItemType="*">
<AttributeList>
<Attribute Name="UnknownAttribute" />
<!--This is how an attribute as white list item is configured-->
</AttributeList>
</WhiteListItem>
...
</WhiteList>

The following example depicts the whitelist meta file for sub attributes:

<?xml version="1.0"encoding="utf-8" ?>


<!-- Copyright @ Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
<WhiteListItem ItemType="AutomationProjectConfigurationRoleClassLib/DeviceItem">
<SubAttributeList>
<Attribute Name ="Address">
<Attribute Name ="2">
<SubAttribute Name="UnknownSubAttribute"/> <!--This is how sub attribute as white list item
is configured-->
</Attribute>
</Attribute>
</SubAttributeList>
</WhiteListItem>
...
</WhiteList>

<?xml version="1.0"encoding="utf-8" ?>


<!-- Copyright @ Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
<WhiteListItem ItemType="*">
<SubAttributeList>
<Attribute Name ="Address">
<Attribute Name ="2">
<SubAttribute Name="UnknownSubAttribute"/> <!--This is how sub attribute as white list item
is configured-->
</Attribute>
</Attribute>
</SubAttributeList>
</WhiteListItem>
...
</WhiteList>

Openness: API for automation of engineering workflows


1134 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Note
The value "*" in ItemType shall be used to ignore all the occurrences of a particular attribute/sub-
attribute under all the internal elements/external interfaces inside an AML file.

The following structure example depicts the whitelist meta file for link(s):

<?xml version="1.0" encoding="utf-8" ?>


<!--Copyright @ Siemens AG 2018. All rights reserved.-->
<WhiteList>
...
<WhiteListItem ItemType="AutomationProjectConfigurationRoleClassLib/DeviceItem">
<LinkList>
<Link RefBaseClassPath ="Unknown external interface RefBaseClassPath"/> --><!--This is how
an link as white list item is configured--><!--
</LinkList>
</WhiteListItem>
...
</WhiteList>

<?xml version="1.0" encoding="utf-8" ?>


<!--Copyright @ Siemens AG 2018. All rights reserved.-->
<WhiteList>
...
<WhiteListItem ItemType="*">
<LinkList>
<Link RefBaseClassPath ="Unknown external interface RefBaseClassPath"/> --><!--This is how
an link as white list item is configured--><!--
</LinkList>
</WhiteListItem>
...
</WhiteList>

Note
• ItemType represents type of role class.
• The value "*" in ItemType shall be used to ignore all the occurrences of a particular external
interface under all the internal elements of an AML file.
• RefBaseClassPath represents RefBaseClassPath of an unknown external interface.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1135
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright @ Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
<WhiteListItem ItemType="*">
<LinkList>
<!--This is how ModuleAssignment is white list configured-->
<Link RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
ModuleAssignment" />
</LinkList>
</WhiteListItem>
...
</WhiteList>

Note
ModuleAssignment shall be ignored from all the places in AML file

The following example depicts the whitelist meta file for object(s):

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright © Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
<WhiteListItem ItemType="AutomationProjectConfigurationRoleClassLib/DeviceItem">
<ObjectList>
<!--This is how an object as white list item is configured-->
<Object WhiteListKey="RefBaseClassPath"
WhiteListValue="AutomationProjectConfigurationRoleClassLib/DeviceItem"/>
</ObjectList>
</WhiteListItem>
...
</WhiteList>

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright © Siemens AG 2018. All rights reserved. -->
<WhiteList>
...
<WhiteListItem ItemType="*">
<ObjectList>
<!--This is how an object as white list item is configured-->
<Object WhiteListKey="RefBaseClassPath"
WhiteListValue="AutomationProjectConfigurationRoleClassLib/DeviceItem"/>
</ObjectList>
</WhiteListItem>
...
</WhiteList>

Openness: API for automation of engineering workflows


1136 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Note
• ItemType represents type of role class.
• If we put * in ItemType then this internal element will be ignored from all place of AML file
• WhiteListKey represents RefBaseClassPath
• WhiteListValue represents role class of internal element

Multiple role internal element


From TIA Portal Openness V17 onwards, AML file with multiple role under internal element can
be processed and unknown artifacts should be ignored.
• Multiple role internal element with all unknown/whitelisted role should ignore internal
element and its child's artifacts.

<InternalElement ID="c5e8abf7-efdb-47f9-958c-74c3d88d97ac" Name="S7300/ET200M station_1">


...
<InternalElement ID="eff3a2ea-ebd9-4a18-b5aa-5e26e363b3fb" Name="Rail_0">
...
<Attribute Name="TestAttributeName" AttributeDataType="xs:string">
<Value>TestAttribute</Value>
</Attribute>
<InternalElement ID="b769c1aa-30db-4f25-8333-db90289a6b6c" Name="PLC_1">
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="72a884cd-c526-4801-94ee-aa4fcd193b7b" Name="DI 16x24VDC_1">
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/XYZ" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device" />
</InternalElement>

Here, all roles under internal element Rail_0 are unknown/whitelisted so Rail_0 and its child
artifacts (attributes/sub attributes, internal elements and external interfaces) should ignored.
• Multiple role internal element with 1 or more roles are unknown/whitelisted should ignore
that role and its child attribute(s) and external interface(s) (but not child internal element(s))
should process partially.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1137
Export/import
6.5 Importing/exporting hardware data

<InternalElement ID="c5e8abf7-efdb-47f9-958c-74c3d88d97ac" Name="S7300/ET200M station_1">


...
<InternalElement ID="eff3a2ea-ebd9-4a18-b5aa-5e26e363b3fb" Name="Rail_0">
...
<Attribute Name="TestAttributeName" AttributeDataType="xs:string">
<Value>TestAttribute</Value>
</Attribute>
<InternalElement ID="b769c1aa-30db-4f25-8333-db90289a6b6c" Name="PLC_1">
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="72a884cd-c526-4801-94ee-aa4fcd193b7b" Name="DI 16x24VDC_1">
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/XYZ" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device" />
</InternalElement>

Here, Role AutomationProjectConfigurationRoleClassLib/XYZ and attribute TestAttributeName


are unknown/whitelisted under internal element Rail_0 so it should ignore that role and
attribute and should process all other artifacts.
• Unknown/Whitelisted external interface under multiple role internal element should get
ignored.
Whitelist meta

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright © Siemens AG 2018. All rights reserved. -->
<WhiteList >
...
<WhiteListItem ItemType="AutomationProjectConfigurationDrivesExtensionRoleClassLib/
DriveAssetType">
<LinkList>
<Link RefBaseClassPath="AutomationProjectConfigurationDrivesExtensionInterfaceClassLib/
DriveAssignment" />
</LinkList>
</WhiteListItem>
...
</WhiteList>

Openness: API for automation of engineering workflows


1138 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML file

<InternalElement ID="c1f8718b-8f6d-44a1-b4fc-d50e4f8013c9" Name="DI 16x24VDC_1">


...
<ExternalInterface ID="f8d5a38d-9c51-416e-92e9-f336d1fad2de" Name="DriveAssignment"
RefBaseClassPath="AutomationProjectConfigurationDrivesExtensionInterfaceClassLib/
DriveAssignment" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
<SupportedRoleClass
RefRoleClassPath="AutomationProjectConfigurationDrivesExtensionRoleClassLib/
DriveAssetType" /> </InternalElement>

Here, DriveAssignment external interface under DriveAssetType should get ignored.


• Unknown/Whitelisted attributes under multiple role internal element should get ignored
Whitelist meta

<?xml version="1.0" encoding="utf-8" ?>


<!-- Copyright © Siemens AG 2018. All rights reserved. -->
<WhiteList >
...
<WhiteListItem ItemType="AutomationProjectConfigurationDrivesExtensionRoleClassLib/
DriveAssetType">
<AttributeList>
<Attribute Name="DriveAssetTypeAttributeName" />
</AttributeList>
</WhiteListItem>
...
</WhiteList>

AML file

<InternalElement ID="c1f8718b-8f6d-44a1-b4fc-d50e4f8013c9" Name="DI 16x24VDC_1">


<Attribute Name="DriveAssetTypeAttributeName" AttributeDataType="xs:int">
<Value>4</Value>
</Attribute>
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
<SupportedRoleClass
RefRoleClassPath="AutomationProjectConfigurationDrivesExtensionRoleClassLib/
DriveAssetType" /> </InternalElement>

Here, DriveAssetTypeAttributeName attribute under DriveAssetType should get ignored.


Internal element with Attribute DeviceItemType value Accessory should get ignored in case of
multiple role also.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1139
Export/import
6.5 Importing/exporting hardware data

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.19 Export/Import topology

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
In TIA Portal, you can export the devices with its topology information to an AML file. While
importing to an empty TIA Portal project, the imported device items retains the topology
information.
<InteralLink> element gives link details of port to port interconnection between the device
items. It appears under the common parent of the connected devices, and contains unique tag
names.

Attributes of a "InternalLink" element


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Mandatory The tag names are formatted as "Link to Port_n" (where n varies from 1 to the number of
port to port links).
RefPartnerSideA Mandatory Denotes the port which are linked. Formatted as UniqueIDOfPort:CommunicationPortIn‐
terface
RefPartnerSideB Mandatory Denotes the port which are linked. Formatted as UniqueIDOfPort:CommunicationPortIn‐
terface

Openness: API for automation of engineering workflows


1140 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Example: Topology view

AML structure
The following figures shows a partial element structure of the exported AML file. It contains two
unique ID for the ports in PLCs.

The <InteralLink> element contains three mandatory attributes.

6.5.20 Import of device with Library references

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1141
Export/import
6.5 Importing/exporting hardware data

Application
You can import device (station)/device item (module, sub-modules) in AML file into TIA Portal
using Library references.

AML Structure
The following AML structure describes the XML file that shall be used during the import
operations into TIA Portal project.

...
<InternalElement ID="bed34f88-7a3f-4e37-a32f-df1a6dcb954a" Name="S71500/ET200MP station_1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.S71500</Value>
<Attribute Name="TemplateIdentifier" AttributeDataType="xs:string">
<Value>GlobalLib://StationPlcLibrary/Master copies/DeviceFolder/S71500ET200MP station_1</
Value>
</Attribute>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device" />
...
<InternalElement ID="5082f437-4198-4dcb-b794-35b6b9fcd104" Name="PLC_1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 214-1BE30-0XB0</Value>
<Attribute Name="TemplateIdentifier" AttributeDataType="xs:string">
<Value>GlobalLib://StationPlcLibrary/Master copies/PLC_1</Value>
</Attribute>
</Attribute>
</InternalElement>
...
</InternalElement>
...

Openness: API for automation of engineering workflows


1142 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Example: Imported configuration


The AML snippet above corresponds to station and PLC in TIA Portal is depicted below:

The feature is delivered considering the following points:


• The Scope of this feature restricts the usage of libraries only to Global Libraries.
• In case a device/device item comes with TemplateIdentifier attribute, this has more priority
over Type Identifier.
• The Global Libraries used in the import operation are assumed to be loaded prior to the onset
of import, failing which an appropriate error shall be displayed to the user.
• Amongst all the System Folders found inside a library only the 'Master Copies' folder shall be
considered for import operation.
• In order to support multilingual character of TIA Portal, TemplateIdentifier can have Master
Copy path in all supported TIA languages but should be preceded with "GlobalLib://". And the
user of the Portal has to make sure that the TIA UI language and the language in the AML file
are one and the same.
• For an error free import operations the device/device item master copy in the library and the
device/device item in the AML file shouldn't have conflicting items. Conflicts here can result
in loss of data as well.
• If the device/device item in the AML file has generic Type ID or no Type ID value at all, then the
regular workflow of Type ID substitution shall operate as usual. But the device/device item
shall be created from TemplateIdentifier and after the creation the Type ID shall not be cross
verified with the substituted Type ID.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1143
Export/import
6.5 Importing/exporting hardware data

• In the AML file the TemplateIdentifier sub-attribute under TypeIdentifier attribute can feature
on any Pluggable item and only on pluggable items. Any other entity in the AML file (e.g.
Channel/Tag) if it has a Template reference, shall be treated invalid and appropriate message
to be displayed to the user.
• The character '/' in the TemplateIdentifier path shall be considered as a delimiter for folder
segregation. In case a master copy object has a name having character '/', this might result in
CAx not able to find the master copy object.
• The import merge use cases with respect to device configuration having TemplateIdentifier
should work in same way as that of device configuration having TypeIdentifier
• Existing merge use cases with AML file having only TypeIdentifier should also behave as usual.
• In case of a conflict where the same device is present in both TIA and the AML file (with a
library reference to it), the Device in library if in this case has the PLC inside, the merge
operation shall only be able to rename the Station but not the PLC.
• There is a limitation in setting start address for input output modules when they are imported
from mastercopy. Once a start address is already assigned to a module, then it is not possible
to set the start address when it is created from TemplateIdentifier during import. The
important thing to note here is that users shall add the module into the mastercopy (while
preparing global libraries) before an address is assigned to it , that means the module should
not be connected to its master controller before it is put into the master copy.

Note
• A V16/V17 AML file with device/device item having 'TemplateIdentifier' should be imported
successful in TIA Portal V17
• A V16/V17 AML file with device/device item having 'TemplateReference' should not be
imported successfully in TIA Portal V17
• A V16 AML file with device/device item having 'TemplateReference' should be successful in
V16. This behavior for V16 TIAP shall not be changed.

• Prior to TIA Portal V17, device configuration which does not support module level(especially
main modules like Head module/CPU) library drag and drop support in TIA Portal could not
be supported in CAx library workflows.
However, this kind of configuration supports complete device level library drag and drop
where user shall include pre-configured rack and main module as part of device master copy
itself and put it in to library.
With this support from TIA Portal V17, CAx shall also extend to Import the whole device master
copy from library which shall have preconfigured rack and main module in it

Openness: API for automation of engineering workflows


1144 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Below are some of the expected behavior for importing preloaded device master copy using AML
file.
• In TIA Portal V17, any AML file with device configuration having device level library reference
(with rack and main module) should import successfully by creating device from library by
retaining rack and main module also from device master copy.
– Provided, Library reference is valid
– Provided, TypeIdentifier of rack and main module inside library is inline with respective
AML TypeIdentifier
• In TIA Portal V17, any AML file with device configuration having device level library reference
(with rack and main module) should import with error by still creating device from library
with retaining rack and main module also from device master copy
– When Library reference is valid
– When TypeIdentifier of rack or main module inside library is not matching with respective
AML TypeIdentifier
• In TIA Portal V17, any AML file with device configuration having device level library reference
(with rack and main module) should import without a warning by still creating device from
library with retaining rack and main module also from device master copy, when
– When Library reference is valid
– When FW of rack or main module inside device master copy is not matching with
respective AML FW
• In TIA Portal V17, any AML file with device configuration having device level library reference
(with rack and main module) should import without a warning by still creating device from
library with retaining rack and main module also from device master copy.
– When Library reference is valid
– When FW of rack or main module is missing in AML

Recommendation for library reference usage


In general, CAx shall support multiple ways of handling library references during CAx Import.
The user shall use any of the allowed way to achieve successful import of an AML file. For
example:
1. If TIA Portal supports library workflow (drag and drop support) for main module(like Head
module/CPU) in the device configuration as an "independent" master copy, then CAx user
shall configure the AML file with device/device items as having "independent" library
reference. Here, expectation is that main module exist as an independent master copy in
library.
2. If TIA Portal does not support library workflow (drag and drop support) for main module(like
Head module/CPU) in the device configuration as an "independent" master copy, then CAx
user shall configure the AML file with device having template identifier. Here, expectation is
that main module exist as part of complete device master copy in library.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1145
Export/import
6.5 Importing/exporting hardware data

Note
Every device configuration has different behavior wrt library workflows (drag and drop) in TIA
Portal. Some device families supports library workflows at granular level (device item level) ,
some at only complete device level and some even support both. Hence, CAx user shall
configure AML files with library references by keeping these TIA Portal aspects.

Whitelist and Blacklist


• If a device/deviceitem is mentioned in the whitelist/blacklist, it means
– either the device/deviceitem has been verified as an 'independent' master copy without
any sub device items.
– or the device configuration has been verified as a 'complete' device master copy with rack
and main module in it.
• It is possible that a device item can be used in multiple device configurations. However, if it
is mentioned in the whitelist does not mean that library import for that device item works in
all the possible configuration.
– For ex: If a device item - x is mentioned with firmware version - y, then
- It might not work for different firmware version
- It might not work when plugged inside different module/station

Openness: API for automation of engineering workflows


1146 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Below table shows list of device/deviceitems that supports import using library references.

Whitelist
TypeIdentifier FirmwareVersion

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1147
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 212-1HD30-0XB0
OrderNumber:6ES7 510-1DJ00-0AB0
OrderNumber:6ES7 221-3BD30-0XB0
OrderNumber:6ES7 511-1CK00-0AB0 V2.2
OrderNumber:6ES7 516-3AN01-0AB0 V1.8
OrderNumber:6ES7 518-4AP00-0AB0 V1.0
OrderNumber:6GK7 542-5DX00-0XE0 V1.8
OrderNumber:6ES7 611-4SB00-0YB7 V1.8
OrderNumber:6ES7 315-2FJ14-0AB0 V1.8
OrderNumber:6ES7 154-8AB01-0AB0 V1.0
OrderNumber:6ES7 141-4BF00-0AA0 V4.6
OrderNumber:6ES7 137-6BD00-0BA0 V3.1
OrderNumber:6ES7 147-4JD00-0AB0 V3.2
OrderNumber:6ES7 154-4AB10-0AB0
OrderNumber:3RK7 137-6SA00-0BC1 V2.2
OrderNumber:6ES7 518-4FP00-0AB0 V1.0
OrderNumber:6GK7 543-1AX00-0XE0 V7.0/Cu
OrderNumber:6ES7 516-2GN00-0AB0 V1.1
OrderNumber:6ES7 148-4CA00-0AA0 V2.5
OrderNumber:6ES7 148-4CA60-0AA0 V2.1
OrderNumber:6ES7 154-8FX00-0AB0 V2.1
OrderNumber:6ES7 148-4EA00-0AA0
OrderNumber:6ES7 151-7AA20-0AB0
OrderNumber:6ES7 138-4CA50-0AB0 V3.2
OrderNumber:6ES7 151-8AB00-0AB0
OrderNumber:6ES7 138-4CB11-0AB0 V2.6
OrderNumber:6ES7 151-7AA21-0AB0
OrderNumber:6ES7 138-4CA60-0AB0 V2.7
OrderNumber:6ES7 151-7FA21-0AB0
OrderNumber:6ES7 138-4CA01-0AA0 V3.3
OrderNumber:6GT2002-0HD00
OrderNumber:6ES7 142-4BD00-0AA0 V3.3
OrderNumber:6SL3 235-0TE21-1RB0
OrderNumber:6SL3 235-0TE21-1SB0 V1.0
OrderNumber:6SL3 514-1KE13-5AE0
OrderNumber:6ES7 148-4EB00-0AA0 V3.1
OrderNumber:6ES7 143-4BF00-0AA0 V3.1
OrderNumber:6ES7 134-6JD00-0CA1 V4.7.6
OrderNumber:6ES7 193-6PA00-0AA0
OrderNumber:6ES7 512-1SK00-0AB0
OrderNumber:3RK1 308-0AB00-0CP0 V2.0
OrderNumber:6ES7 512-1DK00-0AB0 V1.1
OrderNumber:6ES7 137-6BD00-0BA0 V1.8
OrderNumber:6ES7 135-6HD00-0BA1 V1.1

Openness: API for automation of engineering workflows


1148 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 137-6AA00-0BA0 V1.8
OrderNumber:6ES7 510-1SJ01-0AB0 V2.1
OrderNumber:6ES7 138-6AA00-0BA0 V1.1
OrderNumber:3RK1 308-0BE00-0CP0 V1.0
OrderNumber:6ES7 135-6HB00-0DA1 V2.1
OrderNumber:6ES7 134-6FF00-0AA1 V1.2
OrderNumber:3RK1 308-0AE00-0CP0 V1.1
OrderNumber:6ES7 390-1***0-0AA0 V2.0
OrderNumber:6ES7 307-1BA00-0AA0 V1.0
OrderNumber:6ES7 318-3FL01-0AB0 V1.1
OrderNumber:6ES7 338-7XF00-0AB0
OrderNumber:6ES7 307-1KA01-0AA0
OrderNumber:6ES7 317-2FK13-0AB0 V3.2
OrderNumber:6GT2002-0GA10
OrderNumber:6ES7 307-1EA00-0AA0
OrderNumber:6ES7 317-6FF04-0AB0 V2.6
OrderNumber:6ES7 323-1BH01-0AA0
OrderNumber:6ES7 307-1EA80-0AA0
OrderNumber:6ES7 315-2FJ14-0AB0 V3.3
OrderNumber:6ES7 350-1AH03-0AE0
OrderNumber:6ES7 307-1EA01-0AA0
OrderNumber:6ES7 318-3EL00-0AB0 V3.2
OrderNumber:6ES7 321-7EH00-0AB0
OrderNumber:6ES7 307-1KA02-0AA0
OrderNumber:6ES7 317-2EK13-0AB0 V2.8
OrderNumber:6ES7 323-1BL00-0AA0
OrderNumber:6ES7 314-6BG03-0AB0
OrderNumber:6ES7 340-1AH02-0AE0 V2.6
OrderNumber:6ES7 313-6BG04-0AB0

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1149
Export/import
6.5 Importing/exporting hardware data

Whitelist
TypeIdentifier FirmwareVersion

Openness: API for automation of engineering workflows


1150 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 360-3AA01-0AA0 V2.6
OrderNumber:6ES7 314-1AG13-0AB0 V1.0
OrderNumber:6ES7 321-7TH00-0AB0 V3.3
OrderNumber:3RK1 335-0AS01-0AA0
OrderNumber:3RK1 305-0AS01-0AA0 V2.6
OrderNumber:3RW4900-0NC0
OrderNumber:6ES7 518-4AP00-0AB0 V41.0
OrderNumber:6ES7 155-5AA00-0AA0
OrderNumber:6ES7 523-1BL00-0AA0 V2.0
OrderNumber:6ES7 534-7QE00-0AB0 V2.1
OrderNumber:6ES7 157-1AA00-0AB0 V4.0
OrderNumber:6ES7 144-5KD00-0BA0 V1.0
OrderNumber:6ES7 145-5ND00-0BA0 V1.0
OrderNumber:6ES7 143-5AF00-0BA0 V1.0
OrderNumber:6ES7 147-5JD00-0BA0 V1.0
OrderNumber:6ES7 314-6EH04-0AB0 V1.0
OrderNumber:6ES7 153-4BA00-0XB0 V1.0
OrderNumber:6GK7 343-2AH01-0XA0 V1.0
OrderNumber:6ES7 155-6BU00-0CN0 V3.3
OrderNumber:6ES7 131-6BF00-0BA0 V4.0
OrderNumber:6ES7 516-3AN01-0AB0 V3.1
OrderNumber:6EP1332-4BA00 V3.1
OrderNumber:6EP3436-8MB00-2CY0 V1.1
OrderNumber:6EP4293-8HB00-0XY0 V2.1
OrderNumber:6EP4297-8HB00-0XY0
OrderNumber:6ES7 212-1BD30-0XB0 V1.1
OrderNumber:6EP4137-3AB00-2AY0 V1.1
OrderNumber:6EP4134-0GB00-0AY0 V1.1
OrderNumber:6ES7 516-3AN00-0AB0 V2.2
OrderNumber:6ES7 400-1TA01-0AA0 V2.2
OrderNumber:6ES7 405-0DA02-0AA0 V1.0
OrderNumber:6ES7 414-3EM05-0AB0 V1.8
OrderNumber:6ES7 412-1XJ05-0AB0
OrderNumber:6GK7 443-1EX11-0XE0
OrderNumber:6ES7 312-1AE13-0AB0 V5.3
OrderNumber:6GK7 343-1CX10-0XE0 V5.3
OrderNumber:6GK7 443-5DX04-0XE0 V2.7
OrderNumber:6GK7 342-5DA02-0XE0 V2.6
OrderNumber:6ES7 511-1AK00-0AB0 V2.4
OrderNumber:6GK7 542-1AX00-0XE0 V6.6
OrderNumber:6ES7 211-1BD30-0XB0 V5.0
OrderNumber:6GK7 242-7KX30-0XE0 V1.8
OrderNumber:6ES7 414-3EM05-0AB0 V1.0
OrderNumber:6ES7 151-1AA05-0AB0 V2.2

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1151
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 155-5AA00-0AC0 V1.0
OrderNumber:6ES7 155-6BU00-0CN0 V5.2
OrderNumber:6ES7 193-6PA00-0AA0
OrderNumber:6ES7 505-0KA00-0AB0 V3.0
OrderNumber:6ES7 521-1BH50-0AA0 V3.0
OrderNumber:6ES7 511-1TK01-0AB0 V1.0
OrderNumber:6ES7 515-2TM01-0AB0 V1.0
OrderNumber:6ES7 521-1BH00-0AB0 V2.0
OrderNumber:6ES7 521-1BL10-0AA0 V2.1
OrderNumber:6ES7 521-7EH00-0AB0 V2.1
OrderNumber:6ES7 521-1FH00-0AA0 V2.1
OrderNumber:6ES7 522-5HH00-0AB0 V1.0
OrderNumber:6AG1 511-1AK00-7AB0 V1.0
OrderNumber:6AG1 505-0KA00-7AB0 V2.0
OrderNumber:6AG1 531-7KF00-7AB0 V1.0
OrderNumber:6AG1 531-7NF10-7AB0 V1.8
OrderNumber:6AG1 532-5HD00-7AB0 V1.0
OrderNumber:6AG1 532-5HF00-7AB0 V2.0
OrderNumber:6AG1 521-1BH00-7AB0 V2.0
OrderNumber:6AG1 521-1FH00-7AA0 V2.0
OrderNumber:6AG1 522-1BF00-7AB0 V2.0
OrderNumber:6AG1 522-5FF00-7AB0 V2.0
OrderNumber:6AG1 550-1AA00-7AB0 V2.0
OrderNumber:6ES7 522-1BH01-0AB0 V2.0
OrderNumber:6AG1 513-1AL00-2AB0 V2.0
OrderNumber:6AG1 541-1AB00-7AB0 V1.1
OrderNumber:6AG1 542-5DX00-7XE0 V1.0
OrderNumber:6ES7 505-0RA00-0AB0 V1.8
OrderNumber:6ES7 518-4AP00-3AB0 V1.0
OrderNumber:6GK7 542-1AX00-0XE0 V1.0
OrderNumber:6ES7 551-1AB00-0AB0 V1.0
OrderNumber:6ES7 531-7PF00-0AB0 V2.1
OrderNumber:6AG1 516-3AN00-7AB0 V2.0
OrderNumber:6ES7 517-3TP00-0AB0 V1.1
OrderNumber:6ES7 540-1AD00-0AA0 V1.1
OrderNumber:6ES7 532-5HD00-0AB0 V1.8
OrderNumber:6ES7 507-0RA00-0AB0 V2.1
OrderNumber:6ES7 515-2AM00-0AB0 V1.0
OrderNumber:7MH4 980-1AA01 V2.1
OrderNumber:7MH4 980-2AA01 V1.0
OrderNumber:6ES7 553-1AA00-0AB0 V1.8
OrderNumber:6ES7 552-1AA00-0AB0
OrderNumber:6ES7 550-1AA00-0AB0
OrderNumber:6AG1 516-3AN00-2AB0 V1.0

Openness: API for automation of engineering workflows


1152 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6AG1 540-1AD00-7AA0 V1.0
OrderNumber:6AG1 540-1AB00-7AA0 V1.1
OrderNumber:6AG1 541-1AD00-7AB0 V1.8
OrderNumber:6ES7 511-1CK00-0AB0 V1.0
OrderNumber:6ES7 531-7NF10-0AB0 V1.0
OrderNumber:6ES7 532-5HF00-0AB0 V1.0
OrderNumber:6ES7 512-1CK00-0AB0 V2.1
OrderNumber:6ES7 521-1BH10-0AA0 V2.1
OrderNumber:6ES7 522-1BF00-0AB0 V2.1
OrderNumber:6ES7 212-1BE40-0XB0 V2.1
OrderNumber:6ES7 234-4HE32-0XB0 V1.0
OrderNumber:6ES7 223-1BH30-0XB0 V2.1
OrderNumber:6GK7 243-1BX30-0XE0 V4.2
OrderNumber:3RK7243-2AA30-0XB0 V2.0
OrderNumber:6ES7 217-1AG40-0XB0 V1.0
OrderNumber:6GT2 002-0LA00 V3.0
OrderNumber:6ES7 518-4FP00-0AB0 V1.1
OrderNumber:6ES7 517-3UP00-0AB0 V4.2
OrderNumber:6ES7 511-1FK00-0AB0 V1.0
OrderNumber:6ES7 531-7QD00-0AB0 V2.1
OrderNumber:6ES7 517-3AP00-0AB0 V2.1
OrderNumber:6ES7 522-5EH00-0AB0 V1.8
OrderNumber:6ES7 522-1BH10-0AA0 V1.0
OrderNumber:3SU1 400-1LK10-*AA1 V2.1
OrderNumber:3SU1 400-1MA10-1BA1 V1.0
OrderNumber:6EP3436-8MB00-2CY0 V1.0
OrderNumber:6EP4436-8XB00-0CY0 V1.0
OrderNumber:6EP4131-0GB00-0AY0 V1.2
GSD:SIEM804C.GSD/M/0 V1.2
OrderNumber:6ES7 143-2BH*0-0AB0 V1.0
OrderNumber:6ES7 143-2BH00-0AB0
OrderNumber:6ES7 407-0DA02-0AA0
OrderNumber:6ES7 460-0AA01-0AB0
OrderNumber:6ES7 412-2XK07-0AB0
OrderNumber:6ES7 450-1AP00-0AE0
OrderNumber:6ES7 211-1AE31-0XB0
OrderNumber:6ES7 241-1CH32-0XB0 V7.0
OrderNumber:6ES7 211-1HD30-0XB0
OrderNumber:6ES7 241-1AH30-0XB0 V3.0
OrderNumber:6ES7 212-1AE31-0XB0 V2.2
OrderNumber:6ES7 221-1BF32-0XB0 V2.2
OrderNumber:6ES7 232-4HD30-0XB0 V1.0
OrderNumber:6ES7 510-1DJ01-0AB0 V3.0
OrderNumber:6ES7 512-1DK01-0AB0 V2.0

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1153
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 157-1AB00-0AB0 V1.0
OrderNumber:6ES7 512-1CK00-0AB0 V1.8
OrderNumber:6AG1 155-6AU00-7BN0 V1.8
OrderNumber:6AG1 193-6PA00-7AA0 V1.0
OrderNumber:6AG1 155-6AU00-7BN0 V1.8
OrderNumber:6ES7 313-6CF03-0AB0 V1.0
OrderNumber:6ES7 318-3EL00-0AB0 V1.0
OrderNumber:6ES7 151-3BA23-0AB0 V3.1
OrderNumber:3RK1 903-0BA00 V2.6
OrderNumber:3RK1 301-0BB13-1AA4 V2.7
OrderNumber:6ES7 518-4AP00-0AB0 V7.0
OrderNumber:6ES7 154-8AB00-0AB0
OrderNumber:6ES7 144-4PF00-0AB0
OrderNumber:6ES7 151-1BA02-0AB0 V1.6
OrderNumber:6ES7 131-4BB01-0AB0 V2.5
OrderNumber:6ES7 132-4BB01-0AA0
OrderNumber:6ES7 131-4BB01-0AA0
OrderNumber:6ES7 132-4BD00-0AB0
OrderNumber:6ES7 407-0KA02-0AA0
OrderNumber:6ES7 401-1DA01-0AA0
OrderNumber:6ES7 416-3ES06-0AB0
OrderNumber:6ES7 318-3EL01-0AB0
OrderNumber:6ES7 138-4DA04-0AB0
OrderNumber:6ES7 518-4FP00-3AB0 V6.0
OrderNumber:6ES7 317-2AJ10-0AB0 V3.2
OrderNumber:6ES7 132-4HB50-0AB0 V1.0
OrderNumber:6ES7 132-4BB31-0AA0 V2.0
OrderNumber:6ES7 416-3ER05-0AB0 V2.6
OrderNumber:6ES7 151-1AA04-0AB0
GSD:SIEM818A.GSD/M/70000
GSD:SIEM818A.GSD/M/13 V5.3
OrderNumber:6ES7 155-6AU00-0CN0
OrderNumber:6ES7 412-2XJ05-0AB0
OrderNumber:6ES7 431-7QH00-0AB0
OrderNumber:6ES7 432-1HF00-0AB0 V3.3
OrderNumber:6ES7 460-1BA01-0AB0 V5.3
OrderNumber:6ES7 416-2XN05-0AB0
GSD:SIEM818A.GSD/M/18
OrderNumber:7MH4 138-6AA00-0BA0
OrderNumber:6ES7 155-6AU00-0BN0 V5.3
OrderNumber:6ES7 513-1AL00-0AB0
OrderNumber:6ES7 521-1BL00-0AB0
OrderNumber:6ES7 522-1BL00-0AB0 V3.3
OrderNumber:6ES7 522-1BH00-0AB0 V1.8

Openness: API for automation of engineering workflows


1154 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 540-1AB00-0AA0 V2.1
OrderNumber:6ES7 541-1AB00-0AB0 V2.0
OrderNumber:6GK7 542-5DX00-0XE0 V2.0
OrderNumber:6ES7 317-2EK14-0AB0 V1.0
OrderNumber:6ES7 516-3AN00-0AB0 V1.0
OrderNumber:6GK7 542-5FX00-0XE0 V2.0
OrderNumber:6GK7 543-1AX00-0XE0 V3.2
OrderNumber:6GK7 543-1AX00-0XE0 V1.1
OrderNumber:6ES7 516-3AN00-0AB0 V1.0
OrderNumber:6GK7 242-7KX30-0XE0 V1.0
OrderNumber:6ES7 211-1BE31-0XB0 V1.1
OrderNumber:6GK7 243-1JX30-0XE0 V1.5
OrderNumber:6GK7 243-5DX30-0XE0 V1.3
OrderNumber:6ES7 132-4BB01-0AB0 V3.0
OrderNumber:6ES7 152-1AA00-0AB0 V1.0
OrderNumber:6ES7 132-7GD00-0AB0 V1.0
OrderNumber:6ES7 334-0KE00-0AB0
OrderNumber:6ES7 151-3BA23-0AB0 V2.0
OrderNumber:OPC Server
OrderNumber:Application
OrderNumber:6ES7 214-1BG40-0XB0 V6.0
OrderNumber:6ES7 221-1BH32-0XB0 SW V14 ...
OrderNumber:6ES7 222-1XF30-0XB0 SW V8.1 SP2 ...
OrderNumber:6ES7 223-1QH30-0XB0 V4.2
OrderNumber:6ES7 231-4HF30-0XB0 V2.0
OrderNumber:6ES7 234-4HE30-0XB0 V1.0
OrderNumber:7MH4960-2AA01 V1.0
OrderNumber:6ES7 214-1AG40-0XB0 V1.0
OrderNumber:6ES7 228-1RC52-0AA0 V1.0
OrderNumber:6ES7 278-4BD32-0XB0
OrderNumber:6ES7 214-1HG31-0XB0 V4.2
OrderNumber:7MH4960-6AA01 V2.2
OrderNumber:7MH4960-4AA01 V2.0
OrderNumber:6ES7 223-1PL30-0XB0 V3.0
OrderNumber:6ES7 215-1BG40-0XB0
OrderNumber:6ES7 231-4HD30-0XB0
OrderNumber:6ES7 231-5PD32-0XB0 V1.0
OrderNumber:6ES7 231-5QF30-0XB0 V4.2
OrderNumber:6ES7 232-4HB32-0XB0 OrderNum‐ V1.0
ber:3RK1 301-0CB10-1AB4 V2.0
OrderNumber:3RK1 903-0CK00 V1.0
OrderNumber:6ES7 215-1HF40-0XB0 V2.0
OrderNumber:6ES7 212-1AF40-0XB0 V10.0
OrderNumber:6ES7 214-1HF40-0XB0

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1155
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 214-1AF40-0XB0 V4.2
OrderNumber:6ES7 515-2FM00-0AB0 V4.2
OrderNumber:6ES7 511-1UK01-0AB0 V4.2
OrderNumber:6ES7 215-1AG31-0XB0 V4.2
OrderNumber:6ES7 221-1BF30-0XB0 V1.8
OrderNumber:6ES7 222-1XF32-0XB0 V2.1
OrderNumber:6ES7 222-1HF30-0XB0 V3.0
OrderNumber:6ES7 223-1BL30-0XB0 V1.0
OrderNumber:6ES7 215-1HG40-0XB0 V2.0
OrderNumber:6ES7 241-1CH31-0XB0 V1.0
OrderNumber:6ES7 212-1HF40-0XB0 V1.0
OrderNumber:6AG1 214-1AG40-4XB0 V4.2
OrderNumber:6AG1 221-1BF32-2XB0 V1.0
OrderNumber:6AG1 221-1BF32-4XB0 V4.2
OrderNumber:6AG1 222-1BH32-2XB0 V4.2
OrderNumber:6AG1 222-1BF32-4XB0 V2.0
OrderNumber:6AG1 223-1BL32-2XB0 V2.0
OrderNumber:6AG1 214-1HG40-2XB0 V2.0
OrderNumber:6AG1 223-1PH32-2XB0 V2.0
OrderNumber:6AG1 223-1PL32-4XB0 V2.0
OrderNumber:6AG1 223-1QH32-4XB0 V4.2
OrderNumber:6AG1 222-1XF32-2XB0 V2.0
OrderNumber:6AG1 222-1HF32-4XB0 V2.0
OrderNumber:6AG1 222-1HH32-2XB0 V2.0
OrderNumber:6AG1 215-1BG40-5XB0 V2.0
OrderNumber:6AG1 231-5QF32-4XB0 V2.0
OrderNumber:6AG1 231-4HD32-4XB0 V2.0
OrderNumber:6AG1 222-1BF32-2XB0 V4.2
OrderNumber:6AG1 234-4HE32-2XB0 V2.0
OrderNumber:6AG1 278-4BD32-4XB0 V2.0
OrderNumber:6AG1 215-1AG40-4XB0 V2.0
OrderNumber:6AG1 221-1BH32-2XB0 V2.0
OrderNumber:6AG1 241-1CH32-2XB0 V2.0
OrderNumber:6AG1 215-1HG40-2XB0 V4.2
OrderNumber:6ES7 223-1PL32-0XB0 V2.0
OrderNumber:6ES7 228-1RC51-0AA0 V2.1
OrderNumber:6ES7 238-5XA32-0XB0 V4.2
OrderNumber:6ES7 215-1AF40-0XB0 V2.0
OrderNumber:6ES7 223-1BL32-0XB0 V2.2
OrderNumber:6AG1 212-1BE40-2XB0 V2.0
OrderNumber:6AG1 243-5DX30-2XE0 V4.2
OrderNumber:6AG1 212-1HE40-2XB0 V2.0
OrderNumber:6AG1 223-1QH32-2XB0 V4.2
OrderNumber:6EP3436-8SB00-2AY0 V1.3

Openness: API for automation of engineering workflows


1156 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6EP3437-8MB00-2CY0 V4.2
OrderNumber:6EP4137-3AB00-2AY0 V2.0
OrderNumber:6EP4136-3AB00-2AY0 V1.1
OrderNumber:6EP4133-0GB00-0AY0 V1.1
OrderNumber:6ES7 138-4DC01-0AB0 V2.1
System:Port.Scalance/Comboport_MAU V2.1
OrderNumber:6GK1 160-4AT01 V1.0
OrderNumber:6GK1 160-4AA00
OrderNumber:6GK1 161-6AA02
OrderNumber:6GK1 551-2AA00 V2.7
OrderNumber:6GK1 571-1AA00 V2.6
OrderNumber:6GK1 562-3AA00 V2.7
OrderNumber:6GK1 561-3AA02 SW V6.1 ...
OrderNumber:6GK7 343-1GX31-0XE0 SW V7.1 SP1 ...
OrderNumber:6GK7 443-5DX05-0XE0 SW V7.1 SP2 ...
OrderNumber:6ES7 214-1BE30-0XB0 SW V12 ...
OrderNumber:6ES7 241-1AH32-0XB0 V3.0
OrderNumber:6ES7 211-1AD30-0XB0 V7.0
OrderNumber:6ES7 231-4HA30-0XB0 V2.2
OrderNumber:6ES7 214-1HG40-0XB0 V2.2
OrderNumber:6GK7 242-7KX30-0XE0 V2.2
OrderNumber:6ES7 212-1AD30-0XB0 V2.0
OrderNumber:6ES7 138-4GA50-0AB0 V4.0
OrderNumber:6ES7 132-4BF00-0AB0 V1.4
OrderNumber:6ES7 154-4AB10-0AB0 V2.0
OrderNumber:6ES7 154-8FB01-0AB0
OrderNumber:6ES7 155-6AU01-0BN0
OrderNumber:6ES7 155-6AU00-0DN0 V7.1/Cu
OrderNumber:6ES7 155-5AA00-0AB0 V3.2
OrderNumber:6ES7 155-5AA01-0AB0 V4.1
OrderNumber:6AG1 155-5AA00-2AC0 V4.0
OrderNumber:6ES7 155-5BA00-0AB0 V3.0
OrderNumber:6AG1 155-5BA00-2AB0 V4.1
OrderNumber:6ES7 518-4AP00-0AB0 V3.0
OrderNumber:6ES7 132-6BF00-0AA0 V3.0
OrderNumber:6ES7 132-6HD00-0BB0 V3.0
OrderNumber:6ES7 132-6BD20-0CA0 V2.5
OrderNumber:6ES7 134-6PA01-0BD0 V1.0
OrderNumber:6ES7 132-6HD00-0BB1 V1.1
OrderNumber:6ES7 531-7NF00-0AB0 V2.0
OrderNumber:6ES7 223-0BD30-0XB0 V3.0
OrderNumber:6ES7 212-1AE40-0XB0 V1.1
OrderNumber:6ES7 221-3AD30-0XB0 V1.1
OrderNumber:6ES7 214-1AE30-0XB0 V1.0

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1157
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 222-1BD30-0XB0 V4.2
OrderNumber:6ES7 222-1AD30-0XB0 V1.0
OrderNumber:6ES7 232-4HA30-0XB0 V2.2
OrderNumber:6ES7 416-3FR05-0AB0 V'.0
OrderNumber:6ES7 964-2AA04-0AB0 V1.0
OrderNumber:6ES7 414-3FM07-0AB0 V1.0
OrderNumber:6ES7 416-2FP07-0AB0 V5.3
OrderNumber:6ES7 151-8FB01-0AB0
OrderNumber:6ES7 151-7FA20-0AB0 V7.0
OrderNumber:6ES7 132-7RD22-0AB0 V7.0
OrderNumber:6ES7 132-7GD21-0AB0 V3.2
OrderNumber:6ES7 315-2EH13-0AB0 V2.6
OrderNumber:6ES7 322-8BH10-0AB0
OrderNumber:7MH4 900-2AA01
OrderNumber:7MH4 900-3AA01 V2.6
OrderNumber:7MH4 950-1AA01
OrderNumber:7MH4 950-2AA01
OrderNumber:7MH4920-0AA01
OrderNumber:7MH4910-0AA01
OrderNumber:6AG1 155-5AA00-7AB0
OrderNumber:6AG1 505-0RA00-7AB0
OrderNumber:6AG1 522-1BL00-7AB0
OrderNumber:3SU1 401-1MC*0-1CA1 V3.0
OrderNumber:3SU1 401-1ME*0-1DA1 V1.0
OrderNumber:6BK1900-0AA00-0AA* V1.0
OrderNumber:6BK1900-0BA00-0AA* V1.0
OrderNumber:6BK1900-0CA00-0AA* V1.0
OrderNumber:6BK1942-2AA00-0AA* /HCS4200
OrderNumber:6ES7 412-2EK06-0AB0 /HCS4200
OrderNumber:6GK7 343-2AH11-0XA0 /HCS4200
OrderNumber:6ES7 313-6CG04-0AB0
OrderNumber:6GK5 991-2AB00-8AA0 V6.0
OrderNumber:6GK5 992-2VA00-8AA0 V3.1
OrderNumber:6GK5 992-2AS00-8AA0 V3.3
OrderNumber:6GK5 400-8AS00-8AP2
OrderNumber:6GK5 905-0PA00
OrderNumber:6GK5 991-1AD00-8AA0 /legacy
OrderNumber:6GK5 992-1AQ00-8AA0
OrderNumber:6GK5 907-4PA00
OrderNumber:6ES7 143-2BH50-0AB0
OrderNumber:6ES7 405-0KA02-0AA0
OrderNumber:6ES7 513-1FL01-0AB0
OrderNumber:6ES7 134-7TD00-0AB0
OrderNumber:6ES7 516-3FN00-0AB0

Openness: API for automation of engineering workflows


1158 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 151-8AB01-0AB0 V2.1
OrderNumber:3RK1 301-0BB10-1AA4
OrderNumber:6ES7 151-1CA00-3BL0 V1.8
OrderNumber:3RK1 301-0CB13-0AA4 V3.2
OrderNumber:6ES7 315-2EH14-0AB0
OrderNumber:6ES7 321-1BH02-0AA0
OrderNumber:6ES7 421-7BH01-0AB0
OrderNumber:6ES7 138-4HA00-0AB0 V3.2
OrderNumber:6SL3 244-0SA00-1AA1
OrderNumber:6SL3 244-0SA01-1AA1
OrderNumber:6GT2 002-0ED00 V1.0
OrderNumber:6ES7 135-7TD00-0AB0 ES9 3.0
OrderNumber:6ES7 340-1CH02-0AE0 3.0
OrderNumber:6ES7 352-1AH02-0AE0 V5.0/GENERIC
OrderNumber:6ES7 400-1TA11-0AA0
OrderNumber:6ES7 416-3XR05-0AB0 V1.0
OrderNumber:3RK1 301-0AB10-1AA3
OrderNumber:6ES7 672-7AC01-0YA0
OrderNumber:6ES7 307-1BA01-0AA0 V5.3
OrderNumber:6ES7 351-1AH01-0AE0
OrderNumber:6ES7 334-0CE01-0AA0 V2.1
OrderNumber:6ES7 312-5BF04-0AB0
OrderNumber:6ES7 313-5BG04-0AB0
OrderNumber:6ES7 338-7XF00-0AB0 IDENT
OrderNumber:6ES7 314-6CH04-0AB0
OrderNumber:6ES7 315-2AH14-0AB0 V3.3
OrderNumber:7ME4 120-2DH21-0EA0 V3.3
OrderNumber:6ES7 322-1CF00-0AA0
OrderNumber:6ES7 335-7HG02-0AB0 V3.3
OrderNumber:6ES7 338-4BC01-0AB0 V3.3
OrderNumber:6ES7 355-2CH00-0AE0
OrderNumber:7ME4 120-2DH20-0EA0
OrderNumber:6ES7 321-1CH20-0AA0
OrderNumber:6ES7 321-1CH00-0AA0 V3.0
OrderNumber:6ES7 322-8BF00-0AB0
OrderNumber:6ES7 322-1BL00-0AA0
OrderNumber:6ES7 322-1FF01-0AA0
OrderNumber:6ES7 305-1BA80-0AA0
OrderNumber:6ES7 341-1BH01-0AE0
OrderNumber:6ES7 331-7KB02-0AB0
OrderNumber:6ES7 331-7KF02-0AB0
OrderNumber:6ES7 331-1KF01-0AB0
OrderNumber:6ES7 332-5HB01-0AB0 V1.0
OrderNumber:6ES7 332-5HD01-0AB0

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1159
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 332-5HF00-0AB0
OrderNumber:6ES7 321-7RD00-0AB0
OrderNumber:6ES7 321-1FH00-0AA0
OrderNumber:6ES7 322-1HH01-0AA0
OrderNumber:6ES7 322-5HF00-0AB0
OrderNumber:6ES7 322-1HF10-0AA0
OrderNumber:6ES7 327-1BH00-0AB0
OrderNumber:6ES7 351-1AH02-0AE0
OrderNumber:6ES7 321-7BH01-0AB0
OrderNumber:6ES7 322-1BH01-0AA0
OrderNumber:6ES7 322-5GH00-0AB0
OrderNumber:6ES7 321-1FF01-0AA0
OrderNumber:6GK7 443-1EX41-0XE0
OrderNumber:6ES7 414-2XK05-0AB0
OrderNumber:6ES7 431-1KF00-0AB0
OrderNumber:6ES7 414-3XM05-0AB0
OrderNumber:6ES7 421-1EL00-0AA0 V1.0
OrderNumber:6ES7 414-3EM07-0AB0 V5.3
OrderNumber:6ES7 416-3XS07-0AB0
OrderNumber:6ES7 414-3FM06-0AB0 V5.3
OrderNumber:6ES7 421-1FH20-0AA0
OrderNumber:6ES7 416-3FS07-0AB0 V7.0
OrderNumber:6ES7 431-0HH00-0AB0 V7.0
OrderNumber:6ES7 416-2FN05-0AB0 V6.0
OrderNumber:6ES7 455-0VS00-0AE0
OrderNumber:6ES7 417-4XT07-0AB0 V7.0
OrderNumber:6ES7 421-1BL01-0AA0
OrderNumber:6ES7 422-1BL00-0AA0 V5.3
OrderNumber:6ES7 452-1AH01-0AE0
OrderNumber:6ES7 422-1BH11-0AA0 V7.0
OrderNumber:6ES7 421-7DH00-0AB0
OrderNumber:6ES7 422-1FH00-0AA0
OrderNumber:6ES7 422-1HH00-0AA0
OrderNumber:6ES7 452-1AH00-0AE0
OrderNumber:6ES7 455-1VS00-0AE0
OrderNumber:6ES7 450-1AP01-0AE0
OrderNumber:6GK7 443-5FX02-0XE0
OrderNumber:6ES7 517-3FP00-0AB0
OrderNumber:6ES7 515-2UM01-0AB0
OrderNumber:6ES7 531-7KF00-0AB0
OrderNumber:6ES7 211-1BE40-0XB0 V4.0
OrderNumber:6AG4114-2yxxx-xxxx//Device V2.1
OrderNumber:6AG4112-2yxxx-xxxx//Device V2.1
OrderNumber:6AG4114-2zxxx-xxxx//Device V2.1

Openness: API for automation of engineering workflows


1160 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6AG4132-2yxxx-xxxx//DeviceOrder‐ V4.2
Number:6AV7884-0xyxx-xxxx//
Device.12inch.Touch
OrderNumber:6ES7647-7Byxx-xxxx//Device Order‐
Number:6AV7884-5xyxx-xxxx//
Device.19inch.Touch
OrderNumber:6AV7884-2xyxx-xxxx//
Device.15inch.Touch
OrderNumber:6ES7647-7Byxx-xxxx//Device
OrderNumber:6ES7647-7Bzxx-xxxx//Device Order‐
Number:6AV7853-0xzxx-xxxx//
Device.15inch.Touch OrderNum‐
ber:6AV7854-0xzxx-xxxx//Device.15inch.Key Or‐
derNumber:6AV7854-0xxxx-xxxx//
Device.15inch.Key OrderNumber:6ES7647-7Ayxx-
xxxx//Device OrderNumber:6AV7856-0xyxx-xxxx//
Device.19inch.Touch OrderNum‐
ber:6ES7647-7Ayxx-xxxx//Device OrderNum‐
ber:6AV7873-xxxxx-xBxx//Device.15inch.Key Or‐
derNumber:6ES7643-8yxxx-xxxx//Device Order‐
Number:6ES7647-6Byxx-xxxx//Device OrderNum‐
ber:6AV7870-xxxxx-xAxx//Device.12inch.Touch
OrderNumber:6AV7872-xxxxx-xAxx//
Device.15inch.Touch OrderNumber:6AV7874-
xxxxx-xBxx//Device.17inch.Touch
OrderNumber:6AV7875-xxxxx
-xAxx//Device.19inch.Touch
OrderNumber:6AG4112-0yxxx-xxxx//Device
ET200eco - HeadModules
ET200eco PN - HeadModules
SIMATIC RF600 - HeadModules
OrderNumber:3RK1 304-5KS40-2AA3
OrderNumber:3RK1 304-5LS40-2AA3
OrderNumber:3RK1 304-0HS00-8AA0
OrderNumber:3RK1 304-0HS00-6AA0
OrderNumber:6ES7 516-2PN00-0AB0
OrderNumber:6ES7 151-3BB23-0AB0 V3.0
OrderNumber:6ES7 154-6AB00-0AB0 V3.0
OrderNumber:6ES7 141-5AH00-0BA0 V1.0
V1.0
OrderNumber:6ES7 142-5AF00-0BA0
V2.1
OrderNumber:6ES7 143-5AH00-0BA0 V7.0
OrderNumber:6GK7 243-8RX30-0XE0 V1.0
OrderNumber:6ES7 212-1HE40-0XB0 V1.0
V1.0
OrderNumber:6ES7 518-4FP00-0AB0
V1.0
OrderNumber:6AG1 215-1HG40-4XB0 V3.0
OrderNumber:6ES7 138-4FD00-0AA0 V4.2
OrderNumber:6ES7 134-4NB51-0AB0 V2.1
V4.2
OrderNumber:6ES7 135-4GB52-0AB0

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1161
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 138-7AA00-0AA0
OrderNumber:6ES7 138-7BB00-0AB0
OrderNumber:6ES7 145-4GF00-0AB0
OrderNumber:6ES7 143-4BF50-0AA0
OrderNumber:6GK5 980-3CB00-0AA1
OrderNumber:6GK5 980-3CB00-0AA7
OrderNumber:6GK5 991-4AB00-8AA0
OrderNumber:6GK5 992-4AL00-8AA0
OrderNumber:6GK5 992-4SA00-8AA0
OrderNumber:6GK5 992-4RA00-8AA0
OrderNumber:6GK5 992-4GA00-8AA0
OrderNumber:6GK5 991-1AE00-8AA0
OrderNumber:6GK5 991-1AF00-8AA0
OrderNumber:6GK5 992-1AL00-8AA0
OrderNumber:6GK5 992-1AN00-8AA0
OrderNumber:6ES7 174-0AA10-0AA0
OrderNumber:6GK5 204-0BA00-2BF2
OrderNumber:6NH9 741-1AA00
OrderNumber:6ES7 133-1BL01-0XB0
OrderNumber:6ES7 132-1BL00-0XB0
OrderNumber:6ES7 132-1BH00-0XB0
OrderNumber:6ES7 131-1BL01-0XB0
OrderNumber:6ES7 131-1BH01-0XB0
OrderNumber:3RK1 207-2BQ44-0AA3 ET200eco -
HeadModules
ET200eco PN - HeadModules
SIMATIC RF600 - HeadModules
OrderNumber:3RK1 304-5KS40-2AA3
OrderNumber:3RK1 304-5LS40-2AA3
OrderNumber:3RK1 304-0HS00-8AA0
OrderNumber:3RK1 304-0HS00-6AA0
OrderNumber:6ES7 516-2PN00-0AB0
OrderNumber:6ES7 151-3BB23-0AB0
OrderNumber:6ES7 154-6AB00-0AB0
OrderNumber:6ES7 141-5AH00-0BA0
OrderNumber:6ES7 142-5AF00-0BA0
OrderNumber:6ES7 143-5AH00-0BA0
OrderNumber:6GK7 243-8RX30-0XE0
OrderNumber:6ES7 212-1HE40-0XB0
OrderNumber:6ES7 518-4FP00-0AB0
OrderNumber:6AG1 215-1HG40-4XB0
OrderNumber:6ES7 138-4FD00-0AA0
OrderNumber:6ES7 134-4NB51-0AB0
OrderNumber:6ES7 135-4GB52-0AB0

Openness: API for automation of engineering workflows


1162 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Whitelist
OrderNumber:6ES7 138-7AA00-0AA0
OrderNumber:6ES7 138-7BB00-0AB0
OrderNumber:6ES7 145-4GF00-0AB0
OrderNumber:6ES7 143-4BF50-0AA0
OrderNumber:6GK5 980-3CB00-0AA1
OrderNumber:6GK5 980-3CB00-0AA7
OrderNumber:6GK5 991-4AB00-8AA0
OrderNumber:6GK5 992-4AL00-8AA0
OrderNumber:6GK5 992-4SA00-8AA0
OrderNumber:6GK5 992-4RA00-8AA0
OrderNumber:6GK5 992-4GA00-8AA0
OrderNumber:6GK5 991-1AE00-8AA0
OrderNumber:6GK5 991-1AF00-8AA0
OrderNumber:6GK5 992-1AL00-8AA0
OrderNumber:6GK5 992-1AN00-8AA0
OrderNumber:6ES7 174-0AA10-0AA0
OrderNumber:6GK5 204-0BA00-2BF2
OrderNumber:6NH9 741-1AA00
OrderNumber:6ES7 133-1BL01-0XB0
OrderNumber:6ES7 132-1BL00-0XB0 V1.1
OrderNumber:6ES7 132-1BH00-0XB0 V5.3
OrderNumber:6ES7 131-1BL01-0XB0 V1.1
OrderNumber:6ES7 131-1BH01-0XB0
OrderNumber:3RK1 207-2BQ44-0AA3

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1163
Export/import
6.5 Importing/exporting hardware data

Below table shows list of device/deviceitems that does not support import using library
references.

Blacklist
TypeIdentifier FirmwareVersion
OrderNumber:6AG1 193-6AR00-7AA0 V0.0
OrderNumber:6ES7 193-6AR00-0AA0 V0.0
OrderNumber:6GK5 991-2VA00-8AA2 V0.0
OrderNumber:6ES7 193-6AM00-0AA0 V0.0
OrderNumber:6ES7 193-6AF00-0AA0 V0.0
OrderNumber:6ES7 193-6AP00-0AA0 V0.0
OrderNumber:6ES7 193-6AP20-0AA0 V0.0
OrderNumber:6ES7 193-6AP40-0AA0 V0.0
OrderNumber:6ES7 193-6AG00-0AA0 V0.0
OrderNumber:6ES7 193-6AG20-0AA0 V0.0
OrderNumber:6ES7 193-6AG40-0AA0 V0.0
OrderNumber:6ES7 193-6AP40-0AA0 V0.0
OrderNumber:6DL1 193-6AG00-0AA0 V0.0
OrderNumber:6DL1 193-6AF00-0AA0 V0.0
OrderNumber:6DL1 193-6AR00-0AA0 V0.0
OrderNumber:6DL1 193-6AG20-0AA0 V0.0
OrderNumber:6DL1 193-6AG40-0AA0 V0.0
OrderNumber:6ES7 655-5PX11-0XX0 V1.2
SIMATIC COMMUNICATION MODULES - HeadMod‐
ules
SIMATIC optical identification systems - HeadMod‐
ules
OrderNumber:6AV6 646-1AC22-0AX0
V2.0
OrderNumber:6GK5 826-2AB00-2AB2
V5.0
OrderNumber:6GK5 991-1AD00-8FA0
SCALANCE XC208 - HeadModules
SCALANCE XB208- HeadModules
SENTRON - HeadModules
OrderNumber:6GK5 992-4AS00-8AA0
Additional Ethernet devices
Industrial PCs
PCU 50.5

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1164 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.21 Export of a device object

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The PLC is offline.

Application
The Device object is a container object for a central or distributed configuration. It is the parent
object for DeviceItem objects and the top level internal element of the instance hierarchy of
the TIA Portal project in between an AML file's structure.
The CAx data export supports the following types of devices specified via the AML type identifier:
• Physical modules
• GSD/GSDML based devices
• Systems
Devices can be grouped in a DeviceUserFolder object.

Note
Export of a single device also exports all subnets in the project.

Attributes
The following table shows the related attributes of the device object for CAx import and export
files:

Attribute Handling Comment


Name Mandatory
TypeIdentifier Mandatory Optional for import starting from AR APC V1.1
for export
Comment Optional Default: ""

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1165
Export/import
6.5 Importing/exporting hardware data

Example: Exported Configuration

AML structure of the export file


The following structure example depicts the export of the single device "S7-400 station_1"
without racks and modules:

Device with no type identifier and generic type identifier


The CAx import shall be able to handle devices having no type Identifier information or having
generic type identifiers ('System:Device.Generic'). It shall be possible that AMl file contains
certain type of device with no type Identifier information or generic type identifier
('System:Device.Generic').

Openness: API for automation of engineering workflows


1166 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

But CAx import shall handle these as well to create proper devices.
The following devices support generic device or no type identifier substitution:
• GSD and GSDML devices
• Devices based on MDD (Non-GSD/GSDML devices)
For Generic device or device having no type identifier and Generic Rack, type identifier
replacement , it is mandatory that the head module (in case of decentral devices) or PLC (in case
of central devices) has to be present in the rack described in the AML file, otherwise the device
with no type identifiers or generic device and generic rack type identifier substitution shall fail.
The following XML structure shows a device configuration with non generic type identifier:

<InternalElement ID="04f5d5f08-316a-4a1d-9290-9bfd75b2b2ca" Name="S7-400 station_1">


<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.S7400</Value>
</Attribute>
<Attribute Name="Comment" AttributeDataType="xs:string">
<Value>S7400 station</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device"/>
</InternalElement>

The following XML structure shows a device configuraton with generic type identifier:

<InternalElement ID="04f5d5f08-316a-4a1d-9290-9bfd75b2b2ca" Name="S7-400 station_1">


<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.Generic</Value>
</Attribute>
<Attribute Name="Comment" AttributeDataType="xs:string">
<Value>S7400 Device</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device"/>
</InternalElement>

The following XML structure shows a device configuration with type identifier available for
device.

<InternalElement ID="a887601f-3ced-4f50-88ff-a9ec6eabb682" Name="S7-400 station_1">


<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.S7400</Value>
</Attribute>
<Attribute Name="Comment" AttributeDataType="xs:string">
<Value>S7400 Device</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device"/>
</InternalElement>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1167
Export/import
6.5 Importing/exporting hardware data

The following XML structure shows a device configuration with No Type Identifier available for
device.

<InternalElement ID="a887601f-3ced-4f50-88ff-a9ec6eabb682" Name="S7-400 station_1">


<Attribute Name="Comment" AttributeDataType="xs:string">
<Value>S7400 Device</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device"/>
</InternalElement>

See also
Structure of the CAx data for importing/exporting (Page 1076)
AML type identifiers (Page 1080)

6.5.22 Import of a device object

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The PLC is offline.

Application
The Device object is a container object for a central or distributed configuration. It is the parent
object for DeviceItem objects and the top level internal element of the instance hierarchy of
the TIA Portal project in between an AML file's structure.
The CAx data import supports the following types of devices specified via the AML type identifier:
• Physical modules
• GSD/GSDML based devices
• Systems
• Generic devices
If a DeviceUserFolder object exists in the TIA Portal project, the devices will be grouped in
the respective folder.
If you only know the identification (TypeIdentifier) of a head module or a PLC and not of the
respective rack and device, you can import a generic rack.
Example: TypeIdentifier = System:<Prefix>.Generic

Openness: API for automation of engineering workflows


1168 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

For generic device replacement, the following elements have to be present in the rack described
in the AML file:
• Central devices: PLC
• Decentral devices: Head module
If devices are generic, the attribute BuiltIn defines the kind of rack or module:
• physical: BuiltIn = True
• generic: BuiltIn = False

Example: Importing a generic device


The following structure example depicts the import of the generic "S7-400 station" device
without racks and modules.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1169
Export/import
6.5 Importing/exporting hardware data

Example: Importing a device user folder hierarchy


The following structure example depicts the import of a folder hierarchy.

Imported user folder hierarchy


The name of the folders for ungrouped and unassignd devics is language specific. It is
recommended to perform an import with the same user interface language as the export.
Otherwise ungrouped and unassigned devices will be imported into folders named according to
the export language.
For example, if you have exported a project which contains Device System Group "Ungrouped
devices" in English language and then import the AML file in Germany language. You will see that
project should have a "Nicht gruppierte Gerate" (German language) exists in device system
group and have "Ungrouped device" created as user group while CAx import.
The following hierarchy is imported into the project navigation:

See also
Structure of the CAx data for importing/exporting (Page 1076)
AML type identifiers (Page 1080)

Openness: API for automation of engineering workflows


1170 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.23 Export/Import of device with set address

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
In TIA Portal, you can export the address objects of IO device items to an AML file. While
importing to an empty TIA Portal project, the imported device items retains the address objects
in its respective IO device items.
The Address attribute in the AML file contains RefSemantic mandatorily set to the specified value
named OrderedListType.
Up to TIA Portal V16, It is expected that addresses should be in same order to support export and
import of device item. For example, if a device item supports two addresses (Input and Output)
in TIA Portal and same device item in AML file comes with addresses (Output and Input),
addresses are not processed due to mismatch in order.
From TIA Portal V17, CAx import operation, for a particular address from AML file shall find the
matching TIA address based on I/O type, and shall try to set the same. The order in the AML file
shall not matter any more.

Attributes of a "Address" element


The following table shows the related attributes of the object for CAx import and export files:

At‐ Han‐ Comment


trib‐ dling
ute
IoType Man‐ Input or Output.
dato‐
ry
Lengt Op‐ Channel width.
h tional This attribute shall always be written to file during export
Star‐ Op‐ Start address of the IO device.
tAd‐ tional This attribute shall always be written to file during export
dress

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1171
Export/import
6.5 Importing/exporting hardware data

Note
• The feature supports any type of device item with an address object of Input/Output type
• Input and Output addresses of length 0 shall be excluded from export and ignored at import
• Export of address attribute shall be skipped for the addresses having startaddress as -1.
However during import, warning message shall be shown for the addresses having
startaddress as -1

Example: IO device items with address objects

Openness: API for automation of engineering workflows


1172 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML Structure
The following figures shows a partial element structure of the exported AML file. It contains the
Address elments and its attributes.

<Attribute Name="Address">
<RefSemantic CorrespondingAttributePath="OrderedListType" />
<Attribute Name="1">
<Attribute Name="StartAddress" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>16</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">
<Value>Input</Value>
</Attribute>
</Attribute>
</Attribute>

Pruned XML
Pruning is the act of optimizing the content by removing certain things which are not necessarily
to be provided in the XML. In this reduced xml, the auto created sub module information are not
be provided, and its corresponding address object are provided under the immediate parent.
The following figure shows a partial element structure of the exported AML file before pruning.

<InternalElement ID="5511a117-42c6-44b7-be5d-0f33cd46e932" Name="AS-i Master_1">


<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>4</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>True</Value>
</Attribute>
<Attribute Name="Address">
<RefSemantic CorrespondingAttributePath="OrderedListType"/>
<Attribute Name="1">
<Attribute Name="StartAddress" AttributeDataType="xs:int">
<Value>20</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>256</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">
<Value>Input</Value>
</Attribute>
</Attribute>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1173
Export/import
6.5 Importing/exporting hardware data

In the pruned AML file, the sub module information like <InternalElement> element is removed
and its corresponding address objects are retained.

<Attribute Name="Address">
<RefSemantic CorrespondingAttributePath="OrderedListType"/>
<Attribute Name="1">
<Attribute Name="StartAddress" AttributeDataType="xs:int">
<Value>20</Value>
</Attribute>
<Attribute Name="Length" AttributeDataType="xs:int">
<Value>256</Value>
</Attribute>
<Attribute Name="IoType" AttributeDataType="xs:string">
<Value>Input</Value>
</Attribute>
</Attribute>
</Attribute>

See also
Pruned AML (Page 1072)

6.5.24 Export/Import of device with channels

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
In TIA Portal, you can export the channel objects of IO device items to an AML file. While
importing to an empty TIA Portal project, the imported device items retains the channel objects
in its respective IO device items.
<ExternalInterface> element represents in node and subnet internal elements, and indicates
that nodes and subnets are connected.

Openness: API for automation of engineering workflows


1174 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Attributes of a "ExternalInterface" element


The following table shows the related attributes of the object for CAx import and export files:

At‐ Han‐ Comment


trib‐ dling
ute
IoType Man‐ Input or Output
dato‐
ry
Lengt Op‐ Channel width (1 for Digitial and 16 for Analog signals)
h tional
Num‐ Man‐ Channel number starts from 0
ber dato‐
ry
Type Man‐ Analog or Digital
dato‐
ry

Channel numbering
Digital Input,Digitial Output, Analog Input, Analog Ouput, and Technology channels are
numbered as DI_0, DO_0, AI_0, AO_0,TO_0 respectively. Channels on the device items itself are
numbered first, and channels on sub-device items are numbered subsequently(depth first).
Every additional device item has its own channel numbers starting from 0.

Example: Devices with channels

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1175
Export/import
6.5 Importing/exporting hardware data

AML structure
The following figures shows a partial element structure of the exported AML file.

6.5.25 Export of device item objects

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The PLC is offline.

Application
The export of device item objets is only applicable for PLC devices.
DeviceItem objects are nested children of a Device object. An object of the type
DeviceItem can be a rack or an inserted module.
• The first child item of a device is of type "rack". The PositionNumber of a rack starts with
0. If there are multiple racks, they are consecutively numbered (1, 2, 3, …).
There are no restrictions about the ordering in the AML file within one hierarchy level.
• All further children of the type "rack" are modules.
The CAx data export supports the following types of device items specified via the AML type
identifier:
• Physical modules
• GSD/GSDML modules

Openness: API for automation of engineering workflows


1176 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Attributes
The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Mandatory
Export-only for "BuiltIn" = TRUE
TypeName Export-only for "BuiltIn" = FALSE
DeviceItemType Export-only Only for PLC (central devices) and device items (physical racks, mod‐
ules, HeadModule).
Optional during import, but any device item except Base units with
DeviceItemType as accessory shall be silently ignored.
PositionNumber Mandatory, For certain device items, Position number is not relevant for exchange
Optional for certain device with external tools like ECAD Systems. For such device items, Position
items number will not be mandatory in AML file and will be assigned an ap‐
propriate value internally by import operation.
BuiltIn Optional Default: FALSE
TypeIdentifier Mandatory for "BuiltIn" = FALSE For integrated built-in device items, this attribute will be exported with
Ignored for "BuiltIn" = TRUE its pluggable parent type identifier information.and have no relevance
during import and hence it is optional.For non-integrated built-in de‐
vice items, this attribute is optional
FirmwareVersion Optional, mandatory
if the object supports firmware
versions
PlantDesignation Optional Default: ""
IEC
LocationIdentifier Optional Default: ""
IEC
Comment Optional for "BuiltIn" = FALSE Default: ""
ProductDesigna‐ Mandatory Import is not supported, if the length of ProductDesignation IEC is
tion IEC if the object supports this attrib‐ greater than 54 characters.
ute in TIA Portal and is non emp‐ Export/ Import under device items as a part of AR APC V1.1.0 support for
ty TIA Portal V16
InstallationDate Mandatory Export/ Import under device items as a part of AR APC V1.1.0 support for
if the object supports this attrib‐ TIA Portal V16
ute in TIA Portal
Address Optional "Address" has nested attributes

The following table shows the nested attributes of the "Address" attribute of the object
"DeviceItem":

Attributes for "Ad‐ Handling Comment


dress"
StartAddress Mandatory
Length Export-only Export/Import of address with Length = 0 is not supported.
IoType Mandatory Input or Output

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1177
Export/import
6.5 Importing/exporting hardware data

Example: Exported Configuration

Openness: API for automation of engineering workflows


1178 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML structure of the export file


The following structure example depicts the export of "UR1_0" and the module "PLC_1".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1179
Export/import
6.5 Importing/exporting hardware data

Openness: API for automation of engineering workflows


1180 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

See also
Export/Import of GSD/GSDML based devices and device items (Page 1184)
Structure of the CAx data for importing/exporting (Page 1076)
AML type identifiers (Page 1080)

6.5.26 Import of device item objects

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• The PLC is offline.

Application
The import of device item objets is only applicable for PLC devices.
DeviceItem objects are nested children of a Device object. An object of the type
DeviceItem can be a rack or an inserted module.
• The first child item of a device has to be of type rack. The PositionNumber of a rack starts
with 0. If there are multiple racks, they are consecutively numbered (1, 2, 3, …).
There are no restrictions about the ordering in the AML file within one hierarchy level.
• All further children of the type rack are modules.
The CAx data imporet supports the following types of device items specified via the AML type
identifier:
• Physical modules
• GSD/GSDML modules
• Generic modules
If you only know the identification (TypeIdentifier) of a head module or a PLC and not of the
respective rack and device, you can import a generic rack.
Example: TypeIdentifier = System:Rack.Generic
For generic rack replacement, the following elements have to be present in the rack described
in the AML file:
• Central devices: PLC
• Decentral devices: Head module
A generic rack type derives from the Device type. Therefore, an AML file that is imported to TIA
Portal can use this rack's type identifier:
In this case the TIA Portal determines the type identifier for the rack.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1181
Export/import
6.5 Importing/exporting hardware data

If racks and modules are generic, the attribute BuiltIn defines the kind of rack or module:
• physical: BuiltIn = True
• generic: BuiltIn = False

Restrictions
While importing, the attribute DeviceItemType has no relevance and hence it is optional.

Note
Attribute "FirmwareVersion"
If no FirmwareVersion is specified in the import file CAx import uses the latest firmware
version which is available in the TIA Portal
If the FirmwareVersion attribute exists in the import file with an empty value, the device item
import fails and an error message will be logged.

Openness: API for automation of engineering workflows


1182 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Example: Importing a generic device


The following structure example depicts the import of the generic rack "Rack_1".

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1183
Export/import
6.5 Importing/exporting hardware data

Imported Configuration
The following figure shows the imported configuration in the TIA Portal user interface:

See also
Structure of the CAx data for importing/exporting (Page 1076)
AML type identifiers (Page 1080)

6.5.27 Export/Import of GSD/GSDML based devices and device items

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Openness: API for automation of engineering workflows


1184 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Application
The CAx Import/Export of GSD/GSDML based devices and device items is similar to the import/
export of standard devices.
For GSD/GSDML based devices and device items the exportable attributes differ, e. g. for GSD/
GSDML the attribute Label exists.
Generic import of devices and racks are possible. For the import, you use the same identifier as
for standard devices:
• Import of a generic device: TypeIdentifier = System:Device.Generic
• Import of a generic rack: TypeIdentifier = System:Rack.Generic
If devices are generic, the attribute BuiltIn defines the kind:
• physical: BuiltIn = True
• generic: BuiltIn = False

Attributes for a device


The following table shows the related attributes of device for CAx import and export files:

Attribute Handling for attribute Comment

Name Mandatory for export and import


TypeIdentifier Mandatory for export and optional
for import starting from AR APC V1.1
Comment Optional for import

Attributes for a device item


The following table shows the related attributes of a device item for CAx import and export files:

Attribute Handling for attribute Handling for attribute Comment


BuiltIn = FALSE BuiltIn = TRUE
Generic device items Physical device items
Name Mandatory Export-only
TypeName Export-only Not applicable
DeviceItem‐ Export-only Export-only Only for PLC (central devices) und Head‐
Type Module (decentral devices) device items
Optional during import, but any device
item except Base units with DeviceItem‐
Type as accessory shall be ignored.
PositionNum‐ Mandatory Mandatory for export
ber Exceptional cases:
Device item type interface: Optional
for import
Device item type port: Optional
BuiltIn Optional Default: FALSE

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1185
Export/import
6.5 Importing/exporting hardware data

Attribute Handling for attribute Handling for attribute Comment


BuiltIn = FALSE BuiltIn = TRUE
Generic device items Physical device items
TypeIdentifier Mandatory for "BuiltIn" = Ignored for "BuiltIn" = TRUE For integrated built-in device items, this
FALSE attribute will be exported with its plugga‐
ble parent type identifier information.
This attribute has no relevance during im‐
port, hence it is optional.
For non-integrated built-in device items,
this attribute has no relevance.
Comment Optional -
Label - -
Device item type interface: Mandato‐
ry
Device item type port: Mandatory

Example: Exported GSD/GSDML device

Openness: API for automation of engineering workflows


1186 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML structure of the export file


The following figure shows the structure of the exported AML file.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1187
Export/import
6.5 Importing/exporting hardware data

Generic & Non generic rack with & without TypeIdentifier


The CAx import shall be able to handle devices with no type identifier information or generic
type identifiers i.e.'System:Device.Generic' and racks with generic type identifiers i.e.
'System:Rack.Generic'.
While importing it shall be possible that AML file contains certain types of devices with no type
identifier or generic type identifier i.e 'System:Device.Generic' and rack device items with
generic type identifier i.e, 'System:Rack.Generic'. But CAx import shall handle these as well to
create proper devices and rack device items.
Following devices support generic device , device with no type identifier and generic rack
substitution:
• GSD and GSDML devices - All the GSD/GSDML devices with GSD/GSDML racks.
• Devices based on MDD (Non-GSD/GSDML devices) - The devices with system rack type
identifiers.
CAx export has no relevance with generic rack handling. CAx always exports non generic rack
type identifiers.
For Generic device or device having no type identifier and Generic Rack, type identifier
replacement , it is mandatory that the head module (in case of decentral devices) or PLC (in case
of central devices) has to be present in the rack described in the AML file, otherwise the device
with no type identifiers or generic device and generic rack type identifier substitution shall fail.
The following XML structure shows a GSDML device configuration with device (with Type
Identifier) and rack (with TypeIdentifier):

<InternalElement ID="bc3b50fa-5cfa-4bf3-a496-8e46080d4f86" Name="GSD device_1">


<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>GSD:GSDML-V2.32-SIEMENS-SINAMICS_DCMASTER-20160531.XML/D</Value>
</Attribute>
<InternalElement ID="c80f2d97-66c9-4f31-bf6b-17e3e0de0509" Name="Rack">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>Rack</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>GSD:GSDML-V2.32-SIEMENS-SINAMICS_DCMASTER-20160531.XML/R/IDD_14</Value>
</Attribute>
<InternalElement ID="f519b4b9-b1f7-4011-bed2-25be85c8c2a8" Name="SINAMICS-DCMaster-CBE20">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>SINAMICS DC MASTER CBE20 V1.1</Value>
</Attribute>
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>HeadModule</Value>
</Attribute>

Openness: API for automation of engineering workflows


1188 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

The following XML structure shows a GSDML device configuration with device (no type
identifier) and rack (generic type identifier):

<InternalElement ID="bc3b50fa-5cfa-4bf3-a496-8e46080d4f86" Name="GSD device_1">


<InternalElement ID="c80f2d97-66c9-4f31-bf6b-17e3e0de0509" Name="Rack">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>Rack</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Rack.Generic</Value>
</Attribute>
<InternalElement ID="f519b4b9-b1f7-4011-bed2-25be85c8c2a8" Name="SINAMICS-DCMaster-CBE20">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>SINAMICS DC MASTER CBE20 V1.1</Value>
</Attribute>
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>HeadModule</Value>
</Attribute>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1189
Export/import
6.5 Importing/exporting hardware data

The following XML structure shows a GSDML device configuration with device (generic type
identifier) and rack (generic type identifier):

<InternalElement ID="bc3b50fa-5cfa-4bf3-a496-8e46080d4f86" Name="GSD device_1">


<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.Generic</Value>
</Attribute>
<InternalElement ID="c80f2d97-66c9-4f31-bf6b-17e3e0de0509" Name="Rack">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>Rack</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>0</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Rack.Generic</Value>
</Attribute>
<InternalElement ID="f519b4b9-b1f7-4011-bed2-25be85c8c2a8" Name="SINAMICS-DCMaster-CBE20">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>SINAMICS DC MASTER CBE20 V1.1</Value>
</Attribute>
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>HeadModule</Value>
</Attribute>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>GSD:GSDML-V2.32-SIEMENS-SINAMICS_DCMASTER-20160531.XML/DAP/IDD_14</Value>
</Attribute>

See also
AML type identifiers (Page 1080)
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.28 Export/Import device configuration with virtual interface

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Openness: API for automation of engineering workflows


1190 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Application
In TIA Portal, ports are used for inter-device communication and found under interfaces. But
there are certain kind of devices where the ports are found directly under the device items which
are not interfaces. This is not in accordance with the AML standards where ports are always
looked for under interfaces.
CAx shall use an imaginary interface referred to Virtual interface to export and import device
configuration in case ports are found directly under non-interface device items.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1191
Export/import
6.5 Importing/exporting hardware data

Export of AML file


The below example shows an AML file having virtual interface:

<InternalElement ID="822622a0-056a-494c-a802-2463c5e1b47d" Name="SCALANCE interface_1">


<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<InternalElement ID="5a604a57-bc2d-4763-8df0-7d20000faf1b" Name="VirtualInterface_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<InternalElement ID="3c4862a1-b8ed-4610-88f3-29dc8328e748" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="220dd49d-8d23-44b1-bdc1-878516540313" Name="Port_2">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P2</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute> <Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="99c6253b-c546-4720-af54-92db926b8231"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>

Openness: API for automation of engineering workflows


1192 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

The virtual interface shall be exported with the following attributes till before TIA Portal v16 :
• Name as ScalanceInterface_1
• Label as Switch
From TIA Portal v16 the virtual interface shall be exported with the below attributes
• Name as VirtualInterface_1
• Label as X1
• Type as Ethernet

Import
CAx shall support import of virtual interfaces. In this case, it is expected to process the ports
under the Virtual interface in the AML file under the right parent in the TIA Portal. Here any
interface with Label as switch is to be considered as virtual interface. But with TIA Portal v16,
Label is nor more identifier as it is changed to X1, which is just like a real interface.
Type attribute although is set to "Ethernet" for virtual interface and it is optional. So with TIA
Portal v16 all interface elements in AML file not labelled to "Switch" shall be treated in a general
way, and whenever encountered in AML file CAx shall try to fetch from TIA Portal.
In case of Virtual interface, CAx shall fail to find it but process the ports inside it. But in case of
real interface if CAx doesn't find it, the ports inside it shall not be processed

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.29 Export/Import of subnets

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

AML structure
Subnets describe a physical network especially which devices are connected to the same
network of type PROFIBUS, PROFINET, MPI or ASI.
The link between a network and the device items are modeled as a reference to the network
object. There is no reference from the network object to the attached device items. The network
parameters are stored in the network object. The parameters concerning a network interface of

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1193
Export/import
6.5 Importing/exporting hardware data

a given device item, attached to a network, are stored in a net node object in that device item.
The communication is often regulated using “channels”, “ports” and “interfaces”.
Subnets are exported as internal elements of the role class "Subnet" in the instance hierarchy in
the AML file.
A subnet has the following related elements in the AML structure:
• Internal element of the role class "Node"
Defines the interface on a device item.
• <InternalLink>
Defines the connected partners of the subnet. <InternalLink> tags name is unique and
is always added under the project's internal element in the AML file.

• <ExternalInterface>
Represents in node and subnet internal elements that nodes and subnets are connected. If
the nodes or subnets are not connected then the <ExternalInterface> element for
node and subnet do not exist.

Application
In TIA Portal V16,CAx import supports Ethernet and Profinet and export will always be Ethernet
for Subnet Type and Node attributes.
The CAx Import/Export supports the following types of subnets:
• Ethernet
• PROFIBUS

Openness: API for automation of engineering workflows


1194 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

• MPI
• ASi

Attributes of a "Subnet" element


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Mandatory
Type Mandatory Ethernet or PROFIBUS or MPI or ASi

Attributes of "CommunicationInterface" elements


The following table shows the related attributes of the objects for CAx import and export files:

Attribute Handling Comment


Name Mandatory No relevance for "fixed" device items.
Label Mandatory Label may be missing if "BuiltIn" = TRUE and "PositionNumber" are specified for the related
"DeviceItem" object.
TypeIdentifier Mandatory For integrated built-in device items, this attribute shall be exported with its pluggable
parent type identifier information. And during import this attribute has no relevance.
For non-integrated built-in device items, this attribute has no relevance.
FirmwareVersion Mandatory
TypeName Export-only No relevance for "BuiltIn" device items.
DeviceItemType Export-only Only for for CPU and HeadModule
This attribute is optional during import but any device item except Base units with DeviceI‐
temType as Accessory shall be silently ignored.
PositionNumber Mandatory No relevance for the import of "BuiltIn" device items.
BuiltIn Mandatory No relevance for the import of "Non-BuiltIn" device items.
for export False by default for import.
Optional for
import
Comment Optional Not applicable for "BuiltIn" device items.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1195
Export/import
6.5 Importing/exporting hardware data

Attributes of "CommunicationPort" elements


The following table shows the related attributes of the objects for CAx import and export files:

Attribute Handling Comment


Name Mandatory No relevance for "BuiltIn" device items.
Label Mandatory Label may be missing if "BuiltIn" = TRUE and "PositionNumber" are specified for the related
"DeviceItem" object.
While importing Port label value, comparison of label value shall be case invariant (For ex:
p1 r, P1 R, P1, p1 etc., ).
For Ports enabled for ring topology, indicated with suffix "R", import shall be treated "equiv‐
alent" to Ports having label values without suffix.
For example: The following port labels are treated as equal:
• P1 equals P1
• P1 equals P1 R
• P1 R equals P1
• P1 R equals P1 R
TypeIdentifier Mandatory For integrated built-in device items, this attribute shall be exported with its pluggable
parent type identifier information. And during import this attribute has no relevance.
For non-integrated built-in device items, this attribute has no relevance
FirmwareVersion Mandatory
TypeName Export-only No relevance for "BuiltIn" device items.
DeviceItemType Export-only Only for for CPU and HeadModule.
Optional during import, but any device item except Base units with DeviceItemType as
accessory shall be silently ignored.
PositionNumber Mandatory Only relevant for the import of "BuiltIn" device items, if "Label" attribute is not specified.
If both "PositionNumber" and "Label" are configured, then "PositionNumber" gets higher
precedence.
BuiltIn Mandatory No relevance for the import of "Non-BuiltIn" device items.
for export False by default for import.
Optional for
import
Comment Optional Not applicable for "BuiltIn" device items.

Attributes of a "Node" element


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Export-only MPI, PROFIBUS, PROFINET
Type Export-only Ethernet or PROFIBUS or MPI or ASi
NetworkAddress Mandatory
SubnetMask Optional PROFINET
For import, default value is retained if no value is set.
RouterAddress Optional PROFINET
For import, default value is retained if no value is set.

Openness: API for automation of engineering workflows


1196 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Attribute Handling Comment


DhcpClientId Optional PROFINET
For import, default value is retained if no value is set.
IpProtocolSelection Optional PROFINET
For import, default value is retained if no value is set.
Values: Project, Dhcp, UserProgram, OtherPath, Address Tailoring

For Profinet node, the availability of attributes which will differ again based on certain pre
conditions. For ex:
• If in TIA Portal UI Ip protocol selected is "Set IP address in the project", then "NetworkAddress"
and "SubnetMask" will be available.
• The attribute "RouterAddress" shall be available for export/import if Ip protocol selected is
"Set IP address in the project" and "Use router" is selected in UI.
• The attribute "DhcpClientId" shall be available for export/import only if the attribute
'IpProtocolSelection' is 'Dhcp'.
CAx Import special case where 'Type' attribute necessary - Profibus subnet connection is done by
changing interface type MPI to PROFIBUS in UI.
• In TIA portal for some device items, by default interface type is Mpi. But it is required to be
changed to Profibus to make Profibus subnet connection. In this case, Type should be
specified with 'Profibus' value in AML file to indicate Type conversion while importing.

Note
• CAx import will support Ethernet and Profinet for Subnet Type and Node Type attribute.
• CAx import of an AML file with 'case invariant' string values for the attributes (For ex:
Profinet, PROFINET, pROFINET, ProFINET etc.,) should be supported.
• CAx export will always be Ethernet.

Attributes of a "Channel" element"


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Type Mandatory Digital or Analog
IoType Mandatory Input or Output
Number Mandatory
Length Export-only

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1197
Export/import
6.5 Importing/exporting hardware data

Example: Exported subnet

Openness: API for automation of engineering workflows


1198 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML structure
The following figures show the structure of the exported AML file:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1199
Export/import
6.5 Importing/exporting hardware data

Extended role for Profinet/Ethernet node


As part of latest recommendation by AR APC 1.2, any Profinet/Ethernet node shall be exchanged
with one additional role 'AutomationProjectConfigurationRoleClassLib/NodeEthernet' along
with the existing role 'AutomationProjectConfigurationRoleClassLib/Node' in case extended
attributes are supported.
The Profinet/Ethernet node shall be exported with additional role in case it supports extended
attributes like SubnetMask, RouterAddress, DhcpClientId, IpProtocolSelection. And it shall be
possible to import node with or without extended role also.

Openness: API for automation of engineering workflows


1200 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Below XML snippet depicts the AML file with Node "Ethernet" with extended role.

<InternalElement ID="9c4393a9-44d5-49b4-9314-02eb0f94b6c0" Name="IE1">


<Attribute Name="SubnetMask" AttributeDataType="xs:string">
<Value>255.255.255.0</Value>
</Attribute>
<Attribute Name="RouterAddress" AttributeDataType="xs:string">
<Value>192.168.0.1</Value>
</Attribute>
<Attribute Name="IpProtocolSelection" AttributeDataType="xs:string">
<Value>Project</Value>
</Attribute>
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value>
</Attribute>
<Attribute Name="NetworkAddress" AttributeDataType="xs:string">
<Value>192.168.0.1</Value>
</Attribute>
<ExternalInterface ID="eea59d3c-3bc4-4d0d-9815-46b4b347369d" Name="LogicalEndPoint_Node"
RefBaseClassPath="CommunicationInterfaceClassLib/LogicalEndPoint" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/Node" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationEthernetRoleClassLib/
NodeEthernet" />
</InternalElement>

See also
Structure of the CAx data for importing/exporting (Page 1076)
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.30 Export/Import of IO-systems

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

AML structure
IO-system are represented in the AML structure as <InternalElement>.
IO-system of as master or IO controller are added under the element
<CommunicationInterface> of an interface device item.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1201
Export/import
6.5 Importing/exporting hardware data

Connected IO-system as slave or IO-device are added as <ExternalInterface> elements


under the element <CommunicationInterface> of an interface device item.

The connected partners of the IO-systems are represented as <InternalLink> elements.


<InternalLink> tags are added under common parent of an IO-system and connected slave
device item, e. g. Project, DeviceFolder, DeviceItem.
<InternalLink> tags name is unique across the common parent.

Openness: API for automation of engineering workflows


1202 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Attributes of an "IO-system" element


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Mandatory The IO-system name. If empty string is imported, the IO-system is created with the default
name.
Number Optional If not specified for import, the default value is applied.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.31 Export/Import of multilingual comments

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
The CAx data exchange exports and imports comments and multilingual comments of the
following hardware objects:
• Devices (Device)
• Modules (DeviceItems)
• Tags (Tag)
The import/export of multilingual comments comprises all TIA Portal languages.

Restrictions
• Export
– Only if a comment exists, a "Comment" attribute is exported to the AML file.
• Import
– The "Comment" attribute is optional.
– For virtual device items, no comments can be imported.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1203
Export/import
6.5 Importing/exporting hardware data

Example: Exported configuration with multilingual comments


The following figure shows the configuration of a SIMATIC S7 1500 (Device) with PLC_1
(DeviceItems). For both objects, comments are set in English, French, German and Chinese.

AML structure
After the export of this configurations, the multilingual comments are generated as nested
attributes of the device, device item or tag.
• The parent attribute "Comment" shall have the value used in default language.
• A child attribute exists for every foreign-language comment.

See also
Structure of the CAx data for importing/exporting (Page 1076)
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1204 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.32 Export/Import ET200 SP/ET200 AL devices with extension rack connections

Requirement
• The TIA Portal Openness application is connected to the TIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is opening
See Opening a Project (Page 113)

Application
It shall be possible to have a device with multiple racks having extension rack connections
exported in to AML file and import it to get same device with extension rack connections created
back in TIA Portal project.
In TIA Portal, extension rack connections between multiple racks are modeled under DeviceItem
objects (ET-Con_1, ET-Con_2 and ET-Connection Receiver) directly. However as per AR APC
recommendation, these connections to be modeled as Port-to-Port connection under a
CommunicationPort.
So, to make it in line with the recommendation, a dummy CommunicationInterface having
dummy CommunicationPort objects shall be added under respective DeviceItem objects.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1205
Export/import
6.5 Importing/exporting hardware data

Device configurations with multiple extension rack connections


The following configuration shows a ET-200AL device with multiple racks having extension rack
connections in TIA Portal.

Openness: API for automation of engineering workflows


1206 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML Export
The AML file that shall be generated during export for the above configuration is depicted below.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1207
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8"?><CAEXFile FileName="ET200AL_with_ExtensionRacks.aml"


SchemaVersion="2.15" xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
...
<InternalElement ID="2b90fa1e-df69-437d-8a77-eaa455cdfaba" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="32758129-15db-43c7-9deb-53613852b208" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X30</Value></Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="c326d6b8-cc1a-444b-8a06-5c63a226a456"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
...
<InternalElement ID="ab4e0e97-8e57-4218-b55c-0e4fe89a9587" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="6bb61ad0-13ac-455b-9a90-6cbaddeaabd4" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X31</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="90c95545-2e43-4701-8fd0-9e87ef0bd412"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<InternalElement ID="54119ad3-34b6-4e63-bc18-bee23312900a" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">

Openness: API for automation of engineering workflows


1208 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="ad638a2a-538e-4840-9d99-7712522431ba" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X30</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="6a517987-ae22-4446-b361-91aea2c768be"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
...
<InternalLink Name="Link To Port_1"
RefPartnerSideA="32758129-15db-43c7-9deb-53613852b208:CommunicationPortInterface"
RefPartnerSideB="ad638a2a-538e-4840-9d99-7712522431ba:CommunicationPortInterface" />
<InternalLink Name="Link To Port_2"
RefPartnerSideA="6bb61ad0-13ac-455b-9a90-6cbaddeaabd4:CommunicationPortInterface"
RefPartnerSideB="cac8af19-67bc-41aa-a3f0-7149af8f67d4:CommunicationPortInterface" />

Note
The extension rack interface shall be exported only when extension rack connections are
present. Also, the number of dummy ports added under extension ET-Con dummy interface is
based on the ports participating in extension rack connection at module level.

Extension rack connection


The XML representation of extension rack connections between multiple racks shall be done
using format shown below.
• ExternalInterface-<ExternalInterface> internal element shall be added under
<CommunicationPort> internal element which participates in the connection

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1209
Export/import
6.5 Importing/exporting hardware data

<InternalElement ID="[IM Module Unique ID]" Name="[IM Module Name]">


<InternalElement ID="[Dummy Interface Unique ID]" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="[Dummy Port Unique ID]" Name="[IM Module Sender/Receiver Name]">
...
<ExternalInterface ID="[External Interface Unique ID]" Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="[Dummy Port Unique ID]" Name="[IM Module Sender/Receiver Name]">
...
<ExternalInterface ID="[External Interface Unique ID]" Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>

Internal link- Extension racks connections are represented using <InternalLink> tags.
<InternalLink> tags shall be added under common parent of multiple racks (i.e., Device).
Internal link name shall be unique across the common parent.

<InternalLink Name="Link To [Internal link Name]" RefPartnerSideA="[Communication Port


UniqueID]:[Communication Port External Interface Name]" RefPartnerSideB="[Communication
Port UniqueID]:[Communication Port External Interface Name]" />

Openness: API for automation of engineering workflows


1210 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Import AML
It shall be possible to import extension rack connections details from an AML file which is
generated out of above-mentioned export. However, it shall also be possible to import AML files
which are created in previous versions of TIA Portal.

Note
1. The export hierarchy change behavior shall be applicable only in version V16 onwards. Older
version TIA portal shall have same behavior as previous.
2. The hierarchy in AML file shall not influence/affect the TIA Portal internal hierarchy after
import.
3. This hierarchy change/transformation behavior is applicable for ET200 AL and ET200 SP with
extension rack connections.
4. The AML file with “case invariant” string values for the Type attribute (For ex: ET-Con, et-con,
ET-con etc.,.) shall also be imported without any failure.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1211
Export/import
6.5 Importing/exporting hardware data

Extension racks with Side by Side Connections


The following configuration shows as extension rack with modules which are connected side by
side. In below mentioned configuration, modules DI_01, DI_02, DI_03, AQ_01 and AQ_02
connected to their subsequent modules in TIA Portal. However, in TIA Portal connection
between BusAdapter-Sender and DI_01 modules are modeled as Extension rack connection and
other module connections not modeled.

Openness: API for automation of engineering workflows


1212 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

The AML file that shall be generated during export for the above configuration is depicted below.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1213
Export/import
6.5 Importing/exporting hardware data

<?xml version="1.0" encoding="utf-8"?><CAEXFile


FileName="ET200SP_with_ET200AL_ExtensionRack_And_SideBySideConnection.aml"
SchemaVersion="2.15" xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
...
<InternalElement ID="aa0f752d-63fb-4f8d-b840-72d39f2ae508" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute> ...
<InternalElement ID="695f110e-2c2b-435f-b3c1-cdc77d83d559" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute> <Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="87b9a1a3-dab8-4c62-8627-fbc8ab84e8f7"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement><SupportedRoleClass
RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/CommunicationInterface" />
</InternalElement>
<InternalElement ID="124371c4-52ca-4ecc-a476-84e7bc1439b8" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="0e354480-219c-4178-9f21-21fb369d446e" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X30</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="ab03743a-59a5-490e-b6c6-ce5359e345fd"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
...
</InternalElement>
<InternalElement ID="a0ff4884-cb81-40ed-85c8-823650687a8f" Name="Port_2">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X31</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>3</Value>

Openness: API for automation of engineering workflows


1214 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="33caac7c-2944-4b1d-9fb8-8a451e4c1c25"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<InternalElement ID="d1aa8afe-e20a-4b82-996a-9fca151b2c51" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="e713beda-1d1c-48d7-8674-8640080c87f7" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X30</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="046e2a6a-dca9-4a63-8f4f-53cabac1a65c"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="81999cc0-694f-4f7b-ba12-72ee9010cb11" Name="Port_2">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X31</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>3</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="e611d310-9ff7-45bb-b379-36e9cbea5080"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1215
Export/import
6.5 Importing/exporting hardware data

...

<InternalElement ID="d21e9e3d-f5ea-4992-87b4-1598ecd2e159" Name="RackExtension">


<Attribute Name="Type" AttributeDataType="xs:string">
<Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="74cff4f7-3023-4235-9255-b36bc9b3e3e6" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X30</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="5322297a-a9c6-474d-82d0-992234730926"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
...
<InternalElement ID="c671263b-4c6e-4914-8a29-cec88bc917bd" Name="RackExtension">
<Attribute Name="Type" AttributeDataType="xs:string"><
Value>ET-Con</Value>
</Attribute>
...
<InternalElement ID="b220aab7-ed61-481e-a9e5-5588b510c46c" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X30</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<ExternalInterface ID="ef830254-217a-42b3-b2f1-2363acf79b69"
Name="CommunicationPortInterface"
RefBaseClassPath="AutomationProjectConfigurationInterfaceClassLib/
CommunicationPortInterface" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<InternalLink Name="Link To Port_1" RefPartnerSideA="695f110e-2c2b-435f-b3c1-
cdc77d83d559:CommunicationPortInterface"
RefPartnerSideB="0e354480-219c-4178-9f21-21fb369d446e:CommunicationPortInterface" />

Openness: API for automation of engineering workflows


1216 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<InternalLink Name="Link To Port_2" RefPartnerSideA="a0ff4884-


cb81-40ed-85c8-823650687a8f:CommunicationPortInterface"
RefPartnerSideB="e713beda-1d1c-48d7-8674-8640080c87f7:CommunicationPortInterface" />
<InternalLink Name="Link To Port_3" RefPartnerSideA="81999cc0-694f-4f7b-
ba12-72ee9010cb11:CommunicationPortInterface" RefPartnerSideB="74cff4f7-3023-4235-9255-
b36bc9b3e3e6:CommunicationPortInterface" />
<InternalLink Name="Link To Port_4"
RefPartnerSideA="0201304e-39a9-4c9a-8316-2dd86fd95d0c:CommunicationPortInterface"
RefPartnerSideB="b220aab7-ed61-481e-a9e5-5588b510c46c:CommunicationPortInterface" />
...

Note
For side by side connections extension rack interface shall be exported only when modules were
plugged next to each other. Also, the number of dummy ports added under extension ET-Con
dummy interface is based on the ports participating in extension rack connection at module
level. In above example, “DI_02” module is plugged in between modules “DI_01” and “DI_03”
modules, so in exported AML file corresponding ET-Con dummy interface has two dummy ports.
But incase of “AI_01” module which does not have any side by side modules. So, in this case
“AI_01” module which is not having any ET-Con dummy interface details. Importing the AML file
back to an empty TIA Portal project shall create the same device having multiple racks with
extension rack connections.

• For ET200 AL and ET200SP modules, TIA Portal support default connection between primary
rack and extension racks when relevant modules are plugged. In such case, connection
information from AML file has no relevance during Import.
• Side by Side connection descriptions in the AML file has no relevance during the import since
the side by side connections are automatically established when there are two adjacent
modules imported into the same rack.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.33 Export/Import of ARE APC Drive 1.2.0

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1217
Export/import
6.5 Importing/exporting hardware data

Application
You can use TIA Portal V17 to perform CAx export/import of AML files with ARE APC Drive
recommendation document of version V1.2.0.
It shall be possible to export/import ARE APC Drive recommendation document identifier as part
of additional information in the AML file, but the drive configuration if present in the project shall
still be exported with respect to AR APC V1.2.0.

AML file
Below XML snippet depicts the AML file with ARE APC Drive document identifier along with AR
APC 1.2.0.

<?xml version="1.0" encoding="utf-8"?>


<CAEXFile FileName="Project11.aml" SchemaVersion="2.15"
xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
<AdditionalInformation>
<WriterHeader>
...
</WriterHeader>
</AdditionalInformation>
<AdditionalInformation AutomationMLVersion="2.0" />
<AdditionalInformation DocumentVersions="Recommendations">
<Document DocumentIdentifier="AR APC" Version="1.2.0" />
<Document DocumentIdentifier="ARE APC Drive" Version="1.2.0" />
</AdditionalInformation>
<InstanceHierarchy Name="APC Sample Instance Hierarchy">
<InternalElement ID="9a108fae-e41d-4157-9e70-c93795e9d683" Name="Project">
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
AutomationProject" />
</InternalElement>
</InstanceHierarchy>
</CAEXFile>

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1218 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.34 Export/Import of PLC tags

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open.
See Opening a project (Page 113)
• PLC is offline.

Application
Exported and imported symbols and tags are assigned to a device item. CAx import/export
concerns hardware oriented symbols and tags. The symbols and tags are exported only with the
controller target device item, e. g. the CPU and not with other device items they might refer to,
e. g. an I/O module. Like devices, the tags are often grouped in tag tables and in a hierarchical
folder structure.

AML structure elements


PLC tags, tag tables and tag user folders can be exported and imported via CAx import/export
function. The tag object are mapped in the following AML structure elements:
• <InternalElement>
Tab tables and tag user folders are mapped as internal elements of the related PLC with the
respective role class.
• <ExternalInterface>
Represents a PLC tag, dedicated to the internal element of the related tag table or tag user
folder.
A mapping channel with a PLC tag is exported as communication partner via the <internal
link> element. The following XML structure shows an example:

PLC tag user folder


The objects "TagUserFolder" only need the "Name" attribute in CAx import and export files.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1219
Export/import
6.5 Importing/exporting hardware data

Attributes of a PLC tag table


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Mandatory, ignor‐
ed if "AssignToDe‐
fault" = TRUE
AssignToDefault Import-only Used to identify the default tag table during import. If "AssignToDefault" = TRUE, all
tags are created under the default tag table of the TIA Portal.

Attributes of a PLC tag


The following table shows the related attributes of the object for CAx import and export files:

Attribute Handling Comment


Name Mandatory
DataType Mandatory
LogicalAddress Optional Imported and exported in international mnemonics format
IoType Optional Input or output
Comment Optional

Note
TIA Portal V16 supports export and import of IoType attribute in AML file with AR APC V1.1.0

Example: AML structure


The following figure shows the structure of the following exported tag objects:
• empty default tag table
• tag user folder "Group_1"
• included tag table "Tag table_1
• four tags

Openness: API for automation of engineering workflows


1220 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

See also
Structure of the CAx data for importing/exporting (Page 1076)
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.35 Export/Import of RH/PLC

Requirement
• The TIA Portal Openness is connected to theTIA Portal
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is offline

Application
You can use TIA Portal to export and import AML file following AR APC V1.1 with R/H PLC having
same IP Address configuration.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1221
Export/import
6.5 Importing/exporting hardware data

Attribute
TIA Portal supports only one attribute in AML file for R/H PLC, if available in TIA Portal user
interface:

Device Item Attribute Name Handling Comment


HNetworkAddress Mandatory Exported/Imported, if the device item R/H PLC sup‐
ports this attribute in TIA Portal and is non empty
otherwise it shall be skipped.
For import, the "Enable the system IP address for
switched connection" shall be set and the HNetwor‐
kAddress shall be valued.

Restriction
• Export
- Only if the "Enable the system IP address for switched connection" in TIA Portal is selected.

Example: Exported configuration


The following configuration shows a device item where the HNetworkAddress are configured.

Openness: API for automation of engineering workflows


1222 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

AML structure of export file


The following figure shows the structure of exported AML file for R/H PLC

<InternalElement ID="e1879cf8-8222-4ce3-b171-60c56aed7f18" Name="PROFINET interface_1">


<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>32768</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<InternalElement ID="a32c67c7-47dc-4362-a9c4-b41b93b58eff" Name="E1">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value>
</Attribute>
<Attribute Name="NetworkAddress" AttributeDataType="xs:string">
<Value>192.168.0.1</Value>
</Attribute>
<Attribute Name="SubnetMask" AttributeDataType="xs:string">
<Value>255.255.255.0</Value>
</Attribute>
<Attribute Name="IpProtocolSelection" AttributeDataType="xs:string">
<Value>Project</Value>
</Attribute>
<Attribute Name="HNetworkAddress" AttributeDataType="xs:string">
<Value>192.168.0.3</Value>
</Attribute>
<ExternalInterface ID="802676fa-212f-4bf5-b112-de94993a0340" Name="LogicalEndPoint_Node"
RefBaseClassPath="CommunicationInterfaceClassLib/LogicalEndPoint" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/Node" />
</InternalElement>

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.36 Export/Import AML with customized tag and deviceitems

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is offline

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1223
Export/import
6.5 Importing/exporting hardware data

Application
You can use TIA Portal to export and import AML file following AR APC V1.1 with 'Customized'
sub-attribute of tag and deviceitem.

Attribute
The following table shows the related attribute available for a tag during CAx import and export
files:

Attribute Name Handling Comment


Customized Optional for export/ Sub-attribute of 'DataType' of a tag.
import True and False are the only allowed values for Customized.
While importing, the attribute customized has no relevance
During export Customized sub-attribute has a value "true" for
datatypes other than IEC 61131 datatypes. For IEC 61131 com‐
pliant datatypes the Customized sub-attribute shall not be ex‐
ported.

The following table shows the related attribute available for a deviceitem during CAx import and
export files:

Attribute Name Handling Comment


Customized Optional for import It is a child attribute to parent 'DeviceItemType' attribute for a
DeviceItem.
True and False are the only allowed values for Customized.
While importing and exporting, Customized attribute has no
relevance

Openness: API for automation of engineering workflows


1224 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Exported AML file


The below AML fiile shall be generated during export of an AML file with customized deviceItems.

<?xml version="1.0" encoding="utf-8"?>


<CAEXFile FileName="Project26.aml" SchemaVersion="2.15"
xsi:noNamespaceSchemaLocation="CAEX_ClassModel_V2.15.xsd">
<AdditionalInformation>
<WriterHeader>
...
</WriterHeader>
</AdditionalInformation>
<AdditionalInformation AutomationMLVersion="2.0" />
<AdditionalInformation DocumentVersions="Recommendations">
<Document DocumentIdentifier="AR APC" Version="1.1.0" />
</AdditionalInformation>
<InstanceHierarchy Name="APC Sample Instance Hierarchy">
<InternalElement ID="03ecf798-3e07-4976-b281-f8b98eb3a590" Name="Project26">
...
<InternalElement ID="c218aea9-93b8-4719-be6f-ccfa9517e2c6" Name="S71500/ET200MP station_1">
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>System:Device.S71500</Value>
</Attribute>
<InternalElement ID="c1ae306f-183f-47b8-91e6-cb331c559278" Name="Rail_0">
...
<InternalElement ID="8d7d5ee1-603a-4897-b47e-8954d4c21a31" Name="PLC_1">
...
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>CPU</Value>
</Attribute>
...
<InternalElement ID="a2a7f0bc-068c-4904-84b1-73ed87e28de1" Name="Tag table_1">
...
<Attribute Name="DataType" AttributeDataType="xs:string">
<Value>Conn_Any</Value>
<Attribute Name="Customized" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
</Attribute>
</InternalElement>
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
Device" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
AutomationProject" />
</InternalElement>
</InstanceHierarchy>
</CAEXFile>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1225
Export/import
6.5 Importing/exporting hardware data

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

6.5.37 Export/Import of FailSafe PLC

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is offline

Application
You can use TIA Portal to export and import an AML file following AR APC V1.1 with FailSafe PLC
having failsafe attributes.

Attributes
The following table shows the list of failsafe attributes for CAx import and export AML files:

Openness Attribute Handling Comment AR APC Name in AML


Failsafe_FSourceAddress Mandatory Export/import only if the device Failsafe_FSourceAddress
item is a failsafe PLC and sup‐
ports this attribute in TIA Portal
and is non empty otherwise it
shall be skipped
Failsafe_LowerBoundForFDesti‐ Mandatory Exported/Imported only if the Failsafe_LowerBoundForFDesti‐
nationAddresses device item is a failsafe PLC and nationAddresses
supports this attribute in TIA
Portal and is non empty other‐
wise it shall be skipped
Failsafe_UpperBoundForFDesti‐ Mandatory Exported/Imported only if the Failsafe_UpperBoundForFDesti‐
nationAddresses device item is a failsafe PLC and nationAddresses
supports this attribute in TIA
Portal and is non empty other‐
wise it shall be skipped

Openness: API for automation of engineering workflows


1226 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Openness Attribute Handling Comment AR APC Name in AML


Failsafe_CentralFSourceAddress Optional Exported/Imported only if the Failsafe_FSourceAddress
device item is a failsafe PLC and
supports this attribute in TIA
Portal and is non empty other‐
wise it shall be skipped
Failsafe_FDestinationAddress Optional Exported/Imported only if the Failsafe_FDestinationAddress
device item is a failsafe PLC and
supports this attribute in TIA
Portal and is non empty other‐
wise it shall be skipped

Example: Exported configuration


The following configuration shows a device item where the attributes are configured.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1227
Export/import
6.5 Importing/exporting hardware data

AML structure of the export file


The following figures show the structure of the exported AML file.

Openness: API for automation of engineering workflows


1228 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<InternalElement ID="9c944d2c-e0ae-4f39-b35a-a63faaf35be7" Name="PLC_1">


<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>CPU 1511TF-1 PN</Value>
</Attribute>
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>CPU</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 511-1UK01-0AB0</Value>
</Attribute>
<Attribute Name="InstallationDate" AttributeDataType="xs:dateTime">
<Value>2019-02-28T08:12:12.987Z</Value>
</Attribute>
<Attribute Name="Failsafe_FSourceAddress" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="Failsafe_LowerBoundForFDestinationAddresses"
AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="Failsafe_UpperBoundForFDestinationAddresses"
AttributeDataType="xs:string">
<Value>99</Value>
</Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string">
<Value>V2.8</Value>
</Attribute>
<InternalElement ID="4f718e93-b541-4983-8f13-1f5b21c3e70c" Name="Default tag table">
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
TagTable"/>
</InternalElement>
<InternalElement ID="20e19f5b-8ace-4e0c-af0b-c710ae4817da" Name="CPU display_1">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>3</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="5a24516f-17d6-4b2a-a4ac-efc1b577875d" Name="Card reader/writer_1">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>4</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1229
Export/import
6.5 Importing/exporting hardware data

<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement> <InternalElement ID="0f746d71-035e-4e64-b0d7-51d0449cfd88" Name="OPC
UA_1">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>254</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value> </Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="a0633104-a2ac-4680-bb99-81df50f5ec40" Name="PROFINET interface_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>X1</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>32768</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<InternalElement ID="e3497176-dbba-4fec-9d3a-772ae13987c4" Name="E1">
<Attribute Name="Type" AttributeDataType="xs:string">
<Value>Ethernet</Value> </Attribute>
<Attribute Name="NetworkAddress" AttributeDataType="xs:string">
<Value>192.168.0.1</Value>
</Attribute>
<Attribute Name="SubnetMask" AttributeDataType="xs:string">
<Value>255.255.255.0</Value>
</Attribute>
<Attribute Name="IpProtocolSelection" AttributeDataType="xs:string">
<Value>Project</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/Node" />
</InternalElement>
<InternalElement ID="3208384f-d5ba-4ccb-b8da-f08ec38ec681" Name="Port_1">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P1 R</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>32769</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<InternalElement ID="4a47c05e-9656-4e02-9b51-23b065b6fe47" Name="Port_2">
<Attribute Name="Label" AttributeDataType="xs:string">
<Value>P2 R</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>32770</Value>
</Attribute>

Openness: API for automation of engineering workflows


1230 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">


<Value>true</Value>
</Attribute>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationPort" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
CommunicationInterface" />
</InternalElement>
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
</InternalElement>
<InternalElement ID="e3fdb611-4b68-4682-b154-ae43c74a24d3" Name="F-DI 16x24V DC_1">
<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>F-DI 16x24V DC</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value> </Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 526-1BH00-0AB0</Value>
</Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string">
<Value>V1.0</Value>
</Attribute>
<InternalElement ID="77c4fea0-baba-44e6-80f2-72b7b830a88a" Name="F-DI 16x24V DC_1">
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>1</Value>
</Attribute> <Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>true</Value>
</Attribute>
<Attribute Name="Failsafe_FSourceAddress" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="Failsafe_FDestinationAddress" AttributeDataType="xs:string">
<Value>655</Value>
</Attribute>
</InternalElement>
</InternalElement>

Extended role for device item


AR APC 1.2 recommends following changes for CAx exchange in TIA Portal V17 onwards, any
device item shall be exchanged with one additional role.
'AutomationProjectConfigurationProfiSafeRoleClassLib/DeviceItemProfiSafe' along with the
existing role 'AutomationProjectConfigurationRoleClassLib/DeviceItem' in case AR APC
recommended failsafe attributes are supported.
The device item shall be exported with additional role in case it supports extended attributes like
Failsafe_FSourceAddress, Failsafe_LowerBoundForFDestinationAddresses,
Failsafe_UpperBoundForFDestinationAddresses, Failsafe_CentralFSourceAddress,

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1231
Export/import
6.5 Importing/exporting hardware data

Failsafe_FDestinationAddress. And it shall be possible to import device item with or without


extended role also.

AML file with device item


Below XML snippet depicts the AML file with "device item" supporting failsafe attributes module
with an extended role.

<InternalElement ID="9d6c270a-2a48-426a-9dae-8cf88c5a591a" Name="PLC_1">


<Attribute Name="TypeName" AttributeDataType="xs:string">
<Value>CPU 414F-3 PN/DP</Value>
</Attribute>
<Attribute Name="DeviceItemType" AttributeDataType="xs:string">
<Value>CPU</Value>
</Attribute>
<Attribute Name="PositionNumber" AttributeDataType="xs:int">
<Value>2</Value>
</Attribute>
<Attribute Name="BuiltIn" AttributeDataType="xs:boolean">
<Value>false</Value>
</Attribute>
<Attribute Name="TypeIdentifier" AttributeDataType="xs:string">
<Value>OrderNumber:6ES7 414-3FM06-0AB0</Value>
</Attribute>
<Attribute Name="Failsafe_FSourceAddress" AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="Failsafe_LowerBoundForFDestinationAddresses"
AttributeDataType="xs:string">
<Value>1</Value>
</Attribute>
<Attribute Name="Failsafe_UpperBoundForFDestinationAddresses"
AttributeDataType="xs:string">
<Value>99</Value>
</Attribute>
<Attribute Name="FirmwareVersion" AttributeDataType="xs:string">
<Value>V6.0</Value>
</Attribute>
...
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationRoleClassLib/
DeviceItem" />
<SupportedRoleClass RefRoleClassPath="AutomationProjectConfigurationProfiSafeRoleClassLib/
DeviceItemProfiSafe" />
</InternalElement>

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1232 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.38 Export/Import of Failsafe IO

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a project (Page 113)
• PLC is offline

Application
You can use TIA Portal to export and import an AML file following AR APC V1.1 with FailSafe IO
having failsafe attributes.

Attributes
The following table shows the related attributes available on Failsafe IO module/submodule for
CAx import and export files :

Device Item Attribute Name Handling Comment


FSourceAddress Mandatory Export/import only if the device item is a failsafe IO
and supports in TIA Portal.
FDestinationAddresses Mandatory Export/Import only if the device item is a failsafe IO
and supports in TIA Portal.

Note
• For most of the Failsafe IO's, FSourceAddress is a ReadOnly it is not writable and is a
reflection of FCentralFSourceAddress attribute of failsafe PLC. The same value shall get
exported and ignored during import.
• If the FSourceAddress and FDestinationAddress are Readonly, then value shall be exported.
However, during import warning message should be displayed in info tab of TIA Portal.
• FSourceAddress and FDestinationAddress should be supported for IO module and sub
module level.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1233
Export/import
6.5 Importing/exporting hardware data

Example: Exported configuration


The following configuration shows a device item where the attributes are configured.

AML structure of the export file


The following figure shows the structure of exported AML file.

<Attribute Name="FSourceAddress" AttributeDataType="xs:string">


<Value>1</Value>
</Attribute>
<Attribute Name="FDestinationAddress" AttributeDataType="xs:string">
<Value>65534</Value>
</Attribute>

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


1234 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

6.5.39 Export/Import vendor specific attribute

Requirement
• The TIA Portal Openness application is connected to the TIA Portal.
See Connecting to the TIA Portal (Page 81)
• A project is open
See Opening a Project (Page 113)

Application
In TIA Portal, you can export and import an AML file for device and deviceitems having
"Manufacturer" attribute so that you can exchange vendor specific information in round trip
scenarios.
The attribute "Manufacturer" is not supported by Openness. It shall be consumed through
"Transformation Plugin" during Export/Import. AML file with AR Drive recommendation
document of version 1.0 is supported.

Note
AML files shall be generated(exported) by TIA Portal V16 following AR APC V1.1.

Export
You can export the "Manufacturer" attribute into AML file, if it is available in AmiModel, which
shall be filled by "Transformation Plugin" users.

Import
You can import "Manufacturer" attribute to TIA Portal, wherein vendor specific attribute is
available in AmiModel which shall be consumed by "Transformation Plugin" users.
Currently this attribute shall be supported only for 'Drive' devices and device items since only
they do have official "Transformation PlugIn" written for CAx.

See also
Connecting to the TIA Portal (Page 81)
Opening a project (Page 113)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1235
Export/import
6.5 Importing/exporting hardware data

6.5.40 AML attributes versus TIA Portal Openness attributes

Access attributes and export/import attributes


Via TIA Portal Openness you can access attributes of hardware objects. Single names you use to
access these attributes e. g. of a device item differs from the attributes names in the export/
import AML file.

Attributes list
The following table provides an overview to both kinds of attributes:

Table 6-6 Attribute names of devices and GSD/GSDML devices

AML file TIA Portal Openness


Name Name
TypeIdentifier TypeIdentifier
Comment Comment

Table 6-7 Attribute names of device items

AML file TIA Portal Openness


Name Name
TypeIdentifier Mapped to substring of <TypeIdentifier> (i.e.,
value before first "/" operator) ignoring firmware
version part in it.
Mapping substring is applicable only when TypeI‐
dentifier starts with <OrderNumber:> prefix and
it has firmware version part otherwise mapped to
complete <TypeIdentifier>.
FirmwareVersion <FirmwareVersion> mapped to substring of
<TypeIdentifier> (i.e., value after first "/" op‐
erator). Mapping substring is applicable only when
<TypeIdentifier> starts
with <OrderNumber:> prefix and it has firmware
version part.
TypeName TypeName
DeviceItemType (for CPU and HeadModule) Classification
PositionNumber PositionNumber
BuiltIn IsBuiltIn
PlantDesignation IEC PlantDesignation
LocationIndentifier IEC LocationIdentifier
Comment Comment

Openness: API for automation of engineering workflows


1236 System Manual, 05/2021, Online documentation
Export/import
6.5 Importing/exporting hardware data

Table 6-8 Attribute names of GSD/GSDML device items

AML file TIA Portal Openness


Name Name
TypeIdentifier TypeIdentifier
TypeName TypeName
DeviceItemType (for HeadModule) Classification
PositionNumber PositionNumber
BuiltIn IsBuiltIn
Comment Comment
Label Label

Table 6-9 Attribute names of tags

AML file TIA Portal Openness


Name Name
DataType DataTypeName
LogicalAddress LogicalAddress
Comment Comment

Table 6-10 Attribute names of tag tables

AML file TIA Portal Openness


Name Name
AssignToDefault IsDefault

Table 6-11 Attribute names of addresses

AML file TIA Portal Openness


StartAddress StartAddress
Length Length
IoType IoType

Table 6-12 Attribute names of ports

AML file TIA Portal Openness


Name Name
TypeIdentifier TypeIdentifier
FirmwareVersion FirmwareVersion
TypeName TypeName
PositionNumber PositionNumber
BuiltIn IsBuiltIn

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1237
Export/import
6.5 Importing/exporting hardware data

AML file TIA Portal Openness


Comment Comment
Label Label

Table 6-13 Attribute names of devices with IO-interface

AML file TIA Portal Openness


Name Name
TypeIdentifier TypeIdentifier
FirmwareVersion FirmwareVersion
TypeName TypeName
DeviceItemType (for CPU and HeadModule) Classification
PositionNumber PositionNumber
BuiltIn IsBuiltIn
Label Label
Comment Comment

Table 6-14 Attribute names of channels

AML file TIA Portal Openness


Type Type
IoType IoType
Number Not mapped to any attribute in TIA Portal Open‐
ness.
Length ChannelWidth

Openness: API for automation of engineering workflows


1238 System Manual, 05/2021, Online documentation
Major Changes 7
7.1 Major changes in TIA Portal Openness V16

Changes
If you have considered the hints concerning programming across versions and you do not
upgrade your project to V16 your applications will run without any restrictions on any computer
even if only a TIA Portal V16 is installed.
If you upgrade your project to V16 it is necessary to recompile your application using the
SiemensEngineering.dll of V16. In some cases it might be necessary to adapt the code of your
application

Export of datablocks with export option "None"


As of TIA Portal Openness V16 members of a datablock which are read only will be exported as
informative items. It is not longer possible to change these attributes in the exported xml.

I&M and Profisafe address attributes of pushbutton panel and key panel
As of TIA Portal Openness V16 I&M and Profisafe address attributes of pushbutton panel and key
panel will be accessible at module level.

Export DB attributes of memory layout property


As of TIA Portal Openness V16 IDB of FBs, ArrayDBs and Graph blocks attributes of memory
layout property will be exported with ReadOnly="True".

Access attribute in units


As of TIA Portal Openness V16 inconsistent import and export of "Access" attribute is supported
in blocks, UDTs and tag table within units

SimaticML XML file’s schema definition


As of TIA Portal Openness V16 boolean attribute node's SystemDefined attribute’s default value
become false in SimaticML XML file’s schema definition. However, the change doesn't affect any
XML export/ import feature. It is only important for users who try to generate XMLs using the
schema file.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1239
Major Changes
7.1 Major changes in TIA Portal Openness V16

Enhance XML import method of blocks and types


As of TIA Portal Openness V16 extend the new import method with additional parameters (i.e.
path, importOptions, and swImportOptions) and a new enum value IgnoreUnitAttribute. By
using swImportOptions.IgnoreUnitAttributes, you can import block from unit to non-unit
composition.

AML GUIDs are stored in App IDs


As of TIA Portal Openness V16 AML GUIDs are stored in CustomIdentity (App IDs) attribute
instead of Comment to support round trip exchange of device and module.

Name of HMI Object classes


As of TIA Portal Openness V16, the following table shows the list of required name changes for
HMI Object classes:

Class Name New Class Name


AnalogAlarmComposition HmiAnalogAlarmComposition
DiscreteAlarmComposition HmiDiscreteAlarmComposition
AlarmClassComposition HmiAlarmClassComposition
DataLogComposition HmiDataLogComposition
AlarmLogComposition HmiAlarmLogComposition
LoggingTagComposition HmiLoggingTagComposition
LogConfiguration DataLog

Addition/Removal of properties name for DataLog/Alarm Log


As of TIA Portal Openness V16, the following new properties "StorageDevice" and
"StorageFolder" are added to DataLog/AlarmLog and properties such as "StoragePath" and
"RequireExplicitRelease" are removed from DataLog/AlarmLog and ScreenItems respectively.
You can find the updated code example for StorageDevice and StorageFolder properties as
below:

HmiDataLog dataLog = hmiSoftware.DataLogs.Find("DataLog1");


dataLog.Settings.StorageDevice = DeviceNode.Local;
dataLog.Settings.StorageFolder = @"D:\workdir\DataLogs";

Remove a property name from HMI Tag


As of TIA Portal Openness V16, the 'DisplayName' property is removed from the HMI Tag object.

Openness: API for automation of engineering workflows


1240 System Manual, 05/2021, Online documentation
Major Changes
7.2 Major changes in TIA Portal Openness V15.1

7.2 Major changes in TIA Portal Openness V15.1

Changes
If you have considered the hints concerning programming across versions and you do not
upgrade your project to V15.1 your applications will run without any restrictions on any
computer even if only a TIA Portal V15.1 is installed.
If you upgrade your project to V15.1 it is necessary to recompile your application using the
SiemensEngineering.dll of V15.1. In some cases it might be necessary to adapt the code of your
application

Type identifiers
The type identifier for racks and devices of "PC with ports" and "Ethernet devices with ports" have
been renamed.

PC with ports Type identifier before V15.1 Type identifier as of V15.1


Device System:DesktopPC.Device System:Device.DesktopPC
Rack System:DesktopPC.Rack System:Rack.DesktopPC
Device item System:DesktopPC.Port<X> System:DeviceItem.EthernetDe‐
<X> denotes the number of ports vice.Port<X>
<X> denotes the number of ports

Ethernet devices with ports


Device System:DummyPC.Device System:Device.EthernetDevice
Rack System:Rack.DummyPC System:Rack.EthernetDevice
Device item System:DummyPC.Port<X>
<X> denotes the number of ports

Failures when trying to connect to TIA Portal


The messages in case of failures when trying to connect to TIA Portal have been enhanced in a
more specific way.

Cross-thread operations
Access to Openness objects is not inherently thread-safe.
If you use multi-threading to improve the performance of your Openness application, it is
recommended to create your TIA Portal instance with an MTA.
If TIA Portal is created or attached within an STA thread, all Openness objects associated with
that Portal instance must be accessed from the same STA thread; otherwise, an exception will
be thrown.

Submodules do not have attributes Author and TypeName


The attributes Author and TypeName have been removed from submodules which cannot be
plugged.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1241
Major Changes
7.2 Major changes in TIA Portal Openness V15.1

Opening of a global library


As of TIA Portal Openness V15.1 a global library can be opened via Openness independant of a
persisted preview mode of the library.

Application exit codes


In case of an application exit code
• Up to TIA Portal Openness V15 you get a non recoverable exception
• As of TIA Portal Openness V15.1 you get a EngineeringRuntimeException or a
EngineeringTargetInvocationException if the error code is known and a non recoverable
exception if the error code is unknown.

Schema extension for nameless parameters


The import of SCL blocks is possible even if ENO is used at a nonformal call..

Header of indexed parameters


As of TIA Portal Openness V15.1 the header of indexed parameters my not be changed via
Openness.
Some drive parameters are modelled as indexed parameters, as they provide several pieces of
data for one topic. The modeling of the indexed drive parameters in Openness follows the drive
specific definition of the respective parameters as they are defined in the respective list manual.
Indexed parameters are modeled as follows:
Header item: The respective drive parameter without any index. The header item contains a
descriptive text, to inform you about the semantics of the referenced indexed drive parameter.
Therefore the header item is readonly, because it holds no actual value.
Indexed Items: The indexed items of the drive parameter below the header item. They provide
descriptive text, defining the semantics of the specific indexed item (readonly). In addition, they
also provide the value that can be retrieved via Openness API. If the respective indexed
parameter is also writeable, than the value can also be set via Openness API.

Attribute TransmissionRateAndDuplex
Some faulty enum values for attribute TransmissionRateAndDuplex have been corrected, for
example the enum value "POFPCF100MbpsFullDuplexLD" has been removed and
"POFPCF100MbpsFullDuplex" has been added. For detail information, please see Configurable
attributes of a port-to-port connection (Page 143)

Attribute AutoNumber for know how protected blocks


As of V15.1 the attribute AutoNumber can not be changed via TIA Portal Openness if a block is
know how protected.

Openness: API for automation of engineering workflows


1242 System Manual, 05/2021, Online documentation
Major Changes
7.2 Major changes in TIA Portal Openness V15.1

Number of channels listed by ChannelInfo interfaace


Up to TIA Portal Openness V15 the ChannelInfo interface the number of available channels
hasn't been correct for some mdoules.

Access to ProDiag FB attributes


The following attributes of a ProDiag FB can be accessauthored via TIA Portal Openness:
• Version
• Initial values acquisition
• Use central timestamp

Import/Export of failsafe blocks


Import of failsafe blocks from previous versions is not possible.
Export of system generated failsafe blocks will be prevented as of TIA Portal Openness V15.1.

R/H systems
Download or access for R/H devices is available at device.
Online and Download Provider are not available for individual R/H PLC (DeviceItems).
For PLC2 of an R/H system, SoftwareContainer will not be available.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1243
Major Changes
7.3 Major changes in TIA Portal Openness V15

7.3 Major changes in TIA Portal Openness V15

Changes
If you have considered the hints concerning programming across versions and you do not
upgrade your project to V15 your applications will run without any restrictions on any computer
even if only a TIA Portal V15 is installed.
If you upgrade your project to V15 it is necessary to recompile your application using the
SiemensEngineering.dll of V15.
In some cases it is necessary to adapt the code of your application
• Behaviour changes for compositions in DeviceItemComposition
• BitOffset of ASi addresses
• Exception class
• System folders of system UDTs
• Submodules do not have attributes Author and TypeName
• Timestamp for last modification
• Export XML for GRAPH blocks
• Importing tag tables
• Modifying not failsafe relevant attributes of a PLC
• Modifying F-parameters while safety password is set
• Accessing TO objects in a S7 1200 CPU

Behaviour changes for compositions in DeviceItemComposition


The following compositions in DeviceItemCompositon have been changed for a dynamic
behaviour. The composition is updated now if an element is added or deleted via the user
interface of TIA Portal.
• IoSystem - ConnectedIoDevices
• Subnet - IoSystems
• Subnet - Nodes
• NetworkInterface - Nodes
• NetworkInterface - Ports
• NetworkPort - ConnectedPorts
• SubnetOwner - Subnets

BitOffset of ASi addresses


If a module has an input and an output address for both address objects the correct attribute
BitOffset will be provided.
If a module has channels the attribute BitOffset will not be provided for the channel.

Openness: API for automation of engineering workflows


1244 System Manual, 05/2021, Online documentation
Major Changes
7.3 Major changes in TIA Portal Openness V15

Exception class
ServiceID and MessageID have been removed from exception class

Submodules do not have attributes Author and TypeName


The attributes Author and TypeName have been removed from submodules which cannot be
plugged.

System folders of system UDTs


For system folders of system UDTs the appropriate folder and composition is provided. This leads
also to a change in the hierarchy of compare results.

Timestamp for last modification


If during an upgrade an object is changed the timestamp for the last modification is changed as
well.

Export XML for GRAPH blocks


The export XML for GRAPH blocks contains an additional empty action: <Actions />

Importing tag tables


Setting tag attributes is not longer dependent from data types.

Modifying not failsafe relevant attributes of a PLC


All not failsafe relevant attributes of a PLC can be modified via TIA Portal Openness, even if a
safety password is set.

Modifying F-parameters while safety password is set


F-parameters of a F-IO can only be modified if the safety password is not set.

Accessing TO objects in a S7 1200 CPU


The access to array tags for the TO objects TO_PositioningAxis and TO_CommandTable has been
changed. You can find details in the chapter about S7-1200 Motion Control.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1245
Major Changes
7.4 Major changes in V14 SP1

7.4 Major changes in V14 SP1

7.4.1 Major changes in V14 SP1

Introduction
The following changes were made in TIA Portal Openness API object modell V14 SP1, which may
impact your existing applications:

Change Required program code adjustment


Impoved handling for master copies The CreateFrom action will create a new object based on a master copy in a
library and place it in the composition where the action was called. The Cre‐
ateFrom action only supports master copies containing only single objects.
The return type corresponds to the respective composed type.
The following composition support CreateFrom:
• Siemens.Engineering.HW.DeviceComposition
• Siemens.Engineering.HW.DeviceItemComposition
• Siemens.Engineering.SW.Blocks.PlcBlockComposition
• Siemens.Engineering.SW.Tags.PlcTagTableComposition
• Siemens.Engineering.SW.Tags.PlcTagComposition
• Siemens.Engineering.SW.Types.PlcTypeComposition
• Siemens.Engineering.SW.TechnologicalObjects.TechnologicalInstan‐
ceDBComposition
• Siemens.Engineering.SW.Tags.PlcUserConstantComposition
• Siemens.Engineering.Hmi.Tag.TagTableComposition
• Siemens.Engineering.Hmi.Tag.TagComposition
• Siemens.Engineering.Hmi.Screen.ScreenComposition
• Siemens.Engineering.Hmi.Screen.ScreenTemplateComposition
• Siemens.Engineering.Hmi.RuntimeScripting.VBScriptComposition
• Siemens.Engineering.HW.SubnetComposition
• Siemens.Engineering.HW.DeviceUserGroupComposition
• Siemens.Engineering.SW.Blocks.PlcBlockUserGroupComposition
• Siemens.Engineering.SW.ExternalSources.PlcExternalSourceUserGroup‐
Composition
• Siemens.Engineering.SW.Tags.PlcTagTableUserGroupComposition
• Siemens.Engineering.SW.Types.PlcTypeUserGroupComposition
Improved handling for global libraries Existing actions on global libraries can now be modifying actions, e.g. delete
a master copy from a global library.
UpdateProject and UpdateLibrary do not longer use the UpdatePathsMode
and DeleteUnusedVersionsMode parameters. Unused versions are not de‐
leted after an update

Openness: API for automation of engineering workflows


1246 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Change Required program code adjustment


Change System.String to System.IO.FileInfo All occurrences where a string path had to be specified are using FileInfo path
Change System.String to System.IO.Director‐ or a DirectoryInfo path. For example:
yInfo • Open project
• Open library
• Create project
• Create global llibrary
• ...

New items in the object model

Name Type Namespace Comment


PlcUserConstant Class Siemens.Engineer‐ Split from PlcConstant.
ing.SW.Tags
PlcUserConstantComposition Class Siemens.Engineer‐ Split from PlcConstantComposition.
ing.SW.Tags
PlcSystemConstant Class Siemens.Engineer‐ Split from PlcConstant.
ing.SW.Tags
PlcSystemConstantComposition Class Siemens.Engineer‐ Split from PlcConstantComposition.
ing.SW.Tags
MultilingualTextItem Class Siemens.Engineering Access to multilingual text.
MultilingualTextItemComposition Class Siemens.Engineering Access to multilingual text.
TiaPortalTrustAuthority.Featur‐ Enum value Siemens.Engineering Access to TIA Portal settings.
eTokens
TiaPortalSetting Class Siemens.Engineering.Set‐ Access to TIA Portal settings.
tings
TiaPortalSettingComposition Class Siemens.Engineering.Set‐ Access to TIA Portal settings.
tings
TiaPortalSettingsFolder Class Siemens.Engineering.Set‐ Access to TIA Portal settings.
tings
TiaPortalSettingsFolderComposi‐ Class Siemens.Engineering.Set‐ Access to TIA Portal settings.
tion tings
LanguageAssociation Class Siemens.Engineering Access to active languages.
LanguageComposition.Find Method Siemens.Engineering Access to active languages.

Modified items in the object model

Name Type Namespace Comment


PlcConstant Class Siemens.Engineer‐ Published base class of PlcUserConstant
ing.SW.Tags and PlcSystemConstant.
PlcTag Class Siemens.Engineer‐ Split from PlcConstantComposition.
ing.SW.Tags
ITargetComparable Interface Siemens.Engineering.Com‐ String attribute DataTypeName instead of
pare an open link DataType.
MultilingualText Class Siemens.Engineering Access to multilingual text.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1247
Major Changes
7.4 Major changes in V14 SP1

Name Type Namespace Comment


ProjectComposition.Create Method Siemens.Engineering Parameters changed to using a DirectoryIn‐
fo and string.
Project.Subnets Attribute Siemens.Engineering Access to subnets
Project.Languages Attribute Siemens.Engineering Moved to be an attribute of Siemens.Engi‐
neering.LanguageSettings to provide sup‐
ported languages

Removed items in the object model

Name Type Namespace Comment


PlcConstantComposition Class Siemens.Engineer‐ Split in PlcSystemConstantComposi‐
ing.SW.Tags tion and PlcUserConstantComposi‐
tion.
CompareResultElement.PathInformation Attribute Siemens.Engineer‐ Not used anymore.
ing.SW.Tags
MultilingualText.GetText(CultureInfo cul‐ Method Siemens.Engineer‐ Modified concept for accessing text
tureInfo) ing.Compare items of MultilingualText.
TiaPortalTrustAuthority.CustomerIdentifi‐ Enum value Siemens.Engineering Not used anymore.
cation
TiaPortalTrustAuthority.ElevatedAcces‐ Enum value Siemens.Engineering Not used anymore.
sExtensions

Behaviour changes

Name Type Namespace Comment


PlcTag.Export(FileInfo path, ExportOp‐ Method Siemens.Engineer‐ The value of the attribute LogicalAd‐
tions options) ing.SW.Tags dress is always exported in interna‐
tional mnemonics now. German
mnemonics are still accepted on im‐
port.
PlcTag.LogicalAddress Attribute Siemens.Engineer‐ The value of the attribute LogicalAd‐
ing.SW.Tags dress is always returned in interna‐
tional mnemonics now. German
mnemonics are accepted on write.

Openness: API for automation of engineering workflows


1248 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

7.4.2 Major changes in the object model

Object model of TIA Portal Openness V14


In order to allow you a comparison between the old and the new object model of TIA Portal
Openness, the diagram below describes the object model of TIA Portal V14.

Note
The object model described on the diagram is obsolete, for information about the object model
of TIA Portal Openness V14 SP1 refer to TIA Portal Openness object model (Page 51)

'HYLFHV Q

8QJURXSHG'HYLFHV*URXS  'HYLFH6\VWHP*URXS 'HYLFH,WHPV 

'HYLFH*URXS
'HYLFHV Q 'HYLFH 'HYLFH,WHPV Q 'HYLFH,WHP
$EVWUDFW!!

'HYLFH*URXSV Q 'HYLFH8VHU*URXS ,6RIWZDUH&RQWDLQHU


6HUYLFH!!

*UDSKLFV Q 0XOWL/LQJXDO*UDSKLF


6RIWZDUH&RQWDLQHU

7,$3RUWDO 3URMHFWV Q 3URMHFW +Z([WHQVLRQV Q ,([WHQVLRQ


6RIWZDUH 

+LVWRU\(QWULHV Q +LVWRU\(QWU\ 6RIWZDUH%DVH


*OREDO/LEUDULHV Q $EVWUDFW!!
/DQJXDJHV Q /DQJXDJH
3URMHFW/LEUDU\ 

8VHG3URGXFWV Q 8VHG3URGXFW 3OF6RIWZDUH +PL7DUJHW


*OREDO/LEUDU\ 3URMHFW/LEUDU\

The following diagramm describes the objects which are located under ProjectLibrary.

0DVWHU&RS\6\VWHP)ROGHU 0DVWHU&RS\8VHU)ROGHU

0DVWHU&RS\)ROGHU  0DVWHU&RS\)ROGHU )ROGHUV Q


$EVWUDFW!! 0DVWHU&RSLHV Q 0DVWHU&RS\

3URMHFW/LEUDU\
/LEUDU\7\SH)ROGHU 7\SHV Q /LEUDU\7\SH 9HUVLRQV Q /LEUDU\7\SH9HUVLRQ
7\SH)ROGHU  $EVWUDFW!! )ROGHUV Q

/LEUDU\7\SH6\VWHP)ROGHU /LEUDU\7\SH8VHU)ROGHU

The following diagramm describes the objects which are located under HmiTarget.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1249
Major Changes
7.4 Major changes in V14 SP1

&RQQHFWLRQV Q &RQQHFWLRQ

&\FOHV Q &\FOH

*UDSKLF/LVWV Q *UDSKLF/LVW

6FUHHQ)ROGHU )ROGHUV Q 6FUHHQ8VHU)ROGHU


6FUHHQ)ROGHU  6FUHHQ6\VWHP)ROGHU
$EVWUDFW!! 6FUHHQV Q 6FUHHQ

6FUHHQ*OREDO(OHPHQWV  6FUHHQ*OREDO(OHPHQWV

+PL7DUJHW

6FUHHQ2YHUYLHZ  6FUHHQ2YHUYLHZ
6FUHHQ7HPSODWH)ROGHU )ROGHUV Q 6FUHHQ7HPSODWH8VHU)ROGHU
$EVWUDFW!! 6FUHHQ7HPSODWHV Q 6FUHHQ7HPSODWH
6FUHHQ7HPSODWH)ROGHU  6FUHHQ7HPSODWH6\VWHP)ROGHU

7DJ)ROGHU )ROGHUV Q 7DJ8VHU)ROGHU


$EVWUDFW!! 7DJ7DEOHV Q
7DJ)ROGHU  7DJ6\VWHP)ROGHU 7DJ7DEOH 7DJV Q 7DJ
'HIDXOW7DJ7DEOH 

7H[W/LVWV Q 7H[W/LVW

9%6FULSW)ROGHU )ROGHUV Q 9%6FULSW8VHU)ROGHU


9%6FULSW)ROGHU  9%6FULSW6\VWHP)ROGHU
$EVWUDFW!! 9%6FULSWV Q 9%6FULSW

The following diagramm describes the objects which are located under PlcSoftware.

Openness: API for automation of engineering workflows


1250 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

6\VWHP%ORFN*URXSV  3OF6\VWHP%ORFN*URXS *URXSV Q


)%

%ORFNV Q &RGH%ORFN


)&
$EVWUDFW!!

2%
3OF%ORFN*URXS %ORFNV Q 3OF%ORFN
$EVWUDFW!! *URXSV Q $EVWUDFW!!
,QVWDQFH'%

%ORFN*URXS  3OF%ORFN6\VWHP*URXS 3OF%ORFN8VHU*URXS 'DWD%ORFN


*OREDO'%
$EVWUDFW!!

$UUD\'%

3OF([WHUQDO6RXUFH*URXS ([WHUQDO6RXUFHV Q


3OF([WHUQDO6RXUFH
$EVWUDFW!! *URXSV Q

([WHUQDO6RXUFH*URXS  3OF([WHUQDO6RXUFH6\VWHP*URXS 3OF([WHUQDO6RXUFH8VHU*URXS

3OF6RIWZDUH

7\SH*URXS  3OF7\SH6\VWHP*URXS 3OF7\SH8VHU*URXS

3OF7\SH6\VWHP*URXS *URXSV Q 3OF7\SH


3OF6WUXFW
$EVWUDFW!! 7\SHV Q $EVWUDFW!!

7DJ7DEOH*URXS  3OF7DJ7DEOH6\VWHP*URXS 3OF7DJ7DEOH8VHU*URXS 3OF7DJ

7DJV Q
3OF7DJ7DEOH*URXS *URXSV Q
$EVWUDFW!! 7DJ7DEOHV Q 3OF7DJ7DEOH

&RQVWDQWV Q

3OF&RQVWDQW

7HFKQRORJLFDO,QVWDQFH'
7HFKQRORJLFDO2EMHFW*URXS  7HFKQRORJLFDO,QVWDQFH'%*URXS 7HFKQRORJLFDO2EMHFWV  7HFKQRORJLFDO,QVWDQFH'%&RPSRVLWLRQ %ORFNV Q
'DWD%ORFN

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1251
Major Changes
7.4 Major changes in V14 SP1

Relationship between TIA Portal and TIA Portal Openness object model
The figure below shows the relationship between the object model and a project in the TIA
Portal:

Project DeviceItem

 PlcSoftware

 HmiTarget

① The object "Project" corresponds to an open project in the TIA Portal.


② The "PlcSoftware" object is of type "SoftwareBase"④, and corresponds to a PLC. The object's contents correspond to
a PLC in the project navigation with access to objects such as blocks or PLC tags.
③ The "HmiTarget" object is of type "SoftwareBase"④, and corresponds to an HMI device. The object's contents corre‐
spond to an HMI device in the project navigation with access to objects such as screens or HMI tags.
④ The object "DeviceItem" corresponds to an object in the "Devices & Networks" editor. An object of the type "DeviceItem"
can be a rack or an inserted module.

Openness: API for automation of engineering workflows


1252 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

7.4.3 Changes on pilot functionality

Introduction
The following changes were made in API object modell V14 SP1 are only relevant for users,
which have used the pilot functionality of HW Config in V14.

Modifications for TIA Portal Openness API types

TIA Portal Openness API type new TIA Portal Openness API type
Siemens.Engineering.HW.IAddress Siemens.Engineering.HW.Address
Siemens.Engineering.HW.IAddressController Siemens.Engineering.HW.Features.AddressController
Siemens.Engineering.HW.IChannel Siemens.Engineering.HW.Channel
Siemens.Engineering.HW.IDevice Siemens.Engineering.HW.Device
Siemens.Engineering.HW.IDeviceItem Siemens.Engineering.HW.DeviceItem
Siemens.Engineering.HW.IExtension Siemens.Engineering.HW.Extensions
Siemens.Engineering.HW.IGsd Siemens.Engineering.HW.Features.GsdObject
Siemens.Engineering.HW.IGsdDevice Siemens.Engineering.HW.Features.GsdDevice
Siemens.Engineering.HW.IGsdDeviceItem Siemens.Engineering.HW.Features.GsdDeviceItem
Siemens.Engineering.HW.IHardwareObject Siemens.Engineering.HW.HardwareObject
Siemens.Engineering.HW.IHwIdentifier Siemens.Engineering.HW.HwIdentifier
Siemens.Engineering.HW.IHwIdentifierController Siemens.Engineering.HW.Features.HwIdentifierController
Siemens.Engineering.HW.IIoConnector Siemens.Engineering.HW.IoConnector
Siemens.Engineering.HW.IIoController Siemens.Engineering.HW.IoController
Siemens.Engineering.HW.IIoSystem Siemens.Engineering.HW.IoSystem
Siemens.Engineering.HW.IInterface Siemens.Engineering.HW.Features.NetworkInterface
Siemens.Engineering.HW.Extensions.ModuleInformationPro‐ Siemens.Engineering.HW.Utilities.ModuleInformationProvid‐
vider er
Siemens.Engineering.HW.INode Siemens.Engineering.HW.Node
Siemens.Engineering.HW.OPCUAExportProvider Siemens.Engineering.HW.Utilities.OpcUaExportProvider
Siemens.Engineering.HW.IPort Siemens.Engineering.HW.Features.NetworkPort
Siemens.Engineering.HW.IRole Siemens.Engineering.HW.Features.HardwareFeature
Siemens.Engineering.HW.Features.DeviceFeature
Siemens.Engineering.HW.Utilities.ModuleInformationProvid‐
er
Siemens.Engineering.HW.SoftwareBase Siemens.Engineering.HW.Software
Siemens.Engineering.HW.ISubnet Siemens.Engineering.HW.Subnet
Siemens.Engineering.HW.ISoftwareContainer Siemens.Engineering.HW.Features.SoftwareContainer
Siemens.Engineering.HW.ISubnetOwner Siemens.Engineering.HW.Features.SubnetOwner

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1253
Major Changes
7.4 Major changes in V14 SP1

Modifications for Enums

TIA Portal Openness API type Data new TIA Portal Openness API type Data
type type
Siemens.Engineering.HW.Enums.AddressContext Siemens.Engineering.HW.AddressContext
Siemens.Engineering.HW.Enums.AddressIoType Siemens.Engineering.HW.AddressIoType
Siemens.Engineering.HW.Enums.AttachmentType Siemens.Engineering.HW.MediumAttachmentType
Siemens.Engineering.HW.Enums.BaudRate Siemens.Engineering.HW.BaudRate
Siemens.Engineering.HW.Enums.BusLoad Siemens.Engineering.HW.CommunicationLoad
Siemens.Engineering.HW.Enums.BusProfile Siemens.Engineering.HW.BusProfile
Siemens.Engineering.HW.Enums.CableLength Siemens.Engineering.HW.CableLength
Siemens.Engineering.HW.Enums.CableName ulong Siemens.Engineering.HW.CableName long
Siemens.Engineering.HW.Enums.ChannelIoType byte Siemens.Engineering.HW.ChannelIoType int
Siemens.Engineering.HW.Enums.ChannelType byte Siemens.Engineering.HW.ChannelType int
Siemens.Engineering.HW.Enums.DeviceItemClassi‐ Siemens.Engineering.HW.DeviceItemClassifica‐
fications tions
Siemens.Engineering.HW.Enums.InterfaceOpera‐ Siemens.Engineering.HW.InterfaceOperatingMo‐
tingModes des
Siemens.Engineering.HW.Enums.IpProtocolSelec‐ Siemens.Engineering.HW.IpProtocolSelection
tion
Siemens.Engineering.HW.Enums.MediaRedundan‐ Siemens.Engineering.HW.MediaRedundancyRole
cyRole
Siemens.Engineering.HW.Enums.NetType Siemens.Engineering.HW.NetType
Siemens.Engineering.HW.Enums.ProfinetUpdateTi‐ removed
meMode
Siemens.Engineering.HW.Enums.RtClass byte Siemens.Engineering.HW.RtClass int
Siemens.Engineering.HW.Enums.SignalDelaySelec‐ byte Siemens.Engineering.HW.SignalDelaySelection int
tion
Siemens.Engineering.HW.Enums.SyncRole byte Siemens.Engineering.HW.SyncRole int
Siemens.Engineering.HW.Enums.TransmissionRa‐ uint Siemens.Engineering.HW.TransmissionRateAndDu‐ int
teAndDuplex plex

Modifications for attributes values of Siemens.Engineering.HW.IoConnector

Attribut Data type new name Data type


ProfinetUpdateTimeMode ProfinetUpdateTimeMode PnUpdateTimeAutoCalculation bool
ProfinetUpdateTime PnUpdateTime
AdaptUpdateTime PnUpdateTimeAdaption
WatchdogFactor PNWatchdogFactor
DeviceNumber string

Modifications for attributes values of Siemens.Engineering.HW.IoController

Attribut Data type new name Data type


DeviceNumber string

Openness: API for automation of engineering workflows


1254 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Modifications for attributes values of Siemens.Engineering.HW.Node

Attribut Data type new name Data type


HighestAddress removed, available only on subnet
TransmissionSpeed removed, available only on subnet
IsoProtocolUsed UseIsoProtocol
IpProtocolUsed UseIpProtocol
RouterAddressUsed UseRouter
PnDeviceNameAutoGener‐ PnDeviceNameAutoGeneration
ated
DeviceNumber removed, moved to IoConnector / IoController

Modifications for attributes values of Siemens.Engineering.HW.Subnet

Attribut Data type new name Data type


HighestAddress byte HighestAddress int
CableConfiguration PbCableConfiguration
RepeaterCount PbRepeaterCount
CopperCableLength PbCopperCableLength
OpticalComponentCount PbOpticalComponentCount
OpticalCableLength PbOpticalCableLength
OpticalRingEnabled PbOpticalRing
OlmP12 PbOlmP12
OlmG12 PbOlmP12
OlmG12Eec PbOlmG12Eec
OlmG121300 PbOlmG121300
AdditionalNetworkDevices PbAdditionalNetworkDevices
AdditionalDpMaster byte PbAdditionalDpMaster int
TotalDpMaster byte PbTotalDpMaster int
AdditionalPassiveDevice byte PbAdditionalPassiveDevice int
TotalPassiveDevice byte PbTotalPassiveDevice int
AdditionalActiveDevice byte PbAdditionalActiveDevice int
TotalActiveDevice byte PbTotalActiveDevice int
PbCommunicationLoad BusLoad PbAdditionalCommunicationLoad CommunicationLoad
OptimizeDde PbDirectDateExchange
MinimizeTslot PbMinimizeTslotForSlaveFailure
OptimizeCableConfig PbOptimizeCableConfiguration
CyclicDistribution PbCyclicDistribution
TslotInit PbTslotInit
Tslot PbTslot
MinTsdr PbMinTsdr
MaxTsdr PbMaxTsdr
Tid1 PbTid1
Tid2 PbTid2

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1255
Major Changes
7.4 Major changes in V14 SP1

Attribut Data type new name Data type


Trdy PbTrdy
Tset PbTset
Tqui PbTqui
Ttr PbTtr
TtrMs removed
TtrTypical PbTtrTypical
TtrTypicalMs removed
Watchdog PbWatchdog
WatchdogMs removed
Gap byte PbGapFactor int
RetryLimit byte PbRetryLimit int
IsochronMode IsochronousMode
AdditionalDevice PbAdditionalPassivDeviceForIsochro‐
nousMode
TotalDevice PbTotalPassivDeviceForIsochronous‐
Mode
DpCycleTimeAutoCalc DpCycleMinTimeAutoCalculation
TiToAutoCalc IsochronousTiToAutoCalculation
Ti IsochronousTi
To IsochronousTo

Modifications for attributes values of Siemens.Engineering.Project

Attribut Data type new name Data type


.HwExtensions .HwUtilities

Modifications for attributes values of Siemens.Engineering.HW.Baudrate

Attribut Data type new name Data type


BaudRate.BAUD_9600 BaudRate.BAUD9600
BaudRate.BAUD_19200 BaudRate.BAUD19200
BaudRate.BAUD_45450 BaudRate.BAUD45450
BaudRate.BAUD_93750 BaudRate.BAUD93750
BaudRate.BAUD_187500 BaudRate.BAUD187500
BaudRate.BAUD_500000 BaudRate.BAUD500000
BaudRate.BAUD_1500000 BaudRate.BAUD1500000
BaudRate.BAUD_3000000 BaudRate.BAUD3000000
BaudRate.BAUD_6000000 BaudRate.BAUD6000000
BaudRate.BAUD_12000000 BaudRate.BAUD12000000

Openness: API for automation of engineering workflows


1256 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Modifications for attributes values of Siemens.Engineering.HW.CableLength

Attribut Data type new name Data type


CableLength.Unknown CableLength.None
CableLength.Length_20m CableLength.Length20m
CableLength.Length_50m CableLength.Length50m
CableLength.Length_100m CableLength.Length100m
CableLength.Length_1000m CableLength.Length1000m
CableLength.Length_3000m CableLength.Length3000m

Modifications for attributes values of Siemens.Engineering.HW.ChannelIoType

Attribut Data type new name Data type


ChannelIoType.Unknown ChannelIoType.Complex

Modifications for attributes values of Siemens.Engineering.HW.IpProtocolSelection

Attribut Data type new name Data type


IpProtocolSelection.Addres‐ IpProtocolSelection.ViaIoController
sTailoring

Modifications for attributes values of Siemens.Engineering.HW.TransmissionRateAndDuplex

Attribut Data new name Data


type type
TransmissionRateAndDuplex.Unknown TransmissionRateAndDuplex.None
TransmissionRateAndDuplex.TP10Mbps_HalfDu‐ TransmissionRateAndDuplex.TP10MbpsHalfDu‐
plex plex
TransmissionRateAndDuplex.TP10Mbps_FullDuplex TransmissionRateAndDuplex.TP10MbpsFullDuplex
TransmissionRateAndDuplex.AsyncFib‐ TransmissionRateAndDuplex.AsyncFib‐
er10Mbps_HalfDuplex er10MbpsHalfDuplex
TransmissionRateAndDuplex.AsyncFib‐ TransmissionRateAndDuplex.AsyncFib‐
er10Mbps_FullDuplex er10MbpsFullDuplex
TransmissionRateAndDuplex.TP100Mbps_HalfDu‐ TransmissionRateAndDuplex.TP100MbpsHalfDu‐
plex plex
TransmissionRateAndDuplex.TP100Mbps_FullDu‐ TransmissionRateAndDuplex.TP100MbpsFullDu‐
plex plex
TransmissionRateAndDuplex.FO100Mbps_FullDu‐ TransmissionRateAndDuplex.FO100MbpsFullDu‐
plex plex
TransmissionRateAndDuplex.X1000Mbps_FullDu‐ TransmissionRateAndDuplex.X1000MbpsFullDu‐
plex plex
TransmissionRateAndDuplex.FO1000Mbps_FullDu‐ TransmissionRateAndDuplex.FO1000MbpsFullDu‐
plex_LD plexLD
TransmissionRateAndDuplex.FO1000Mbps_FullDu‐ TransmissionRateAndDuplex.FO1000MbpsFullDu‐
plex plex

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1257
Major Changes
7.4 Major changes in V14 SP1

Attribut Data new name Data


type type
TransmissionRateAndDuplex.TP1000Mbps_FullDu‐ TransmissionRateAndDuplex.TP1000MbpsFullDu‐
plex plex
TransmissionRateAndDuplex.FO10000Mbps_Full‐ TransmissionRateAndDuplex.FO10000MbpsFull‐
Duplex Duplex
TransmissionRateAndDuplex.FO100Mbps_FullDu‐ TransmissionRateAndDuplex.FO100MbpsFullDu‐
plex_LD plexLD
TransmissionRateAndDu‐ TransmissionRateAndDu‐
plex.POFPCF100Mbps_FullDuplex_LD plex.POFPCF100MbpsFullDuplexLD

7.4.4 Changes for export and import

7.4.4.1 Changes for export and import

Introduction
The export and import via TIA Portal Openness API was extended in V14 SP1 in order to handle
comments at array elements. This required a new schema. Block interface import and export will
handle from now on two schema versions:
• For import: The decision about used schema version is made based on namespace: <Sections
xmlns=http://www.siemens.com/automation/Openness/SW/Interface/v2>
• For export: The decision about used schema version is made based on the project version.
Projects V14 SP1 lead to version 2, projects V14 lead to version v1

7.4.4.2 Changes in API

Generate source
The following methods have been removed from ProgramBlocks:
• GenerateSourceFromBlocks
• GenerateSourceFromTypes
The following methodes have been added:
• GenerateSource to PlcExternalSourceSystemGroup

Openness: API for automation of engineering workflows


1258 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Example

// generate source for V14


var blocks = new List<PlcBlock>(){block1};
var types = new List<PlcBlock>(){udt1};
var fileInfoBlock = new FileInfo("D:\Export\Block.scl");
var fileInfoType = new FileInfo("D:\Export\Type.udt");

PlcBlocksSystemGroup blocksGroup = ...;


blocksGroup.GenerateSourceFromBlocks(blocks, fileInfo);
PlcTypesSystemGroup plcDataTypesGroup = ...;
plcDataTypesGroup.GenerateSourceFromTypes(types, fileInfo);

//generate source as of V14 SP1


var blocks = new List<PlcBlock>(){block1};
var types = new List<PlcBlock>(){udt1};
var fileInfoBlock = new FileInfo("D:\Export\Blocks.scl");
var fileInfoType = new FileInfo("D:\Export\Type.udt");

PlcExternalSourceSystemGroup externalSourceGroup = plc.ExternalSourceGroup;


externalSourceGroup.GenerateSource(blocks, fileInfoBlock);
externalSourceGroup.GenerateSource(types, fileInfoType);

7.4.4.3 Schema extension

Schema extension for comments and start values


Comments and start values are stored in new element called "Subelement" which refers to the
array element with "Path" attribute.
Subelement contains start value and comment for the referenced array element. Attribute
"Path" at StartValue is removed in the new schema.

Schema definition of "Subelement":

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1259
Major Changes
7.4 Major changes in V14 SP1

Extension of member type:

Examples:
Storage of comments and start values in simple arrays:

Storage of comments and start values in arrays of UDT:

Openness: API for automation of engineering workflows


1260 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Storage of comments and start values in arrays of struct:

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1261
Major Changes
7.4 Major changes in V14 SP1

7.4.4.4 Schema changes

Access node in SW.PlcBlocks.Access.xsd


Type attribute of the Access node has been moved to the children nodes of Access at
• AbsoluteOffset as required
• Address as optional

Type attribute of Constant has been replaced with new ConstantType subnode.

The value of the Scope attribute in Access has been renamed to TypedConstant if the
ConstantValue contains type qualified value(e.g.: int#10).
Constant does not have Type attribute if ConstantValue contains type qualified value (e.g.:
int#10).
Local variables do not have Address node if Scope is LocalVariable.
If an Access is nested within another Access at any level, only the outer Access must have an UId.

Address node in SW.PlcBlocks.Access.xsd


BitOffset attribute of Address node became optional.
Declarations for exporting absolute access have changed as shown in the following table:

Area as of V14 SP1 Type Block number Bit offset Example


DB Block_DB mandatory forbidden OPN %DB12
DB unordered existing mandatory %DB100.DBX10.3
DB unordered not existing mandatory %DB100.DBX10.3
L unordered forbidden mandatory %LW10.0
I unordered forbidden mandatory %I0.0
Q %Q0.0
M %M0.0
T unordered forbidden mandatory %T0
C %C1

Openness: API for automation of engineering workflows


1262 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Area as of V14 SP1 Type Block number Bit offset Example


Block_FC Block_FC mandatory forbidden Call %FB4, %DB5 Input_1 := %FC10
Block_FB Block_FB Call %FB4, %DB5 Input_2 := %FB11
PeripheryInput unordered forbidden mandatory
Periphery Output unordered forbidden mandatory

Area node in SW.PlcBlocks.Access.xsd


Area node has got a simplified enum list:
• LocalC and LocalN became Local
• DBc, DBv, DBr are eliminated.

CallInfo node in SW.PlcBlocks.Access.xsd


Name attribute of CallInfo node became optional
BlockType attribute of CallInfo node became required
+2.2.5 User Block Calls

Constant node in SW.PlcBlocks.Access.xsd


Constant node references CostantType node with minOccurs=0
Constant node doesn't reference IntegerAttribute node any more

ConstantValue node in SW.PlcBlocks.Access.xsd


ConstantValue node gets an Informative attribute

Instruction node in SW.PlcBlocks.Access.xsd


Instruction node references Acces node with minOccurs=0
Parameter attributes Section, Type and TemplateReference have been deleted at Instruction.

Parameter node in SW.PlcBlocks.Access.xsd


SectionName attribute of the Parameter node became optional.

Values for Scope in SW.PlcBlocks.Access.xsd


Enum list of Scope has been extended with:
• TypedConstant
• AddressConstant
• LiteralConstant
• AlarmConstant

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1263
Major Changes
7.4 Major changes in V14 SP1

• Address
• Statusword
• Expression
• Call
• CallWithType

Statusword node in SW.PlcBlocks.Access.xsd


Enum list of Statusword has been extended with:
• STW

ConstantType node in SW.PlcBlocks.Access.xsd


New node ConstantType is introduced with optionally used attribute Informative.

CallRef node in SW.PlcBlocks.LADFBD.xsd


CallRef node is renamed to Call and omits the BooleanAttribute subnode.

InstructionRef node in SW.PlcBlocks.LADFBD.xsd


InstructionRef node is replaced by Part node

Part node in SW.PlcBlocks.LADFBD.xsd


New node ConstantType is introduced and replaces the InstructionRef node
• Attributes: Name and Version
• Subnodes: Instruction subnode as new choice to existing Equation
• doesn't have neither BooleanAttribute subnode nor Gate attribute

Wire node in SW.PlcBlocks.LADFBD.xsd


Name attribe of Wire node removed.

TemplateReference node in SW.PlcBlocks.LADFBD.xsd


TemplateReference node is deleted.

StatementList node in SW.PlcBlocks.STL.xsd


Enum list of of StatementList (STL_TE):
• L_STW has been removed
• T_STW has been removed

Openness: API for automation of engineering workflows


1264 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

7.4.4.5 Behaviour changes

Absolute Access
In V14 the import of absolute access has been aborted for most combinations. As of V14 SP1 the
import of absolute access works for the following areas:
• Input
• Outpt
• Memory
• Timer, if supported on the PLC
• Counter, if supported on the PLC
• DB
• DI
If a symbol access and an absolute access is used at the same time and is not rejected by schema
or node kind validation the import will only succeed when box access informations are
successfully resolved. When the symbol access leads to different information in comparison to
the absolute access the import is rejected.

Indirect DB Access
As of V14 SP1 indirect DB Access can only be imported, when the 'offset', 'type' and 'symbol' are
provided.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1265
Major Changes
7.4 Major changes in V14 SP1

Symbolic and absolute information for local access


When importing "symbolic access" all possible provided "absolute access informations" are
validated, if they are not flaged as "informative". As of V14 SP1 the import will be aborted when
the absolute information does not match.

Block interface constraints


In V14SP1 several constrains are checked. These constrains are well known to users of the block
interface editor. Whenever the block interface editor renames a parameter by adding or
increasing '_1' the OPNS import will be aborted.
The following constrains are validated for instance:
• Duplicated parameter names
• Wrong section names. Including 'Return-Section' for FB blocks
• Restricted words

Sorting sections on import


When the called block does not exist at the time of import the interface definition at the call side
will be used to display the called user block. In V14 SP1 the sections will be sorted in the order
they would be displayed in the block interface of the called block, if it would have been existing
with the same parameters.
The section order of the parameters imported is:
• Input
• Output
The following STL xml example

Openness: API for automation of engineering workflows


1266 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

will result in

CALL "Block_2"
Input_1 :="Tag_1"
Input_2 :="Tag_2"
Output_1 :="Tag_3"
Output_2 :="Tag_4"

Unique user block callee names


In TIA Portal names have to be unique. This means for instance a tag can not have the same name
like a block. For TIA Portal Openness API XML import this means when the XML contains a user
block call, where the called block does not exist at the time of import, the name of the called
block has to be unique to all existing names in the project. When the called block name is not
unique the import will be aborted.
In the following example the import will be aborted, because the Name of the called Block
"Tag_1" is already used for a tag table.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1267
Major Changes
7.4 Major changes in V14 SP1

In the following example the import will be aborted, because two parameters have the same
name ""Input1".

Library block calls


The imported XML may contain calls of user blocks. These user blocks are identified by name.
User blocks can also call library elements. These library elements can be generated as 'library
block calls'. Because library blocks are using the same namespace as user blocks, the import of
a user block call done by name can call the implementation of a library block.

Openness: API for automation of engineering workflows


1268 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Before V14 SP1 the import tried to map the parameters between the user block call and the
instruction block call. Sometimes the import aborted, sometimes the import deleted all not
matching parameters.
As of V14 SP1 the user block call will still find the library block, but the call will not become valid.

Block type mismatch


When the XML contains a user block call of 'Block_1' with more parameters as the corresponding
FC in the project as of V14 SP1 the import defines a new called block interface matching the user
block call from the XML. The next program block compile will attempt the call update.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1269
Major Changes
7.4 Major changes in V14 SP1

New scopes for contants


With V14SP1 several new scopes for constants have been invented. The import only succeeds
when the values in the xml match the constant scope. The import may abort when not all the
provided information for a constant match the existing constant.

Openness: API for automation of engineering workflows


1270 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Instruction version annotation


As of V14 SP1 only instruction versions usable on the PLC to import to can be imported.When no
instruction version is annotated in the xml the version selected in the PLC will be used. In LAD
and FBD some elements represented as instruction do not use versioning. These elements can
only be imported without version.

Disabled ENO
The "disabled ENO" feature is used on 1200 and 1500 PLC to deactivate runtime consuming ENO
connection state calculation.
As of V14 SP1 the DisabledENO flag can only be imported on PLC's supporting the feature.

Type validation for absolute L-Stack access


As of V14 SP1 the import is aborted when the type can not be used or mapped.

Validation of index idents


Index access's are usable where 'symbolic access to memory' is defined. For instance, local
access, global access, indirect access.
When a literal constant is used as index, the singed and unsigned integer types are changed to
Dint. As of V14 SP1 the import is aborted when a type outside the mentioned range is provided.
All index access's are checked, whether the kind of access can be used as 'index access' at all. As
of V14 SP1 the import is aborted when the defined index access can not be used.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1271
Major Changes
7.4 Major changes in V14 SP1

Element order sorting


As of V14 SP1 the elements in LAD and FBD will be sorted 'code generation order' where
automatically possible during export. In some very rare cases the exported XML is not
importable again. In these cases either the XML has to be adapted or the corresponding
networks have to be deleted and reprogrammed. But the order of wires and references is still not
reliable.

Alarm Constants
With V14 SP1 the compile checks for valid alarm constants have been extended. It might occur
that projects are not compilable in V14 SP1 due to an xml imported in V14 with broken alarm
constants. In this case open the relevant network in LAD/FDB editor and delete the alarm actual
operand. The editor will automatically recreate a valid alarm constant.

Constraints for instances of user blocks and instructions


In V14 it was possible to import user FC block calls with an instance and sometimes even compile
these calls.
As of V14 SP1 the import of instances is only possible where instances are supported. Existing
projects with instances at FC user block calls and instructions may not compile any more. In this
case the call has to be deleted and reprogrammed. Any attempt to do a call update or 'other
means of automated repair' will fail.

Openness: API for automation of engineering workflows


1272 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

EnEno visible
In V14 the EN and ENO connections of 'InstructionRef' have been usable or not depending on the
ENENO flag.
As of V14SP1 the OPNS during the import based on the element and the wiring either the EN and
ENO connections are used. Because of this automatic detection a different EN and ENO
connection usage can be noticed. Most probably only the IEC timer and IEC counter boxes may
show some issues.

UId assignment
The assignment of UIds to parts, access and wires changes with V14 SP1. The UIds for
statements, CallInfo and operands have to be unique within a compile unit. From TIA Portal point
of view the UIds in the XML are keys, without any additional meaning besides identifying an
element.

Checking of character strings


More strict checks concerning quotation marks, surrogate characters and control characters are
performed for the Name attribute during the import of
• IntegerAttribute
• StringAttribute
• DateAttribute
• AutomaticTyped
• Component
• Invisible
• Label
• NameCon
• Negated
• TemplateValue
• CallInfo
• Instruction
• Parameter
• Part
• Step
More strict checks concerning surrogate characters and control characters are performed during
the import of
• Titles of blocks and networks
• LineComment text
• Constant strings (String, WString, Char, Wchar typed)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1273
Major Changes
7.4 Major changes in V14 SP1

More strict checks concerning surrogate characters and control characters ( tab and new line
allowed) are performed during the import of
• Comments of blocks and networks
• String attributes
• Nodes defining multilanguage texts, e.g. Alarmtext, Comments
• Token texts

Case insensitivity of template operations and parameters


As of V14 SP1 case insenitivity of template operations for instructions and call or instruction
parameters will be imported and automatically corrected.
The following code will be imported and the incorrect value "Eq" will be corrected to "EQ" and the
incorrect parameter "iN1" will be corrected to "IN1":

Multiinstances used in calls


As of V14 SP1 the import is aborted if the multiinstance used in a call does not exists.
The following code shows an xml example where the multiinstance is defined correctly in the
interface section:

Openness: API for automation of engineering workflows


1274 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

Template cardinalities in STL


In STL the template cardinalities for every instruction has a fixed default value which is the only
valid value. As of V14 SP1 the import is aborted if another value is used for the cardinality.

Importing indirect access


As of V14 SP1 indirect access can only be imported where they can be compiled.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1275
Major Changes
7.4 Major changes in V14 SP1

Importing statuswords
As of V14 SP1 the statusword can only be imported at statements where they are supported.
• L - Supported statusword: STW
• T - Supported statusword: STW
• A - Supported statusword: BR, OV, OS, EQ, NE, GT, Lt, GE, LE, U0, NU
• AN - Supported statusword: BR, OV, OS, EQ, NE, GT, Lt, GE, LE, U0, NU
• O - Supported statusword: BR, OV, OS, EQ, NE, GT, Lt, GE, LE, U0, NU
• ON - Supported statusword: BR, OV, OS, EQ, NE, GT, Lt, GE, LE, U0, NU
• X - Supported statusword: BR, OV, OS, EQ, NE, GT, Lt, GE, LE, U0, NU
• XN - Supported statusword: BR, OV, OS, EQ, NE, GT, Lt, GE, LE, U0, NU

Note
Most statuswords are only useful on 300 and 400 plcs.

Empty statements
The import is aborted if a statement does not have a node <StlStatement/>. In case of an empty
statement, add the <StlToken Text="Empty_Line" /> node.
The import is aborted if an empty statement has comments. For a statement with only
comments use the <StlToken Text="COMMENT" />.

7.4.4.6 Block attribute changes

Changes in general attributes


AutoNumber has got a new default value (false) at classic OBs
HeaderVersion has got a new type System.Version (instead of String)
IsKnowHowProtected is applied for user defined data types as well

Openness: API for automation of engineering workflows


1276 System Manual, 05/2021, Online documentation
Major Changes
7.4 Major changes in V14 SP1

ILibraryTypeInstance.ConnectedVersion, ILibraryTypeInstance.Dependencies,
ILibraryTypeInstance.Dependents are eliminated from the table of general attributes because
they are neither exported in XML nor accessible via API.
MemoryLayout gets new default: Standard in classic PLCs and Optimized on plus PLCs
Number is applied for user defined data types and it is represented in XML and accessible via API
as well

Changes in specific attributes


IsOnlyStoredInLoadMemory and IsWriteProtectedInAS became read-only for IDBofUDT if it
belongs to a system library element.
OfSystemLibElement and OfSystemLibVersion are relocated from general to specific attributes
OfSystemLibVersion has got a new type System.Version (instead of String)
ParameterPassing remains read-write at FCs and FBs only if
• ProgrammingLanguage is STL and
• MemoryLayout is standard and
• interface is empty
GraphVersion has got a new type System.Version (instead of String)
a new attribute called ExtensionBlockName is introduced for FBs written in Graph as of Graph
version V4
a new attribute called InvalidValuesAcquisition is introduced for FBs written in Graph as of
Graph version V4
a new attribute called IsWriteProtected is introduced for code blocks
DownloadWithoutReinit became read-only and also applied for IDBofFBs
Supervisions became read-only on IDBofFBs .

Changes in enums
The enum values for ProgrammingLanguage are changed as follows:
• a new enum value F_CALL is introduced
• a new enum value Motion_DB is introduced for Motion technological object
• GRAPH_SEQUENCE, GRAPH_ACTIONS, GRAPH_ADDINFOS are deleted from the enum. They
are replaced with GRAPH.
The enum values for BlockType are changed as follows:
• the values OB, FC, DB, SFC are deleted because this enum is only used at InstanceOfType
attribute

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1277
Major Changes
7.5 Major changes in V14

7.5 Major changes in V14

7.5.1 Major changes of the object model

Object model of TIA Portal Openness V13 SP1 and older


In order to allow you a comparison between the old and the new object model of TIA Portal
Openness, the diagram below describes the object model of TIA Portal V13 SP1.

Note
The object model described on the diagram is obsolete, for information about the object model
of TIA Portal Openness V14 SP1 refer to TIA Portal Openness object model (Page 51)

Openness: API for automation of engineering workflows


1278 System Manual, 05/2021, Online documentation
Major Changes
7.5 Major changes in V14

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1279
Major Changes
7.5 Major changes in V14

7.5.2 Before updating an application to TIA Portal Openness V14

Application
Before updating an application to TIA Portal Openness V14 change the following settings:
1. Adapt thr references to the V14 API by adding the following TIA Portal Openness APIs:
– Siemens.Engineering
– Siemens.Engfineering.Hmi
2. Change the .Net framework of your Visual Studio to version 4.6.1
3. Update the assembly resolve method by adapting the new installation path of the TIA Portal.
– If you have evaluated from the registry, adapt the new key, according to the following
example:
"HKEY_LOCAL_MACHINE\SOFTWARE\Siemens\Automation\_InstalledSW
\TIAP14\TIA_Opns\..."
– If you are using the application configuration file, adapt the paths to the new installation
path.

7.5.3 Major string changes

Introduction
The following changes were made in TIA Portal Openness V14, which may impact your existing
applications:

Change Required program code adjustment


Compile methods have been changed. Change the compile methods according to the following ex‐
ample:
• TIA Portal Openness V13 SP1(obsolete):
controllerTarget.Compile(CompilerOptions.
Software, BuildOptions.Rebuild);
• TIA Portal Openness V14:
plcSoftware.GetService<ICompilable>().Com
pile();
New namespaces have been added. 1. Add the following namespace statements:
Siemens.Engineering.SW.Blocks;
Siemens.Engineering.SW.ExternalSources;
Siemens.Engineering.SW.Tags;
Siemens.Engineering.SW.Types;
2. Remove the using ControllerTarget =
Siemens.Engineering.HW.ControllerTarget
namespace statement.
3. Compile the application.

Openness: API for automation of engineering workflows


1280 System Manual, 05/2021, Online documentation
Major Changes
7.5 Major changes in V14

Change Required program code adjustment


ControllerTarget has been replaced by PlcSoftware 1. Review the code examples in the documentation which
and functionality has been changed in some cases. belong to your application functionality.
2. Update the program code of your TIA Portal Openness ap‐
plication according to the following example:
– TIA Portal Openness V13 SP1(obsolete):
ControllerTarget controllerTarget =
deviceItem as ControllerTarget
– TIA Portal Openness V14:
PlcSoftware plcSoftware =
deviceItem.GetService<SoftwareContainer
>().Software as PlcSoftware
3. Compile the application.
Objects have been replaced. 1. Search and replace the following objects:
DeviceUserFolderAggregation =
DeviceUserGroupComposition
DeviceFolders = DeviceGroups
DeviceUserFolder = DeviceUserGroup
ProgramblockSystemFolder =
PlcBlockSystemGroup
ProgramblockUserFolder = PlcBlockUserGroup
IBlock = PlcBlock
ControllerDatatypeSystemFolder =
PlcTypeSystemGroup
ControllerDatatypeUserFolder =
PlcTypeUserGroup
ControllerDatatype = PlcType
ControllerTagSystemFolder =
PlcTagTableSystemGroup
ControllerTagUserFolder =
PlcTagTableUserGroup
ControllerTagTable = PlcTagTable
ControllerTag = PlcTag
ControllerConstant = PlcConstant
ExternalSourceSystemFolder =
PlcExternalSourceSystemGroup
ExternalSource = PlcExternalSource
IOnline = OnlineProvider
ILibraryType = LibraryType
2. Compile the application.

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1281
Major Changes
7.5 Major changes in V14

Change Required program code adjustment


Aggregations have been replaced by compositions. 1. Replace every Aggregation of your code
by Composition according to the following examples:
ProjectAggregation = ProjectComposition
IDeviceAggregation = IDeviceComposition
TagTableAggregation = TagTableComposition
CycleAggregation = CycleComposition
GraphicListAggregation =
GraphicListComposition
TextListAggregation = TextListComposition
ConnectionAggregation =
ConnectionComposition
MultiLingualGraphicAggregation =
MultiLingualGraphicComposition
UpdateCheckResultMessageAggregation =
UpdateCheckResultMessageComposition
2. Compile the application.
Folders have been replaced by groups in every relationship 1. Replace every Folder in your program code by Group
except HMI devices. except code parts which concern to HMI devices.
2. Compile the application.
The GetAttributeNames method has been replaced by 1. Use IList<EngineeringAttributeInfo>
the GetAttributeInfos method. IEngineeringObject.GetAttributeInfos(Attr
ibuteAccessMode attributeAccessMode); to de‐
terminate attributes.
2. Compile the application.
For more detailed information, refer to Determining the
object structure and attributes (Page 129).
The Close method for closing an object has changed. 1. Replace
project.Close(CloseMode.PromptIfModified)
; by project.Close();.
2. Compile the application.
For more detailed information, refer to Closing a project
(Page 142).

Openness: API for automation of engineering workflows


1282 System Manual, 05/2021, Online documentation
Major Changes
7.5 Major changes in V14

Change Required program code adjustment


Simultaneous access has been replaced by exclusive access 1. Replace simultaneous access by exclusive access and
and transactions. transactions according to the following examples:
– TIA Portal Openness V13 SP1(obsolete):
tiaProject.StartTransaction("Reseting
project to default");
...
tiaProject.CommitTransaction();
– TIA Portal Openness V14:
//Use exclusive access to avoid user
changes
ExclusiveAccess exclusiveAccess =
tiaPortal.ExclusiveAccess();
...
exclusiveAccess.Dispose();
//Use transaction to be able to
rollbank changes:
Transaction transaction =
exclusiveAccess.Transaction(tiaProject,
"Compiling device");
transaction.CommitOnDispose();
2. Compile the application.
See Exclusive access (Page 96) and Transaction handling
(Page 105) for further information.
Online access to the CPU has been changed 1. Change the online access to the CPU according to the fol‐
lowing examples:
– TIA Portal Openness V13 SP1(obsolete):
((IOnline)controllerTarget).GoOffline()
;
– TIA Portal Openness V14:
((DeviceItem)
plcSoftware.Parent.Parent).GetService<O
nlin
eProvider>().GoOffline();
2. Compile the application.
The hardware configuration has been changed 1. Change the hardware configuration:
Device.Elements = Device.Items
2. Remove the following hardware attributes:
– Device.InternalDeviceItem
– Device.SubType
3. Compile the application.

See also
Handling exceptions (Page 862)
Connecting to the TIA Portal (Page 81)

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1283
Major Changes
7.5 Major changes in V14

7.5.4 Import of files generated with TIA Portal Openness V13 SP1 and previous

Application
When you try to import files which were generated with TIA Portal Openness V13 SP1 or previous
an exeption will be thrown because of incompatibility. This is caused by changes on HMI tags
and HMI screen items. The following tables are showing the main attribute changes, for more
detailed information refer to the chapter "Creating screens Working with objects and object
groups > Working with objects > Configuring ranges" of the TIA Portal online help:

Changes of HMI tags


The following table shows the main changes of HMI tag attributes:

Removed attributes Added attributes


RangeMaximumType LimitUpper2Type.
RangeMaximum LimitUpper2.
RangeMinimumType LimitLower2Type.
RangeMinimum LimitLower2.
LimitUpper1Type
LimitUpper1
LimitLower1Type
LimitLower1

Changes of HMI screen items


The following table shows the main changes of slider attributes:

Removed attributes Added attributes


RangeLower1Color
RangeLower1Enabled
RangeLower2Color
RangeLower2Enabled
RangeNormalColor
RangeNormalEnabled
RangeUpper1Color
RangeUpper1Enabled
RangeUpper2Color
RangeUpper2Enabled
ScalePosition
ShowLimitLines
ShowLimitMarkers
ShowLimitRanges

Openness: API for automation of engineering workflows


1284 System Manual, 05/2021, Online documentation
Major Changes
7.5 Major changes in V14

The following table shows the main changes of gauge attributes:

Removed attributes Added attributes


DangerRangeColor RangeLower1Color
DangerRangeStart RangeLower1Enabled
DangerRangeVisible RangeLower2Color
WarningRangeColor RangeLower2Enabled
WarningRangeStart RangeNormalColor
WarningRangeVisible RangeNormalEnabled
RangeUpper1Color
RangeUpper1Enabled
RangeUpper1Start
RangeUpper2Color
RangeUpper2Enabled
RangeUpper2Start

The following table shows the main changes of bar attributes:

Removed attributes Added attributes


AlarmLowerLimitColor RangeLower1Color
AlarmUpperLimitColor RangeLower1Enabled
RangeLower2Color
RangeLower2Enabled
RangeNormalColor
RangeNormalEnabled
RangeUpper1Color
RangeUpper1Enabled
RangeUpper2Color
RangeUpper2Enabled

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1285
Major Changes
7.5 Major changes in V14

Openness: API for automation of engineering workflows


1286 System Manual, 05/2021, Online documentation
Index
Encoders for analog drives by hardware
address, 616
" Encoders for PROFIdrives by hardware
address, 614
"Devices & networks" editor
Measuring input, 634
Open, 204
Output cam, 633
"Tags" editor
PROFIdrives by data block, 617
Starting, 642
PROFIdrives by hardware address, 613
PTO-Output, 612
Synchronous axis with leading values, 635
A telegram 750, 629
Accessing Connection to the TIA Portal
Master copy in project library, 173 Close, 90
Acknowledging system events program- Setting up, 81
controlled, 89 Copy
Content of a master copy in project folder, 176
Master copy, 179
B Create
User-defined folders for HMI tags, 313
Basic structure of an AML export file, 1074
User-defined screen folders, 308
Basic structure of an export file, 895, 1077
User-defined script folders, 316
Block
Creating
Creating group, 575
Cam track, 619
Deleting, 575
Group for block, 575
Deleting group, 576
Measuring input, 619
Exporting, 998
Output cam, 619
Generate source, 586
Technology object, 603
Importing, 997
User-defined folder for PLC tag tables, 645
Querying information, 571
Block editor
Starting, 592
D
Data types
C Technology object, 601
Deleting
Compiling
All screens, 310
Hardware, 137
Block, 575
Software, 137
Connection, 313
Technology object, 604
Cycle, 311
Technology object group, 605
Deleting a PLC tag table from a folder, 649
Configuration
Graphic list, 312
Your Openness application and the TIA Portal run
Group for block, 576
on different computers, 44
Individual tag in a PLC tag table, 651
Connecting
Individual tags of a tag table, 314
Analog drives by data block, 617
PLC constants, 652
Analog drives by hardware address, 615
Program block, 575
Cam track, 633
Project graphics, 137
Drives, 626
Screen, 308
Encoders, 631
Screen template, 309
Encoders by data block, 618
Tag table, 315

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1287
Index

Technology object, 604 Parameter of technology object, 608


Text list, 311 Technology object, 606
User data type, 591 Folders
User-defined folder for PLC tag tables, 646 Deleting, 196
VB script from a folder, 316 Functions, 71
Closing a project, 142
Creating a user-defined folder for PLC tag
E tables, 645
Creating user-defined folders for HMI tags, 313
Editing situation
Creating user-defined screen folders, 308
Your Openness application and the TIA Portal run
Creating user-defined script subfolders, 316
on the same computer, 45
Deleting a connection, 313
Enumerating
Deleting a cycle, 311
All tags of a tag table, 314
Deleting a graphic list, 312
Blocks, 569
Deleting a PLC tag table, 649
Device items, 289
Deleting a screen, 308
Devices, 273, 276
Deleting a screen template, 309
Multilingual texts, 127, 132
Deleting a tag from a PLC tag table, 651
Parameter of technology object, 607
Deleting a tag from a tag table, 314
PLC tag tables, 646
Deleting a tag table, 315
PLC tags, 650
Deleting a text list, 311
System subfolders, 567
Deleting a user-defined folder for PLC tag
Technology object, 606
tables, 646
User-defined block folders, 568
Deleting a VB script from a folder, 316
User-defined folder for PLC tags, 644
Deleting all screens, 310
Enumerating device items, 289
Deleting project graphics, 137
Enumerating devices, 273, 276
Determining the system folder, 566
Enumerating multilingual texts, 127, 132
Enumerating blocks, 569
Establishing a connection to the TIA Portal, 81
Enumerating device items, 289
Example program, 71
Enumerating devices, 273, 276
Exceptions
Enumerating multilingual texts, 127, 132
When accessing the TIA Portal via public APIs, 862
Enumerating PLC tag tables in folders, 646
Export file
Enumerating PLC tags, 650
Basic structure, 895, 1074, 1077
Enumerating system subfolders, 567
Contents, 884
Enumerating tags of an HMI tag table, 314
Structure of the XML file, 895, 1077
Enumerating user-defined block folders, 568
Export/import
Enumerating user-defined folders for PLC
Application, 49
tags, 644
Exportable screen objects, 916
Exporting a tag or constant from a PLC tag
Exporting
table, 1069
Block, 998
General, 81, 89, 90
Individual tag or constant from a PLC tag
General TIA portal settings, 119
table, 1069
HMI, 308, 309, 310, 311, 312, 313, 314, 315,
Technology objects, 1049
316
User data type, 998
Importing a tag into a PLC tag table, 1070
Importing PLC tag tables, 1068
Limitation to projects of TIA Portal V13, 113
F Open project, 113
Finding PLC, 566, 567, 568, 569, 571, 645, 646, 649, 651,
Cam track, 619 652, 1068, 1069, 1070
Measuring input, 619 PLC constants, 652
Output cam, 619

Openness: API for automation of engineering workflows


1288 System Manual, 05/2021, Online documentation
Index

Projects, 113, 119, 127, 132, 137, 141, 142, 205, Exportable screen objects, 916
273, 276, 289, 643, 644, 646, 647, 650 Exporting a screen from a screen folder, 921
Public API application example, 76 Exporting a screen with a faceplate instance, 936
Querying information from a PLC tag table, 647 Exporting a selected tag, 904
Querying PLC and HMI targets, 205 Exporting a tag from a tag table, 904
Querying system folders for PLC tags, 643 Exporting all graphics of a project, 888
Querying the "Program blocks" folder, 566 Exporting all screen templates, 927
Querying the block author, 571 Exporting blocks with know-how protection, 956
Querying the block family, 571 Exporting blocks without know-how
Querying the block name, 571 protection, 998
Querying the block number, 571 Exporting configuration data, 884
Querying the block title, 571 Exporting connections, 914
Querying the block type, 571 Exporting cycles, 898
Querying the block version, 571 Exporting graphic lists, 913
Querying the consistency attribute of a block, 571 Exporting HMI tag tables, 900
Querying the time stamp of a block, 571 Exporting multilingual comments, 1184, 1193,
Reading the time of the last changes to a PLC tag 1201, 1203
table, 649 Exporting only modified values, 884
Saving a project, 141 Exporting permanent areas, 925
Exporting PLC tag table, 1067
Exporting pop-up screens, 931
G Exporting screen templates, 928
Exporting screens of an HMI device, 920
General TIA portal settings, 119
Exporting slide-in screen, 934
Generate
Exporting system blocks, 994
source from block, 586
Exporting tags, 1219
source from user data type, 586
Exporting text lists, 910
Global library
Exporting VB scripts, 907, 908
Accessing, 147, 151
Field of application, 881
Accessing language settings, 149
Graphics, 887
HMI, 898, 899, 900, 903, 904, 905, 906, 907, 908,
909, 910, 911, 913, 915, 916, 920, 921, 923, 925,
H 926, 927, 928, 930, 931, 932, 934, 935, 936, 938,
Hardware 1067
Compiling, 137 Importable objects, 879
Hierarchy of hardware objects of the object Importing a graphic list, 913
model, 65 Importing a screen including a faceplate
HMI tags of the "UDT" data type, 906 instance, 938
Importing an HMI tag into a tag table, 905
Importing configuration data, 885
I Importing connections, 915
Importing cycles, 899
Import/Export
Importing graphics to a project, 889
Advanced XML formats for export/import of text
Importing multilingual comments, 1184, 1193,
lists, 911
1201, 1203
Also export default values, 884
Importing permanent areas, 926
Basics, 879
Importing pop-up screen, 932
Data structure, 895, 1077
Importing screen templates, 930
Editing an XML file, 883
Importing screens to an HMI device, 923
Export format, 881
Importing slide-in screen, 935
Export scope, 884
Importing tag table to a tag folder, 903
Export settings, 884
Importing tags, 1219
Exportable objects, 879

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1289
Index

Importing text list, 910 Objects


Importing VB scripts, 909 Exportable objects, 879
Objects of AML, 1074 Importable objects, 879
PLC, 956, 994, 998 Open
Procedure for importing, 886 "Devices & networks" editor, 204
Project data, 888, 889 Opening a project, 113
Restricting exports to modified values, 884
Restrictions, 881
Round trip devices and modules, 1129 P
Setting the import behavior by means of program
Parameter of technology object
codes, 885
Enumerating, 607
Special considerations for integrated HMI
Finding, 608
tags, 906
Reading, 609
Stable AML GUIDs, 1129
Writing, 610
Technology objects, 1049, 1051
Parameters
Importing
Counting, 641
An individual tag into a PLC tag table, 1070
Easy Motion Control, 641
Block, 997
PID control, 640
PLC tag tables, 1068
S7-1500 Motion Control, 621
Technology objects, 1051
PLC
User data type, 1032
Comparing, 512
Installation
Comparison with actual status, 512
Access authentication check, 37
Determining status, 523
Adding users to the user group, 37
Disconnecting an online connection, 546
Standard steps for accessing the TIA Portal, 43
Establishing an online connection, 546
TIA Openness V13 add-on package, 36
Program block
Installing the add-on package, 36
Deleting, 575
Instances
Programming overview, 71
Determining type versions, 179
Project
Integrated HMI tags, 906
Close, 142
Open, 113
Querying HMI targets, 205
L Querying PLC targets, 205
Library Querying the device type, 205
Accessing folders, 158 Save, 141
Determining type versions of instances, 179 Project library
Functions, 146 Accessing, 147, 151
Accessing master copies, 173
Public API application example, 76
M
Master copies
Deleting, 196
Q
Master copy Querying
Copy content to project folder, 176 Block author, 571
Copying, 179 Block family, 571
Block name, 571
Block number, 571
O Block title, 571
Block type, 571
Object model, 51
Block version, 571
Consistency attribute of a block, 571

Openness: API for automation of engineering workflows


1290 System Manual, 05/2021, Online documentation
Index

Finding the, 566 Technology object group


Information from a PLC tag table, 647 Compiling, 605
Information of block, 571 Technology objects
Information of user data type, 571 Exporting, 1049
Program blocks folder, 566 Importing, 1051
System folders for PLC tags, 643 Terminating the connection to the TIA Portal, 90
Technology object, 602 TIA Portal Openness, 47
Time stamp of a block, 571 Access, 48
Access rights, 37
Adding users to the user group, 37
R Basic concepts of aggregations, 101
Basic concepts of associations, 101
Read
Basic concepts of object equality verification, 102
Time of the last changes to a tag table, 649
Basic concepts when handling exceptions, 862
Reading
Configuration, 43
Parameter of technology object, 609
Export/import, 49
Functional scope, 47
Functions, 71
S Introduction, 47
Saving a project, 141 Necessary user knowledge, 35
Siemens.Engineering, 73 Programming overview, 71
Siemens.Engineering.Hmi, 73 Public API, 71
Siemens.Engineering.Hmi.Communication, 73 Requirements, 35
Siemens.Engineering.Hmi.Cycle, 73 Standard steps for accessing the TIA Portal, 43
Siemens.Engineering.Hmi.Globalization, 73 Typical tasks, 48
Siemens.Engineering.Hmi.RuntimeScripting, 73 Types
Siemens.Engineering.Hmi.Screen, 73 Deleting, 196
Siemens.Engineering.Hmi.Tag, 73
Siemens.Engineering.Hmi.TextGraphicList, 73
Siemens.Engineering.HW, 73 U
Siemens.Engineering.SW, 73
User data type
Software
Deleting, 591
Compiling, 137
Exporting, 998
Special considerations for HMI tags of the "UDT" data
Generate source, 586
type, 906
Importing, 1032
Starting
Querying information, 571
"Tags" editor, 642
Block editor, 592
Status (PLC)
Determining, 523
W
Structure of the export data, 895, 1074, 1077 Writing
Parameter of technology object, 610

T
Technology object, 599, 1046
X
Compiling, 604 XML file
Creating, 603 Edit, 883
Data types, 601 Export, 884
Deleting, 604
Enumerating, 606
Finding, 606
Querying, 602

Openness: API for automation of engineering workflows


System Manual, 05/2021, Online documentation 1291
Index

Openness: API for automation of engineering workflows


1292 System Manual, 05/2021, Online documentation

You might also like