manual tf6100 tc3 opc-ua

179
Manual TF6100 TC3 OPC-UA TwinCAT 2.2 2016-05-19 TF6100 Version: Date: Order No.:

Upload: danghanh

Post on 01-Jan-2017

364 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Manual TF6100 TC3 OPC-UA

Manual

TF6100 TC3 OPC-UA

TwinCAT

2.22016-05-19TF6100

Version:Date:Order No.:

Page 2: Manual TF6100 TC3 OPC-UA
Page 3: Manual TF6100 TC3 OPC-UA

Table of contents

Table of contents1 Foreword .................................................................................................................................................... 5

1.1 Notes on the documentation.............................................................................................................  51.2 Safety instructions ............................................................................................................................  6

2 Product description................................................................................................................................... 72.1 Scenarios..........................................................................................................................................  72.2 Important information for OPC-UA Clients......................................................................................  102.3 Version information.........................................................................................................................  102.4 Application examples......................................................................................................................  13

2.4.1 Post-processing in the Cloud .............................................................................................. 13

3 Installation................................................................................................................................................ 193.1 System requirements......................................................................................................................  193.2 Installation.......................................................................................................................................  203.3 Installation Windows CE .................................................................................................................  233.4 Installation Tc2................................................................................................................................  253.5 Installation Windows CE Tc2 ..........................................................................................................  273.6 Licensing.........................................................................................................................................  32

4 Configuration ........................................................................................................................................... 374.1 Server .............................................................................................................................................  37

4.1.1 Overview ............................................................................................................................. 374.1.2 Quick Start .......................................................................................................................... 384.1.3 PLC ..................................................................................................................................... 404.1.4 C++ ..................................................................................................................................... 714.1.5 I/O ....................................................................................................................................... 854.1.6 Matlab/Simulink................................................................................................................... 934.1.7 File Transfer...................................................................................................................... 1014.1.8 Security ............................................................................................................................. 1034.1.9 Miscellaneous ................................................................................................................... 105

4.2 Client.............................................................................................................................................  1144.2.1 Overview ........................................................................................................................... 1144.2.2 Data Type Mapping........................................................................................................... 1154.2.3 Best practice ..................................................................................................................... 1164.2.4 Security ............................................................................................................................. 130

4.3 Gateway........................................................................................................................................  1324.3.1 Overview ........................................................................................................................... 1324.3.2 Quick Start ........................................................................................................................ 1324.3.3 Licensing........................................................................................................................... 1354.3.4 Setup scenarios ................................................................................................................ 1354.3.5 Configurator ...................................................................................................................... 1364.3.6 Migrating from Tx6120 ...................................................................................................... 141

4.4 Configurator ..................................................................................................................................  1434.4.1 Overview ........................................................................................................................... 1434.4.2 Data Access...................................................................................................................... 1444.4.3 Historical Access............................................................................................................... 1454.4.4 Security ............................................................................................................................. 1464.4.5 Online Panel ..................................................................................................................... 146

4.5 Sample Client ...............................................................................................................................  1484.5.1 Overview ........................................................................................................................... 1484.5.2 Securely connect to a OPC-UA Server............................................................................. 1494.5.3 Browsing the UA-Namespace........................................................................................... 1524.5.4 Using the Watchlist ........................................................................................................... 153

5 PLC libraries .......................................................................................................................................... 155

TF6100 TC3 OPC-UA 3Version: 2.2

Page 4: Manual TF6100 TC3 OPC-UA

Table of contents

5.1 Tc3_PLCopen_OpcUa..................................................................................................................  1555.1.1 Function Blocks................................................................................................................. 1555.1.2 Data Types........................................................................................................................ 165

6 Samples.................................................................................................................................................. 1716.1 Overview.......................................................................................................................................  171

7 Appendix ................................................................................................................................................ 1727.1 OPC-UA Server error codes .........................................................................................................  1727.2 OPC-UA Client error codes ..........................................................................................................  1727.3 ADS Return Codes .......................................................................................................................  174

8 Third party samples .............................................................................................................................. 1798.1 Sample of OPC UA from Inosoft...................................................................................................  179

TF6100 TC3 OPC-UA4 Version: 2.2

Page 5: Manual TF6100 TC3 OPC-UA

Foreword

1 Foreword

1.1 Notes on the documentationThis description is only intended for the use of trained specialists in control and automation engineering whoare familiar with the applicable national standards.It is essential that the following notes and explanations are followed when installing and commissioningthese components.

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

DisclaimerThe documentation has been prepared with care. The products described are, however, constantly underdevelopment.For that reason the documentation is not in every case checked for consistency with performance data,standards or other characteristics.In the event that it contains technical or editorial errors, we retain the right to make alterations at any timeand without warning.No claims for the modification of products that have already been supplied may be made on the basis of thedata, diagrams and descriptions in this documentation.

TrademarksBeckhoff®, TwinCAT®, EtherCAT®, Safety over EtherCAT®, TwinSAFE®, XFC®and XTS® are registeredtrademarks of and licensed by Beckhoff Automation GmbH.Other designations used in this publication may be trademarks whose use by third parties for their ownpurposes could violate the rights of the owners.

Patent PendingThe EtherCAT Technology is covered, including but not limited to the following patent applications andpatents:EP1590927, EP1789857, DE102004044764, DE102007017835with corresponding applications or registrations in various other countries.

The TwinCAT Technology is covered, including but not limited to the following patent applications andpatents:EP0851348, US6167425 with corresponding applications or registrations in various other countries.

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

Copyright© Beckhoff Automation GmbH & Co. KG, Germany.The reproduction, distribution and utilization of this document as well as the communication of its contents toothers without express authorization are prohibited.Offenders will be held liable for the payment of damages. All rights reserved in the event of the grant of apatent, utility model or design.

TF6100 TC3 OPC-UA 5Version: 2.2

Page 6: Manual TF6100 TC3 OPC-UA

Foreword

1.2 Safety instructions

Safety regulationsPlease note the following safety instructions and explanations!Product-specific safety instructions can be found on following pages or in the areas mounting, wiring,commissioning etc.

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

Personnel qualificationThis description is only intended for trained specialists in control, automation and drive engineering who arefamiliar with the applicable national standards.

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

DANGER

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

WARNING

Risk of injury!Failure to follow the safety instructions associated with this symbol endangers the life andhealth of persons.

CAUTION

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

Attention

Damage to the environment or devicesFailure to follow the instructions associated with this symbol can lead to damage to the en-vironment or equipment.

Note

Tip or pointerThis symbol indicates information that contributes to better understanding.

TF6100 TC3 OPC-UA6 Version: 2.2

Page 7: Manual TF6100 TC3 OPC-UA

Product description

2 Product descriptionOPC Unified Architecture (UA) is the next generation of the classic OPC-standard and describes a worldwidestandardized communication protocol, which enables a vendor- and platform-independent transfer ofprocess data. OPC-UA integrates well established security mechanisms directly into the protocol. Anotheradvantage, compared to classic OPC, is the independence of the old COM/DCOM standard. For detailedinformation about OPC-UA, please consider visiting the websites of the OPC Foundation.

ComponentsThe following software components are included for Win32/64 and Windows CE-based systems:

Software component DescriptionOPC-UA Server [} 37] Offers an OPC-UA Server interface in order to enable

UA-Clients to access the TwinCAT Runtime.OPC-UA Client Provides an OPC-UA Client functionality in order to

be able to communicate with other OPC-UA Serversbased on PLCopen-designed Function Blocks.

The following software components are included for Win32/64 based systems:

Software component (Windows-only) DescriptionOPC-UA Configurator [} 143] A graphical UI to configure the TwinCAT OPC-UA

ServerOPC-UA Sample Client [} 148] A graphical OPC-UA Client sample implementation to

allow a first connection test of the TwinCAT OPC-UAServer

OPC-UA Gateway [} 132] A wrapper technology that provides an OPC-COM-DA server interface as well as OPC-UA serveraggregation capabilities

2.1 ScenariosThe following documentation article explains several scenarios in which the components can be deployedand used, depending on the customer’s infrastructure and use case. It consists of the following topics:

• OPC-UA Server: Integrated into Industrial-PC or Embedded-PC• OPC-UA Server: Running on a central computer with connection to remote TwinCAT Runtime(s)• OPC-UA Server: Access to BC controllers

TF6100 TC3 OPC-UA 7Version: 2.2

Page 8: Manual TF6100 TC3 OPC-UA

Product description

OPC-UA Server: Integrated into Industrial-PC or Embedded-PCOne of the biggest advantages of the TwinCAT OPC-UA Server is that it can be integrated even on thesmallest Embedded platform, e.g. the CX8000 series. This integration makes the overall handling very easyand comfortable. OPC-UA Clients, e.g. HMI or MES/ERP systems, can connect to the OPC-UA Server andread or write symbol information that comes from the TwinCAT Runtime.

Note

RecommendedThis is the recommended scenario in which the TwinCAT OPC-UA Server should be oper-ated under normal circumstances.

The central server runs the following software components and configurations:

• Third party OPC-UA Client, which could be an HMI, MES, or ERP system

The Industrial-PC or Embedded-PC runs the following software components and configurations:

• TwinCAT OPC-UA Server, automcatically connects to first local TwinCAT PLC Runtime• TwinCAT Runtime

This scenario has the following advantages:

• Network utilization is optimized because it is based on OPC-UA communication technologies, e.g.OPC-UA Subscriptions

• Memory consumption is distributed – every device is responsible only for his own memory consumption• Security – OPC-UA has security mechanisms directly integrated into the protocol. This might come in

handy if one of the Industrial-PCs or Embedded-PCs is located on the Internet

TF6100 TC3 OPC-UA8 Version: 2.2

Page 9: Manual TF6100 TC3 OPC-UA

Product description

OPC-UA Server: Running on a central computer with connection to remote TwinCATRuntime(s)This scenario describes the classic way of deploying OPC-Servers. Servers that use the old OPC-DAtechnology, were often deployed on a central server instead of the Industrial-PC that runs the TwinCATRuntime to avoid DCOM configurations. (Remember: In contrast to OPC-UA, OPC-DA was based on COM/DCOM technologies)

The central server runs the following software components and configurations:

• TwinCAT 3 ADS (or TwinCAT 2 CP) for necessary ADS connectivity• TwinCAT OPC-UA Server, configured with Data Access devices for remote TwinCAT Runtimes• ADS routes to remote TwinCAT Runtimes• Symbol files of every remote TwinCAT Runtime• OPC-UA Client, which could be an HMI, MES or ERP system

The Industrial-PC or Embedded-PC runs the following software components and configurations:

• TwinCAT Runtime• ADS-Route to central server

Although the network utilization in this scenario might still be good, it may get more utilized the more remoteTwinCAT Runtimes are being connected to the central TwinCAT OPC-UA Server. The OPC-UA Server usesadvanced ADS sampling technologies to retrieve symbol values from the TwinCAT Runtime. The moresymbols there are, the more cyclic sampling traffic is put on the wire. Therefore the optimized OPC-UAcommunication is only taking place locally on the central server (between OPC-UA Client and OPC-UAServer)!

Therefore this scenario has, compared to the first scenario, the following disadvantages:

• Network utilization could be very high, depending on how much devices and symbols there are• Memory consumption is very high on central server because the OPC-UA Server needs to import

symbol information from EVERY TwinCAT Runtime• No security between central server and TwinCAT Runtime by the means of data encryption – ADS has

been designed for high performance and does not provide data encryption• Necessity to exchange symbol files between TwinCAT Runtime and central server every time a PLC

program changes

OPC-UA Server: Access to BC controllersAlthough our small BC controllers are not capable of running an own OPC-UA Server, you still can accessthe PLC runtime running on a remote BC controller, e.g. a BC9191, and publish its symbol values via OPC-UA. In this scenario, you need to run the OPC-UA Server together with a TwinCAT 3 ADS (or TwinCAT 2CP) on another computer and configure the scenario in the same way as scenario 2.

TF6100 TC3 OPC-UA 9Version: 2.2

Page 10: Manual TF6100 TC3 OPC-UA

Product description

2.2 Important information for OPC-UA ClientsThis article provides information about important differences between different product versions. Thisinformation might be important when upgrading the software product between major software versions.Please consult our Version Information [} 10] page to see which setup includes which product version.

Changes overview TwinCAT OPC-UA Server

Important changes inversion

Component Notes

all versions Arrays in a PLC program By default, array elements of a PLC array arenot displayed as separate nodes in UAnamespace. Instead, only one node is used forthe complete array and UA-Clients can accesseach element by its IndexRange. Please consultour article about ArraySubItemLegacySupport[} 66] for more information.

2.1 Enums in a PLC program By default, enums in a PLC program are nowdisplayed as EnumTypes in UA namespace. Inprevious version this has simply been an Int16.

2.1 NamespaceName Since version 2.1 the NamespaceName isgenerated according to the URI concept andalways includes the hostname of the computerthat the UA-Server runs on. In older versions,the NamespaceName equals the name as set inthe Configurator tool, e.g. “PLC1”. Thisinformation is especially important if a UA-Clientresolves the NamespaceName to aNamespaceIndex before accessing a node. Forcompatibility purposes and to make upgradeseasier without touching the UA-Client, version2.2 of the TwinCAT OPC-UA Server providesmechanisms to activate the oldNamespaceName concept. Please consult theTwinCAT OPC-UA Server documentation formore information.

2.2 Structures in PLC Since version 2.2.x, structures in a PLCprogram are accessible via a StructuredType inUA namespace. This enables UA-Clients tointerpret types of elements in the struct. Pleaseconsult our article about StructuredTypes [} 63]for more information.

2.2 Namespace design of a C++module instance

Compared to previous versions (up until 2.1.x)the UA namespace of a C++ module has beenre-designed in version 2.2.x to allow advancedfunctionalities like method calls for a C++module instance.

2.3 Version informationThe following tables show, which product versions the TS6100/TF6100 setups contain.

Note

Important notesPlease consult the readme.txt that is being delivered with the setup for important notes, es-pecially when upgrading from older versions of a included software component (e.g. whenupgrading TcOpcUaServer.exe from version 2.0.x to 2.1.x).

TF6100 TC3 OPC-UA10 Version: 2.2

Page 11: Manual TF6100 TC3 OPC-UA

Product description

Table 1: Setup version 3.3.5

Filename VersionTwinCAT OPC-UA Server 2.2.0.37TwinCAT OPC-UA Client 2.1.0.28TwinCAT OPC-UA Gateway 1.4.0TwinCAT OPC-UA Configurator 2.1.0.33TwinCAT OPC-UA Sample Client 1.5.0.1PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.1.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.6.0

Table 2: Setup version 3.3.4

Filename VersionTwinCAT OPC-UA Server 2.2.0.35TwinCAT OPC-UA Client 2.1.0.28TwinCAT OPC-UA Gateway 1.3.12.299TwinCAT OPC-UA Configurator 2.1.0.32TwinCAT OPC-UA Sample Client 1.5.0.1PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.6.0

Table 3: Setup version 3.3.3

Filename VersionTwinCAT OPC-UA Server 2.2.0.33TwinCAT OPC-UA Client 2.1.0.28TwinCAT OPC-UA Gateway 1.3.10TwinCAT OPC-UA Configurator 2.1.0.32TwinCAT OPC-UA Sample Client 1.5.0.1PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.6.0

Table 4: Setup version 3.3.2

Filename VersionTwinCAT OPC-UA Server 2.2.0.32TwinCAT OPC-UA Client 2.1.0.28TwinCAT OPC-UA Configurator 2.1.0.32TwinCAT OPC-UA Sample Client 1.5.0.1PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.6.0

Table 5: Setup version 3.3.1

Filename VersionTwinCAT OPC-UA Server 2.2.0.26TwinCAT OPC-UA Client 2.1.0.28TwinCAT OPC-UA Configurator 2.1.0.32TwinCAT OPC-UA Sample Client 1.5.0.1PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.6.0

TF6100 TC3 OPC-UA 11Version: 2.2

Page 12: Manual TF6100 TC3 OPC-UA

Product description

Table 6: Setup version 3.2.2

Filename VersionTwinCAT OPC-UA Server 2.1.0.29TwinCAT OPC-UA Client 2.1.0.28TwinCAT OPC-UA Configurator 2.1.0.32TwinCAT OPC-UA Sample Client 1.5.0.1PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.6.0

Table 7: Setup version 3.2.1

Filename VersionTwinCAT OPC-UA Server 2.1.0.28TwinCAT OPC-UA Client 2.1.0.18TwinCAT OPC-UA Configurator 2.1.0.29TwinCAT OPC-UA Sample Client 1.5.0.0PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.2.0

Table 8: Setup version 3.1.20

Filename VersionTwinCAT OPC-UA Server 2.0.0.72TwinCAT OPC-UA Client 2.1.0.18TwinCAT OPC-UA Configurator 2.1.0.24TwinCAT OPC-UA Sample Client 1.5.0.0PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.2.0

Table 9: Setup version 3.1.18

Filename VersionTwinCAT OPC-UA Server 2.0.0.71TwinCAT OPC-UA Client 2.1.0.18TwinCAT OPC-UA Configurator 2.1.0.23TwinCAT OPC-UA Sample Client 1.5.0.0PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.2.0

Table 10: Setup version 3.1.16

Filename VersionTwinCAT OPC-UA Server 2.0.0.70TwinCAT OPC-UA Client 2.1.0.18TwinCAT OPC-UA Configurator 2.1.0.22TwinCAT OPC-UA Sample Client 1.5.0.0PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.2.0

TF6100 TC3 OPC-UA12 Version: 2.2

Page 13: Manual TF6100 TC3 OPC-UA

Product description

Table 11: Setup version 3.1.14

Filename VersionTwinCAT OPC-UA Server 2.0.0.67TwinCAT OPC-UA Client 2.1.0.18TwinCAT OPC-UA Configurator 2.1.0.22TwinCAT OPC-UA Sample Client 1.5.0.0PLC library Tc2_PLCopen_OpcUa (only TS6100) 1.0.1.0PLC library Tc3_PLCopen_OpcUa (only TF6100) 3.1.2.0

2.4 Application examples

2.4.1 Post-processing in the CloudThe overall concept for providing a generic, standardized and callable interface in the Cloud that acceptsincoming data for further analysis, is, apart from the decentralized clients that invoke this service, based onan endpoint in the Cloud that is either a Windows-based Virtual Machine or a real hardware that runs theWindows Operating System. During this documentation, this device will be generally referred to as the “OPC-UA Server” (in the Cloud).

TF6100 TC3 OPC-UA 13Version: 2.2

Page 14: Manual TF6100 TC3 OPC-UA

Product description

Application example: Data loggerThe overall document demonstrates how to access computational resources in the Cloud and connectdistributed TwinCAT PLC devices to use these resouces. As a first application example, this use case canbe simply extended to a typical data logging scenario in which the distributed TwinCAT PLC device cyclicallysend data to the Cloud, in which the incoming data is persisted in a SQL database via the TwinCATDatabase Server. As the general scenario also includes sending data back and forth (sending parameters tothe Cloud, let the Cloud perform its calculations and then expect the computed results), this specific scenariodoes not require to get any results from the Cloud.

System requirements: OPC-UA Server („The Cloud“)The Cloud needs to be able to host either of the following Operating Systems variations. Please note that theuse of virtualization technologies require a more cost-intensive solution for 64-bit Operating Systems.

Device is a Virtual Machine• 32-bit Windows Operating System• 64-bit Windows Operating System with CPU Core Isolation (requires at least 2 cores)

Device is a dedicated hardware• 32-bit Windows Operating System• 64-bit Windows Operating System

In addition, the following software components need to be installed on the device:

• TwinCAT 3 XAR (Runtime-only) or XAE (Runtime + Engineering)• TwinCAT 3 Function TF6100 OPC-UA

Please note: By installling a full-blown TwinCAT 3 XAE, further configuration settings might become morehandy, e.g. the handling of licenses or the possibility to debug the device directly in the Cloud. To be able tostore the data that is received by a client in a central database, the following software components need tobe installed:

• TwinCAT 3 Function TF6420 Database

TF6100 TC3 OPC-UA14 Version: 2.2

Page 15: Manual TF6100 TC3 OPC-UA

Product description

System requirements: Decentralized OPC-UA ClientThe decentralized OPC-UA Client is based on a TwinCAT 3 PLC Runtime and can therefore be hosted onany hardware configuration that supports to run a TwinCAT 3 PLC. In addition, the TwinCAT 3 FunctionTF6100 OPC-UA needs to be installed on the Client device to be able to use the TwinCAT OPC-UA Client toexecute UA methods on the Server in the Cloud.

Technical descriptionThe realization of an OPC-UA Server in the Cloud is highly application specific. Beckhoff provides a generalarchitecture description independent of a detailed use case. As an application example, this article oftendescribes a data aggregation scenario, in which process data from decentralized Clients is transfered viaOPC-UA to the central Server on which the data is aggregated in a central database. The advantage ofOPC-UA in this case is not only the standardized interface (and therefore to use this concept with any kind ofOPC-UA Client) but also the possibilities to secure the communication channel by using the integratedsecurity mechanisms of OPC-UA.

The TwinCAT OPC-UA Server is used to expose the IEC61131-3 PLC defined methods to the OPC-UANamespace. These methods can be invoked by either the TwinCAT OPC-UA Client (based on PLCopenfunctionblocks) or by an 3rd-Party OPC-UA Client.

Decentralized OPC-UA Client

The main purpose of the OPC-UA Client is to invoke methods on the remote Server. Most probably, theClient device will be a embedded TwinCAT 3 device fulfilling the decentral part of the application. For thedata aggregation sample this would be to sample process data and send them to the Server by calling amethod.

Interface description (to the Cloud)

As an interface to the centralized cloud system there are only two methods that are provided by the Server:

• int Send(data): This method submits the data via an OPC-UA Method Call and returns a JobID• int QueryState(jobID): Using the previously retrieved JobID, the Client can query the current state of

the job cyclically. This could be skipped if the Server in the Cloud can guarantee to handle all situationsor the client cannot help out on issues.

Communication between Clients and the Cloud can be secured by the built-in security concepts of OPC-UA,e.g. by the use of Client and Server certificates to encrypt data communication. Please consult the TF6100documentation for more information.

The Cloud

The OPC-UA Server in the Cloud is based on TwinCAT 3 PLC methods that are exposed to the OPC-UANamespace. The PLC project contains the following three components:

• MethodCall provider: This component provides the previously mentioned Send() method, whichgathers the data, generates a JobID and stores the data as different jobs on the Queue. Additionallythere might be a QueryState() method to enable OPC-UA clients to query the current job status.

• Queue: The queue stores a list of jobs that should be executed. Each job in the queue contains thefollowing information: {ID, Status, Data}. New items (jobs) are added by the MethodCall provider andmight be deleted by it, too. The whole queue can be based on a hashtable within the PLC program.

• Aggregator: The application, which processes the jobs. It looks cyclically if there are any unfinishedjobs in the Queue. If so, it takes over the job (sets its status to “processing”) and starts processing thejob, e.g. connecting to a database via functionblocks of the TwinCAT DatabaseServer. Please notethat there may be more than one instance of an Aggregator to allow parallel processing of the Queue.

TF6100 TC3 OPC-UA 15Version: 2.2

Page 16: Manual TF6100 TC3 OPC-UA

Product description

SampleThe following sample illustrates the scenario by performing simple jobs: Jobs can be submitted by the OPC-UA Client to the Server. In this sample, the job data is a defineable time interval, which is taken by theAggregator to finish the job. The sample consist of the following PLC components on the OPC-UA Server:

• ST_JobEntry: Represents a Job in the Queue. The Job consists of just a name and a duration as data.A duration defines the timespan that a job takes.

• E_JobState: Represents the state of a job. The sample implementation defines the following values:QUEUED, PROCESSING, READY, FAILED and INVALID.

• LongTerm: Represents the MethodCall Server (Consists of the methods Calc_Request andCalc_Response) as well as the aggregator processing the job (implemented in the body of theFunctionblock)

• FB_SpecialHashTableCtrl: Represents the Queue in form of a Hastable, as demonstrated by standardPLC samples from Beckhoff Information System. Recommends different methods to handle the queue(Add, Count, GetFirst, GetNext, Lookup, Remove, Reset).

Using the Sample

The UA Expert could be used as a sample client to call the methods provided by the OPC-UA Server in theCloud. By calling the method Calc_Request, the client gets a JobID (or 0 to indicate an error):

TF6100 TC3 OPC-UA16 Version: 2.2

Page 17: Manual TF6100 TC3 OPC-UA

Product description

By taking the returned JobId to the method Calc_Response, the client can query the JobState. Rapidly afterCalc_Request, this will be 0100 and later on:

In addition, the previously set duration and job name will be returned for later reference.

InstallationThe following chapter describes the installation and configuration of each software component that isrequired on the Server in the Cloud.

Runtime only

If the Server device should not host the engineering environment of TwinCAT 3, the TwinCAT 3 XARinstallation need to be used. Please note, that, in this case the overall handling will involve more steps toperform and future maintenance might be more difficult because the XAR installation therefore also lacks theprogramming and debugging environment. One of the things that the user must ensure in this scenario is themaintenance of ADS routes between the actual engineering computer (where the PLC program for theserver is developed) and the device that hosts the Server in the Cloud, not only to allow the download anddebugging of the PLC program but also to allow the activation of licenses for the TwinCAT 3 runtime. Please

TF6100 TC3 OPC-UA 17Version: 2.2

Page 18: Manual TF6100 TC3 OPC-UA

Product description

note that you need to open firewall ports to allow ADS traffic. Please consult the ADS documentation formore information. To allow easier handling of TwinCAT 3 Runtime licenses, the TC3 License RequestGenerator utility has been developed. It is available for download via the Beckhoff FTP Server and allows thecreation of License Request files and the import of License Response files:

ftp.beckhoff.com/Software/TwinCAT/Unsupported_Utilities/TC3-LicenseGen/

Runtime and engineering

This is the recommended setup scenario. The server in the Cloud hosts a TwinCAT 3 Runtime and thecorresponding engineering components to allow debugging and easier handling of the runtime system. Inthis case, a TwinCAT 3 XAE is required to be installed on the system.

Additional software

After TwinCAT XAE or XAR has been installed, the following software components need to be installed andconfigured on the device:

TF6100 OPC-UA

The TF6100 Function installs an OPC-UA Server (and Client) on the device. The Server is required toprovide the PLC methods to OPC-UA Clients. Please install the TF6100 Setup as mentioned in the TF6100documentation. When downloading the PLC program into the runtime, the OPC-UA Server automaticallyimports the first PLC runtime into his namespace. All variables and methods from the PLC, which have beentagged to be available via OPC-UA, will be imported into the OPC-UA namespace and will be available forclients. Please consult the TF6100 documentation for more information.

TF6420 Database

If the server should store the data received by the clients in a database, the TF6420 Function has to beused. It provides generic functionblocks for the TwinCAT 3 PLC to access database, e.g. to insert values intoa database table. Please install the TF6420 Setup and consult the TF6420 documentation for moreinformation about how to use the corresponding functionblocks.

LicensingAll TwinCAT 3 software products require a license to be available on the server device. The license caneither be a 7-day trial or a full license. Licenses can be activated by using the TwinCAT 3 XAE LicenseManager. If a TwinCAT 3 XAR installation is used on the server, please make use of the TC3 LicenseGenerator, as mentioned above.

TF6100 TC3 OPC-UA18 Version: 2.2

Page 19: Manual TF6100 TC3 OPC-UA

Installation

3 Installation

3.1 System requirements

OPC-UA Server• Operating systems:

◦ Windows XP Pro SP3◦ Windows 7 Pro (32-bit and 64-bit)◦ Windows XP Embedded◦ Windows Embedded Standard 2009◦ Windows Embedded 7◦ Windows Server 2008 R2◦ Windows Server 2012◦ Windows CE6◦ Windows CE7

• TwinCAT:◦ TwinCAT 3 ADS Build 4012 (or above)◦ TwinCAT 3 XAR Build 3100 (or above)◦ TwinCAT 3 XAE Build 3100 (or above)◦ TwinCAT 2

Any difference between these systems will be described in the corresponding installation manual.

OPC-UA Client• Operating systems:

◦ Windows XP Pro SP3◦ Windows 7 Pro (32-bit and 64-bit)◦ Windows XP Embedded◦ Windows Embedded Standard 2009◦ Windows Embedded 7◦ Windows Server 2008 R2◦ Windows Server 2012◦ Windows CE6◦ Windows CE7

• TwinCAT:◦ TwinCAT 3 ADS Build 4012 (or above)◦ TwinCAT 3 XAR Build 3100 (or above)◦ TwinCAT 3 XAE Build 3100 (or above)◦ TwinCAT 2.11 R3 Build 2245 (or above)

OPC-UA Configurator• Operating systems:

◦ Windows XP Pro SP3◦ Windows 7 Pro (32-bit and 64-bit)◦ Windows XP Embedded◦ Windows Embedded Standard 2009

TF6100 TC3 OPC-UA 19Version: 2.2

Page 20: Manual TF6100 TC3 OPC-UA

Installation

◦ Windows Embedded 7◦ Windows Server 2008 R2◦ Windows Server 2012

• Miscellaneous:◦ .NET Framework 2.0 SP1

OPC-UA Sample Client• Operating systems:

◦ Windows XP Pro SP3◦ Windows 7 Pro (32-bit and 64-bit)◦ Windows XP Embedded◦ Windows Embedded Standard 2009◦ Windows Embedded 7◦ Windows Server 2008 R2◦ Windows Server 2012

• Miscellaneous:◦ .NET Framework 4.0

3.2 InstallationDescription of the installation procedure of a TwinCAT 3 Function for Windows-based operating Systems.

1. Double-click the downloaded setup file "TE1610 TC3 EAP-Configurator.exe".Please note: Under Windows 32-bit/64-bit, please start the installation with "Run as Administrator" byright-clicking the setup file and selecting the corresponding option in the context menu.

2. Click on "Next" and accept the license Agreement.

TF6100 TC3 OPC-UA20 Version: 2.2

Page 21: Manual TF6100 TC3 OPC-UA

Installation

3. Enter your user information in the specified area.

4. To install the full product, including all sub-components, please choose "Complete" as the SetupType.Alternatively you can also install each component seperately by choosing "Custom".

TF6100 TC3 OPC-UA 21Version: 2.2

Page 22: Manual TF6100 TC3 OPC-UA

Installation

5. Click on "Install"after pressing the "Next" to start the Installation.

The TwinCAT system has to be stopped before proceeding with installation6. Confirm the Dialog with "Yes".

TF6100 TC3 OPC-UA22 Version: 2.2

Page 23: Manual TF6100 TC3 OPC-UA

Installation

7. Select "Finish" to end the installation process.

ð The installation is complete now.

After a successful installation the TC 3 Function needs to be licensed [} 32]

3.3 Installation Windows CEThis part of the documentation describes, how you can install the TwinCAT 3 Function TF6100 OPC-UA ona Beckhoff Embedded PC Controller based on Windows CE.

The setup process consists of four steps:

• Downloading the setup file• Installation on a host computer• Transfering the executable to the Windows CE device• Software upgrade• Software upgrade

Downloading the setup fileThe CAB installation files for Windows CE are part of the TF6100 OPC-UA setup. Therefore you only needto download one setup file from www.beckhoff.com which contains binaries for Windows XP, Windows 7 andWindows CE (x86 and ARM).

The installation procedure of the TF6100 OPC-UA setup is described in the regular installation article.

Installation on a host computerAfter installation, the install folder contains three directories - each one for a different hardware platform:

• CE-ARM: ARM-based Embedded Controllers running Windows CE, e.g. CX8090, CX9020• CE-X86: X86-based Embedded Controllers running Windows CE, e.g. CX50xx. CX20x0• Win32: Embedded Controllers running Windows XP, Windows 7 or Windows Embedded Standard

TF6100 TC3 OPC-UA 23Version: 2.2

Page 24: Manual TF6100 TC3 OPC-UA

Installation

The CE-ARM and CE-X86 folders contain the TF6100 CAB-File for Windows CE - corresponding to thehardware platform of your Windows CE device. This file needs to be transfered to the Windows CE device,see next chapter.

Transfering the executable to the Windows CE deviceTransfer the corresponding CAB-File to you Windows CE device. This can be done via one of the followingways:

• via a Shared Folder• via the integrated FTP-Server• via ActiveSync• via a CF card

For more information, please consult the "Windows CE" section in our Infosys documentation system.

Software installationAfter the file has been transfered via one of the above methods, you need to execute the file andacknowledge the following dialog with "Ok". Restart your Windows CE device after the installation hasfinished.

After the restart has been completed, the TF6100 executables (Client and Server) will be automaticallystarted in background and is now available to use.

The software will be installed in the following directory on the CE device: \Hard Disk\TwinCAT\Functions\TF6100-OPC-UA

Software upgradeIf you already have a version of TF6100 installed on your Windows CE device, you need to perform thefollowing things on the Windows CE device to upgrade to a newer version:

1. Open the CE Explorer by clicking on Start --> Run and entering "explorer"2. Navigate to \Hard Disk\TwinCAT\Functions\TF6100-OPC-UA\Server and (in a second step) \Hard Disk

\TwinCAT\Functions\TF6100-OPC-UA\Client3. Rename TcOpcUaServer.exe and TcOpcUaClient.exe4. Restart the Windows CE device5. Transfer the new CAB-File to the CE device6. Execute the CAB-File and install the new version of TF6100

TF6100 TC3 OPC-UA24 Version: 2.2

Page 25: Manual TF6100 TC3 OPC-UA

Installation

7. Delete the old (renamed) files8. Restart the Windows CE deviceð After the restart is complete, the new version is active.

3.4 Installation Tc2This part of the documentation gives a step-by-step explaination of the TwinCAT OPC-UA setup process forWindows XP based operating systems. The following topics are part of this document:

• Downloading the setup file• Starting the installation• After the installation

Downloading the setup fileLike many other TwinCAT Supplement products, OPC-UA is available for download via the BeckhoffWebsite. The download represents the most current version, which can be licensed either as a 30-DayDemo or as a full version.

Starting the installationTo install the Supplement, please perform the following steps:

• Double-click the downloaded setup file TcOpcUaSvr.exe. Please note: Under Windows 7 32-bit/64-bit,please start the installation with "Run as Administrator" by right-clicking the setup file and selecting thecorresponding option in the context menu

• Select an installation language• Click on "Next" and accept the license agreement

TF6100 TC3 OPC-UA 25Version: 2.2

Page 26: Manual TF6100 TC3 OPC-UA

Installation

• Enter your user information. All fields are mandatory. If you would like to install a 30-Day demo, pleaseenter "DEMO" as a license key

• Click on Install to start installation

TF6100 TC3 OPC-UA26 Version: 2.2

Page 27: Manual TF6100 TC3 OPC-UA

Installation

• At the end of the setup process, please restart your computer

After the installationThe Supplement TwinCAT OPC-UA is automatically configured by the setup process and no additionalsettings are required to use the product. Additional steps could include:

• Starting a first connection to the installed UA-Server and testing its configuration with the softwareOPC-UA SampleClient

• Customizing UA-Server setup by using the OPC-UA Configurator• Please also make sure that your Firewall opens the TCP port 4840, because this port is required by the

OPC-UA Server

3.5 Installation Windows CE Tc2This part of the documentation describes, how you can install the Supplement TwinCAT OPC-UA on aBeckhoff Embedded PC Controller based on Windows CE, for example CX1000, CX1020, CX9000, CX9001,CX9010, CX8090, CP62xx, C69xx, ...

The setup process consists of four steps:

• Downloading the setup file• Installation on a host computer• Transfering the setup file to the Windows CE device• Executing the setup on the Windows CE device

TF6100 TC3 OPC-UA 27Version: 2.2

Page 28: Manual TF6100 TC3 OPC-UA

Installation

Note

Installation on small embedded platforms (CX9001, CX9010)Very small embedded devices might require some additional manual steps to be taken sothat the CAB file can be installed. These steps may involve the deletion of unnecessaryfiles on the devices storage so that enough space is available to install all files for the appli-cation.

Downloading the setup fileLike many other TwinCAT Supplement products, OPC-UA for CE is available for download via the BeckhoffFTP-Server. The download represents the most current version.

Installation on a host computerTo get the installation files for Windows CE, you first need to install the downloaded setup file on a hostcomputer, which can be any Windows CE based system. Please perform the following steps:

1. Double-click the downloaded file TcOpcUaSvrCE.exe2. Select an installation language3. Click on Next and accept the license agreement

TF6100 TC3 OPC-UA28 Version: 2.2

Page 29: Manual TF6100 TC3 OPC-UA

Installation

4. Enter your user information. All fields are mandatory. Please note that OPC-UA for CE is currently notavailable as a demo version. Therefore, you need a valid license key to continue installation.

TF6100 TC3 OPC-UA 29Version: 2.2

Page 30: Manual TF6100 TC3 OPC-UA

Installation

5. Select Complete as the setup type and click on Next

6. Click on Install to start installationð After installation, the setup files for Windows CE can be found in the directory ".\TwinCAT\CE". This di-

rectory contains setup files for the following CE platforms:• TwinCAT OPC UA Client CE\I586: OPC-UA Client (PLC library) for x86 based CPUs (like CX10xx,

CP62xx, C69xx, ...)• TwinCAT OPC UA Client CE\ARMV4I: OPC-UA Client (PLC library) for ARM based CPUs (like

CX9001, CX9010, CP6608, ...)• TwinCAT OPC UA Server CE\I586: OPC-UA Server for x86 based CPUs (like CX10xx, CP62xx,

C69xx, ...)• TwinCAT OPC UA Server CE\ARMV4I: OPC-UA Server for ARM based CPUs (like CX9001, CX9010,

CP6608, ...)

Transfering the setup file to the Windows CE deviceTransfer the corresponding setup file to you CE device. This can be done in the following ways:

• via a Shared Folder• via the integrated FTP-Server• via ActiveSync• via a CF card

For more information, please consult the "Windows CE" section in our Infosys documentation system.

Executing the setup on the Windows CE deviceNow the transferred setup file TcOpcUaSvrCe.xxxx.CAB needs to be executed on the CE device. Pleaseperform the following steps:

TF6100 TC3 OPC-UA30 Version: 2.2

Page 31: Manual TF6100 TC3 OPC-UA

Installation

1. Navigate to the directory where you transferred the setup file to

2. Double-click the CAB file. Should you get a message box stating that this program is not compatiblewith the current operating system, please re-check if you used the correct CAB-file (ARM, I586) for yourIPC/Embedded-PC.

3. If you are sure that the CAB-file corresponds to the Embedded-PC/IPC, please acknowledge thismessage box with "Yes".

4. Select \Hard Disk\System\ as the destination directory

5. Click on OK to start installation

After installation, the setup file will be automatically deleted.

TF6100 TC3 OPC-UA 31Version: 2.2

Page 32: Manual TF6100 TC3 OPC-UA

Installation

NOTE! If you installed the OPC-UA Server, this component will be available after a restart of yourCE device.

3.6 LicensingThe TwinCAT 3 functions are available both as a full and as a 7-Day trial version. Both license types can beactivated via TwinCAT XAE.For more information about TwinCAT 3 licensing, please consult the TwinCAT 3Help System.The following document describes both licensing scenarios for a TwinCAT 3 function onTwinCAT 3 and is divided into the following sections:

• Licensing a 7-Day trial version [} 32]

• Licensing a full version [} 33]

Licensing a 7-Day trial version1. Start TwinCAT XAE2. Open an existing TwinCAT 3 project or create a new project3. In “Solution Explorer”, please navigate to the entry “System\License”

4. Open the tab "Manage Licenses" and add a "Runtime License" for your product (in this screenshot“TE1300: TC3 Scope View Professional”)

5. Optional: If you would like to add a license for a remote device, you first need to connect to the remotedevice via TwinCAT XAE toolbar

TF6100 TC3 OPC-UA32 Version: 2.2

Page 33: Manual TF6100 TC3 OPC-UA

Installation

6. Switch to the tab "Order Information" and click the button "Activate 7 Days Trial License..."toactivate a test version

7. Please restart TwinCAT 3 afterwards.

Licensing a full version8. Start TwinCAT XAE9. Open an existing TwinCAT 3 project or create a new project

10. In "Solution Explorer", please navigate to the entry "SYSTEM\License"

11. Open the tab "Manage Licenses" and add a "Runtime License" for your product (in this screenshot "TE1300: TC3 Scope View Professional”).

TF6100 TC3 OPC-UA 33Version: 2.2

Page 34: Manual TF6100 TC3 OPC-UA

Installation

12. Optional:If you would like to add a license for a remote device, you first need to connect to the remotedevice via TwinCAT XAE toolbar

13. Navigate to the "Order Information" tabThe fields "System-ID" and "HW Platform" cannot be changed and just describe the platform for thelicensing process in general a TwinCAT 3 license is always bound to these two identifiers:the "System-ID" uniquely identifies your system.The "HW Platform" is an indicator for the performance of the device.

14. Optionally, you may also enter an own order number and description for your convenience

15. enter the "Beckhoff License ID" and click on "Generate License Request File...". If you are not awareof your "Beckhoff License ID" please contact your local sales representative.

16. After the license request file has been saved, the system asks whether to send this file via E-Mail to theBeckhoff Activation Server

17. After clicking "Yes", the standard E-Mail client opens and creates a new E-Mail message to"[email protected]" which contains the "License Request File"

18. Send this Activation Request to BeckhoffNOTE! The “License Response File“ will be sent to the same E-Mail address used for sending

out the ”License Request File”

TF6100 TC3 OPC-UA34 Version: 2.2

Page 35: Manual TF6100 TC3 OPC-UA

Installation

19. After receiving the activation file, please click on the button "Activate License Response File..."in theTwinCAT XAE license Interface.

20. Select the received "Licnse response file" and click on "Open"

21. The "License Response File" will be imported and all included licenses will be activated. If there havebeen any trial licenses, these will be removed accordingly.

TF6100 TC3 OPC-UA 35Version: 2.2

Page 36: Manual TF6100 TC3 OPC-UA

Installation

22. Please restart TwinCAT to activate licenses..

NOTE! The license file will be automatically copied to "..\TwinCAT\3.1\Target\License" on thelocal device.

TF6100 TC3 OPC-UA36 Version: 2.2

Page 37: Manual TF6100 TC3 OPC-UA

Configuration

4 Configuration

4.1 Server

4.1.1 OverviewThe TwinCAT OPC-UA Server offers a standardized communication interface for the access to symbolvalues of the TwinCAT PLC and C++ runtime respectively I/O task.

This part of the documentation describes the basic configuration of the TwinCAT OPC-UA Server.

Please note: • Our Quick Start documentation is a good place to start

You can find more information about the following topics:

• OPC-UA Configurator: A graphical user interface to configure the OPC-UA Server via its configurationfile (see below)

• OPC-DA (Data Access): Access to TwinCAT PLC and IO-Tasks via OPC-UA• OPC-HA (Historical Access): Provided a feature to store historical data, either in RAM, in a File or in a

Database• OPC-AC (Alarm & Conditioning): Provides a Condition Monitoring feature for PLC variables• OPC-UA Security: Describes how to use the integrated security features of OPC-UA

Advanced configurationDepending on your environment, you may want to set additional parameters like:

TF6100 TC3 OPC-UA 37Version: 2.2

Page 38: Manual TF6100 TC3 OPC-UA

Configuration

• Configuration file [} 107]: Explains the configuration file "ServerConfig.xml" of the TwinCAT OPC-UAServer. This file should usually be edited by the OPC-UA Configurator (see above)

• Options for PLC variables [} 67]: Gives an overview about all configurable options (via PLCcomments) for a PLC variable

• Additional ADS devices [} 108]: You may want to connect additional runtime devices to your OPC-UAServer. This article explains how to do so

• Multiple OPC-UA Servers [} 109]: Describes how to configure multiple OPC-UA Server instances onone computer

• OPC-UA via NAT [} 111]: Describes how to configure an OPC-UA communication via a NAT-device,e.g. a Firewall or Router

• Change array handling in OPC-UA namespace [} 66]: Describes two different options how PLC arraysare handled in the OPC-UA namespace

4.1.2 Quick StartAfter installation and licensing, the following steps may be performed to establish a first connection to theUA-Server:

• Step 1: Configuring PLC variables for the OPC-UA access• Step 2: Configuring the OPC-UA namespace• Step 3: Connecting to the OPC-UA Server

This Quick Start article assumes that you have installed the OPC-UA server on the same system as the PLCruntime.

Step 1: Configuring PLC variables for the OPC-UA accessOpen an existing PLC project and insert the following comment before selected variables:

TwinCAT 3 (with TMC import):{attribute 'OPC.UA.DA' := '1'}bVariable : BOOL;

TwinCAT 2 (with TPY import):bVariable : BOOL; (*~ (OPC:1:some description) *)

Step 2: Configuring the OPC-UA namespaceBy default the OPC-UA Server connects to the first PLC runtime on the local system (local = the samesystem on which also the OPC-UA server is installed) and uses its corresponding symbol file (TMC-File) forconfiguring the OPC-UA namespace. To automatically transfer this symbol file to the PLC runtime, thedownload of the symbol file has to be activated in the PLC Project.

TwinCAT 3:

TF6100 TC3 OPC-UA38 Version: 2.2

Page 39: Manual TF6100 TC3 OPC-UA

Configuration

TwinCAT 2:

Every time the PLC project gets activated, the symbol file will be automatically copied to the TwinCAT Bootdirectory.

The default configuration of the OPC-UA Server reads this symbol file automatically upon startup.

Now activate the configuration and restart TwinCAT. Log in to the PLC runtime and start the PLC program.

Continue with step 3.

TF6100 TC3 OPC-UA 39Version: 2.2

Page 40: Manual TF6100 TC3 OPC-UA

Configuration

Step 3: Connecting to the OPC-UA ServerTo establish a connection from an OPC-UA Client, the client has to connect to the URL of the OPC-UAServer. This URL is described as follows:

opc.xxx://<ip or name>:port• opc = Pre-defined• xxx = Transport to OPC-UA Server, for example "tcp"• port = Port number of OPC-UA Server, for example 4840 (default)

Note

Important notePlease note that the default port 4840 may be in use by other OPC-UA servers, e.g. the Lo-cal Discovery Server (LDS) from the OPC Foundation, which is deployed with OPC-UAsoftware packages by some vendors.

Examples:• opc.tcp://CX_0215AF:4840• opc.tcp://172.16.2.80:4840

Start the included UA Sample Client (at Windows-systems with activated UAC, e.g. Windows 7, with theoption „Run As Administrator“) and connect to the URL of the OPC-UA server, e.g. opc.tcp://localhost:4840,by clicking on “Get Endpoints“ and a following “Connect“.

NOTE! You can find the UA Sample Client on the Windows Start Menu or in the installationdirectory of the product, e.g. C:\TwinCAT\Functions\TF6100-OPC-UA\Win32\SampleClient\.

After connecting successfully you find the PLC runtime „PLC1“ with the published variables (see step 1) inthe UA namespace underneath the node „Objects“.

4.1.3 PLC

4.1.3.1 Access to PLC runtime

This part of the documentation describes how the namespace of the TwinCAT OPC-UA Server can beconfigured. The UA namespace describes the structure into which the PLC variables are mapped. So that aPLC variable is accessible via the UA namespace, it must be enabled for this. The following guide describesseveral possibilities to enable variables in a PLC program.

Please note: At this point it should be pointed out again that the OPC-UA server by default always connectsto the first local PLC runtime system, therefore configuration is not required in most cases; please alsocompare the article about Quick Start. A separate configuration is only necessary in exceptional cases, e.g. iffurther runtimes are to be shown in the UA namespace, or if the PLC of a BC device is to be accessed.

This article consists of the following topics:

• General information• Step 1: Select PLC variables that should be published via OPC-UA• Step 2: Activate symbol description download in PLC project• [optional] Step 3: Configure Data Access device in OPC-UA server

General informationFor the configuration of the OPC-UA namespace and access to PLC variables, several parameters areavailable that affect the way in which the PLC runtime is displayed and how communication with it takesplace. These parameters can be conveniently set using the OPC-UA configurator. Alternatively you can alsoset them directly in the ServerConfig.xml configuration file. The following table provides an overview of all theparameters that are relevant when accessing a PLC runtime.

TF6100 TC3 OPC-UA40 Version: 2.2

Page 41: Manual TF6100 TC3 OPC-UA

Configuration

Parameter Description Possible valuesADS Port Defines the ADS port under which the

PLC runtime is accessible. The ADS portcan be read in the features of the PLCproject.

800 (BC Controller)801 (TwinCAT 2)811 (TwinCAT 2)…851 (TwinCAT 3 - default)852 (TwinCAT 3)…

AutoCfg Initially defines the type of target runtimeused for communication, e.g. PLC, C++, I/O. A further distinction can then takeplace within these categories. EveryAutoCfg option is available as anunfiltered and a filtered option. Filteredmeans that users can select which PLCsymbols should be published via OPC-UAvia PLC comments (see below). By usingan unfiltered option, every PLC symbolwill be published to OPC-UA.

7 TwinCAT 2 (TPY)8 TwinCAT 2 (TPY) filtered4040 TwinCAT 3 (TMC)4041 TwinCAT 3 (TMC)filtered

AutoCfgSymFile Symbol file of the respective PLC runtime.By default the automatically generatedsymbol file of the first PLC runtime of thelocal system is imported.

Path to the symbol file. Pointsby default to the symbol file(TMC) of the first local PLCruntime.

IoMode Defines the method of accessing symbols.This is important in particular for access toBC devices.

1 (access via handle - default)3 (access to BC controllers)

ArraySubItemLegacySupport By default, subelements of an array arenot mapped as separate nodes in the UAnamespace. Instead, only the array ismapped as a single element.Nevertheless, UA clients can accesssubelements via their so-called‘IndexRange. Some older OPC-UA clientsunfortunately do not offer this support yet.This flag was introduced so that accesscan nevertheless be enabled for theseclients; the flag causes each arrayposition to be displayed as a separatenode in the UA namespace. Caution: thisleads to higher memory consumption ofthe OPC-UA Server!

0 (deactivated - default)1 (activated)

Disabled Deactivates the PLC runtime in the UAnamespace, as a result of which thecorresponding node is not displayed. Werecommend the activation of thisparameter if certain PLC runtimes are notyet available at the time of the projectplanning, e.g. if the respective devices arenot yet connected to the network.

0 (deactivated - default)1 (activated)

The following steps show by way of example how variables from a PLC program can be imported into the UAnamespace and what steps are necessary for this. It is assumed here that the OPC-UA Server in itsstandard configuration (delivery state after installation) and the PLC runtime are on the same computer.

TF6100 TC3 OPC-UA 41Version: 2.2

Page 42: Manual TF6100 TC3 OPC-UA

Configuration

Step 1: Selecting PLC variables that should be published via OPC-UAThe OPC-UA server automatically establishes a connection to the first PLC runtime on the local system. ThePLC symbols that were marked for OPC-UA in the PLC program (TwinCAT PLC-Control) are provided.Marking takes place by means of a comment in the appropriate place (instance, structure, variable) in thePLC program code. It is best to show this clearly by means of two examples:

Example 1: In this example the PLC variables bMemFlag1, bMemFlag2, bMemAlarm2 and iReadOnly are enabled byOPC-UA. The PLC variable “bMemAlarm1” should not be available via the OPC-UA Server. The PLCprogram in PLC-Control would then look like this – depending on which TwinCAT version you use:

TwinCAT 3 (with TMC import):{attribute 'OPC.UA.DA' := '1'}bMemFlag1 : BOOL;

{attribute 'OPC.UA.DA' := '1'}bMemFlag2 : BOOL;

bMemAlarm1 : BOOL;

{attribute 'OPC.UA.DA' := '1'}bMemAlarm2 : BOOL;

{attribute 'OPC.UA.DA' := '1'}{attribute 'OPC.UA.DA.Access' := '1'}iReadOnly    : INT;

TwinCAT 2 (with TPY import):bMemFlag1 : BOOL; (*~ (OPC:1:some description) *)

bMemFlag2 : BOOL; (*~ (OPC:1:some description) *)

bMemAlarm1 : BOOL;

bMemAlarm2 : BOOL; (*~ (OPC:1:some description) *)

iReadOnly    : INT; (*~ (OPC:1:some description) (OPC_PROP[0005]:1:read-only flag) *)

Please note that the TPY formatation may also be used in TwinCAT 3 PLC projects for migration purposes,e.g. if a TwinCAT 2 project should be easily converted to a TwinCAT 3 project.

Please also note that, due to the additional comment “OPC.UA.DA.Access”, the Access Level of variableiReadOnly has been set to “ReadOnly”. Please refer to the complete list of PLC comments to see thedifferent possibilities.

To set a description for a variable in UA namespace, you can enter a regular PLC comment behind thecorresponding variable, for example:

TwinCAT 3 (with TMC import):{attribute 'OPC.UA.DA' := '1'}bMemFlag1 : BOOL; (* Description for variable bMemFlag1 *)

TwinCAT 2 (with TPY import): functionality not available

This comment is automatically set as the Description attribute of the node in UA namespace:

TF6100 TC3 OPC-UA42 Version: 2.2

Page 43: Manual TF6100 TC3 OPC-UA

Configuration

Example 2: In this example the two instances fbTest1 and fbTest2 of the FB_BLOCK1 function block are to be availablevia OPC-UA. If a whole instance is enabled, then all the symbols that it contains will also be available viaOPC-UA. The PLC program could look like this, for example:

TwinCAT 3 (with TMC import):PROGRAM MAINVAR{attribute 'OPC.UA.DA' := '1'}fbTest1 : FB_BLOCK1;fbTest2 : FB_BLOCK1;END_VAR

FUNCTION_BLOCK FB_BLOCK1VAR_INPUT{attribute 'OPC.UA.DA' := '1'}ni1 : INT;ni2 : INT;END_VARVAR_OUTPUT{attribute 'OPC.UA.DA' := '1'}no1 : INT; no2 : INT;END_VARVAR{attribute 'OPC.UA.DA' := '1'}nx1 : INT;nx2 : INT;END_VAR

TwinCAT 2 (with TPY import):PROGRAM MAINVARfbTest1 : FB_BLOCK1; (*~ (OPC:1:some description) *)fbTest2 : FB_BLOCK1;END_VAR

FUNCTION_BLOCK FB_BLOCK1VAR_INPUTni1 : INT; (*~ (OPC:1:some description) *)ni2 : INT;END_VARVAR_OUTPUTno1 : INT; (*~ (OPC:1:some description) *)no2 : INT;END_VARVARnx1 : INT; (*~ (OPC:1:some description) *)

TF6100 TC3 OPC-UA 43Version: 2.2

Page 44: Manual TF6100 TC3 OPC-UA

Configuration

nx2 : INT;END_VAR

The instance “fbTest1” would be enabled for OPC-UA, as a result of which all the symbols that it containsare also automatically available via OPC-UA, e.g. fbTest.ni1, fbTest.ni2, etc. . The instance “fbTest2” is notmarked for OPC-UA; however, the three variables that it contains - ni1, no1 and nx1 - were marked in thefunction block. These are thus available in all instances via OPC-UA.

Step 2: Activate symbol description download in PLC projectThe so-called symbol file contains information about all the available PLC variables in a PLC project. TheOPC-UA Server requires this information for building up its namespace. By default the current symbolinformation is downloaded automatically into a symbol file. This is located in the project folder of therespective TwinCAT project. In order to transfer the symbol file to the target runtime, you must activate the‘symbol file download’ option in the PLC project.

TwinCAT 3:

Fig. 1: TwinCAT 2:

TF6100 TC3 OPC-UA44 Version: 2.2

Page 45: Manual TF6100 TC3 OPC-UA

Configuration

When creating a boot project, the symbol file is then automatically copied into the boot directory of the PLCruntime and it also reflects the respective ADS port of the PLC runtime in its file name at the same time.

If the OPC-UA server and the PLC runtime are on the same system, then you don’t need to do anything elseapart from restarting the OPC-UA server. The OPC-UA Server is configured by default such that itautomatically loads the symbol file from the TwinCAT Boot directory and generates its namespace based onthe symbol information from this file. If another symbol file is to be used, then please configure it in the OPC-UA configurator or, alternatively, directly in the ServerConfig.xml file.

[optional] Step 3: Configure Data Access device in OPC-UA serverBy default the OPC-UA Server is configured to connect to the first PLC runtime on the local system. If youwould like to publish more than one PLC runtime into UA namespace, you need to configure additional DataAccess devices in the OPC-UA Configurator. This configuration could be necessary in the followingscenarios:

• You have another (second or third) PLC runtime from which you would like to publish symbolinformation to OPC-UA

• You have another Industrial-PC or Embedded-PC from which you would like to publish its PLC runtimeand the corresponding symbol information to OPC-UA

Please also consider to read our Scenarios article, which explains different use cases in which the OPC-UAServer can be deployed and used.

To configure additional devices for Data Access, please open the OPC-UA Configurator and add new DataAccess devices:

TF6100 TC3 OPC-UA 45Version: 2.2

Page 46: Manual TF6100 TC3 OPC-UA

Configuration

Continue with configuring all necessary parameters, as explained above under General. If you configure aremote Industrial-PC or Embedded-PC, please make sure to enter the correct parameters for AdsNetId,AdsPort and supply the corresponding symbol file of the PLC program that runs on that PC.

4.1.3.2 Historical Access

This article describes the steps necessary to configure the variables in the namespace of the TwinCAT OPC-UA Server for Historical Access (HA). Historical Access is the name given to a functionality of OPC-UA inwhich the variable values are saved – either on a persistent data storage medium (file or database) or in thedevice RAM - for later retrieval by the Client. The way in which the OPC-UA Server reads in and saves thevariable values can be configured.

PrerequisitesThe following prerequisites apply to the use of Historical Access:

• The runtime system whose symbols are to be saved for Historical Access must be configured as DataAccess. (compare the documentation article on Data Access)

• The SQL Compact Runtime 3.5 SP2 must be installed on the OPC-UA Server in order to use an SQLCompact Database as a storage medium.

• At least OPC-UA Server version 2.0 must be installed in order to use an SQL Server Database.

GeneralThe following steps must be executed once in order to enable a value history of PLC variables via OPC-UAHistorical Access:

• Activation of Historical Access on the OPC-UA Server• Activation of Historical Access in the TwinCAT 2/3 PLC program• Activation of Historical Access in the TwinCAT 3 C++ module• Display of Historical Access values in an OPC-UA Client

These steps are described in more detail below. At the end you will find further information on how to readout stored variable values via Historical Access with the help of the UA-Expert software.

Activation of Historical Access on the UA ServerVarious storage media can be used for the storage of value histories; these media have to be activated oncein the OPC-UA Server. These settings take place either in the ServerConfig.xml file or conveniently using theOPC-UA configurator. The PLC program then specifies which storage medium is to be used. Once one ormore storage media have been activated on the OPC-UA Server, the PLC program selects the storagemedium that is to be used for each symbol (see Step 2 below). The following four storage media arecurrently supported:

• Main memory: saves the symbol values in the RAM of the device on which the OPC-UA Server isrunning.

• File: saves the values in a file with the specified path.• SQL Compact Database: saves the values in an SQL Compact Database with the specified path. In

this case the SQL Compact Runtime 3.5 SP2 must be installed as the database version on the OPC-UA Server.

• SQL Server Database: saves the values in an SQL Server Database specified by the parametersServername, Databasename, Username and Password.

The following screenshots show the configuration of these modes using the OPC-UA configurator anddirectly via the ServerConfig.xml file.

TF6100 TC3 OPC-UA46 Version: 2.2

Page 47: Manual TF6100 TC3 OPC-UA

Configuration

The XML tags shown below must be inserted between <OpcServerConfig><UaServerConfig> and </UaServerConfig></OpcServerConfig> in the ServerConfig.xml file.<HaModes><HaMode Type="RAM"/><HaMode Type="File" DataStore="C:\Temp\"/><HaMode Type="SQLServerCompact" DbName="C:\Temp\TcOpcUaServer.sdf"/><HaMode Type=”SQLServer” Servername=”SERVERNAME\SQLEXPRESS” DbName=”TcOpcUaServer” User=”sa”Pass=”123”/></HaModes>

The necessary parameters for each mode are:

Mode Necessary parametersMemory Saves the values in the RAM of the device on which the OPC-UA Server is

running. No further parameters are required. Attention: following a restart ofthe device the stored values are no longer available; the storage medium istherefore non-persistent.

File Saves the values in several files whose storage location is specified by theDataStore parameter. Each symbol configured for this storage medium (seeStep 2 below) is given its own file in this directory. In addition, a backup fileexists for each symbol, which is created as soon as the specified buffer length(see Step 2 below) is reached. The contents of the data file are then saved asa backup file and a new file is generated.

SQL Server Compact Saves the values in an SQL Compact Database whose storage location isspecified by the DbName parameter. The requirements specified above apply.

SQL Server Saves the values in an SQL Server Database specified by the parametersServername, DbName, User and Pass.

Activation of Historical Access in the TwinCAT PLC programIf the PLC runtime is configured as a Data Access device (see relevant documentation articles), those PLCvariables that were enabled for this in the PLC program by means of comments are automatically madeavailable by the OPC-UA server via OPC-UA. In the same way as the enabling of variables for access viaOPC-UA, individual variables can be activated or deactivated for Historical Access. This similarly takes placein the PLC program by entering comments to the right of a symbol. The following parameters can bespecified here:

TwinCAT 3 (with TMC import):

TF6100 TC3 OPC-UA 47Version: 2.2

Page 48: Manual TF6100 TC3 OPC-UA

Configuration

Parameter Comment DescriptionActivate {attribute 'OPC.UA.DA' := '1'} Activates the symbol for Data Access.

This is needed to make the symbolavailable for Historical Access as well.

Activate for HA {attribute 'OPC.UA.HA' := '1'} Activates the symbol for HistoricalAccess.

Storage medium {attribute 'OPC.UA.HA.Storage' := '1'} Defines the data memory to be usedfor the storage of the symbol values (1= RAM, 2 = File, 3 = SQL CompactDatabase, 4 = SQL Server Database).

Sampling rate {attribute 'OPC.UA.HA.Sampling' := '50'} Defines the rate with which thevariable values are to be read from thecontroller and saved in the respectivestorage medium. The OPC-UA Serveruses fixed defined sampling rates thatcan be employed here. Thesesampling rates can be extended in theServerConfig if necessary. Normallythere is no need for this, however, andyou are advised against making thesesettings.

Buffer length {attribute 'OPC.UA.HA.Buffer' := '10000'} Defines the number of elements thatthe buffer is to hold.

TwinCAT 2 (with TPY import):

Parameter Comment DescriptionActivate (*~ (OPC:1:some description) *) Activates the symbol for Data Access.

This is needed to make the symbolavailable for Historical Access as well.

Storage medium (*~ (OPC_UA_PROP[5000]:1:RAM) *) Defines the data memory to be usedfor the storage of the symbol values (1= RAM, 2 = File, 3 = SQL CompactDatabase, 4 = SQL Server Database).

Sampling rate (*~ (OPC_UA_PROP[5000][1]:50:SamplingRate) *)

Defines the rate with which thevariable values are to be read from thecontroller and saved in the respectivestorage medium. The OPC-UA Serveruses fixed defined sampling rates thatcan be employed here. Thesesampling rates can be extended in theServerConfig if necessary. Normallythere is no need for this, however, andyou are advised against making thesesettings.

Buffer length (*~ (OPC_UA_PROP[5000][2]:5000:Buffer)*)

Defines the number of elements thatthe buffer is to hold.

The following extract from a PLC program demonstrates the use of the parameters listed above using fourPLC variables:

TwinCAT 3 (with TMC import):{attribute 'OPC.UA.DA' := '1'}{attribute 'OPC.UA.HA' := '1'}{attribute 'OPC.UA.HA.Storage' := '1'}{attribute 'OPC.UA.HA.Sampling' := '5'}{attribute 'OPC.UA.HA.Buffer' := '1000'}_HistoryMem : UINT;

{attribute 'OPC.UA.DA' := '1'}{attribute 'OPC.UA.HA' := '1'}{attribute 'OPC.UA.HA.Storage' := '2'}

TF6100 TC3 OPC-UA48 Version: 2.2

Page 49: Manual TF6100 TC3 OPC-UA

Configuration

{attribute 'OPC.UA.HA.Sampling' := '20'}{attribute 'OPC.UA.HA.Buffer' := '200'}_HistoryFile : UINT;

{attribute 'OPC.UA.DA' := '1'}{attribute 'OPC.UA.HA' := '1'}{attribute 'OPC.UA.HA.Storage' := '3'}{attribute 'OPC.UA.HA.Sampling' := '50'}{attribute 'OPC.UA.HA.Buffer' := '10000'}_HistoryDBcompact : UINT;

{attribute 'OPC.UA.DA' := '1'}{attribute 'OPC.UA.HA' := '1'}{attribute 'OPC.UA.HA.Storage' := '4'}{attribute 'OPC.UA.HA.Sampling' := '5'}{attribute 'OPC.UA.HA.Buffer' := '1000000'}_HistoryDB : UINT;

TwinCAT 2 (with TPY import):_HistoryMem : UINT; (*~ (OPC:1:available for OPC-UA Clients)(OPC_UA_PROP[5000]:1:Memory)(OPC_UA_PROP[5000][1]:5:SamplingRate)(OPC_UA_PROP[5000][2]:1000:Buffer) *)

_HistoryFile : UINT; (*~ (OPC:1:available for OPC-UA Clients)(OPC_UA_PROP[5000]:2:File)(OPC_UA_PROP[5000][1]:20:SamplingRate)(OPC_UA_PROP[5000][2]:200:Buffer) *)

_HistoryDBcompact : UINT; (*~ (OPC:1:available for OPC-UA Clients)(OPC_UA_PROP[5000]:3:SQLCompact)(OPC_UA_PROP[5000][1]:50:SamplingRate)(OPC_UA_PROP[5000][2]:10000:Buffer) *)

_HistoryDB : UINT; (*~ (OPC:1:available for OPC-UA Clients)(OPC_UA_PROP[5000]:4:SQL)(OPC_UA_PROP[5000][1]:5:SamplingRate)(OPC_UA_PROP[5000][2]:1000000:Buffer) *)

Activation of Historical Access in the TwinCAT 3 C++ moduleEvery TwinCAT 3 C++ symbol that should be historized needs to be configured accordingly. Similar to theconfiguration of PLC symbols for Historical Access (see above), the same parameters need to be configuredfor a C++ symbol, as the following table shows:

Parameter Comment DescriptionActivate OPC.UA.DA := 1 Activates the symbol for Data Access.

This is needed to make the symbolavailable for Historical Access as well.

Activate HA OPC.UA.HA := 1 Activates the symbol for HistoricalAccess.

Storage medium OPC.UA.HA.Storage := 1 Defines the data memory to be usedfor the storage of the symbol values (1= RAM, 2 = File, 3 = SQL CompactDatabase, 4 = SQL Server Database).

Sampling rate OPC.UA.HA.Sampling := 50 Defines the rate with which thevariable values are to be read from thecontroller and saved in the respectivestorage medium. The OPC-UA Serveruses fixed defined sampling rates thatcan be employed here. Thesesampling rates can be extended in theServerConfig if necessary. Normallythere is no need for this, however, andyou are advised against making thesesettings.

Buffer length OPC.UA.HA.Buffer := 10000 Defines the number of elements thatthe buffer is to hold.

TF6100 TC3 OPC-UA 49Version: 2.2

Page 50: Manual TF6100 TC3 OPC-UA

Configuration

However, in TwinCAT 3 C++, these parameters are being configured in the TMC Code Editor of thecorresponding C++ module. By using the TMC Code Editor, navigate to the symbol that should be activatedfor Historical Access and add these parameters to the “Optional properties” section of the symbol properties.Please also make sure to activate the checkbox “Create symbol”:

Display of Historical Access values in an OPC-UA ClientThe following example is based on the above PLC program, which is also available as a download in thesample section of this documentation. Furthermore a ServerConfig.xml file configured for Historical Access isrequired; see Step 1 above. Please carry out the following steps:

1. Open the PLC program in the TwinCAT XAE by creating a new TwinCAT solution and importing thetpzip file into it as a PLC project.

2. Activate the TMC/TPY download in the PLC project properties3. Activate the configuration

ð The OPC-UA Server now collects symbol values with the specified parameters (storage medium,sampling rate, buffer length). You can then display these data with an OPC-UA Client that supportsHistorical Access, for example with the help of the UA-Expert software from Unified Automation. The following tests were carried out with UA-Expert version 1.2.0.132.

4. Make sure that your system meets the requirements (see beginning of article)

TF6100 TC3 OPC-UA50 Version: 2.2

Page 51: Manual TF6100 TC3 OPC-UA

Configuration

5. Start the “UA-Expert” software and connect to the OPC-UA Server

TF6100 TC3 OPC-UA 51Version: 2.2

Page 52: Manual TF6100 TC3 OPC-UA

Configuration

6. Add a new “History Trend View”

7. Browse to the PLC1 namespace and add the PLC variables _HistoryDB, _HistoryDBcompact,_HistoryFast and _HistorySlowPersist by drag & drop.

TF6100 TC3 OPC-UA52 Version: 2.2

Page 53: Manual TF6100 TC3 OPC-UA

Configuration

8. You can now set the desired period of the symbol values to be displayed using the StartTime andEndTime control elements, or if necessary start a CyclicUpdate for these variables.

At this point it should be pointed out once again that certain requirements apply to the use of a databasestorage medium, which were described at the beginning of this article.

4.1.3.3 Alarms & Conditions

This article describes the steps necessary to configure OPC-UA Alarms & Conditions (A&C) on the TwinCATOPC-UA Server. The concept behind is independent of the TwinCAT Runtime and therefore involves thesame configuration steps, no matter if a PLC, C++, or TcCOM Runtime or simply an I/O-Task is used.

OPC-UA Alarms & Conditions (part 9 of the OPC-UA specification) describes a model for monitoring processvalues and sending out alarms and events on status changes of a runtime symbol. The use

PrerequisitesThe following prerequisites apply to the use of Alarms & Conditions:

• The runtime symbols that should be monitored need to be available in the namespace (comparedocumentation article on “Runtime Access” topic)

• The OPC-UA Client needs to support Alarms & Conditions. In this documentation article, the UA-Expert(by Unified Automation) is used as a reference UA-Client.

TF6100 TC3 OPC-UA 53Version: 2.2

Page 54: Manual TF6100 TC3 OPC-UA

Configuration

GeneralThe following steps must be executed once in order to enable a symbol for A&C:

• Activation of a Runtime symbol for Data Access (to make the symbol generally available via OPC-UA)• Activation of Alarms & Conditions for a symbol• Sending custom user data with an event• Firing an event via FireEvent() method• Configuration of multi-language alarm texts• Subscribing to A&C with a reference OPC-UA Client

These steps are described in more detail below. At the end you will find further information on how to receiveconfigured alarms via A&C by using the UA-Expert reference client.

Supported Alarm TypesThe TwinCAT OPC-UA A&C implementation currently supports the following alarm types:

• LimitAlarmType: Define different limits for a symbol. If a limit is reached, the UA-Server sends out analarm.

• OffNormalAlarmType: Define a value that is considered as “normal”. If the current value differs from the“normal” value, the UA-Server sends out an alarm.

Activation of a Runtime symbol for Data AccessThis topic is briefly described in our documentation articles about how to generally make a runtime symbolavailable via OPC-UA.

Activation of Alarms & Conditions for a symbolTo easily configure a runtime symbol for A&C, the A&C configurator can be used. This configurator toolprovides an easy to use graphical user interface to edit the XML file behind. The following snippet shows asample of this XML file to better understand the overall behavior and design of the A&C implementation.<TcUaAcConfig>  <ConditionController Name="ConditionController1" >    <Condition Name="Counter" Severity="200">    <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter1" />    </Condition>    <Condition Name="Switch" Severity="500">      <OffNormalAlarmType Normal="0" MessageNormal="100" MessageOffNormal="20" />      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.bSwitch" />    </Condition>    <Condition Name="Struct" Severity="300">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.stStruct" />    </Condition>          </ConditionController>  <ConditionController Name="ConditionController2" >    <Condition Name="Counter2" Severity="200">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter2" />    </Condition>  </ConditionController></TcUaAcConfig>

A “Condition” defines the runtime symbol that should be monitored and also the alarm limits and alarm texts.Every “Condition” is organized in a so-called “ConditionController”, which is the object that OPC-UA Clientslater subscribe to.

TF6100 TC3 OPC-UA54 Version: 2.2

Page 55: Manual TF6100 TC3 OPC-UA

Configuration

When creating a Condition, the NamespaceName (NS) and NodeID need to be specified to reference the UAnode that should be monitored. The configurator tool provides an easy graphical browsing mechanism tochoose a node. In the XML, the wildcard “[NodeName]” may be used in the NamespaceName to easily movethe XML file between two different hardware systems. Remember: The NamespaceName always includesthe hostname of the IPC or Embedded PC that the OPC-UA Server runs on. When choosing “[NodeName]”this tag is replaced with the hostname of the actual IPC or Embedded PC that the UA Server runs on.

The SamplingRate specifies how often the UA-Server should sample a value from the node to determine ifone of the alarm limits has been reached.

Alarm texts are identified by an ID. The ID uniquely identifies an alarm text in its resource file, which isexplained in the following chapter.

Sending custom user data with an alarmAlarms may include custom user data fields that can extend the data that is send out with the alarm. Theseuser data fields can be created and filled with content from within the Runtime application by creating aSTRUCT which first element is named “value”. During an alarm, all following elements are then send out inan additional user data field. Example PLC application:TYPE ST_CustomStruct :STRUCT  value : INT;  data  : ST_SomeStruct;END_STRUCTEND_TYPE

TYPE ST_SomeStruct :STRUCT  Data1 : INT;  Data2 : REAL;  Data3 : LREAL;END_STRUCTEND_TYPE

The instance of ST_CustomStruct is then activated for Data Access by our regular mechanisms, e.g. inTwinCAT 3:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  stCustomStruct : ST_CustomStruct;END_VAR

When subscribing to a ConditionController, OPC-UA Clients need to subscribe to specialAlarmConditionTypes called “BkUaLimitAlarmType” and “BkUaOffNormalAlarmType” in order to be able toreceive the special user data fields when an alarm arrives.

TF6100 TC3 OPC-UA 55Version: 2.2

Page 56: Manual TF6100 TC3 OPC-UA

Configuration

The OPC-UA Client then receives the custom user data in the fields “BkUaEventData” and“BkUaEventValue” of the incoming alarm. In the example from above, this is the value of the PLC variable aswell as the user data that is represented by the PLC struct “ST_SomeStruct”.

Firing an event via FireEvent() methodEvery ConditionController includes a method FireEvent() which enables OPC-UA Clients to fire a genericevent including custom EventFields.

TF6100 TC3 OPC-UA56 Version: 2.2

Page 57: Manual TF6100 TC3 OPC-UA

Configuration

When executing this method, an event is thrown on the TwinCAT OPC-UA Server. Other OPC-UA Clientscan receive these events when subscribing to the corresponding ConditionController.

The custom EventFields are attached to the event as “UserEventData”. This data can be received by theOPC-UA Client that subscribes to the SimpleEventType “UserEventType”.

TF6100 TC3 OPC-UA 57Version: 2.2

Page 58: Manual TF6100 TC3 OPC-UA

Configuration

Configuration of multi-language alarm textsThe A&C implementation in the TwinCAT OPC-UA Server supports the use of multi-language alarm texts.Depending on the language that a UA-Client connects to the Server, another alarm text is used. Alarm textsare configured in XML files in which each language is represented by an own file. All these files are locatedin the “res” (resource) folder of the TwinCAT OPC-UA Server. The Configurator can be used to add orremove alarm texts in a convenient way without the need to edit the XML files directly.

Every alarm text is identified by an ID, which is unique for the whole file. Example:<TcOpcUaSvrRes Lang="en">  <Text ID="0">Text not available</Text>  <Text ID="1">Some alarm text</Text>      <Text ID="2">Value is High range</Text>  <Text ID="3">Value is HighHigh range</Text>  <Text ID="4">Value is OffNormal</Text>  ...</TcOpcUaSvrRes>

Subscribing to A&C with a reference OPC-UA ClientAn OPC-UA Client needs to create a subscription to one of the ConditionControllers in order to be able toreceive events for Conditions that are configured for this particular ConditionController. The UA-Expertprovides functionalities to subscribe to and receive UA events. After UA-Expert has been started and aconnection to the TwinCAT OPC-UA Server has been established, please add a new document view called“Event View” to your workspace.

You can then subscribe to a ConditionController by dragging the corresponding object to the EventView. Theevents for this ConditionController are then shown in the “Event Window”.

Please note that you might need to subscribe to special alarm and/or event types in order to be able toreceive all fields of an incoming event or alarm. Please follow the instructions in this document whichdemonstrate how to do so.

TF6100 TC3 OPC-UA58 Version: 2.2

Page 59: Manual TF6100 TC3 OPC-UA

Configuration

4.1.3.4 Method Call

Method calls are a very basic part of the OPC-UA specification. By now introducing these functionalities intothe PLC world, TwinCAT 3 provides customers with a very efficient way of executing RPC calls into theIEC61131 world and thus reduces classic communication handshake patterns between devices. TheTwinCAT OPC-UA Server imports PLC methods as OPC-UA methods via its TMC import.

Please note that, although the PLC method seems to be just a regular method in UA namespace, it is still anIEC61131 method that is executed within the realtime context - and therefore falls under the context of arealtime task! The PLC developer therefore needs to take precautions that the method execution time fitsinto the task cycle time!

Methods in IEC61131-3Methods in the IEC61131 world are always configured below a functionblock. Speaking in high-levellanguage terms, the functionblock can be seen as the sorrounding class of the method. The method itselfneeds to be declared with a special PLC attribute so that the TwinCAT system nows that the method shouldbe activated for a remote method call.{attribute ‘TcRpcEnable’:=’1’}METHOD M_Sum : INTVAR_INPUT  a : INT;  b : INT;END_VAR

Filtered or unfiltered modeDepending on which import mode is being used, the sorrounding functionblock needs to be enabled forOPC-UA access as well. This can be done by using the regular PLC attributes for OPC-UA access, asdescribed in other parts of this documentation.

Example: The method M_Sum is located in a functionblock FB_Mathematics. The declaration of thefunctionblock instance uses the PLC attribute that enabled the functionblock - and therefore the method aswell - for OPC-UA access.PROGRAM MAINVAR  {attribute ‘OPC.UA.DA’:=’1’}  fbMathematics : FB_Mathematics;END_VAR

Please note that you are only required to use the PLC attributes if the filtered mode is used to enablesymbols from the PLC for OPC-UA access. This is the default setting of the OPC-UA Server.

TF6100 TC3 OPC-UA 59Version: 2.2

Page 60: Manual TF6100 TC3 OPC-UA

Configuration

4.1.3.5 Type system

One of the biggest advantages of OPC-UA is the Meta-Modell, which is used to provide pre-defined types aswell as expand the type system with own models. The same mechanisms are used to represent the actualobjects (nodes) thus OPC-UA Clients can determine a type of a object.

The TwinCAT 3 OPC-UA Server publishes type information from the IEC61131 world into its namespace.This not only includes basic types such as BOOL, INT, DINT or REAL but also enhanced type informationsuch as the actual class (functionblock) or structure that an object represents.

Location of type informationType information is part of the UA namespace. The TwinCAT OPC-UA Server expands the base typeinformation as follows:

Local type information (that is valid for one runtime only) is stored in the same namespace as the runtimesymbols.

Global type information (that may be valid via several runtimes) is stored in an own global namespace.

The type system is also visually available and can be seen in the Types section of the OPC-UA Server:

Every non-standard data type is shown below the BeckhoffCtrlTypes section.

BasicsLet’s assume that the TwinCAT 3 PLC consists of a PLC program with several STRUCTs. Each STRUCT isrepresented as a node in UA namespace, with each element of the structure a child node.

TF6100 TC3 OPC-UA60 Version: 2.2

Page 61: Manual TF6100 TC3 OPC-UA

Configuration

In the example from above, the STRUCT stSampleStruct consists of three child elements: a variablenValue1 of type INT, a variable bValue2 of type BOOL and another STRUCT stSubStruct which just includesone child element – a variable nValue of type INT.

The structure itself is just a regular variable in UA namespace, which has the data type ByteString. Clientscan therefore easily connect to the root element (the structure itself) and read/write its values by interpretingthe ByteString. To make an interpretation of each child element easier, the type system includes moreinformation about the structure itself, first of all in the references of the instance:

Then, the type system includes more information about ST_SampleStruct:

And in the references of ST_SampleStruct:

TF6100 TC3 OPC-UA 61Version: 2.2

Page 62: Manual TF6100 TC3 OPC-UA

Configuration

As a matter of fact, if a client wants to read the ByteString representation of a structure root node, the typesystem can provide very useful information about how to interpret each position of the ByteString. In theexample from above, the client actually “sees” that the first byte of ST_SampleStruct represents a BOOLvariable, the second and third bytes represent an INT variable and the fourth and fifth bytes also represent avariable of data type INT.

Object-oriented-extensionsLet’s assume that the TwinCAT 3 PLC runtime includes a PLC program which structure can be visualized asfollows:

The two functionblocks Scanner and Drive are derived from the base class Device by using the object-oriented-extensions of the IEC61131-3. The MAIN program now includes the following declarations:PROGRAM MAINVAR  {attribute ‘OPC.UA.DA’:=’1’}  Scanner1 : Scanner;  {attribute ‘OPC.UA.DA’:=’1’}  Scanner2 : Scanner;  {attribute ‘OPC.UA.DA’:=’1’}  DriveX : Drive;END_VAR

All three objects are of type Device but also of their specialized data type. The OPC-UA Server now importsthe objects as follows:

TF6100 TC3 OPC-UA62 Version: 2.2

Page 63: Manual TF6100 TC3 OPC-UA

Configuration

The underlying data type can now be determined in the References of each object, e.g. object Scanner1:

Corresponding to the underlying IEC61131 program, the object Scanner1 is of data type Scanner, alsoshows which variables it includes and what kind of variable it is: An Input, Output or Internal (Local) variable.A quick look at the diagram from above shows that not only the variables from the actual functionblock areshown here but also the derived variables from the base class! The whole IEC61131-3 inheritance chain isrepresented in UA namespace.

4.1.3.6 Structured Types

Structured Types provide the functionality to read or write structures without the need to interpret each bytebecause the UA-Server returns the type information for each element of the structure. Sophisticated inmodern OPC-UA SDK’s enable OPC-UA Clients to browse and interpret this structural information.

Since version 2.2.x of the TwinCAT OPC-UA Server, structures from the TwinCAT 3 Runtime (TMC and TMIimport only) can be created as a StructuredType in UA namespace. Example:

Struct ST_Communication:TYPE ST_Communication :STRUCT  a : INT;  b : INT;  c : INT;END_STRUCTEND_TYPE

MAIN program:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  {attribute 'OPC.UA.DA.StructuredType' := '1'}  stCommunication : ST_Communication;END_VAR

TF6100 TC3 OPC-UA 63Version: 2.2

Page 64: Manual TF6100 TC3 OPC-UA

Configuration

Note

Filtered modeWhen using one of the filtered modes (as seen above) to make symbols available via OPC-UA, please note that a struct or function block needs to be made fully available in UAnamespace in order to be displayed as a StructuredDataType.

The instance “stCommunication” is then displayed as a StructuredType in UA namespace:

Alternatively, the PLC attribut may also be set on the struct definition to make all instances of the structavailable as a StructuredType.{attribute 'OPC.UA.DA.StructuredType' := '1'}TYPE ST_Communication :STRUCT  a : INT;  b : INT;  c : INT;END_STRUCTEND_TYPE

To deactivate the StructuredType on a specific instance, the following attribute may be used:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}

TF6100 TC3 OPC-UA64 Version: 2.2

Page 65: Manual TF6100 TC3 OPC-UA

Configuration

  {attribute 'OPC.UA.DA.StructuredType' := '0'}  stCommunication : ST_Communication;END_VAR

Function Block StructuredTypeIn addition, every function block from the TwinCAT 3 PLC, also includes a new child node called“FunctionBlock”, which contains the whole function block as a StructuredDataType. Example:

Function block:FUNCTION_BLOCK FB_FunctionBlockVAR_INPUT  Input1 : INT;   Input2 : LREAL;END_VARVAR_OUTPUT  Output1 : LREAL; END_VAR

Function block instance:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  {attribute 'OPC.UA.DA.StructuredType' := '1'}  fbFunctionBlock : FB_FunctionBlock; END_VAR

Instance of function block in OPC-UA namespace:

FunctionBlock node with StructuredDataType

Alternatively, the PLC attribut may also be set on the function block definition to make all instances of thefunction block available as a StructuredType.{attribute 'OPC.UA.DA.StructuredType' := '1'}FUNCTION_BLOCK FB_FunctionBlockVAR_INPUT  Input1 : INT;   Input2 : LREAL;END_VARVAR_OUTPUT  Output1 : LREAL; END_VAR

To deactivate the StructuredType on a specific instance, the following attribute may be used:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}

TF6100 TC3 OPC-UA 65Version: 2.2

Page 66: Manual TF6100 TC3 OPC-UA

Configuration

  {attribute 'OPC.UA.DA.StructuredType' := '0'}  fbFunctionBlock : FB_FunctionBlock; END_VAR

4.1.3.7 Use of arrays

By default arrays are regarded as individual nodes in the UA namespace. This means that if you define, forexample, an array dyn_BOOL[10] in the PLC (and have also enabled it for OPC-UA), it will subsequentlyappear in the UA namespace as follows:

The advantage of this approach is a considerable reduction in the complexity of the UA namespace AND inmemory consumption, since not every position of an array needs to be made available as an individual nodein the namespace. However, modern UA Clients can continue to access the individual array positions via theso-called “RangeOffset”.

In order to support older UA Clients that don’t offer this feature, however, you can also make the positions ofan array available as individual nodes in the UA namespace. That would then look like this:

This setting is made available by activating the “Legacy Array Handling” option in the UA configuratorwithin the respective namespace configuration (e.g. UaServer\UaServerConfig\Namespaces\PLC1).

Alternatively you can also manually edit the configuration file [} 107] and add the following nodes to it:

TF6100 TC3 OPC-UA66 Version: 2.2

Page 67: Manual TF6100 TC3 OPC-UA

Configuration

However, please note, that, depending on the scope of the PLC project, this will considerably increase thecomplexity of the UA namespace, which in turn is reflected by an increase in the use of memory of the UAServer.

Changes to the settings listed above only become active after restarting the UA Server.

4.1.3.8 List of attributes and comments

The configuration of runtime variables for the various OPC-UA functionalities (e.g. Data Access or HistoricalAccess) takes place directly from the PLC program or from within the TMC Code Editor (when usingTwinCAT 3 C++). The advantage of this is that a TwinCAT developer can decide, directly from the programcode with which he is familiar, whether and how a variable is to be activated for OPC-UA. Such an activationthen takes place by inserting a comment together with the appropriate OPC-UA tag before the variable, e.g.:

TwinCAT 3 PLC (TMC):{attribute 'OPC.UA.DA' := '1'}bVariable : BOOL;

TwinCAT 2 PLC (TPY):bVariable : BOOL; (*~ (OPC:1:available)*)

For a detailed description about how to use each attribute or comment, please consult the correspondingchapter about the runtime component that is being used (PLC, C++, I/O Task, ...).

The following table provides a summary of all definable tags and their meaning. Refer to the relevantsubsection of the respective feature for a detailed description of the functional principle.

TF6100 TC3 OPC-UA 67Version: 2.2

Page 68: Manual TF6100 TC3 OPC-UA

Configuration

Table 12: TwinCAT 3 (TMC):

OPC-UA feature PLC tag C++ TMC Code Editor(Optional Properties)

Meaning

Data Access (DA) {attribute 'OPC.UA.DA' :='0'}

Name: OPC.UA.DAValue: 0

Deactivates a variable forOPC-UA, as a result ofwhich it becomes invisiblein the UA namespace.

Data Access (DA) {attribute 'OPC.UA.DA' :='1'}

Name: OPC.UA.DAValue: 1

Activates a variable forOPC-UA, as a result ofwhich it becomes visible inthe UA namespace. Thistag must always be set if avariable is to be used forUA.

Data Access (DA) {attribute'OPC.UA.DA.Access' := 'x'}

Name: OPC.UA.DA.AccessValue: see right column

Sets Read/Write access fora variable, depending onthe parameter “x”0 = None1 = ReadOnly2 = WriteOnly3 = ReadWrite (default if tagis not used)

Data Access (DA) {attribute'OPC.UA.DA.StructuredType' := '0'}

Name:OPC.UA.DA.StructuredTypeValue: 0

Deactivates theStructuredType for a structor function block

Data Access (DA) {attribute'OPC.UA.DA.StructuredType' := '1'}

Name:OPC.UA.DA.StructuredTypeValue: 1

Activates theStructuredType for a structor function block

Historical Access(HA) [} 46]

{attribute 'OPC.UA.HA' :='1'}

Name: OPC.UA.HAValue: 1

Activates a variable for“Historical Access”. Needsto be used together with{attribute 'OPC.UA.DA' :='1'}.

Historical Access(HA) [} 46]

{attribute'OPC.UA.HA.Storage' := 'x'}

Name: OPC.UA.HA.StorageValue: see right column

Defines the storage locationfor Historical Access,depending on theparameter “x”1 = Memory2 = File3 = SQL CompactDatabase4 = SQL Server Database

Historical Access(HA) [} 46]

{attribute'OPC.UA.HA.Sampling' :='x'}

Name:OPC.UA.HA.SamplingValue: see right column

Defines the sampling ratewith which the variablevalues are to be saved,depending on theparameter “x” in [ms]

Historical Access(HA) [} 46]

{attribute'OPC.UA.HA.Buffer' := 'x'}

Name: OPC.UA.HA.BufferValue: see right column

Defines the maximumnumber of values to be heldin the data memory,depending on theparameter “x”

TF6100 TC3 OPC-UA68 Version: 2.2

Page 69: Manual TF6100 TC3 OPC-UA

Configuration

Table 13: TwinCAT 2 (TPY):

OPC-UA feature PLC tag MeaningData Access (DA) (*~ (OPC:0:not available) *) Deactivates a variable for OPC-UA, as

a result of which it becomes invisiblein the UA namespace.

Data Access (DA) (*~ (OPC:1:available) *) Activates a variable for OPC-UA, as aresult of which it becomes visible inthe UA namespace. This tag mustalways be set if a variable is to beused for UA.

Data Access (DA) (*~ (OPC_PROP[0005]:1:read-only) *) Sets Read-only access for a variable.Needs to be used together with (*~(OPC:1: available) *).

Data Access (DA) (*~ (OPC_UA_PROP[5100] : x : Aliasname) *)

Sets x as the node name in UAnamespace - so-called Alias mapping.

Historical Access (HA) [} 46] (*~ (OPC_UA_PROP[5000]:x:Storagemedia) *)

Activates a variable for “HistoricalAccess”. Needs to be used togetherwith (*~ (OPC:1: available) *). xdefines the storage media that shouldbe used to store the data values andcan be either of the following:1 = Memory2 = File3 = SQL Compact Database4 = SQL Server Database

Historical Access (HA) [} 46] (*~ (OPC_UA_PROP[5000][1]:x:SamplingRate) *)

Defines the sampling rate with whichthe variable values are to be saved,depending on the parameter “x” in[ms]

Historical Access (HA) [} 46] (*~ (OPC_UA_PROP[5000][2]:x:Buffer)*)

Defines the maximum number ofvalues to be held in the data memory,depending on the parameter “x”

4.1.3.9 Status Code

The TwinCAT OPC-UA Server enables to change the OPC-UA StatusCode from within a PLC application.To configure and influence the StatusCode of a variable, please perform the following steps:

Create a PLC structTo ensure data consistency, the concept of changing the OPC-UA StatusCode is based onStructuredDataTypes [} 63]. Every variable which UA StatusCode should be influenced needs to be wrappedby a struct. Create a new struct and add a PLC attribute in front of the struct definition.{attribute 'OPC.UA.DA.STATUS' := 'quality'}TYPE ST_StatusCodeOverride :STRUCT  value  : REAL;  quality: DINT;END_STRUCTEND_TYPE

The struct contains the variable itself and a variable of data type DINT that represents the StatusCode. Thisvariable is also referenced by its name in the attribute in front of the struct definition.

Now create an instance of this struct, e.g. in the program MAIN, and add the regular PLC attribute to makethis instance available via OPC-UA.

TF6100 TC3 OPC-UA 69Version: 2.2

Page 70: Manual TF6100 TC3 OPC-UA

Configuration

PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  stStatusCodeOverride : ST_StatusCodeOverride;END_VAR

This instance is now available in the OPC-UA namespace as a StructuredDataType.

Override the StatusCodeTo override the UA StatusCode for the struct, simply edit the value of variable “quality”. By setting it, forexample to “-2147155968“, the StatusCode of the struct changes to “BadCommunicationError”.

The value that has to be set is defined by the OPC-UA specification. The following table shows only some ofthe available status codes and their corresponding decimal representation. Please have a look at the officialOPC-UA specification for a more thorough list of status codes.

StatusCode Hex DecimalBadUnexpectedError 0x80010000 -2147418112BadInternalError 0x80020000 -2147352576BadCommunicationError 0x80050000 -2147155968BadTimeout 0x800A0000 -2146828288BadServiceNotSupported 0x800B0000 -2146762752

Note

UA StatusCodesWhen calculating other UA StatusCodes from their hexadecimal representation to decimal,please make sure that your calculator is set to DWORD, e.g. the Windows Calculator (“Pro-grammer” view).

NOTE!

TF6100 TC3 OPC-UA70 Version: 2.2

Page 71: Manual TF6100 TC3 OPC-UA

Configuration

4.1.4 C++

4.1.4.1 Access to C++ runtime

This part of the documentation describes how to configure the namespace of the OPC-UA Server in order toobtain access to symbols from a TwinCAT 3 C++ module. To do this you can either use OPC-UAConfigurator, or you can carry out the configuration directly and manually by using the ServerConfig.xml fileof the OPC-UA Server.

This article consists of the following topics:

• Step 1: Project-related settings• Step 2: Configuration of the UA-Server

Step 1: Project-related settingsTo configure specific symbols in a TwinCAT 3 C++ module instance to be made available via OPC-UA, thefollowing steps need to be made in the settings of the corresponding C++ module instance in TwinCAT XAE:

1. The OPC-UA Server requires the TMI symbol file, which by default is not transferred to the targetruntime. Activate the transfer by activating the following option:

ð The generated TMI-File is named after the ObjectId, e.g. “Obj_01010020.tmi” and stored in the Twin-CAT Boot directory, e.g. “C:\TwinCAT\Boot\Tmi\”.

TF6100 TC3 OPC-UA 71Version: 2.2

Page 72: Manual TF6100 TC3 OPC-UA

Configuration

2. In the next step, you need to select which symbols for the respective variables should be madeavailable by activating the checkbox “Create symbol” in the TMC-CodeGenerator. Please make sure toexecute the TMC-CodeGenerator afterwards:

Step 2: Configuration of the UA Server3. You can configure and parameterize access to TwinCAT 3 C++ modules conveniently using the OPC-

UA Configurator. To do this you must add a new device with the type “CPP TwinCAT 3 (TMI) filtered” inthe “Data Access” section.

4. The field “Symbol File” must point to the TMI-File that was being generated for the C++ moduleinstance, see steps above. These TMI-Files are located in the TwinCAT Boot directory, e.g. “C:\TwinCAT\Boot\Tmi\”, and are named after the ObjectId of the TwinCAT 3 C++ module instance.

The adjustable parameters describe the following functionalities:

TF6100 TC3 OPC-UA72 Version: 2.2

Page 73: Manual TF6100 TC3 OPC-UA

Configuration

Parameter Description Possible valuesADS Port Defines the ADS port under which the C++ module

instance is accessible. The ADS port can be read inthe features of the C++ task.

351352…

AutoCfg Initially defines the type of target runtime used forcommunication, e.g. PLC, C++, I/O. A furtherdistinction can then take place within these categories.Every AutoCfg option is available as an unfiltered anda filtered option. Filtered means that users can selectwhich C++ symbols should be published via OPC-UA.By using an unfiltered option, every C++ symbol will bepublished to OPC-UA.

4020 CPP TwinCAT 3(TMI)4021 CPP TwinCAT 3(TMI) filtered

AutoCfgSymFile Symbol file (TMI) of the respective C++ moduleinstance.

Path to the symbol file.(TMI)

IoMode Defines the method of accessing symbols. 1 (access via handle -default)

ArraySubItemLegacySupport

By default, subelements of an array are not mappedas separate nodes in the UA namespace. Instead, onlythe array is mapped as a single element.Nevertheless, UA clients can access subelements viatheir so-called ‘IndexRange. Some older OPC-UAclients unfortunately do not offer this support yet. Thisflag was introduced so that access can neverthelessbe enabled for these clients; the flag causes eacharray position to be displayed as a separate node inthe UA namespace. Caution: this leads to highermemory consumption of the OPC-UA Server!

0 (deactivated - default)1 (activated)

Disabled Deactivates the C++ module instance in the UAnamespace, as a result of which the correspondingnode is not displayed. We recommend the activation ofthis parameter if certain C++ runtimes are not yetavailable at the time of the project planning, e.g. if therespective devices are not yet connected to thenetwork.

0 (deactivated - default)1 (activated)

4.1.4.2 Alarms & Conditions

This article describes the steps necessary to configure OPC-UA Alarms & Conditions (A&C) on the TwinCATOPC-UA Server. The concept behind is independent of the TwinCAT Runtime and therefore involves thesame configuration steps, no matter if a PLC, C++, or TcCOM Runtime or simply an I/O-Task is used.

OPC-UA Alarms & Conditions (part 9 of the OPC-UA specification) describes a model for monitoring processvalues and sending out alarms and events on status changes of a runtime symbol. The use

PrerequisitesThe following prerequisites apply to the use of Alarms & Conditions:

• The runtime symbols that should be monitored need to be available in the namespace (comparedocumentation article on “Runtime Access” topic)

• The OPC-UA Client needs to support Alarms & Conditions. In this documentation article, the UA-Expert(by Unified Automation) is used as a reference UA-Client.

GeneralThe following steps must be executed once in order to enable a symbol for A&C:

• Activation of a Runtime symbol for Data Access (to make the symbol generally available via OPC-UA)• Activation of Alarms & Conditions for a symbol

TF6100 TC3 OPC-UA 73Version: 2.2

Page 74: Manual TF6100 TC3 OPC-UA

Configuration

• Sending custom user data with an event• Firing an event via FireEvent() method• Configuration of multi-language alarm texts• Subscribing to A&C with a reference OPC-UA Client

These steps are described in more detail below. At the end you will find further information on how to receiveconfigured alarms via A&C by using the UA-Expert reference client.

Supported Alarm TypesThe TwinCAT OPC-UA A&C implementation currently supports the following alarm types:

• LimitAlarmType: Define different limits for a symbol. If a limit is reached, the UA-Server sends out analarm.

• OffNormalAlarmType: Define a value that is considered as “normal”. If the current value differs from the“normal” value, the UA-Server sends out an alarm.

Activation of a Runtime symbol for Data AccessThis topic is briefly described in our documentation articles about how to generally make a runtime symbolavailable via OPC-UA.

Activation of Alarms & Conditions for a symbolTo easily configure a runtime symbol for A&C, the A&C configurator can be used. This configurator toolprovides an easy to use graphical user interface to edit the XML file behind. The following snippet shows asample of this XML file to better understand the overall behavior and design of the A&C implementation.<TcUaAcConfig>  <ConditionController Name="ConditionController1" >    <Condition Name="Counter" Severity="200">    <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter1" />    </Condition>    <Condition Name="Switch" Severity="500">      <OffNormalAlarmType Normal="0" MessageNormal="100" MessageOffNormal="20" />      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.bSwitch" />    </Condition>    <Condition Name="Struct" Severity="300">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.stStruct" />    </Condition>          </ConditionController>  <ConditionController Name="ConditionController2" >    <Condition Name="Counter2" Severity="200">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter2" />    </Condition>  </ConditionController></TcUaAcConfig>

A “Condition” defines the runtime symbol that should be monitored and also the alarm limits and alarm texts.Every “Condition” is organized in a so-called “ConditionController”, which is the object that OPC-UA Clientslater subscribe to.

When creating a Condition, the NamespaceName (NS) and NodeID need to be specified to reference the UAnode that should be monitored. The configurator tool provides an easy graphical browsing mechanism tochoose a node. In the XML, the wildcard “[NodeName]” may be used in the NamespaceName to easily movethe XML file between two different hardware systems. Remember: The NamespaceName always includesthe hostname of the IPC or Embedded PC that the OPC-UA Server runs on. When choosing “[NodeName]”this tag is replaced with the hostname of the actual IPC or Embedded PC that the UA Server runs on.

TF6100 TC3 OPC-UA74 Version: 2.2

Page 75: Manual TF6100 TC3 OPC-UA

Configuration

The SamplingRate specifies how often the UA-Server should sample a value from the node to determine ifone of the alarm limits has been reached.

Alarm texts are identified by an ID. The ID uniquely identifies an alarm text in its resource file, which isexplained in the following chapter.

Sending custom user data with an alarmAlarms may include custom user data fields that can extend the data that is send out with the alarm. Theseuser data fields can be created and filled with content from within the Runtime application by creating aSTRUCT which first element is named “value”. During an alarm, all following elements are then send out inan additional user data field. Example PLC application:TYPE ST_CustomStruct :STRUCT  value : INT;  data  : ST_SomeStruct;END_STRUCTEND_TYPE

TYPE ST_SomeStruct :STRUCT  Data1 : INT;  Data2 : REAL;  Data3 : LREAL;END_STRUCTEND_TYPE

The instance of ST_CustomStruct is then activated for Data Access by our regular mechanisms, e.g. inTwinCAT 3:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  stCustomStruct : ST_CustomStruct;END_VAR

When subscribing to a ConditionController, OPC-UA Clients need to subscribe to specialAlarmConditionTypes called “BkUaLimitAlarmType” and “BkUaOffNormalAlarmType” in order to be able toreceive the special user data fields when an alarm arrives.

The OPC-UA Client then receives the custom user data in the fields “BkUaEventData” and“BkUaEventValue” of the incoming alarm. In the example from above, this is the value of the PLC variable aswell as the user data that is represented by the PLC struct “ST_SomeStruct”.

TF6100 TC3 OPC-UA 75Version: 2.2

Page 76: Manual TF6100 TC3 OPC-UA

Configuration

Firing an event via FireEvent() methodEvery ConditionController includes a method FireEvent() which enables OPC-UA Clients to fire a genericevent including custom EventFields.

TF6100 TC3 OPC-UA76 Version: 2.2

Page 77: Manual TF6100 TC3 OPC-UA

Configuration

When executing this method, an event is thrown on the TwinCAT OPC-UA Server. Other OPC-UA Clientscan receive these events when subscribing to the corresponding ConditionController.

The custom EventFields are attached to the event as “UserEventData”. This data can be received by theOPC-UA Client that subscribes to the SimpleEventType “UserEventType”.

Configuration of multi-language alarm textsThe A&C implementation in the TwinCAT OPC-UA Server supports the use of multi-language alarm texts.Depending on the language that a UA-Client connects to the Server, another alarm text is used. Alarm textsare configured in XML files in which each language is represented by an own file. All these files are locatedin the “res” (resource) folder of the TwinCAT OPC-UA Server. The Configurator can be used to add orremove alarm texts in a convenient way without the need to edit the XML files directly.

Every alarm text is identified by an ID, which is unique for the whole file. Example:<TcOpcUaSvrRes Lang="en">  <Text ID="0">Text not available</Text>  <Text ID="1">Some alarm text</Text>      <Text ID="2">Value is High range</Text>  <Text ID="3">Value is HighHigh range</Text>  <Text ID="4">Value is OffNormal</Text>  ...</TcOpcUaSvrRes>

TF6100 TC3 OPC-UA 77Version: 2.2

Page 78: Manual TF6100 TC3 OPC-UA

Configuration

Subscribing to A&C with a reference OPC-UA ClientAn OPC-UA Client needs to create a subscription to one of the ConditionControllers in order to be able toreceive events for Conditions that are configured for this particular ConditionController. The UA-Expertprovides functionalities to subscribe to and receive UA events. After UA-Expert has been started and aconnection to the TwinCAT OPC-UA Server has been established, please add a new document view called“Event View” to your workspace.

You can then subscribe to a ConditionController by dragging the corresponding object to the EventView. Theevents for this ConditionController are then shown in the “Event Window”.

Please note that you might need to subscribe to special alarm and/or event types in order to be able toreceive all fields of an incoming event or alarm. Please follow the instructions in this document whichdemonstrate how to do so.

4.1.4.3 Method Call

Method calls are a very basic part of the OPC-UA specification. By now introducing these functionalities intothe PLC world, TwinCAT 3 provides customers with a very efficient way of executing RPC calls into the C++realtime context and thus reduces classic communication handshake patterns between devices. TheTwinCAT OPC-UA Server imports C++ methods as OPC-UA methods via its TMI import.

Please note that, although the C++ method seems to be just a regular method in UA namespace, it is still arealtime method that is executed within the realtime context - and therefore falls under the context of arealtime task! The TwinCAT C++ developer therefore needs to take precautions that the method executiontime fits into the task cycle time!

TF6100 TC3 OPC-UA78 Version: 2.2

Page 79: Manual TF6100 TC3 OPC-UA

Configuration

Methods in TwinCAT 3 C++TwinCAT modules (TcCOM Modules) could implement Interfaces, which have predefined Methods. Themethod itself needs to be enabled for RPC calls during their definition (see TwinCAT Module Class Wizarddocumentation) so that the OPC-UA Server knows that it is available for execution.

To also make the ReturnValue of the method available, the corresponding checkbox needs to be set. Pleasealso note that the interface, under which the method was created, needs to be implemented.

TF6100 TC3 OPC-UA 79Version: 2.2

Page 80: Manual TF6100 TC3 OPC-UA

Configuration

Filtered or unfiltered modeDepending on which import mode is being used, the method needs to be declared to be available for accessvia OPC-UA. This can be done by using the TMC Editor and by using the regular OPC-UA attributes asOptional Properties.

4.1.4.4 Structured Types

Structured Types provide the functionality to read or write structures without the need to interpret each bytebecause the UA-Server returns the type information for each element of the structure. Sophisticated inmodern OPC-UA SDK’s enable OPC-UA Clients to browse and interpret this structural information.

Since version 2.2.x of the TwinCAT OPC-UA Server, structures from the TwinCAT 3 Runtime (TMC and TMIimport only) can be created as a StructuredType in UA namespace. Example:

Struct ST_Communication:TYPE ST_Communication :STRUCT  a : INT;  b : INT;  c : INT;END_STRUCTEND_TYPE

MAIN program:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  {attribute 'OPC.UA.DA.StructuredType' := '1'}  stCommunication : ST_Communication;END_VAR

Note

Filtered modeWhen using one of the filtered modes (as seen above) to make symbols available via OPC-UA, please note that a struct or function block needs to be made fully available in UAnamespace in order to be displayed as a StructuredDataType.

The instance “stCommunication” is then displayed as a StructuredType in UA namespace:

TF6100 TC3 OPC-UA80 Version: 2.2

Page 81: Manual TF6100 TC3 OPC-UA

Configuration

Alternatively, the PLC attribut may also be set on the struct definition to make all instances of the structavailable as a StructuredType.{attribute 'OPC.UA.DA.StructuredType' := '1'}TYPE ST_Communication :STRUCT  a : INT;  b : INT;  c : INT;END_STRUCTEND_TYPE

To deactivate the StructuredType on a specific instance, the following attribute may be used:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  {attribute 'OPC.UA.DA.StructuredType' := '0'}  stCommunication : ST_Communication;END_VAR

Function Block StructuredTypeIn addition, every function block from the TwinCAT 3 PLC, also includes a new child node called“FunctionBlock”, which contains the whole function block as a StructuredDataType. Example:

TF6100 TC3 OPC-UA 81Version: 2.2

Page 82: Manual TF6100 TC3 OPC-UA

Configuration

Function block:FUNCTION_BLOCK FB_FunctionBlockVAR_INPUT  Input1 : INT;   Input2 : LREAL;END_VARVAR_OUTPUT  Output1 : LREAL; END_VAR

Function block instance:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  {attribute 'OPC.UA.DA.StructuredType' := '1'}  fbFunctionBlock : FB_FunctionBlock; END_VAR

Instance of function block in OPC-UA namespace:

FunctionBlock node with StructuredDataType

Alternatively, the PLC attribut may also be set on the function block definition to make all instances of thefunction block available as a StructuredType.{attribute 'OPC.UA.DA.StructuredType' := '1'}FUNCTION_BLOCK FB_FunctionBlockVAR_INPUT  Input1 : INT;   Input2 : LREAL;END_VARVAR_OUTPUT  Output1 : LREAL; END_VAR

To deactivate the StructuredType on a specific instance, the following attribute may be used:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  {attribute 'OPC.UA.DA.StructuredType' := '0'}  fbFunctionBlock : FB_FunctionBlock; END_VAR

TF6100 TC3 OPC-UA82 Version: 2.2

Page 83: Manual TF6100 TC3 OPC-UA

Configuration

4.1.4.5 List of attributes and comments

The configuration of runtime variables for the various OPC-UA functionalities (e.g. Data Access or HistoricalAccess) takes place directly from the PLC program or from within the TMC Code Editor (when usingTwinCAT 3 C++). The advantage of this is that a TwinCAT developer can decide, directly from the programcode with which he is familiar, whether and how a variable is to be activated for OPC-UA. Such an activationthen takes place by inserting a comment together with the appropriate OPC-UA tag before the variable, e.g.:

TwinCAT 3 PLC (TMC):{attribute 'OPC.UA.DA' := '1'}bVariable : BOOL;

TwinCAT 2 PLC (TPY):bVariable : BOOL; (*~ (OPC:1:available)*)

For a detailed description about how to use each attribute or comment, please consult the correspondingchapter about the runtime component that is being used (PLC, C++, I/O Task, ...).

The following table provides a summary of all definable tags and their meaning. Refer to the relevantsubsection of the respective feature for a detailed description of the functional principle.

TF6100 TC3 OPC-UA 83Version: 2.2

Page 84: Manual TF6100 TC3 OPC-UA

Configuration

Table 14: TwinCAT 3 (TMC):

OPC-UA feature PLC tag C++ TMC Code Editor(Optional Properties)

Meaning

Data Access (DA) {attribute 'OPC.UA.DA' :='0'}

Name: OPC.UA.DAValue: 0

Deactivates a variable forOPC-UA, as a result ofwhich it becomes invisiblein the UA namespace.

Data Access (DA) {attribute 'OPC.UA.DA' :='1'}

Name: OPC.UA.DAValue: 1

Activates a variable forOPC-UA, as a result ofwhich it becomes visible inthe UA namespace. Thistag must always be set if avariable is to be used forUA.

Data Access (DA) {attribute'OPC.UA.DA.Access' := 'x'}

Name: OPC.UA.DA.AccessValue: see right column

Sets Read/Write access fora variable, depending onthe parameter “x”0 = None1 = ReadOnly2 = WriteOnly3 = ReadWrite (default if tagis not used)

Data Access (DA) {attribute'OPC.UA.DA.StructuredType' := '0'}

Name:OPC.UA.DA.StructuredTypeValue: 0

Deactivates theStructuredType for a structor function block

Data Access (DA) {attribute'OPC.UA.DA.StructuredType' := '1'}

Name:OPC.UA.DA.StructuredTypeValue: 1

Activates theStructuredType for a structor function block

Historical Access(HA) [} 46]

{attribute 'OPC.UA.HA' :='1'}

Name: OPC.UA.HAValue: 1

Activates a variable for“Historical Access”. Needsto be used together with{attribute 'OPC.UA.DA' :='1'}.

Historical Access(HA) [} 46]

{attribute'OPC.UA.HA.Storage' := 'x'}

Name: OPC.UA.HA.StorageValue: see right column

Defines the storage locationfor Historical Access,depending on theparameter “x”1 = Memory2 = File3 = SQL CompactDatabase4 = SQL Server Database

Historical Access(HA) [} 46]

{attribute'OPC.UA.HA.Sampling' :='x'}

Name:OPC.UA.HA.SamplingValue: see right column

Defines the sampling ratewith which the variablevalues are to be saved,depending on theparameter “x” in [ms]

Historical Access(HA) [} 46]

{attribute'OPC.UA.HA.Buffer' := 'x'}

Name: OPC.UA.HA.BufferValue: see right column

Defines the maximumnumber of values to be heldin the data memory,depending on theparameter “x”

TF6100 TC3 OPC-UA84 Version: 2.2

Page 85: Manual TF6100 TC3 OPC-UA

Configuration

Table 15: TwinCAT 2 (TPY):

OPC-UA feature PLC tag MeaningData Access (DA) (*~ (OPC:0:not available) *) Deactivates a variable for OPC-UA, as

a result of which it becomes invisiblein the UA namespace.

Data Access (DA) (*~ (OPC:1:available) *) Activates a variable for OPC-UA, as aresult of which it becomes visible inthe UA namespace. This tag mustalways be set if a variable is to beused for UA.

Data Access (DA) (*~ (OPC_PROP[0005]:1:read-only) *) Sets Read-only access for a variable.Needs to be used together with (*~(OPC:1: available) *).

Data Access (DA) (*~ (OPC_UA_PROP[5100] : x : Aliasname) *)

Sets x as the node name in UAnamespace - so-called Alias mapping.

Historical Access (HA) [} 46] (*~ (OPC_UA_PROP[5000]:x:Storagemedia) *)

Activates a variable for “HistoricalAccess”. Needs to be used togetherwith (*~ (OPC:1: available) *). xdefines the storage media that shouldbe used to store the data values andcan be either of the following:1 = Memory2 = File3 = SQL Compact Database4 = SQL Server Database

Historical Access (HA) [} 46] (*~ (OPC_UA_PROP[5000][1]:x:SamplingRate) *)

Defines the sampling rate with whichthe variable values are to be saved,depending on the parameter “x” in[ms]

Historical Access (HA) [} 46] (*~ (OPC_UA_PROP[5000][2]:x:Buffer)*)

Defines the maximum number ofvalues to be held in the data memory,depending on the parameter “x”

4.1.5 I/O

4.1.5.1 Access to IO task

This article describes how IO task variables can be made accessible via the Data Access functionalities ofthe OPC-UA Server.

In order to make IO variables available via OPC-UA, two steps must be configured once only:

• Step 1: configuration of the TwinCAT IO task in order to enable the symbol handling• Step 2: configuration of the OPC-UA Server in order to integrate the IO task into the OPC-UA

namespace

General informationVariables from a Task with Process Image can be published via OPC-UA.

TF6100 TC3 OPC-UA 85Version: 2.2

Page 86: Manual TF6100 TC3 OPC-UA

Configuration

Several parameters are available that affect the way in which the variables are displayed and howcommunication with them takes place. These parameters can be conveniently set using the OPC-UAConfigurator. Alternatively you can also set them directly in the ServerConfig.xml configuration file. Thefollowing table provides an overview of all the parameters that are relevant when accessing the I/O task.

Parameter Description Possible valuesADS Port Defines the ADS port under which the I/O Task

is accessible. The ADS port can be read in theproperties of the I/O Task.

301302…

AutoCfg Initially defines the type of target runtime usedfor communication, e.g. PLC, C++, I/O. A furtherdistinction can then take place within thesecategories. Every AutoCfg option is available asan unfiltered and a filtered option. Filtered meansthat users can select which I/O variable shouldbe published to OPC-UA via comments. Byusing an unfiltered option, every task variable willbe published to OPC-UA.

107 I/O TwinCAT 2/3108 I/O TwinCAT 2/3 filtered

AutoCfgSymFile Specifies the path to CurrentConfig.xml, whichusually resides in C:\TwinCAT\3.1\Boot\

Path to CurrentConfig.xml

Disabled Deactivates the I/O task in the UA namespace,as a result of which the corresponding node isnot displayed. We recommend the activation ofthis parameter if certain runtimes are not yetavailable at the time of the project planning, e.g.if the respective devices are not yet connected tothe network.

0 (deactivated - default)1 (activated)

The following steps demonstrate how variables from the I/O task can be imported into the UA namespaceand what steps are necessary for this. It is assumed here that the OPC-UA Server and the runtime are onthe same computer.

Step 1: Configure TwinCAT I/O task in order to enable the symbol handlingOpen the I/O Task settings and activate the “Create symbols” option. At this point please also make a note ofthe ADS Port of the I/O task (which is 301 in the example).

TwinCAT 3:

TF6100 TC3 OPC-UA86 Version: 2.2

Page 87: Manual TF6100 TC3 OPC-UA

Configuration

TwinCAT 2:

Step 2: Add I/O Task to the OPC-UA namespaceIn the next step you have to configure the OPC-UA server so that it provides access to the I/O task. Usingthe OPC-UA Configurator, please add a new “IO TwinCAT 2/3” device and configure its settings forAdsNetId, AdsPort and SymbolFile (path to CurrentConfig.xml).

After setting the appropriate properties, please restart the OPC-UA Server for the changes to become active.

TF6100 TC3 OPC-UA 87Version: 2.2

Page 88: Manual TF6100 TC3 OPC-UA

Configuration

4.1.5.2 Alarms & Conditions

This article describes the steps necessary to configure OPC-UA Alarms & Conditions (A&C) on the TwinCATOPC-UA Server. The concept behind is independent of the TwinCAT Runtime and therefore involves thesame configuration steps, no matter if a PLC, C++, or TcCOM Runtime or simply an I/O-Task is used.

OPC-UA Alarms & Conditions (part 9 of the OPC-UA specification) describes a model for monitoring processvalues and sending out alarms and events on status changes of a runtime symbol. The use

PrerequisitesThe following prerequisites apply to the use of Alarms & Conditions:

• The runtime symbols that should be monitored need to be available in the namespace (comparedocumentation article on “Runtime Access” topic)

• The OPC-UA Client needs to support Alarms & Conditions. In this documentation article, the UA-Expert(by Unified Automation) is used as a reference UA-Client.

GeneralThe following steps must be executed once in order to enable a symbol for A&C:

• Activation of a Runtime symbol for Data Access (to make the symbol generally available via OPC-UA)• Activation of Alarms & Conditions for a symbol• Sending custom user data with an event• Firing an event via FireEvent() method• Configuration of multi-language alarm texts• Subscribing to A&C with a reference OPC-UA Client

These steps are described in more detail below. At the end you will find further information on how to receiveconfigured alarms via A&C by using the UA-Expert reference client.

Supported Alarm TypesThe TwinCAT OPC-UA A&C implementation currently supports the following alarm types:

• LimitAlarmType: Define different limits for a symbol. If a limit is reached, the UA-Server sends out analarm.

• OffNormalAlarmType: Define a value that is considered as “normal”. If the current value differs from the“normal” value, the UA-Server sends out an alarm.

Activation of a Runtime symbol for Data AccessThis topic is briefly described in our documentation articles about how to generally make a runtime symbolavailable via OPC-UA.

Activation of Alarms & Conditions for a symbolTo easily configure a runtime symbol for A&C, the A&C configurator can be used. This configurator toolprovides an easy to use graphical user interface to edit the XML file behind. The following snippet shows asample of this XML file to better understand the overall behavior and design of the A&C implementation.<TcUaAcConfig>  <ConditionController Name="ConditionController1" >    <Condition Name="Counter" Severity="200">    <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter1" />    </Condition>    <Condition Name="Switch" Severity="500">      <OffNormalAlarmType Normal="0" MessageNormal="100" MessageOffNormal="20" />      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.bSwitch" />    </Condition>

TF6100 TC3 OPC-UA88 Version: 2.2

Page 89: Manual TF6100 TC3 OPC-UA

Configuration

    <Condition Name="Struct" Severity="300">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.stStruct" />    </Condition>          </ConditionController>  <ConditionController Name="ConditionController2" >    <Condition Name="Counter2" Severity="200">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter2" />    </Condition>  </ConditionController></TcUaAcConfig>

A “Condition” defines the runtime symbol that should be monitored and also the alarm limits and alarm texts.Every “Condition” is organized in a so-called “ConditionController”, which is the object that OPC-UA Clientslater subscribe to.

When creating a Condition, the NamespaceName (NS) and NodeID need to be specified to reference the UAnode that should be monitored. The configurator tool provides an easy graphical browsing mechanism tochoose a node. In the XML, the wildcard “[NodeName]” may be used in the NamespaceName to easily movethe XML file between two different hardware systems. Remember: The NamespaceName always includesthe hostname of the IPC or Embedded PC that the OPC-UA Server runs on. When choosing “[NodeName]”this tag is replaced with the hostname of the actual IPC or Embedded PC that the UA Server runs on.

The SamplingRate specifies how often the UA-Server should sample a value from the node to determine ifone of the alarm limits has been reached.

Alarm texts are identified by an ID. The ID uniquely identifies an alarm text in its resource file, which isexplained in the following chapter.

Sending custom user data with an alarmAlarms may include custom user data fields that can extend the data that is send out with the alarm. Theseuser data fields can be created and filled with content from within the Runtime application by creating aSTRUCT which first element is named “value”. During an alarm, all following elements are then send out inan additional user data field. Example PLC application:TYPE ST_CustomStruct :STRUCT  value : INT;  data  : ST_SomeStruct;END_STRUCTEND_TYPE

TYPE ST_SomeStruct :STRUCT  Data1 : INT;  Data2 : REAL;  Data3 : LREAL;END_STRUCTEND_TYPE

The instance of ST_CustomStruct is then activated for Data Access by our regular mechanisms, e.g. inTwinCAT 3:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  stCustomStruct : ST_CustomStruct;END_VAR

When subscribing to a ConditionController, OPC-UA Clients need to subscribe to specialAlarmConditionTypes called “BkUaLimitAlarmType” and “BkUaOffNormalAlarmType” in order to be able toreceive the special user data fields when an alarm arrives.

TF6100 TC3 OPC-UA 89Version: 2.2

Page 90: Manual TF6100 TC3 OPC-UA

Configuration

The OPC-UA Client then receives the custom user data in the fields “BkUaEventData” and“BkUaEventValue” of the incoming alarm. In the example from above, this is the value of the PLC variable aswell as the user data that is represented by the PLC struct “ST_SomeStruct”.

Firing an event via FireEvent() methodEvery ConditionController includes a method FireEvent() which enables OPC-UA Clients to fire a genericevent including custom EventFields.

TF6100 TC3 OPC-UA90 Version: 2.2

Page 91: Manual TF6100 TC3 OPC-UA

Configuration

When executing this method, an event is thrown on the TwinCAT OPC-UA Server. Other OPC-UA Clientscan receive these events when subscribing to the corresponding ConditionController.

The custom EventFields are attached to the event as “UserEventData”. This data can be received by theOPC-UA Client that subscribes to the SimpleEventType “UserEventType”.

TF6100 TC3 OPC-UA 91Version: 2.2

Page 92: Manual TF6100 TC3 OPC-UA

Configuration

Configuration of multi-language alarm textsThe A&C implementation in the TwinCAT OPC-UA Server supports the use of multi-language alarm texts.Depending on the language that a UA-Client connects to the Server, another alarm text is used. Alarm textsare configured in XML files in which each language is represented by an own file. All these files are locatedin the “res” (resource) folder of the TwinCAT OPC-UA Server. The Configurator can be used to add orremove alarm texts in a convenient way without the need to edit the XML files directly.

Every alarm text is identified by an ID, which is unique for the whole file. Example:<TcOpcUaSvrRes Lang="en">  <Text ID="0">Text not available</Text>  <Text ID="1">Some alarm text</Text>      <Text ID="2">Value is High range</Text>  <Text ID="3">Value is HighHigh range</Text>  <Text ID="4">Value is OffNormal</Text>  ...</TcOpcUaSvrRes>

Subscribing to A&C with a reference OPC-UA ClientAn OPC-UA Client needs to create a subscription to one of the ConditionControllers in order to be able toreceive events for Conditions that are configured for this particular ConditionController. The UA-Expertprovides functionalities to subscribe to and receive UA events. After UA-Expert has been started and aconnection to the TwinCAT OPC-UA Server has been established, please add a new document view called“Event View” to your workspace.

You can then subscribe to a ConditionController by dragging the corresponding object to the EventView. Theevents for this ConditionController are then shown in the “Event Window”.

TF6100 TC3 OPC-UA92 Version: 2.2

Page 93: Manual TF6100 TC3 OPC-UA

Configuration

Please note that you might need to subscribe to special alarm and/or event types in order to be able toreceive all fields of an incoming event or alarm. Please follow the instructions in this document whichdemonstrate how to do so.

4.1.6 Matlab/Simulink

4.1.6.1 Access to Matlab/Simulink modules

The TwinCAT OPC-UA Server provides the functionality to use TwinCAT 3 TMI files to build its namespace.TMI files are generated by TcCOM modules and therefore for example TwinCAT 3 C++ module instancesand also Matlab/Simulink module instances.

TMI Import for TcCOM ModulesThe import of TMI files can be configured in the TwinCAT OPC-UA Configurator. To enable the generation ofa TMI file and let TwinCAT automatically copy the TMI file to the target system, please enable the option“Copy TMI to Target” in the settings of the TcCOM module:

TF6100 TC3 OPC-UA 93Version: 2.2

Page 94: Manual TF6100 TC3 OPC-UA

Configuration

The target’s boot directory will then include the TMI file for the TcCOM module, which in turn can be importedinto the OPC-UA namespace by using the OPC-UA Configurator:

The configured OPC-UA namespace will then include a representation of the Matlab/Simulink block diagram.

TF6100 TC3 OPC-UA94 Version: 2.2

Page 95: Manual TF6100 TC3 OPC-UA

Configuration

Filtered or unfiltered modePlease note that there is currently no filtered mode for generic TcCOM module instances. The filtered modeis only possible for TwinCAT 3 C++ module instances when using the TMC Code Editor. The TwinCATMatlab/Simulink integration provides some filtering possibilities that are described here.

If a generic TcCOM module instance (e.g. a Matlab/Simulink module) should be imported, the unfilteredoption needs to be used and therefore all symbols from the module are published into the OPC-UAnamespace.

4.1.6.2 Alarms & Conditions

This article describes the steps necessary to configure OPC-UA Alarms & Conditions (A&C) on the TwinCATOPC-UA Server. The concept behind is independent of the TwinCAT Runtime and therefore involves thesame configuration steps, no matter if a PLC, C++, or TcCOM Runtime or simply an I/O-Task is used.

TF6100 TC3 OPC-UA 95Version: 2.2

Page 96: Manual TF6100 TC3 OPC-UA

Configuration

OPC-UA Alarms & Conditions (part 9 of the OPC-UA specification) describes a model for monitoring processvalues and sending out alarms and events on status changes of a runtime symbol. The use

PrerequisitesThe following prerequisites apply to the use of Alarms & Conditions:

• The runtime symbols that should be monitored need to be available in the namespace (comparedocumentation article on “Runtime Access” topic)

• The OPC-UA Client needs to support Alarms & Conditions. In this documentation article, the UA-Expert(by Unified Automation) is used as a reference UA-Client.

GeneralThe following steps must be executed once in order to enable a symbol for A&C:

• Activation of a Runtime symbol for Data Access (to make the symbol generally available via OPC-UA)• Activation of Alarms & Conditions for a symbol• Sending custom user data with an event• Firing an event via FireEvent() method• Configuration of multi-language alarm texts• Subscribing to A&C with a reference OPC-UA Client

These steps are described in more detail below. At the end you will find further information on how to receiveconfigured alarms via A&C by using the UA-Expert reference client.

Supported Alarm TypesThe TwinCAT OPC-UA A&C implementation currently supports the following alarm types:

• LimitAlarmType: Define different limits for a symbol. If a limit is reached, the UA-Server sends out analarm.

• OffNormalAlarmType: Define a value that is considered as “normal”. If the current value differs from the“normal” value, the UA-Server sends out an alarm.

Activation of a Runtime symbol for Data AccessThis topic is briefly described in our documentation articles about how to generally make a runtime symbolavailable via OPC-UA.

Activation of Alarms & Conditions for a symbolTo easily configure a runtime symbol for A&C, the A&C configurator can be used. This configurator toolprovides an easy to use graphical user interface to edit the XML file behind. The following snippet shows asample of this XML file to better understand the overall behavior and design of the A&C implementation.<TcUaAcConfig>  <ConditionController Name="ConditionController1" >    <Condition Name="Counter" Severity="200">    <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter1" />    </Condition>    <Condition Name="Switch" Severity="500">      <OffNormalAlarmType Normal="0" MessageNormal="100" MessageOffNormal="20" />      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.bSwitch" />    </Condition>    <Condition Name="Struct" Severity="300">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.stStruct" />    </Condition>          </ConditionController>

TF6100 TC3 OPC-UA96 Version: 2.2

Page 97: Manual TF6100 TC3 OPC-UA

Configuration

  <ConditionController Name="ConditionController2" >    <Condition Name="Counter2" Severity="200">      <LimitAlarmType LowLowLimit="-10" LowLimit="0" HighLimit="10" HighHighLimit="20" MessageNor-mal="100" MessageLowLow="10" MessageLow="11" MessageHigh="12" MessageHighHigh="13"/>      <ItemToMonitor SamplingRate="100" NS="urn:[NodeName]:BeckhoffAutomation:Ua:PLC1"NodeId="s=MAIN.nCounter2" />    </Condition>  </ConditionController></TcUaAcConfig>

A “Condition” defines the runtime symbol that should be monitored and also the alarm limits and alarm texts.Every “Condition” is organized in a so-called “ConditionController”, which is the object that OPC-UA Clientslater subscribe to.

When creating a Condition, the NamespaceName (NS) and NodeID need to be specified to reference the UAnode that should be monitored. The configurator tool provides an easy graphical browsing mechanism tochoose a node. In the XML, the wildcard “[NodeName]” may be used in the NamespaceName to easily movethe XML file between two different hardware systems. Remember: The NamespaceName always includesthe hostname of the IPC or Embedded PC that the OPC-UA Server runs on. When choosing “[NodeName]”this tag is replaced with the hostname of the actual IPC or Embedded PC that the UA Server runs on.

The SamplingRate specifies how often the UA-Server should sample a value from the node to determine ifone of the alarm limits has been reached.

Alarm texts are identified by an ID. The ID uniquely identifies an alarm text in its resource file, which isexplained in the following chapter.

Sending custom user data with an alarmAlarms may include custom user data fields that can extend the data that is send out with the alarm. Theseuser data fields can be created and filled with content from within the Runtime application by creating aSTRUCT which first element is named “value”. During an alarm, all following elements are then send out inan additional user data field. Example PLC application:TYPE ST_CustomStruct :STRUCT  value : INT;  data  : ST_SomeStruct;END_STRUCTEND_TYPE

TYPE ST_SomeStruct :STRUCT  Data1 : INT;  Data2 : REAL;  Data3 : LREAL;END_STRUCTEND_TYPE

The instance of ST_CustomStruct is then activated for Data Access by our regular mechanisms, e.g. inTwinCAT 3:PROGRAM MAINVAR  {attribute 'OPC.UA.DA' := '1'}  stCustomStruct : ST_CustomStruct;END_VAR

When subscribing to a ConditionController, OPC-UA Clients need to subscribe to specialAlarmConditionTypes called “BkUaLimitAlarmType” and “BkUaOffNormalAlarmType” in order to be able toreceive the special user data fields when an alarm arrives.

TF6100 TC3 OPC-UA 97Version: 2.2

Page 98: Manual TF6100 TC3 OPC-UA

Configuration

The OPC-UA Client then receives the custom user data in the fields “BkUaEventData” and“BkUaEventValue” of the incoming alarm. In the example from above, this is the value of the PLC variable aswell as the user data that is represented by the PLC struct “ST_SomeStruct”.

Firing an event via FireEvent() methodEvery ConditionController includes a method FireEvent() which enables OPC-UA Clients to fire a genericevent including custom EventFields.

TF6100 TC3 OPC-UA98 Version: 2.2

Page 99: Manual TF6100 TC3 OPC-UA

Configuration

When executing this method, an event is thrown on the TwinCAT OPC-UA Server. Other OPC-UA Clientscan receive these events when subscribing to the corresponding ConditionController.

The custom EventFields are attached to the event as “UserEventData”. This data can be received by theOPC-UA Client that subscribes to the SimpleEventType “UserEventType”.

TF6100 TC3 OPC-UA 99Version: 2.2

Page 100: Manual TF6100 TC3 OPC-UA

Configuration

Configuration of multi-language alarm textsThe A&C implementation in the TwinCAT OPC-UA Server supports the use of multi-language alarm texts.Depending on the language that a UA-Client connects to the Server, another alarm text is used. Alarm textsare configured in XML files in which each language is represented by an own file. All these files are locatedin the “res” (resource) folder of the TwinCAT OPC-UA Server. The Configurator can be used to add orremove alarm texts in a convenient way without the need to edit the XML files directly.

Every alarm text is identified by an ID, which is unique for the whole file. Example:<TcOpcUaSvrRes Lang="en">  <Text ID="0">Text not available</Text>  <Text ID="1">Some alarm text</Text>      <Text ID="2">Value is High range</Text>  <Text ID="3">Value is HighHigh range</Text>  <Text ID="4">Value is OffNormal</Text>  ...</TcOpcUaSvrRes>

Subscribing to A&C with a reference OPC-UA ClientAn OPC-UA Client needs to create a subscription to one of the ConditionControllers in order to be able toreceive events for Conditions that are configured for this particular ConditionController. The UA-Expertprovides functionalities to subscribe to and receive UA events. After UA-Expert has been started and aconnection to the TwinCAT OPC-UA Server has been established, please add a new document view called“Event View” to your workspace.

You can then subscribe to a ConditionController by dragging the corresponding object to the EventView. Theevents for this ConditionController are then shown in the “Event Window”.

TF6100 TC3 OPC-UA100 Version: 2.2

Page 101: Manual TF6100 TC3 OPC-UA

Configuration

Please note that you might need to subscribe to special alarm and/or event types in order to be able toreceive all fields of an incoming event or alarm. Please follow the instructions in this document whichdemonstrate how to do so.

4.1.7 File Transfer

4.1.7.1 Access files and folders via OPC-UA

As of OPC-UA specification version 1.02, OPC-UA includes a specialized ObjectType for File Transfer,which is described in Annex C of the specification. This special ObjectType, called FileType, describes theinformation model for file transfer. Files can be modelled in OPC-UA as simple variables using ByteStrings.The FileType represents a file with Methods to access the file. Please consult the OPC-UA specification formore information about FileType and the design and handling of its underlying Methods and Properties toaccess a file in OPC-UA namespace.

Beckhoff has implemented a generic way to load Files and Folders from the local hard disk to OPC-UANamespace. Each file is represented by a FileType and therefore allows you to perform read or writeoperations on that file. In addition, each folder contains a method CreateFile() to create new files on harddisk and a property FolderPath to determine the actual path to the folder on the OPC-UA Server device.

TF6100 TC3 OPC-UA 101Version: 2.2

Page 102: Manual TF6100 TC3 OPC-UA

Configuration

Note

FileTransfer in Device Manager OPC-UA ServerThis functionality has been added exclusively to the OPC-UA Server of the Beckhoff DeviceManager. Although the TwinCAT OPC-UA Server provides some parts of this File Transferfunctionality as well, the generic functionality that allows you to expose all files and folders,has been added exclusively to the OPC-UA Server that is part of the Device Managerprod-uct, which is automatically available on every Beckhoff Industrial-PC or Embedded-PC.Please consult the Device Manager documentation for more information.

ConfigurationFileType objects are created in a separate namespace called “FileTransfer”. To configure this namespaceand select which files and folders should be available via OPC-UA, a XML file is used that needs to beplaced in the same directory as the executable file of the OPC-UA Server. The XML file contains informationabout the folder path and a search mask that defines which files are to be published to the OPC-UAnamespace:<Files>  <FolderObject DisplayName="TwinCAT">    <FolderObject DisplayName="3.1">      <FolderObject DisplayName="Boot" Path="c:/TwinCAT/3.1/Boot" Search="*.*" >        <FolderObject DisplayName="Plc" Path="c:/TwinCAT/3.1/Boot/Plc" Search="*.*" ></FolderObject>        <FolderObject DisplayName="Tmi" Path="c:/TwinCAT/3.1/Boot/Tmi" Search="*.*" ></FolderObject>      </FolderObject>    </FolderObject>  </FolderObject></Files>

TF6100 TC3 OPC-UA102 Version: 2.2

Page 103: Manual TF6100 TC3 OPC-UA

Configuration

4.1.8 Security

4.1.8.1 Overview

Security was a central requirement in the development of OPC UA. It is addressed in various areas:

• Encryption• Integrity• Authentication

The confidentiality of the exchanged information is secured by the encryption of the exchanged messages.Modern cryptographic algorithms are used for this. In order to be able to cope with future securityrequirements as well, even stronger and more modern algorithms can subsequently be added to anapplication without changing the protocol. Different security levels can be selected according to therequirements of the respective application. In some areas it is sufficient to sign the messages in order toprevent changes being made by third parties, while additional coding of the messages is necessary in othercases where the data must also not be read by third parties. TF6100 OPC-UA offers the following securitylevels (security end points) with which Clients can connect themselves:

• None: no security• Sign: signed messages• Sign&Encrypt: signed and encrypted messages

The signing of messages prevents a third party from changing the contents of a message. This prevents, forexample, a write statement to open a switch being falsified by a third party and the switch being closedinstead.

OPC-UA applications identify themselves via so-called software and application instance certificates. Withthe aid of software certificates it is possible to grant certain client applications extended access to theinformation on an OPC UA server, for example for the engineering of an OPC UA server. Applicationinstance certificates can be used to ensure that an OPC UA server communicates only with preconfiguredclients. A client can ensure by means of the server’s application instance certificate that it is speaking to thecorrect server (similar to the certificates of a Web browser). The taking into account of these certificates isoptional, i.e. an OPC UA server can also grant the same access to each client, depending on the user rights.

The TwinCAT OPC-UA Client and TwinCAT OPC-UA Server generate a self-signed certificate during the firststart procedure. This certificate consists of a private key and a public key. The private key is saved in the\PKI\CA\private directory and the corresponding public key in the \PKI\CA\certs directory. Any OPC-UAClient wishing to establish a secure connection with the Server via one of the security end points (Sign,Sign&Encrypt) must know the public key of the OPC-UA Server. Conversely the OPC-UA Server must knowthe Client’s public key. This so-called key exchange is described in the following articles.

4.1.8.2 Authentication

In addition to the certificate exchange, the TwinCAT OPC-UA Server also offers the possibility to perform anauthentication via user name/password. A connecting OPC-UA Client must therefore provide a valid username/password combination in order for the connection to be successful.

The TwinCAT OPC-UA Server uses standard Windows mechanisms for the validation of user names. If thecomputer on which the TwinCAT OPC-UA Server is running is a member of a Windows domain (e.g. ActiveDirectory), then the domain is checked for a valid user name/password combination. If the computerconcerned is a stand-alone device, then the local user database is checked by Windows.

The configuration of the TwinCAT OPC-UA Server allows two settings:

• Activation/deactivation of anonymous accesses (without authentication)• Activation/deactivation of user name/password validation

Both settings can be configured either by using the OPC-UA configurator or manually by editing theServerConfig.xml file.

TF6100 TC3 OPC-UA 103Version: 2.2

Page 104: Manual TF6100 TC3 OPC-UA

Configuration

ConfiguratorThe above two settings can be configured via the “Security” tab in the OPC-UA configurator.

ManualYou can also manually edit the above settings in the ServerConfig.xml file. To do this you have to adapt thefollowing components accordingly:<UserIdentityTokens>  <EnableAnonymous>true</EnableAnonymous>  <EnableUserPw>true</EnableUserPw></UserIdentityTokens>

4.1.8.3 Certificate exchange

Communication between an OPC-UA Client and an OPC-UA Server can optionally be secured by encryptingthe data traffic. By default both the TwinCAT OPC-UA Server and the TwinCAT OPC-UA Client generate atthe first time of starting a machine-specific, self-signed certificate for authentication.

If you wish to use an encrypted connection in your environment, you must set up a trust relationship betweenOPC-UA Server and OPC-UA Client.

This article consists of the following sections, which describe the general exchange of Client and Servercertificates:

• Announcement of the OPC-UA Client to the OPC-UA Server• Announcement of the OPC-UA Server to the OPC-UA Client

Announcement of the OPC-UA Client to the OPC-UA ServerIf you wish to authenticate one or more OPC-UA Clients via certificates on the OPC-UA Server, then theOPC-UA Server must trust the Client’s public keys. To do this the public key of the respective Client must becopied to the following subfolder of the OPC-UA Server:

TF6100 TC3 OPC-UA104 Version: 2.2

Page 105: Manual TF6100 TC3 OPC-UA

Configuration

• TwinCAT 2: %InstallDir%\UA\PKI\CA\certs• TwinCAT 3: %InstallDir%\Server\PKI\CA\certs

This folder contains all the Client certificates that the OPC-UA Server trusts and with which an authenticatedconnection can be established. So that the OPC-UA Server can process them, the Client certificates mustexist here in the format “<AnyName>.der”. The following guide shows you a way of accessing the Clientcertificate, which is probably the simplest possibility to access a Client certificate for many applications. Here,you establish a connection to the UA Server using a security end point (e.g. Basic128Rsa15/Sign&Encrypt)without having copied the Client certificate to the UA server beforehand. This connection is naturally rejectedby the UA Server, since it does not trust the UA Client at this point in time. In this case the TwinCAT OPC-UA Client would return the error 0xE4DD0102, for example. After rejecting the connection, however, the UAServer stores a copy of the Client certificate in the following directory:

• TwinCAT 2: %InstallDir%\UA\PKI\CA\crl• TwinCAT 3: %InstallDir%\Server\PKI\CA\crl

The name of the certificate corresponds here to the “thumbprint” of the certificate and can thus be clearlyassigned to the UA Client certificate. You can now copy this file directly into the “certs” folder so that the UAServer trusts the UA Client and accepts further connection requests.

• TwinCAT 2: %InstallDir%\UA\PKI\CA\certs• TwinCAT 3: %InstallDir%\Server\PKI\CA\certs

Announcement of the OPC-UA Server to the OPC-UA ClientDepending on the OPC-UA Client employed, different steps may need to be taken so that the OPC-UAClient trusts the OPC-UA Server. The following guide therefore applies only to the TwinCAT OPC-UA Client.

The public key of the OPC-UA Server is located in the following directory as a DER file:

• TwinCAT 2: %InstallDir%\UA\PKI\CA\certs• TwinCAT 3: %InstallDir%\Server\PKI\CA\certs

The name of the file is “Beckhoff_OpcUaServer.der”. This file must be copied into the following folderon the OPC-UA Client:

• TwinCAT 2: %InstallDir%\UA Client\PKI\CA\certs• TwinCAT 3: %InstallDir%\Client\PKI\CA\certs

In the case of an OPC-UA Client from a third-party vendor, this file must be announced in a similar form.

The respective TwinCAT OPC-UA Client now trusts the UA Server and allows a connection to be establishedwith it.

4.1.9 Miscellaneous

4.1.9.1 Endpoints and default port

By default the TwinCAT OPC-UA Server provides the following endpoints and default port for OPC-UAClients to connect to:

TF6100 TC3 OPC-UA 105Version: 2.2

Page 106: Manual TF6100 TC3 OPC-UA

Configuration

Note

Default portPlease note that the default port 4840 may be in use by other OPC-UA servers, e.g. the Lo-cal Discovery Server (LDS) from the OPC Foundation, which is deployed with OPC-UAsoftware packages by some vendors.

Endpoint DescriptionNone - None No securityBasic128Rsa15 - Sign & Encrypt Signing and encryption of messages for medium security

requirements. Requires certificate exchange and themanagement of trust lists. Please consult the OPC-UA Serversecurity chapter [} 103] for more information.

Basic256 - Sign & Encrypt Signing and encryption of messages for medium to high securityrequirements. Requires more computing time (higher demandsto the computer’s CPU). Requires certificate exchange and themanagement of trust lists. Please consult the OPC-UA Serversecurity chapter [} 103] for more information.

4.1.9.2 Generation of NamespaceUri

The NamespaceUri is important for the unique identification of a node in UA namespace. Every NodeIDconsists of a NamespaceIndex, an IdentifierType and an Identifier. Because the NamespaceIndex can begenerated dynamically by an OPC-UA Server, an UA-Client should always use the static NamespaceUri toresolve it to its actual NamespaceIndex. All NamespaceUris and their corresponding NamespaceIndex arelisted in the so-called NamespaceArray of an OPC-UA Server.

Please consult the article about Communication parameters [} 116] for more information about theNamespaceArray and its content.

The NamespaceUri for every TwinCAT Runtime is generated according to the following naming scheme:

urn:[NodeName]:BeckhoffAutomation:Ua:[Name]

[NodeName] represents the hostname of the computer that the TwinCAT OPC-UA Server is running onwhereas [Name] is a string that can be set in the server’s configuration file or via the TwinCAT OPC-UAConfigurator.

Please note that older versions of the TwinCAT OPC-UA Server did not use the URI-based format togenerate the NamespaceUri but instead just used the <Name> attribute as configured in the server’sconfiguration file. Because this might be a breaking change in case of upgrading from older versions, theTwinCAT OPC-UA Server provides a so-called Legacy-URI format switch, which can be activated for everyTwinCAT Runtime in the server’s configuration file or via the OPC-UA Configurator.

<UaNodeManager>  <Name>PLC1</Name>  <AdsPort>851</AdsPort>  <AdsNetId>127.0.0.1.1.1</AdsNetId>  <AdsTimeout>2000</AdsTimeout>  <AdsTimeSuspend>20000</AdsTimeSuspend>  <AutoCfg>4041</AutoCfg>  <IoMode>1</IoMode>  <AutoCfgSymFile>C:\TwinCAT\3.1\Boot\Plc\Port_851.tmc</AutoCfgSymFile>

TF6100 TC3 OPC-UA106 Version: 2.2

Page 107: Manual TF6100 TC3 OPC-UA

Configuration

  <Disabled>0</Disabled>  <ArraySubItemLegacySupport>0</ArraySubItemLegacySupport>  <MaxGetHandle>100</MaxGetHandle>  <ReleaseAdsVarHandles>0</ReleaseAdsVarHandles>  <LegacyUriFormat>1</LegacyUriFormat></UaNodeManager>

When set to “0”, the NamespaceName is generated according to the scheme described above. When set to“1”, the NamespaceName equals the <Name> XML tag and is therefore generated as in older versions of theTwinCAT OPC-UA Server.

4.1.9.3 Configuration file

All settings for the TwinCAT OPC-UA Server can be made with the help of a configurator [} 143], which isdelivered via the setup from UA-Server version 1.6.80. The configurator makes it easier for the user toconfigure the UA-Server via its “ServerConfig.xml” configuration file. This configuration file contains ahierarchical, XML-based structure of all adjustable parameters of the UA Server. The following illustrationshows an example structure of this file.

We generally recommend the use of the OPC-UA configurator, since errors in the configuration can beavoided in this way.

The configuration file is always located in the same directory as TcOpcUaServer.exe, for example:

• Windows XP / 7 with TwinCAT 2: %TwinCATDIR%\OPC\UA\• Windows XP / 7 with TwinCAT 3: %TwinCATDIR%\Functions\TF6100-OPC-UA\Win32\Server\• Windows CE TwinCAT 2 : HardDisk\System• Windows CE TwinCAT 3: HardDisk\TwinCAT\Functions\TF6100-OPC-UA\Server\

TF6100 TC3 OPC-UA 107Version: 2.2

Page 108: Manual TF6100 TC3 OPC-UA

Configuration

4.1.9.4 Configuration of multiple TwinCAT runtimes

You can optionally add further TwinCAT ADS devices to the UA namespace. Through the configuration ofthe namespace the OPC-UA Server knows which TwinCAT ADS device (e.g. PLC, IO task, C++ runtime,etc.) is to be made available via the OPC-UA Server and shows its symbol information in the UA namespaceaccordingly. This configuration only needs to be done once.

Adding/removing further ADS devices to/from the UA namespaceThe TwinCAT OPC-UA server is configured by default such that it connects to the first PLC runtime of thelocal system. In order to make further ADS devices or further runtimes available via the UA namespace, youmust carry out the following steps:

If the device to be added is a local device:

• Add the remote device for the configuration of the OPC-UA Server, e.g. using the OPC-UA configuratoror by direct editing of the ServerConfig.xml file

If the device to be added is a remote device:

• Manufacture ADS routes between the computer on which the OPC-UA Servers is running and theremote system

• Add the remote device for the configuration of the OPC-UA Server, e.g. using the OPC-UA configuratoror by direct editing of the ServerConfig.xml file

Use of the OPC-UA configuratorUse the OPC-UA configurator to add further ADS devices to the UA namespace.

In the “Data Access” section of the OPC-UA configurator you can manage the ADS devices integrated in theUA namespace, add new devices or remove existing devices. To add, first select the type of device from theassociated drop-down box (e.g. “8 (PLC: Subset)”) and then click on “Add”. An additional entry is added tothe list of the ADS devices. Make the desired settings and then click on “Activate” in the “Configuration”menu if you wish to activate the configuration immediately.

Different settings have to be made for the individual parameters, depending on the device to be added.Please consult the documentation article from the “Data Access” section.

Please note that you have to restart the OPC-UA Server in order for the changes to become effective. Thiscan also be done via the configurator by selecting the “Restart” option in the “Server” menu. Alternatively aTwinCAT restart is sufficient for this.

[Optional] Editing the ServerConfig.xml fileYou can also directly edit the ServerConfig.xml file in order to add further ADS devices to the UAnamespace. In this configuration file there is a section, <UaNodeManager>, which defines the access to anADS device in each case, for example:

TF6100 TC3 OPC-UA108 Version: 2.2

Page 109: Manual TF6100 TC3 OPC-UA

Configuration

Different settings have to be made for the individual parameters, depending on the device to be added.Please consult the documentation article from the “Data Access” section.

Please note that you have to restart the OPC-UA Server in order for the changes to become effective. Thiscan also be done via the configurator by selecting the “Restart” option in the “Server” menu. Alternatively aTwinCAT restart is sufficient for this.

4.1.9.5 Configuration of multiple Server instances

It is possible to install several TwinCAT OPC-UA Servers on one system. This part of the documentationdescribes the configuration steps that are necessary for this. The configuration is identical under WindowsCE and Windows XP-based operating systems and consists of the following sub-steps:

• Installation of the TwinCAT OPC-UA Server• Copying of the installed UA Servers files into a new directory• Adaptation of the configuration file of the second UA Server

The only differences between the two operating systems are the paths, and the differences will be referred toaccordingly in the individual steps.

Notice: The TwinCAT OPC-UA Server enables the use of OPC-UA directly from the PLC level. An ADSserver was integrated into the product for this so that PLC programmers can transmit data by function blockover OPC-UA. If you would like to have several TwinCAT OPC-UA Servers running in parallel on one systemas described in these instructions, then please note that only the first instance of the UA Server can beaddressed by function block.

TF6100 TC3 OPC-UA 109Version: 2.2

Page 110: Manual TF6100 TC3 OPC-UA

Configuration

Installation of the first TwinCAT OPC-UA ServerTo install TwinCAT OPC-UA Server, you can use the available setup file on the Beckhoff FTP-Server. Bydefault, the UA-Server will be installed in the following directory:

• Windows XP: %TwinCATDIR%\Function\TF6100-OPC-UA\Win32\Server\

Copying the installed UA-Server filesIn a second step you need to copy the installed UA-Server files to a new directory. Create a new directory"Server2" in a folder of your choice, for example:

• Windows XP: %TWINCATDIR%\Function\TF6100-OPC-UA\Win32\Server2\

Now you need to copy the contents of the original folder to the new directory.

Customizing the configuration file of the second UA-ServerThe second UA-Server needs to use another TCP-Port, so that it can be reached from a UA-Client. Tochange the default TCP port of the UA-Server, you need to edit its configuration file "ServerConfig.xml" witha text editor of your choice, for example Notepad. Additional information about this configuration file can befound here [} 107]. In this file, search for the entry "<Url>opc.tcp://[NodeName]:4840</Url>" beneath thenode "<UaEndpoint>" and change its current port number (4840) to a new TCP port, for example 4849:

TF6100 TC3 OPC-UA110 Version: 2.2

Page 111: Manual TF6100 TC3 OPC-UA

Configuration

Additionally, you need to change the node <ServerInstanceUri>[NodeName]/Beckhoff/TcOpcUaServer/ 1</ServerInstanceUri> and insert a new number, for example:

By executing the following file with the parameter "-console", you can now start the second UA-Server:

• Windows XP: %TWINCATDIR%\Function\TF6100-OPC-UA\Win32\Server2\TcOpcUaServer.exe -console

4.1.9.6 Configuration of Firewalls

In order to enable an OPC-UA communication also via a NAT device, e.g. an Internet router, this must beable to forward the UA port used to the TwinCAT OPC-UA Server (so-called port forwarding). By default theTwinCAT OPC-UA Server is configured for UA communication via the TCP port 4840; however, you canadapt this configuration yourself if necessary, either via the server configuration file [} 107] or using the OPC-UA configurator [} 143]. The following picture clearly shows once again the relationship between portforwarding and the UA Server.

TF6100 TC3 OPC-UA 111Version: 2.2

Page 112: Manual TF6100 TC3 OPC-UA

Configuration

In this example the OPC-UA Client establishes a UA connection to the NAT device via the TCP port 4840,which then forwards this communication connection to the TwinCAT OPC-UA Server by means of portforwarding. The NAT device thus only needs to forward the UA port configured in the TwinCAT OPC-UAServer to the target device. You can view the port used by the UA Server either in the server configurationfile [} 107] or also very conveniently via the UA configurator [} 143]; in the delivery state, however, this isalways the TCP port 4840. For the appropriate configuration of your NAT device for port forwarding pleaserefer to its documentation.

4.1.9.7 Configuration namespace

Since version 2.1.x, the TwinCAT OPC-UA Server provides a separate configuration namespace, whichincludes the following functionalities:

• Management of the ServerConfig (Read/Write access) of the OPC-UA Server• Certificate management for trusted/rejected client certificates

TF6100 TC3 OPC-UA112 Version: 2.2

Page 113: Manual TF6100 TC3 OPC-UA

Configuration

Management of ServerConfigThe ServerConfig is published to the namespace as a regular OPC-UA FileType and therefore provides thecorresponding methods and properties to get access to the file.

Management of clientcertificatesEach client certificate that is known to the server is published to the namespace as a OPC-UACertificateType. Certificates are categorized into “Rejected” and “Trusted” certificates, which is representedby a separate folder in the namespace.

By calling the method Move(), a certificate can be moved between the trust lists.

In addition, for easy identification, several Properties provide more information about the certificate itself.

TF6100 TC3 OPC-UA 113Version: 2.2

Page 114: Manual TF6100 TC3 OPC-UA

Configuration

Using the configuration namespaceThe configuration namespace can only be used by authenticated users. This means that an OPC-UA Clientneeds to authenticate itself against the OPC-UA server by providing a valid username/passwordcombination. Valid usernames are either local users or also users from a Windows domain if the computeron which the OPC-UA Server runs is member of a Windows domain.

In its ServerConfig, the OPC-UA Server provides the following XML tags to configure access to theconfiguration namespace:<ServerConfigNamespace Exposed="True" MinUserlevel="14" /><Users>  <User Level="15">Administrator</User>  <User Level="10">domain\RegularUser</User></Users>

In the example from above, the local username “Administrator” is allowed to access the configurationnamespace whereas the Windows domain user account “domain\RegularUser” is not allowed to access thisnamespace because its UserLevel is too low.

4.2 Client

4.2.1 OverviewThe TwinCAT OPC-UA Client makes an OPC-UA interface directly available from the PLC. As a result, thePLC programmer is provided with a standardized communication interface for connecting to OPC-UAServers via PLC function blocks. The usable function blocks have been standardized by a PLCopen workinggroup.

The OPC-UA Client is always used together with the PLC library Tcx_PLCopen_OpcUa, which is also acomponent of the product setup. This library makes various OPC-UA functionalities available, which canthen be used from a PLC program.

The following table provides an overview of the functionalities offered:

TF6100 TC3 OPC-UA114 Version: 2.2

Page 115: Manual TF6100 TC3 OPC-UA

Configuration

Functionality Description Relevant function blocksConnect / Disconnect Establishment and disconnection of

connections to OPC-UA Servers.UA_ConnectUA_Disconnect

Polling (Read/Write) Reading and writing of variables inthe UA namespace in the pollingmode. Contains no subscriptions.

UA_ConnectUA_DisconnectUA_ReadUA_WriteUA_GetNamespaceIndexUA_NodeGetHandleUA_NodeReleaseHandle

Method call Execution of methods in the UAnamespace.

UA_ConnectUA_DisconnectUA_MethodGetHandleUA_MethodReleaseHandleUA_MethodCall

Security Establishment of an encryptedconnection to an OPC-UA Server.

UA_ConnectUA_Disconnect

The interfaces of each function block are documented in detail in the PLC libraries section of thisdocumentation.

4.2.2 Data Type MappingThe PLC Library Tc3_PLCopen_OpcUa provides access from the PLC world to the UA world. For readingand writing data the data type representation between these two worlds have to be mapped. This pagedescribes this mapping

Base data types

The base data types are mapped as described in the PLCopen OPC UA Information Model for IEC 61131-3.

OPC-UA Data Type PLC Data TypeBoolean BOOLSByte SINTByte USINTInt16 INTInt32 DINTString STRINGUSint BYTEFloat REALDouble LREALUInt16 UINTUInt32 UDINTInt64 LINTUInt64 ULINTDateTime DT

Derived data typesOPC-UA defines base data types. Other data types are derived from these.

TF6100 TC3 OPC-UA 115Version: 2.2

Page 116: Manual TF6100 TC3 OPC-UA

Configuration

On client side the PLC data types have to be used to provide access to the whole range of UA data types.The currently supported non-base data types on client side are:

• Counter (use UDINT in PLC)

Accessing ArraysWhile creating a node handle, the system checks capabilities to access the node. Further checks are appliedduring read and write operations.

For accessing nodes of arrays as well as in and out parameters of method calls, some constraints have to befulfilled:

• For Node access: The array dimensions and data-length have to match the provided data for read/writeoperations

• Reading of string arrays: If ONE string length exceeds the provided length of PLC string, the read willfail

• Only array dimensions of up to 3 levels are supported

4.2.3 Best practice

4.2.3.1 How to determine communication parameters

No matter which OPC-UA functionality you would like to implement, there are a few things that will help PLCproject development. It is common practice to use a graphical OPC-UA client to help determining theattributes of a node or method that need to be used together with the PLC function blocks, e.g.:

• Node Identifier• Node Namespace Index and corresponding Namespace URI• Node Data Type• Method Node ID and Object Node ID

The following documentation uses the generic OPC-UA Client UA-Expert as an example. This client may beacquired from the websites of Unified Automation at www.unified-automation.com.

Node IdentifierA very common task is to read or write variables – which are generally referred to as nodes in terms of OPC-UA. Nodes are identified by the following three things:

• Namespace Index: The namespace in which the node resides, e.g. the PLC runtime• Identifier: Unique identifier of the node within its namespace• Identifier Type: There are three different types: String, Guid and Numeric.

These attributes form the so-called NodeID – the representation of a node on an OPC-UA Server – and theyare required by some of the function blocks to. By using UA-Expert, developers can easily determine theseattributes by connecting to the OPC-UA Server and browsing to the desired node. The attributes are thenvisible in the Attributes panel, e.g.:

TF6100 TC3 OPC-UA116 Version: 2.2

Page 117: Manual TF6100 TC3 OPC-UA

Configuration

Node Namespace Index and corresponding Namespace URIAccording to the OPC-UA specification, the Namespace Index (as seen above) may be a dynamicallygenerated value. Therefore OPC-UA clients should always use the corresponding Namespace URI toresolve the Namespace Index before acquiring a node handle. This can be done by using the function blockUA_GetNamespaceIndex [} 157]. However, to be able to use this function block, one has to know theNamespace URI. The Namespace URI can be easily determined by using UA-Expert. Connect to the OPC-UA Server and browse to the following node:

This node contains information about all registered Namespaces on the OPC-UA Server. You can see theircorresponding Namespace URIs in the Attributes panel:

As an example: In the chapter about Node Identifiers (see above), we have seen a NodeID in which theNamespace Index was 5. According to the above Namespace Array, its corresponding Namespace URI isurn://SVENG-NB04/BeckhoffAutomation/Ua/PLC1. This URI can now be used for the function blockUA_GetNamespaceIndex. The OPC-UA Server makes sure that this URI always stays the same, even aftera restart. However, the previously mentioned Namespace Index may change which is why the NamespaceURI and function block UA_GetNamespaceIndex should always be used to resolve the correct NamespaceIndex for later use with other function blocks, e.g. UA_Read [} 163], UA_Write [} 164].

Node Data TypeThe data type of a node is required to see which PLC data type should be used to map a read value to orwhich PLC data type should be used if a node should be written to. By using UA-Expert, simply connect tothe OPC-UA Server, browse to the variable and read its Data Type from the Attributes panel, e.g.:

TF6100 TC3 OPC-UA 117Version: 2.2

Page 118: Manual TF6100 TC3 OPC-UA

Configuration

In this case the Data Type is Int16, which should be mapped to an equivalent data type in the PLC, e.g. INT.The PLCopen IEC61131-to-OPC-UA specification describes the defined data type mapping. The followingtable is an extract of this specification:

IEC61131 elementary data types OPC-UA built in data typesBOOL BooleanSINT SByteUSINT ByteINT Int16UINT UInt16DINT Int32UDINT UInt32LINT Int64ULINT UInt64BYTE ByteWORD UInt16DWORD UInt32LWORD UInt64REAL FloatLREAL DoubleSTRING StringCHAR ByteWSTRING StringWCHAR UInt16DTDATE_AND_TIME

DateTime

DATE DateTimeTODTIME_OF_DAY

DateTime

TIME Double

Method Node ID and Object Node IDWhen calling methods from the OPC-UA namespace, two Identifiers are required when acquiring the methodhandle by using the function block UA_MethodGetHandle [} 159]:

• Object Node ID: Identifies the UA object that contains the method• Method Node ID: Identifies the method itself

Both NodeIDs can easily be determined by using UA-Expert. Connect to the OPC-UA Server and browse tothe desired method, e.g.:

TF6100 TC3 OPC-UA118 Version: 2.2

Page 119: Manual TF6100 TC3 OPC-UA

Configuration

The Method Identifier can then be read from the Attributes panel:

Next, browse to the UA object that contains this method. In the example from above this would be the objectfbMathematics:

The Object Identifier can then be read from the Attributes panel:

4.2.3.2 How to establish a connection

The following article describes how the TcX_PLCopen_OpcUa function blocks should be used to connect toa local or remote OPC-UA Server. This connection may then be used to call further functionalities, e.g. reador write nodes or call methods. The article consists of the following topics:

• Overview• Schematic workflow• Things to consider• Code snippet

TF6100 TC3 OPC-UA 119Version: 2.2

Page 120: Manual TF6100 TC3 OPC-UA

Configuration

OverviewThe following function blocks are required to establish a connection to an OPC-UA Server and laterdisconnect the session: UA_Connect [} 155], UA_Disconnect [} 156]. We highly recommend to first read ourarticle about How to determine communication parameters [} 116] to be able to understand certain UAfunctionalities, e.g. how to determine Node Identifiers.

Schematic workflowThe schematic workflow of every TwinCAT OPC-UA Client can be categorized into three different phases:Preparation, Work and Cleanup. The use case described in this article can be visualized as follows:

Things to considerThe function block UA_Connect requires the following information to be able to establish a connection to alocal or remote OPC-UA Server:

• Server URL• Session Connect Information

The Server URL consists basically of a prefix, a hostname and a port. The prefix describes the OPC-UAtransport protocol that should be used for the connection, e.g. ‘opc.tcp://’ for a binary TCP connection(default). The hostname or IP address part describes address information of the target OPC-UA Server, e.g.‘192.168.1.1’ or ‘CX-12345’. The port number is the target port of the OPC-UA Server, e.g. ‘4840’. In total,the Server URL may look as follows: opc.tcp://CX-12345:4840.

Code snippetDeclaration:(* Declarations for UA_Connect *)fbUA_Connect : UA_Connect;SessionConnectInfo : ST_UASessionConnectInfo;nConnectionHdl : DWORD;

(* Declarations for UA_Disconnect *)fbUA_Disconnect : UA_Disconnect;

(* Declarations for state machine and output handling *)iState : INT;bDone    : BOOL;bBusy    : BOOL;bError : BOOL;nErrorID : DWORD;

Implementation:CASE iState OF

  0:      bError := FALSE;      nErrorID := 0;      SessionConnectInfo.tConnectTimeout := T#1M;      SessionConnectInfo.tSessionTimeout := T#1M;      SessionConnectInfo.sApplicationName := '';      SessionConnectInfo.sApplicationUri := '';      SessionConnectInfo.eSecurityMode := eUASecurityMsgMode_None;      SessionConnectInfo.eSecurityPolicyUri := eUASecurityPolicy_None;      SessionConnectInfo.eTransportProfileUri := eUATransportProfileUri_UATcp;      stNodeAddInfo.nIndexRangeCount := nIndexRangeCount;

TF6100 TC3 OPC-UA120 Version: 2.2

Page 121: Manual TF6100 TC3 OPC-UA

Configuration

      stNodeAddInfo.stIndexRange := stIndexRange;      iState := iState + 1;

  1:    fbUA_Connect(      Execute := TRUE,      ServerURL := ‘opc.tcp://192.168.1.1:4840’,      SessionConnectInfo := SessionConnectInfo,      Timeout := T#5S,      ConnectionHdl => nConnectionHdl);    IF NOT fbUA_Connect.Busy THEN      fbUA_Connect(Execute := FALSE);      IF NOT fbUA_Connect.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_Connect.ErrorID;        nConnectionHdl := 0;        iState := 0;       END_IF    END_IF

  2:    fbUA_Disconnect(      Execute := TRUE,      ConnectionHdl    := nConnectionHdl);

    IF NOT fbUA_Disconnect.Busy THEN      fbUA_Disconnect(Execute := FALSE);      IF NOT fbUA_Disconnect.Error THEN        iState := 0;      ELSE        bError := TRUE;        nErrorID := fbUA_Disconnect.ErrorID;        iState := 0;        nConnectionHdl := 0;      END_IF    END_IF

END_CASE

4.2.3.3 How to read nodes

The following article describes how the TcX_PLCopen_OpcUa function blocks should be used to read anOPC-UA node from a local or remote OPC-UA Server. We recommend to read our article about How toestablish a connection [} 119] first. The article consists of the following topics:

• Overview• Schematic workflow• Things to consider• Code snippet

OverviewThe following function blocks are required to establish a connection to an OPC-UA Server, read UA nodesand later disconnect the session: UA_Connect [} 155], UA_GetNamespaceIndex [} 157], UA_NodeGetHandle[} 161], UA_Read [} 163], UA_NodeReleaseHandle [} 162], UA_Disconnect [} 156]. We highly recommend tofirst read our article about How to determine communication parameters [} 116] to be able to understandcertain UA functionalities, e.g. how to determine Node Identifiers.

Schematic workflowThe schematic workflow of every TwinCAT OPC-UA Client can be categorized into three different phases:Preparation, Work and Cleanup. The use case described in this article can be visualized as follows:

TF6100 TC3 OPC-UA 121Version: 2.2

Page 122: Manual TF6100 TC3 OPC-UA

Configuration

WorkPreparation

UA_Connect

Cleanup

UA_NodeReleaseHandleUA_Read

UA_GetNamespaceIndex

UA_NodeGetHandle

UA_Disconnect

Things to considerThe function block UA_Connect requires the following information to be able to establish a connection to alocal or remote OPC-UA Server – which has already been covered in the article about How to establish aconnection [} 119].

• Server URL• Session Connect Information

The function block UA_GetNamespaceIndex requires a Connection Handle (from UA_Connect) andNamespace URI to resolve it into a Namespace Index, which will later be used by UA_NodeGetHandle toacquire a node handle. The concept of Namespace URIs and Namespace Index has already been coveredin the article about How to determine communication parameters [} 116].

The function block UA_NodeGetHandle requires a Connection Handle (from UA_Connect) and NodeID (fromST_UANodeID) to acquire a node handle. The concepts behind a NodeID have already been covered in thearticle about How to determine communication parameters [} 116].

The function block UA_Read requires a connection handle (from UA_Connect), node handle (fromUA_NodeGetHandle) and pointer to a destination variable (where the read value should be stored). Pleasemake sure that the destination variable has the correct data type, as described in the article about How todetermine communication parameters [} 116].

The function block UA_NodeReleaseHandle requires the connection handle (from UA_Connect) and nodehandle (from UA_NodeGetHandle).

Code snippetDeclaration:(* Declarations for UA_GetNamespaceIndex *)fbUA_GetNamespaceIndex : UA_GetNamespaceIndex;nNamespaceIndex : UINT;

(* Declarations for UA_NodeGetHandle *)fbUA_NodeGetHandle : UA_NodeGetHandle;NodeID : ST_UANodeID;nNodeHdl : DWORD;

(* Declarations for UA_Read *)fbUA_Read : UA_Read;stIndexRange : ARRAY [1..nMaxIndexRange] OF ST_UAIndexRange;nIndexRangeCount : UINT;stNodeAddInfo : ST_UANodeAdditionalInfo;sNodeIdentifier : STRING(MAX_STRING_LENGTH) := 'MAIN.nCounter';nReadData : INT;cbDataRead : UDINT;

(* Declarations for UA_NodeReleaseHandle *)fbUA_NodeReleaseHandle : UA_NodeReleaseHandle;

Implementation:

TF6100 TC3 OPC-UA122 Version: 2.2

Page 123: Manual TF6100 TC3 OPC-UA

Configuration

CASE iState OF  0:    [...]

  2: (* GetNS Index *)    fbUA_GetNamespaceIndex(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NamespaceUri := sNamespaceUri,      NamespaceIndex => nNamespaceIndex      );    IF NOT fbUA_GetNamespaceIndex.Busy THEN      fbUA_GetNamespaceIndex(Execute := FALSE);      IF NOT fbUA_GetNamespaceIndex.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_GetNamespaceIndex.ErrorID;        iState := 6;      END_IF    END_IF

  3: (* UA_NodeGetHandle *)    NodeID.eIdentifierType := eUAIdentifierType_String;    NodeID.nNamespaceIndex := nNamespaceIndex;    NodeID.sIdentifier := sNodeIdentifier;    fbUA_NodeGetHandle(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NodeID := NodeID,      NodeHdl => nNodeHdl);    IF NOT fbUA_NodeGetHandle.Busy THEN      fbUA_NodeGetHandle(Execute := FALSE);      IF NOT fbUA_NodeGetHandle.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_NodeGetHandle.ErrorID;        iState := 6;      END_IF    END_IF

  4: (* UA_Read *)    fbUA_Read(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NodeHdl := nNodeHdl,      cbData := SIZEOF(nReadData),      stNodeAddInfo := stNodeAddInfo,      pVariable := ADR(nReadData));    IF NOT fbUA_Read.Busy THEN      fbUA_Read( Execute := FALSE, cbData_R => cbDataRead);      IF NOT fbUA_Read.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_Read.ErrorID;        iState := 6;      END_IF    END_IF

  5: (* Release Node Handle *)    fbUA_NodeReleaseHandle(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NodeHdl := nNodeHdl);    IF NOT fbUA_NodeReleaseHandle.Busy THEN      fbUA_NodeReleaseHandle(Execute := FALSE);      IF NOT fbUA_NodeReleaseHandle.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_NodeReleaseHandle.ErrorID;        iState := 6;      END_IF    END_IF

  6:

TF6100 TC3 OPC-UA 123Version: 2.2

Page 124: Manual TF6100 TC3 OPC-UA

Configuration

    [...]

END_CASE

4.2.3.4 How to write nodes

The following article describes how the TcX_PLCopen_OpcUa function blocks should be used to writevalues to an OPC-UA node from a local or remote OPC-UA Server. We recommend to read our article aboutHow to establish a connection [} 119] first. The article consists of the following topics:

• Overview• Schematic workflow• Things to consider• Code snippet

OverviewThe following function blocks are required to establish a connection to an OPC-UA Server, write UA nodesand later disconnect the session:UA_Connect [} 155], UA_GetNamespaceIndex [} 157], UA_NodeGetHandle[} 161], UA_Write [} 164], UA_NodeReleaseHandle [} 162], UA_Disconnect [} 156]. We highly recommend tofirst read our article about How to determine communication parameters [} 116] to be able to understandcertain UA functionalities, e.g. how to determine Node Identifiers.

Schematic workflowThe schematic workflow of every TwinCAT OPC-UA Client can be categorized into three different phases:Preparation, Work and Cleanup. The use case described in this article can be visualized as follows:

WorkPreparation

UA_Connect

Cleanup

UA_NodeReleaseHandleUA_Write

UA_GetNamespaceIndex

UA_NodeGetHandle

UA_Disconnect

Things to considerThe function block UA_Connect requires the following information to be able to establish a connection to alocal or remote OPC-UA Server – which has already been covered in the article about How to establish aconnection [} 119].

• Server URL• Session Connect Information

The function block UA_GetNamespaceIndex requires a Connection Handle (from UA_Connect) andNamespace URI to resolve it into a Namespace Index, which will later be used by UA_NodeGetHandle toacquire a node handle. The concept of Namespace URIs and Namespace Index has already been coveredin the article about How to determine communication parameters [} 116].

The function block UA_NodeGetHandle requires a Connection Handle (from UA_Connect) and NodeID (fromST_UANodeID) to acquire a node handle. The concepts behind a NodeID have already been covered in thearticle about How to determine communication parameters [} 116].

TF6100 TC3 OPC-UA124 Version: 2.2

Page 125: Manual TF6100 TC3 OPC-UA

Configuration

The function block UA_Write requires a connection handle (from UA_Connect), node handle (fromUA_NodeGetHandle) and pointer to a variable that holds the value that should be written. Please make surethat the destination variable has the correct data type, as described in the article about How to determinecommunication parameters [} 116].

The function block UA_NodeReleaseHandle requires the connection handle (from UA_Connect) and nodehandle (from UA_NodeGetHandle).

Code snippetDeclaration:(* Declarations for UA_GetNamespaceIndex *)fbUA_GetNamespaceIndex : UA_GetNamespaceIndex;nNamespaceIndex : UINT;

(* Declarations for UA_NodeGetHandle *)fbUA_NodeGetHandle : UA_NodeGetHandle;NodeID : ST_UANodeID;nNodeHdl : DWORD;

(* Declarations for UA_Write *)fbUA_Write : UA_Write;stIndexRange : ARRAY [1..nMaxIndexRange] OF ST_UAIndexRange;nIndexRangeCount : UINT;stNodeAddInfo : ST_UANodeAdditionalInfo;sNodeIdentifier: STRING(MAX_STRING_LENGTH) := 'MAIN.nNumber';nWriteData: INT := 42;

(* Declarations for UA_NodeReleaseHandle *)fbUA_NodeReleaseHandle : UA_NodeReleaseHandle;

Implementation:CASE iState OF  0:    [...]

  2: (* GetNS Index *)    fbUA_GetNamespaceIndex(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NamespaceUri := sNamespaceUri,      NamespaceIndex => nNamespaceIndex      );    IF NOT fbUA_GetNamespaceIndex.Busy THEN      fbUA_GetNamespaceIndex(Execute := FALSE);      IF NOT fbUA_GetNamespaceIndex.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_GetNamespaceIndex.ErrorID;        iState := 6;      END_IF    END_IF

  3: (* UA_NodeGetHandle *)    NodeID.eIdentifierType := eUAIdentifierType_String;    NodeID.nNamespaceIndex := nNamespaceIndex;    NodeID.sIdentifier := sNodeIdentifier;    fbUA_NodeGetHandle(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NodeID := NodeID,      NodeHdl => nNodeHdl);    IF NOT fbUA_NodeGetHandle.Busy THEN      fbUA_NodeGetHandle(Execute := FALSE);      IF NOT fbUA_NodeGetHandle.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_NodeGetHandle.ErrorID;        iState := 6;      END_IF    END_IF

  4: (* UA_Write *)

TF6100 TC3 OPC-UA 125Version: 2.2

Page 126: Manual TF6100 TC3 OPC-UA

Configuration

    fbUA_Write(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NodeHdl := nNodeHdl,      stNodeAddInfo := stNodeAddInfo,      cbData := SIZEOF(nWriteData),      pVariable := ADR(nWriteData));    IF NOT fbUA_Write.Busy THEN      fbUA_Write(        Execute := FALSE,        pVariable    := ADR(nWriteData));      IF NOT fbUA_Write.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_Write.ErrorID;        iState := 6;      END_IF    END_IF

  5: (* Release Node Handle *)    fbUA_NodeReleaseHandle(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NodeHdl := nNodeHdl);    IF NOT fbUA_NodeReleaseHandle.Busy THEN      fbUA_NodeReleaseHandle(Execute := FALSE);      IF NOT fbUA_NodeReleaseHandle.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_NodeReleaseHandle.ErrorID;        iState := 6;      END_IF    END_IF

  6:    [...]

END_CASE

4.2.3.5 How to call methods

The following article describes how the TcX_PLCopen_OpcUa function blocks should be used to callmethods on a local or remote OPC-UA Server. We recommend to read our article about How to establish aconnection [} 119] first. The article consists of the following topics:

• Overview• Schematic workflow• Things to consider• Code snippet

OverviewThe following function blocks are required to establish a connection to an OPC-UA Server, call UA methodsand later disconnect the session: UA_Connect [} 155], UA_GetNamespaceIndex [} 157],UA_MethodGetHandle [} 159], UA_MethodCall [} 158], UA_MethodReleaseHandle [} 160], UA_Disconnect[} 156]. We highly recommend to first read our article about How to determine communication parameters[} 116] to be able to understand certain UA functionalities, e.g. how to determine Method Identifiers.

Schematic workflowThe schematic workflow of every TwinCAT OPC-UA Client can be categorized into three different phases:Preparation, Work and Cleanup. The use case described in this article can be visualized as follows:

TF6100 TC3 OPC-UA126 Version: 2.2

Page 127: Manual TF6100 TC3 OPC-UA

Configuration

WorkPreparation

UA_Connect

Cleanup

UA_MethodReleaseHandleUA_MethodCall

UA_GetNamespaceIndex

UA_MethodGetHandle

UA_Disconnect

Things to considerThe function block UA_Connect requires the following information to be able to establish a connection to alocal or remote OPC-UA Server – which has already been covered in the article about How to establish aconnection [} 119].

• Server URL• Session Connect Information

The function block UA_GetNamespaceIndex requires a Connection Handle (from UA_Connect) andNamespace URI to resolve it into a Namespace Index, which will later be used by UA_NodeGetHandle toacquire a node handle. The concept of Namespace URIs and Namespace Index has already been coveredin the article about How to determine communication parameters [} 116].

The function block UA_MethodGetHandle requires a Connection Handle (from UA_Connect), an ObjectNodeID and Method NodeID to acquire a method handle. The concepts behind an Object and MethodNodeID have already been covered in the article about How to determine communication parameters[} 116].

The function block UA_MethodCall requires a connection handle (from UA_Connect), method handle (fromUA_MethodGetHandle) and information about the input and output arguments of the method that should becalled. Information about the input arguments is represented by the pInputArgInfo and pInputArgData inputparameters of UA_MethodCall. Information about the output parameters is represented by thepOutputArgInfo and pOutputArgData input parameters of UA_MethodCall. The input parameterpOutputArgInfoAndData then represents a pointer to a structure that contains the return results of themethod call, including all output parameters. In the code snippets below, the pInputArgInfo andpInputArgData parameters are calculated and prepared in the M_Init() method.

The function block UA_MethodReleaseHandle requires the connection handle (from UA_Connect) andmethod handle (from UA_MethodGetHandle).

Code snippetM_Init() – Initialization method of function block that contains UA method callMEMSET(ADR(nInputData),0,SIZEOF(nInputData));nArg := 1;

(********** Input parameter 1 **********)InputArguments[nArg].DataType := eUAType_Int16;InputArguments[nArg].ValueRank := -1; (* Scalar = -1 or Array *)InputArguments[nArg].ArrayDimensions[1] := 0; (* Number of Dimension in case its an array *)InputArguments[nArg].nLenData := SIZEOF(numberIn1); (* Length if its a STRING *)IF nOffset + SIZEOF(numberIn1) > nInputArgSize THEN   bInputDataError := TRUE;  RETURN;ELSE  MEMCPY(ADR(nInputData)+nOffset,ADR(numberIn1),SIZEOF(numberIn1)); (* VALUE in BYTES FORM *)  nOffset := nOffset + SIZEOF(numberIn1);END_IFnArg := nArg + 1;

TF6100 TC3 OPC-UA 127Version: 2.2

Page 128: Manual TF6100 TC3 OPC-UA

Configuration

(********** Input parameter 2 **********)InputArguments[nArg].DataType := eUAType_Int16;InputArguments[nArg].ValueRank := -1; (* Scalar = -1 or Array *)InputArguments[nArg].ArrayDimensions[1] := 0; (* Number of Dimension in case its an array *)InputArguments[nArg].nLenData := SIZEOF(numberIn2); (* Length if its a STRING *)IF nOffset + SIZEOF(numberIn2) > nInputArgSize THEN   bInputDataError := TRUE;  RETURN;ELSE  MEMCPY(ADR(nInputData)+nOffset,ADR(numberIn2),SIZEOF(numberIn2));(* VALUE in BYTES FORM *)  nOffset := nOffset + SIZEOF(numberIn2);END_IF

cbWriteData := nOffset;

Declaration:(* Declarations for UA_GetNamespaceIndex *)fbUA_GetNamespaceIndex : UA_GetNamespaceIndex;nNamespaceIndex : UINT;

(* Declarations for UA_MethodGetHandle *)fbUA_MethodGetHandle: UA_MethodGetHandle;ObjectNodeID: ST_UANodeID;MethodNodeID: ST_UANodeID;nMethodHdl: DWORD;

(* Declarations for UA_MethodCall *)fbUA_MethodCall: UA_MethodCall;sObjectNodeIdIdentifier : STRING(MAX_STRING_LENGTH) := 'MAIN.fbMathematics';sMethodNodeIdIdentifier : STRING(MAX_STRING_LENGTH) := 'MAIN.fbMathematics#M_Mul';nAdrWriteData: PVOID;numberIn1: INT := 42; // change according to input value and data typenumberIn2: INT := 42; // change according to input value and data typenumberOutPro: DINT; // result (output parameter of M_Mul())cbWriteData: UDINT; // calculated automatically by M_Init()InputArguments: ARRAY[1..2] OF ST_UAMethodArgInfo; // change according to input parametersstOutputArgInfo: ARRAY[1..1] OF ST_UAMethodArgInfo; // change according to output parametersstOutputArgInfoAndData: ST_OutputArgInfoAndData;nInputData: ARRAY[1..4] OF BYTE; // numberIn1(INT16)(2) + numberIn2(INT16)(2)nOffset: UDINT; // calculated by M_Init()nArg: INT; // used by M_Init()

(* Declarations for UA_MethodReleaseHandle *)fbUA_MethodReleaseHandle: UA_MethodReleaseHandle;

Implementation:CASE iState OF  0:    [...]

  2: (* GetNS Index *)    fbUA_GetNamespaceIndex(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      NamespaceUri := sNamespaceUri,      NamespaceIndex => nNamespaceIndex);    IF NOT fbUA_GetNamespaceIndex.Busy THEN      fbUA_GetNamespaceIndex(Execute := FALSE);      IF NOT fbUA_GetNamespaceIndex.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_GetNamespaceIndex.ErrorID;        iState := 7;      END_IF    END_IF

  3: (* Get Method Handle *)    ObjectNodeID.eIdentifierType := eUAIdentifierType_String;    ObjectNodeID.nNamespaceIndex := nNamespaceIndex;    ObjectNodeID.sIdentifier := sObjectNodeIdIdentifier;    MethodNodeID.eIdentifierType := eUAIdentifierType_String;    MethodNodeID.nNamespaceIndex := nNamespaceIndex;    MethodNodeID.sIdentifier := sMethodNodeIdIdentifier;

    M_Init();

    IF bInputDataError = FALSE THEN

TF6100 TC3 OPC-UA128 Version: 2.2

Page 129: Manual TF6100 TC3 OPC-UA

Configuration

      iState := iState + 1;    ELSE      bBusy := FALSE;      bError := TRUE;      nErrorID := 16#70A; //out of memory    END_IF

  4: (* Method Get Handle *)    fbUA_MethodGetHandle(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      ObjectNodeID := ObjectNodeID,      MethodNodeID := MethodNodeID,      MethodHdl => nMethodHdl);    IF NOT fbUA_MethodGetHandle.Busy THEN      fbUA_MethodGetHandle(Execute := FALSE);      IF NOT fbUA_MethodGetHandle.Error THEN        iState := iState + 1;      ELSE        bError := TRUE;        nErrorID := fbUA_MethodGetHandle.ErrorID;        iState := 6;      END_IF    END_IF

  5: (* Method Call *)    stOutputArgInfo[1].nLenData := SIZEOF(stOutputArgInfoAndData.pro);    fbUA_MethodCall(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      MethodHdl := nMethodHdl,      nNumberOfInputArguments := nNumberOfInputArguments,      pInputArgInfo := ADR(InputArguments),      cbInputArgInfo := SIZEOF(InputArguments),      pInputArgData := ADR(nInputData),      cbInputArgData := cbWriteData,      pInputWriteData := 0,      cbInputWriteData := 0,      nNumberOfOutputArguments := nNumberOfOutputArguments,      pOutputArgInfo := ADR(stOutputArgInfo),      cbOutputArgInfo := SIZEOF(stOutputArgInfo),      pOutputArgInfoAndData := ADR(stOutputArgInfoAndData),      cbOutputArgInfoAndData := SIZEOF(stOutputArgInfoAndData));    IF NOT fbUA_MethodCall.Busy THEN      fbUA_MethodCall(Execute := FALSE);      IF NOT fbUA_MethodCall.Error THEN        iState := iState + 1;        numberOutPro := stOutputArgInfoAndData.pro;      ELSE        bError := TRUE;        nErrorID := fbUA_MethodCall.ErrorID;        iState := 6;      END_IF    END_IF

  6: (* Release Method Handle *)    fbUA_MethodReleaseHandle(      Execute := TRUE,      ConnectionHdl := nConnectionHdl,      MethodHdl := nMethodHdl);    IF NOT fbUA_MethodReleaseHandle.Busy THEN      fbUA_MethodReleaseHandle(Execute := FALSE);      bBusy := FALSE;      IF NOT fbUA_MethodReleaseHandle.Error THEN        iState := 7;      ELSE        bError := TRUE;        nErrorID := fbUA_MethodReleaseHandle.ErrorID;        iState := 7;      END_IF    END_IF

  7:    [...]

END_CASE

TF6100 TC3 OPC-UA 129Version: 2.2

Page 130: Manual TF6100 TC3 OPC-UA

Configuration

4.2.4 Security

4.2.4.1 Overview

Security was a central requirement in the development of OPC UA. It is addressed in various areas:

• Encryption• Integrity• Authentication

The confidentiality of the exchanged information is secured by the encryption of the exchanged messages.Modern cryptographic algorithms are used for this. In order to be able to cope with future securityrequirements as well, even stronger and more modern algorithms can subsequently be added to anapplication without changing the protocol. Different security levels can be selected according to therequirements of the respective application. In some areas it is sufficient to sign the messages in order toprevent changes being made by third parties, while additional coding of the messages is necessary in othercases where the data must also not be read by third parties. TF6100 OPC-UA offers the following securitylevels (security end points) with which Clients can connect themselves:

• None: no security• Sign: signed messages• Sign&Encrypt: signed and encrypted messages

The signing of messages prevents a third party from changing the contents of a message. This prevents, forexample, a write statement to open a switch being falsified by a third party and the switch being closedinstead.

OPC-UA applications identify themselves via so-called software and application instance certificates. Withthe aid of software certificates it is possible to grant certain client applications extended access to theinformation on an OPC UA server, for example for the engineering of an OPC UA server. Applicationinstance certificates can be used to ensure that an OPC UA server communicates only with preconfiguredclients. A client can ensure by means of the server’s application instance certificate that it is speaking to thecorrect server (similar to the certificates of a Web browser). The taking into account of these certificates isoptional, i.e. an OPC UA server can also grant the same access to each client, depending on the user rights.

The TwinCAT OPC-UA Client and TwinCAT OPC-UA Server generate a self-signed certificate during the firststart procedure. This certificate consists of a private key and a public key. The private key is saved in the\PKI\CA\private directory and the corresponding public key in the \PKI\CA\certs directory. Any OPC-UAClient wishing to establish a secure connection with the Server via one of the security end points (Sign,Sign&Encrypt) must know the public key of the OPC-UA Server. Conversely the OPC-UA Server must knowthe Client’s public key. This so-called key exchange is described in the following articles.

4.2.4.2 Certificate exchange

Communication between an OPC-UA Client and an OPC-UA Server can optionally be secured by encryptingthe data traffic. By default both the TwinCAT OPC-UA Server and the TwinCAT OPC-UA Client generate atthe first time of starting a machine-specific, self-signed certificate for authentication.

If you wish to use an encrypted connection in your environment, you must set up a trust relationship betweenOPC-UA Server and OPC-UA Client.

This article consists of the following sections, which describe the general exchange of Client and Servercertificates:

• Announcement of the OPC-UA Client to the OPC-UA Server• Announcement of the OPC-UA Server to the OPC-UA Client

TF6100 TC3 OPC-UA130 Version: 2.2

Page 131: Manual TF6100 TC3 OPC-UA

Configuration

Announcement of the OPC-UA Client to the OPC-UA ServerIf you wish to authenticate one or more OPC-UA Clients via certificates on the OPC-UA Server, then theOPC-UA Server must trust the Client’s public keys. To do this the public key of the respective Client must becopied to the following subfolder of the OPC-UA Server:

• TwinCAT 2: %InstallDir%\UA\PKI\CA\certs• TwinCAT 3: %InstallDir%\Server\PKI\CA\certs

This folder contains all the Client certificates that the OPC-UA Server trusts and with which an authenticatedconnection can be established. So that the OPC-UA Server can process them, the Client certificates mustexist here in the format “<AnyName>.der”. The following guide shows you a way of accessing the Clientcertificate, which is probably the simplest possibility to access a Client certificate for many applications. Here,you establish a connection to the UA Server using a security end point (e.g. Basic128Rsa15/Sign&Encrypt)without having copied the Client certificate to the UA server beforehand. This connection is naturally rejectedby the UA Server, since it does not trust the UA Client at this point in time. In this case the TwinCAT OPC-UA Client would return the error 0xE4DD0102, for example. After rejecting the connection, however, the UAServer stores a copy of the Client certificate in the following directory:

• TwinCAT 2: %InstallDir%\UA\PKI\CA\crl• TwinCAT 3: %InstallDir%\Server\PKI\CA\crl

The name of the certificate corresponds here to the “thumbprint” of the certificate and can thus be clearlyassigned to the UA Client certificate. You can now copy this file directly into the “certs” folder so that the UAServer trusts the UA Client and accepts further connection requests.

• TwinCAT 2: %InstallDir%\UA\PKI\CA\certs• TwinCAT 3: %InstallDir%\Server\PKI\CA\certs

Announcement of the OPC-UA Server to the OPC-UA ClientDepending on the OPC-UA Client employed, different steps may need to be taken so that the OPC-UAClient trusts the OPC-UA Server. The following guide therefore applies only to the TwinCAT OPC-UA Client.

The public key of the OPC-UA Server is located in the following directory as a DER file:

• TwinCAT 2: %InstallDir%\UA\PKI\CA\certs• TwinCAT 3: %InstallDir%\Server\PKI\CA\certs

The name of the file is “Beckhoff_OpcUaServer.der”. This file must be copied into the following folderon the OPC-UA Client:

• TwinCAT 2: %InstallDir%\UA Client\PKI\CA\certs• TwinCAT 3: %InstallDir%\Client\PKI\CA\certs

TF6100 TC3 OPC-UA 131Version: 2.2

Page 132: Manual TF6100 TC3 OPC-UA

Configuration

In the case of an OPC-UA Client from a third-party vendor, this file must be announced in a similar form.

The respective TwinCAT OPC-UA Client now trusts the UA Server and allows a connection to be establishedwith it.

4.3 Gateway

4.3.1 OverviewThe TwinCAT OPC-UA Gateway is the newest addition to our TS6100 / TF6100 software product. It not onlyincludes a classic OPC-DA interface to connect legacy OPC COM DA applications to the TwinCAT OPC-UAServer and can therefore be considered as the successor to our old TwinCAT OPC-DA Server (TS6120 /TF6120), but also provides an OPC-UA interface to aggregate multiple underlying TwinCAT OPC-UAServers into one central OPC-UA server channel.

4.3.2 Quick StartThe TS6100 / TF6100 setup automatically installs the TwinCAT OPC-UA Gateway and registers theapplication as a Windows Service. The setup automatically configures access to a TwinCAT OPC-UA Serverthat runs on the same computer as the Gateway.

If more than one TwinCAT OPC-UA Server should be added to the Gateway, or the server is running onanother computer, changes to the default configuration are necessary. Please use the Administration Tool[} 136] to configure these settings.

TF6100 TC3 OPC-UA132 Version: 2.2

Page 133: Manual TF6100 TC3 OPC-UA

Configuration

Note

Important notePlease check the configuration of the TwinCAT OPC-UA Server and make sure that it isworking as expected before proceeding. We recommend to check out our QuickStart articleof the Server component [} 38] for more information about configuring the TwinCAT OPC-UA Server.

QuickStart OPC-COM-DATo connect an OPC-COM-DA Client to the Gateway, please start the client and establish a connection to thefollowing ProgId:UnifiedAutomation.UaGateway.1

When browsing the Gateway, one or more TwinCAT OPC-UA Servers (as described above) are visible in theGateway’s namespace.

TF6100 TC3 OPC-UA 133Version: 2.2

Page 134: Manual TF6100 TC3 OPC-UA

Configuration

QuickStart OPC-UAThe Gateway not only offers an OPC-COM-DA interface but also allows the aggregation of one or moreTwinCAT OPC-UA Servers. For this, the Gateway also opens an OPC-UA interface. The Gateway isavailable via the following OPC-UA Server URL:opc.tcp://[HostnameOrIpAddressOrLocalhost]:48050

The Gateway’s namespace then contains all underlying TwinCAT OPC-UA Servers.

TF6100 TC3 OPC-UA134 Version: 2.2

Page 135: Manual TF6100 TC3 OPC-UA

Configuration

4.3.3 LicensingThe TwinCAT OPC-UA Gateway is delivered to customers for free. No additional licensing is required.Please note that the Gateway component can only be used to connect to TwinCAT OPC-UA Servers.Connection to third-party UA-Servers is prohibited by design. If the customer environment requires toconnect a third-party UA-Server, we recommend to use the Unified Automation UA-Gateway, which can bepurchased at http://www.unified-automation.com.

4.3.4 Setup scenariosDue to the open and flexible PC-based automation technology by Beckhoff, the TwinCAT OPC-UA Gatewaymay be operated and installed in different ways. The following article describes different setup scenarios andalso includes the advantages and disadvantages of each setup.

Gateway and UA-Server on the same computerIn this scenario, the Gateway and UA-Server are installed on the same computer. The Gateway is configuredwith its default setting to connect to the local TwinCAT OPC-UA Server with the following Server URL:opc.tcp://localhost:4840.

This scenario would only work on non-Windows CE devices. Remember: The TwinCAT OPC-UA Server isalso available for Windows CE but the Gateway is only available for big-Windows platforms.

Gateway and UA-Server on different computersIn this scenario, the Gateway and UA-Server are installed on different computers. The Gateway is configuredto connect to the remote TwinCAT OPC-UA Server by setting its corresponding Server URL, e.g.opc.tcp://192.168.1.1:4840.

TF6100 TC3 OPC-UA 135Version: 2.2

Page 136: Manual TF6100 TC3 OPC-UA

Configuration

The TwinCAT OPC-UA Server may be installed on a small Embedded device (e.g. a CX8090 with WindowsCE) whereas the Gateway component is installed on a separate big-Windows platform, e.g. a central serverdevice.

Gateway connected to multiple UA-Server devicesPlease note that, no matter which of the scenarios described above you actually use, it would be of coursepossible to connect other TwinCAT OPC-UA Servers to the Gateway as well. For example, the Gatewaycould be configured to access the following servers:

• The local TwinCAT OPC-UA Server (e.g. opc.tcp://localhost:4840)• A remote TwinCAT OPC-UA Server (e.g. opc.tcp://192.168.1.1:4840)• Another remote TwinCAT OPC-UA Server (e.g. opc.tcp://192.168.1.21:4841)• ...

4.3.5 Configurator

4.3.5.1 Overview

The UA Gateway Administration Tool is a graphical UI to configure the Gateway and available from withinthe context menu of the Gateway icon in the Windows System Tray.

After starting the Administration Tool via the menu entry “Administrate UaGateway”, the graphical userinterface is shown and provides several configuration options, which are described in this documentation.

TF6100 TC3 OPC-UA136 Version: 2.2

Page 137: Manual TF6100 TC3 OPC-UA

Configuration

4.3.5.2 General settings

AutostartHere, you can configure the autostart behaviour of UaGateway. Select “UaGateway Runtime Process” toautomatically start the UaGateway Service when starting the computer, and select “Notification Area Icon” tostart the Notification Area Icon when a user logs on.

Launching UserThe UaGateway runs as Windows NT service. A specific user context is assigned to this service to allowproper COM/DCOM configuration. The user you select is assigned to the UaGateway service. In addition,the user is granted the LogOnAsService right (to allow him/her to start the service) and is added into a local

TF6100 TC3 OPC-UA 137Version: 2.2

Page 138: Manual TF6100 TC3 OPC-UA

Configuration

user group (“UaGatewayUsers”). This group is added to the Access Control List (ACL) of the local machine.For proper COM/DCOM configuration you now just need to add all users that should be able to start andaccess the UaGateway to this group.

Configuration PermissionsIt is possible to allow only certain users to change the configuration of UaGateway, i.e. to add or removeconnections to underlying servers. You can choose between the following settings:

• Everyone Everyone (including the UA anonymous log-on) connecting to UaGateway can perform configurationchanges.

• Limit to operating system users Ony local users and users from the same domain can change the configuration.

• Limit to users of this group: Limit the permission to change the configuration to users of a certain group. If the drop-down box“Group” does not show all available groups (or a newly created group is missing), it is possible to readin this group by pressing the button Refresh.

Remote DCOM AccessWhen checking “Allow Remote Connection to UaGateway OPC COM Server”, DCOM port 135 and theUaGateway executable are added to the firewall exception list.

When “Allow starting UaGateway by DCOM Clients” is disabled, DCOM clients cannot start UaGateway. Inthis case, UaGateway can still be started or stopped using the Notification Area Icon or the start menuentries.

UA Discovery RegistrationHere you can set if the UaGateway should register at the OPC-UA LDS (Local Discovery Server), if any isinstalled.

4.3.5.3 Additional UA Servers

This configuration tab provides options to configure the underlying TwinCAT OPC-UA Servers. By default,the Gateway already connects to the local TwinCAT OPC-UA Server (running on the same computer).

TF6100 TC3 OPC-UA138 Version: 2.2

Page 139: Manual TF6100 TC3 OPC-UA

Configuration

To configure additional TwinCAT OPC-UA servers or remove servers from the configuration, use the Plusand Minus buttons in the lower right corner and click on Apply to save any changes.

4.3.5.4 Additional endpoints

The UA Endpoint is the connection information a UA Client needs to connect with the Gateway. Thefollowing paragraphs describe the UA Endpoint Configuration.

GeneralUse the check boxes to specify which log-on methods a client can use to connect to your UaGateway.

TF6100 TC3 OPC-UA 139Version: 2.2

Page 140: Manual TF6100 TC3 OPC-UA

Configuration

EndpointsHere, you can perform all required settings for different UA Endpoints. By default the endpoint configurationis set to standard values. It is represented by one single UA Endpoint that offers two security options: Noneand Basic128RSsa15.

The None security policy allows every UA Client to connect to the UaGateway, it is recommended to use thisconfiguration just during commissioning and testing, in a production environment this configuration should beswitched off.

The different configuration elements are described in the following paragraphs.

Network ConfigurationEndpoint URL

This is the Endpoint URL of the UaGateway as it will be seen in FindServers and GetEndpoint calls.

Protocol

This is the protocol used for this endpoint.

Hostname/IP

This is the hostname of the UaGateway (it also could be the IP Address of the PC the UaGateway runs on).

Network Adapter

This is the Network Adapter to bind to. Possible selections are:

• AllSelect to bind to all IP addresses of the computer. The endpoint will be reachable on the given port onall IP addresses.

• Network AdapterSelect a Network Adapter and an IP address (below) to bind only to this address. The Endpoint will bereachable for clients only connecting to the selected IP address.

• Local onlyIf this is selected the UaGateway binds to the loopback adapter only. The Endpoint will be reachableonly for clients on the same machine as the UaGateway runs.

Port

This is the TCP port of the Endpoint (typically 48050).

SecurityThe supported security settings of the Endpoint can be configured here. Check the boxes in front of thesecurity policies that should be allowed for a specific Endpoint. For policies other than None, the availablemessage security mode(s) must be specified. Signing ensures that messages cannot be changed and areexchanged between the applications that have established the communication. Encryption ensures thatnobody can read the messages.

4.3.5.5 OPC COM DA settings

The following paragraph describes the configuration of the COM DA Server of the UaGateway using theAdministration Tool.

GeneralItemIDs of the COM DA Server are constructed of the namespace URI and the identifier of the variable nodein the OPC UA address space. The namespace part can be omitted for one namespace. In the drop-downbox “Default Name Space” the default name space can be set to a name space of an underlying OPCServer. The ItemIDs of that particular namespace will then be accessible through the identifier only, because

TF6100 TC3 OPC-UA140 Version: 2.2

Page 141: Manual TF6100 TC3 OPC-UA

Configuration

the default name space is internally automatically added when accessing the Item. This feature can be usedto avoid reconfiguring all ItemIDs in the Client that accesses the UaGateway’s Server used as tunnellingsolution for an underlying COM DA Server and to preserve the ItemIds of the original COM DA Server.

In the second drop-down box, the Timestamp Source can be set. The following options are available:

• InternalThe timestamps are created by the OPC COM DA Server.

• SourceTimestampThe SourceTimestamps are used as timestamps provided by the OPC COM DA Server.

• ServerTimestampThe ServerTimestamps are used as timestamps provided by the OPC COM DA Server.

Property mapping from UA to COM DAWhen connecting to the OPC COM DA Server of the UaGateway, all six standard properties (DataType,Value, Quality, TimeStamp, AccessRights and ScanRate) are mapped automatically. Underlying OPCServers may provide additional properties (e.g. user defined properties, DI properties, etc.) Those propertiescan be mapped to vendor specific properties (PropertyID ≧ 5000) in the UaGateway’s COM DA Server.

These vendor specific PropertyIDs are assigned automatically when the properties are requested for the firsttime. You can use this dialog to change the assigned PropertyIDs or to configure how the OPC UAproperties in the UaGateway’s address space should be mapped to COM DA vendor specific properties. Youmust specify the UA side property name and the namespace of the property in the UaGateway and assignthem to COM DA PropertyIDs. When connecting to the COM DA Server of the UaGateway you canQueryAvailableProperties of an individual OPCItem and you will see the mapped properties as configured (inthe range of vendor specific PropertyIDs above 5000).

To add or remove a specific property, press the buttons “+” or “-”. To change the content of a certain field,double-click on it and enter the desired values. Double-clicking on a value in the column “UA PropertyNameSpace URI” displays a drop-down menu to choose from.

When adding a new property by pressing the button “+”, the values of the last entries are copied to the newline and the Property ID is counted up automatically.

4.3.6 Migrating from Tx6120One of the primary purposes of the UA Gateway is to provide a future-proven connectivity component toreplace the Tx6120 OPC-DA Supplement. For users that want to migrate from Tx6120 OPC-DA to UAGateway, some things might need to be considered and configured.

Overview default configurationThe default configuration of the UA Gateway automatically connects to the local TwinCAT OPC-UA Serverand provides an OPC-DA interface to OPC-DA Clients. When connecting to this default configuration, OPC-DA Clients need to take into account the following things:

• The default ProgID of the UA-Gateway is “UnifiedAutomation.Gateway.1” . The TwinCAT OPC-DAServer was using another ProgID (“Beckhoff.TwinCATOpcServerDA”)

• The UA-Gateway only uses one ProgID instead of several clones.• The identifier of a OPC symbol is created differently in UA-Gateway. This behavior can be changed,

please see below for more information.

How to change syntax of Item IdentifiersThe syntax that the UA-Gateway uses for Item Identifiers can be changed to appear more in the style of theTwinCAT OPC-DA Server. By default the UA-Gateway uses another syntax than the TwinCAT OPC-DAServer to build its identifiers.

Example UA-Gateway:

TF6100 TC3 OPC-UA 141Version: 2.2

Page 142: Manual TF6100 TC3 OPC-UA

Configuration

Example TwinCAT OPC-DA Server:

As you can see, the UA-Gateway attaches a prefix to be able to uniquely identify the underlying OPC-UAServer from which the variable is coming from.

To configure the UA-Gateway to build its identifiers in an almost identical way than the TwinCAT OPC-DAServer, the following settings need to be made. This functionality has been implemented to make themigration process more easy.

1. Open the UA-Gateway configuration file from C:\Program Files (x86)\UnifiedAutomation\UaGateway\bin\uagateway.config.xml

2. In the XML, look for the following XML tags:<OpcServerConfig>  <ComDaServerConfig>    <ComDaNamespaceUseAlias>false</ComDaNamespaceUseAlias>  </ComDaServerConfig></OpcServerConfig>

3. By setting the ComDaNamespaceUseAlias XML tag to “true”, custom prefixes may be set. To do so,please perform the following steps:

4. In the same XML file, look for the following XML tag:<OpcServerConfig>  <UaServerConfig>    <ConfiguredNamespaces>      ...    </ConfiguredNamespaces  </UaServerConfig></OpcServerConfig>

5. In this XML structure, identify the TwinCAT OPC-UA Server namespace. By default, this should be:<OpcServerConfig>  <UaServerConfig>    <ConfiguredNamespaces>      ...      <Namespace>        <Index>...</Index>        <Uri>TcOpcUaServer/urn:Hostname:BeckhoffAutomation:Ua:PLC1</Uri>        <AllowRenameUri>false</AllowRenameUri>

TF6100 TC3 OPC-UA142 Version: 2.2

Page 143: Manual TF6100 TC3 OPC-UA

Configuration

        <UniqueId>TcOpcUaServer#TcOpcUaServer/urn:Hostname:BeckhoffAutomation:Ua:PLC1</UniqueId>        <ComAlias>...</ComAlias>      </Namespace>      ...    </ConfiguredNamespaces  </UaServerConfig></OpcServerConfig>

6. The wildcard “...” may be different on your computer. Set the <ComAlias> to the preferred prefix thatyou would like to use, for example “PLC1”. This will result in the identifiers being build with the prefix“PLC1”.

4.4 Configurator

4.4.1 OverviewThis documentation is intended to give an insight into the use of the TwinCAT OPC-UA configurator. TheOPC-UA configurator parameterizes the TwinCAT OPC-UA Server or serves as a GUI for the configurationof the ServerConfig.xml file and offers the following configuration options:

• Addition/removal of devices for data access (PLC runtimes, TwinCAT 3 C++ instances, I/O tasks)• Activation/deactivation of Historical Access• Activation/deactivation of anonymous accesses or user name/password authentication• Restart or shutdown of the OPC-UA Server

When starting the TwinCAT OPC-UA configurator, the currently active configuration of the TwinCAT OPC-UA Server is automatically loaded, which is located as standard in the \%InstallDir%\Server\ directory as theServerConfig.xml file. However, you can also load, save and activate other ServerConfig.xml files via themenu.

The user interface of the OPC-UA configurator consists of the following sections:

• Menu section: Saving and activation of configurations• Categories section: Grouping of the individual parameters into various categories, e.g. Data Access• Parameter section: Individual parameters for activating/deactivating certain features

TF6100 TC3 OPC-UA 143Version: 2.2

Page 144: Manual TF6100 TC3 OPC-UA

Configuration

• Notice: Please consult the documentation for the respective categories (Data Access, HistoricalAccess, etc.) in order to learn the meaning of the individual configuration parameters.

4.4.2 Data AccessThe Data Access tab provides configuration settings for TwinCAT Runtime devices. This is where a devicethat should be available via OPC-UA needs to be configured.

Every TwinCAT Runtime device requires the following settings:

TF6100 TC3 OPC-UA144 Version: 2.2

Page 145: Manual TF6100 TC3 OPC-UA

Configuration

Setting DescriptionName Display Name of TwinCAT Runtime on OPC-UA namespaceAdsNetId AmsNetId of the TwinCAT Runtime. Use 127.0.0.1.1.1 for a

local Runtime or the corresponding AmsNetId of a remotedevice. Please note that ADS routes need to be configuredwhen communicating with a remote device.

AdsPort AdsPort of the TwinCAT Runtime, e.g. 851 for the firstTwinCAT 3 PLC Runtime.

SymbolFile Symbol file that includes information about all availablevariables and object instances of the Runtime.

AdsTimeout Timeout setting when communicating with target Runtime. Werecommed to leave this setting on its default value.

AdsTimeSuspend TimeSuspend setting when communicating with targetRuntime. We recommed to leave this setting on its defaultvalue. The TimeSuspend timeout will be triggered when atarget Runtime is temporarily not available. The OPC-UAServer will then retry the communication after theTimeSuspend.

Type Type of target Runtime that the OPC-UA Server shouldcommunicate with, e.g. TwinCAT 3 PLC, TwinCAT 2 PLC, ...

AccessMode The Access Mode is usually only required if the OPC-UAServer should communicate with a Runtime that is hosted on aBeckhoff BC/BX device. In this case, the corresponding settingneeds to be activated. In all other case, the default setting isjust fine.

LegacyArrayHandling If legacy OPC-UA Clients require that array elements areavailable as separate UA nodes, activate this setting.

Disabled Set this checkbox to disable the Runtime so that it won’t bepublished to OPC-UA namespace.

Please consult the OPC-UA Server documentation [} 37] for more information about runtime-specificparameters.

4.4.3 Historical AccessThe Historical Access tab is used to configure global settings for Historical Access. This is where the storagemedia that should be used for Historical Access is activated and configured

Please consult the OPC-UA Server documentation [} 37] for more information about Historical Access.

TF6100 TC3 OPC-UA 145Version: 2.2

Page 146: Manual TF6100 TC3 OPC-UA

Configuration

4.4.4 SecurityThe Security tab provides global settings for security and endpoint mechanisms of the OPC-UA Server.

The following table provides an overview about all possible settings:

Setting DescriptionUser Identity Active or deactivate a certain user identity, e.g. deactivate the

checkbox “Anonymous Access” to force user authentication.Endpoints Activate or deactivate specific endpoints, e.g. deactivate the “No

security” endpoint to force UA-Clients to connect with the “Sign andEncrypt” endpoint.

Configuration namespace Allows the activation or deactivation of the configuration namespace[} 112] and to set a specific security level that is required to accessthis namespace (user authentication required).

User Management Allows to configure existing user accounts and set an Access Levelfor each account. Access levels are currently only used to configureaccess to the configuration namespace [} 112]. Please note that, ifthe computer that runs the OPC-UA Server is a member of aWindows domain, the user account may also be an account in thisdomain.

Client Certificates Allows to move OPC-UA Client certificates between the Rejectedand Accepted trust lists. This is where client certificates can easilybe identified and trusted or rejected if clients should connect to oneof the secure endpoints.

4.4.5 Online PanelThe Online Panel extends the TwinCAT OPC-UA Configurator by OPC-UA Client functionalities. It allowsusers to connect to a local or remote TwinCAT OPC-UA Server to acquire diagnostic or administrativefunctionalities.

TF6100 TC3 OPC-UA146 Version: 2.2

Page 147: Manual TF6100 TC3 OPC-UA

Configuration

The following table describes each area in the Online Panel:

Area DescriptionServer information Provides overall diagnostic information of the currently connected to TwinCAT

OPC-UA Server. Useful information could be:Licensing statusAmount of currently established OPC-UA client sessionsAmount of available nodes (may take some time to calculate)Server version

Server logging Provides functionalities to activate a logfile on the TwinCAT OPC-UA Server.This should only be used if advised from Beckhoff Support because the logfilecreation may affect overall system performance.

Device States Provides diagnostic information about each configured ADS device on theTwinCAT OPC-UA Server. This information might be very useful if theconnection to an ADS device needs to be checked. Common configurationissues could for example be that the corresponding symbol file (TPY, TMC)could not be loaded by the TwinCAT OPC-UA Server. The Device States panelwill show a related error message if this is the case.

TF6100 TC3 OPC-UA 147Version: 2.2

Page 148: Manual TF6100 TC3 OPC-UA

Configuration

4.5 Sample Client

4.5.1 OverviewSince version 1.6.80 of the TwinCAT OPC-UA Server, a small program called "UA Sample Client" isautomatically installed. This software enables users to browse the OPC-UA namespace and test the UA-Server installation. It can be found in the Windows start menu and the installation directory of theSupplement/Function. You may execute this UA-Client either directly on the UA-Server or on a computer inyour network. At the moment, the UA-SampleClient provides the following functionalities:

• Connection establishment: Connect to a OPC-UA Server

• Secure connection establishment [} 149]: Securely connect to a OPC-UA Server

• Browsing [} 152]: Browse through the UA-Namespace of a OPC-UA Server

• Watchlist [} 153]: Add UA-Nodes from the namespace to a Watchlist, which periodically reads thenode's value

Please note: • To start the software, simply execute the file "UA SampleClient.exe"• Please make sure to start this application with the option "Run As Administrator "• This application is only a sample OPC-UA client. It does not provide any sophisticated functionalities

but has been developed to provide users with an easy-to-use interface to execute first tests against theTwinCAT OPC-UA Server

Note

Important noteThe OPC-UA Sample Client first connects to a specified Server URL. The client then ac-quires all endpoints of the OPC-UA Server (see DropDownBox “Endpoints”). The list that isreturned by the Server then includes more information about all available endpoints that theClient can connect to. Each endpoint may include the Hostname of the OPC-UA Server in-stead of the IP address. The Client then uses the information from the endpoint to connectto the Server. If name resolution does not work in the user’s network, the Client is unable toconnect. If the endpoint that the Client should connect to includes the Server’s Hostname,please make sure that name resolution works in your network and that the Hostname of theServer is reachable!

TF6100 TC3 OPC-UA148 Version: 2.2

Page 149: Manual TF6100 TC3 OPC-UA

Configuration

4.5.2 Securely connect to a OPC-UA Server1. In the first textbox, please specify the endpoint URL of a OPC-UA Server2. click on the button "Get Endpoints".

TF6100 TC3 OPC-UA 149Version: 2.2

Page 150: Manual TF6100 TC3 OPC-UA

Configuration

ð As a result, all configured endpoints on the UA-Server will be displayed in the drop down box "End-points".

3. In this sample, please select the entry " <SomeName>/Beckhoff/TcOpcUaServer/1 [Basic128Rsa15,SignAndEncrypt] [opc.tcp://<SomeName>:4840]" and click on "Connect".

NOTE! You need to copy the Public Key of the UA-SampleClient certificate to the UA-Server, sothat it trusts the SampleClient, otherwise the connection establishment will fail("BadSecureChannelClosed").

TF6100 TC3 OPC-UA150 Version: 2.2

Page 151: Manual TF6100 TC3 OPC-UA

Configuration

For more information about the certificate management of TwinCAT OPC-UA Server, please click here[} 130].

TF6100 TC3 OPC-UA 151Version: 2.2

Page 152: Manual TF6100 TC3 OPC-UA

Configuration

4. Via the browser part on the left side of the window, the UA namespace can be browsed.

4.5.3 Browsing the UA-NamespaceVia the browser on the left side of the UA SampleClient window, the UA namespace can be browsed. Thenode "PLC1" represents the first TwinCAT PLC runtime and all variables configured for OPC-UA can beaccessed from below this node. For more information about configuring PLC variables for OPC-UA, pleasesee the corresponding article.

TF6100 TC3 OPC-UA152 Version: 2.2

Page 153: Manual TF6100 TC3 OPC-UA

Configuration

4.5.4 Using the WatchlistAll PLC variables of the UA namespace may be added to the Watchlist, for example to cyclically read theirvalues. To add a variable to the Watchlist, please right-click it and select "Add to Watchlist". The variablewill be automatically added to the Watchlist, the values will be automatically cyclically readout from the plc.

TF6100 TC3 OPC-UA 153Version: 2.2

Page 154: Manual TF6100 TC3 OPC-UA

Configuration

TF6100 TC3 OPC-UA154 Version: 2.2

Page 155: Manual TF6100 TC3 OPC-UA

PLC libraries

5 PLC libraries

5.1 Tc3_PLCopen_OpcUa

5.1.1 Function Blocks

5.1.1.1 UA_Connect

This function block opens an OPC-UA session to a remote OPC-UA server, which is specified via itsServerUrl and SessionConnectInfo. The function block returns a connection handle which can be used forother function blocks, e.g. UA_Read.

VAR_INPUTVAR_INPUT    Execute            : BOOL;    ServerUrl          : STRING(MAX_STRING_LENGTH);    SessionConnectInfo : ST_UASessionConnectInfo;        Timeout            : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

ST_UASessionConnectInfo [} 168]

Execute : The command is triggered by a rising edge at this input.

ServerUrl : OPC-UA server URL. e.g. 'opc.tcp://172.16.3.207:4840' or 'opc.tcp://CX_0193BF:4840'.

SessionConnectInfo : Information for session connection. Please see ST_UASessionConnectInfo [} 168].

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.Please note: ST_UASessionConnectInfo [} 168].tSessionTimeout needs to be shorter than this Timeout.

VAR_OUTPUTVAR_OUTPUT    ConnectionHdl : DWORD;    Done          : BOOL;    Busy          : BOOL;    Error         : BOOL;    ErrorID       : DWORD;END_VAR

ConnectionHdl : OPC-UA connection handle.

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘ErrorID’.

TF6100 TC3 OPC-UA 155Version: 2.2

Page 156: Manual TF6100 TC3 OPC-UA

PLC libraries

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.1.2 UA_Disconnect

This function block closes an OPC-UA session to a remote OPC-UA server. The session is specified via itsconnection handle.

VAR_INPUTVAR_INPUT    Execute          : BOOL;    ConnectionHdl    : DWORD;        Timeout          : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    Done       : BOOL;    Busy       : BOOL;    Error      : BOOL;    ErrorID    : DWORD;END_VAR

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘nErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

TF6100 TC3 OPC-UA156 Version: 2.2

Page 157: Manual TF6100 TC3 OPC-UA

PLC libraries

5.1.1.3 UA_GetNamespaceIndex

This function block acquires the namespace index for a namespace URI. The namespace index is requiredfor symbol identification, e.g. when using the UA_Read [} 163] or UA_Write [} 164] function blocks.

VAR_INPUTVAR_INPUT    Execute       : BOOL;    ConnectionHdl : DWORD;    NamespaceUri  : STRING(MAX_STRING_LENGTH);        Timeout       : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

NamespaceUri : The namespace URI which should be resolved. In case of a TwinCAT OPC-UA Server,this would be "PLC1" for the first PLC runtime.

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    NamespaceIndex : UINT;    Done           : BOOL;    Busy           : BOOL;    Error          : BOOL;    ErrorID        : DWORD;END_VAR

NamespaceIndex : Namespace index of the given Namespace URI. This may be used in other functionblocks, e.g. UA_Read or UA_Write.

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘ErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

TF6100 TC3 OPC-UA 157Version: 2.2

Page 158: Manual TF6100 TC3 OPC-UA

PLC libraries

5.1.1.4 UA_MethodCall

This function block calls a method on a remote UA Server. The method is determined by a connection andmethod handle. The former can be retrieved by using UA_Connect [} 155] and the later can be retrieved byusing UA_MethodGetHandle [} 159].

VAR_INPUTVAR_INPUT    Execute                  : BOOL;    ConnectionHdl            : DWORD;    MethodHdl                : DWORD;    nNumberOfInputArguments  : UDINT;    pInputArgInfo            : POINTER TO ST_UAMethodArgInfo;    cbInputArgInfo           : UDINT;    pInputArgData            : PVOID;    cbInputArgData           : UDINT;    pInputWriteData          : PVOID;    cbInputWriteData         : UDINT;    nNumberOfOutputArguments : UDINT;    pOutputArgInfo           : POINTER TO ST_UAMethodArgInfo;    cbOutputArgInfo          : UDINT;     pOutputArgInfoAndData    : PVOID;    cbOutputArgInfoAndData   : UDINT;     Timeout                  : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

ST_UAMethodArgInfo [} 169] ST_UAMethodArgInfo [} 169]

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

MethodHdl : Method handle, which has been previously acquired by using the function blockUA_MethodGetHandle [} 159].

nNumberOfInputArguments : Number of input parameters.

pInputArgInfo : Points to address of buffer where input parameter information is located as an array of typeST_UAMethodArgInfo [} 169].

cbInputArgInfo : Size of buffer where input parameter information is located.

pInputArgData : Points to address of buffer where input parameters (of constant length) are located.

cbInputArgData : Size of input buffer where input parameters (of constant length) are located.

TF6100 TC3 OPC-UA158 Version: 2.2

Page 159: Manual TF6100 TC3 OPC-UA

PLC libraries

pInputWriteData : Pointer to address of buffer where input parameters (of dynamic length) are located.

cbInputWriteData : Size of input buffer where input parameters (of dynamic length) are located.

nNumberOfOutputArguments : Number of output parameters.

pOutputArgInfo : Points to address of buffer where output parameter information is located as an array oftype ST_UAMethodArgInfo [} 169];For output parameters, nLenData is required for defining target memory per parameter.All other elements could be set for enabling type-checking of returned parameters or can be left undefined-

cbOutputArgInfo : Size of buffer where output parameter information is located.;

pOutputArgInfoAndData : Points to address of buffer where output parameters should be stored as aBYTE array. BYTE Array will contain number of output parameters as DINT, 4 reserved bytes and parameterinformation as ARRAY OF ST_UAMethodArgInfo [} 169] (with length of output parameters) followed by puredata. Please note that the data therefore is packed as 1byte alignment.

cbOutputArgInfoAndData : Size of buffer where output parameters should be stored as a BYTE array.

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    cbRead_R    : UDINT;    Done        : BOOL;    Busy        : BOOL;    Error       : BOOL;    ErrorID     : UDINT;END_VAR

cbRead_R : count of overall received bytes

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘nErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUa

5.1.1.5 UA_MethodGetHandle

This function block acquires a handle for a UA method, which can then be used to call a method viaUA_MethodCall [} 158].

TF6100 TC3 OPC-UA 159Version: 2.2

Page 160: Manual TF6100 TC3 OPC-UA

PLC libraries

VAR_INPUTVAR_INPUT    Execute          : BOOL;    ConnectionHdl    : DWORD;    ObjectNodeID     : ST_UANodeID;    MethodNodeID     : ST_UANodeID;    Timeout          : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

ST_UANodeID [} 170] ST_UANodeID [} 170]

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

ObjectNodeID : Object Node ID of method to be called.

MethodNodeID : Method Node ID of method to be called. This equals the Identifier attribute in UAnamespace.

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    MethodHdl    : DWORD;    Done         : BOOL;    Busy         : BOOL;    Error        : BOOL;    ErrorID      : UDINT;END_VAR

MethodHdl : Returns method handle which can then be used to call a method via UA_MethodCall [} 158].

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘nErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUa

5.1.1.6 UA_MethodReleaseHandle

This function block releases the specified method handle.

TF6100 TC3 OPC-UA160 Version: 2.2

Page 161: Manual TF6100 TC3 OPC-UA

PLC libraries

VAR_INPUTVAR_INPUT    Execute          : BOOL;    ConnectionHdl    : DWORD;    MethodHdl        : DWORD;    Timeout          : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

MethodHdl : Method handle, which has been previously acquired by using the function blockUA_MethodGetHandle [} 159].

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    Done    : BOOL;    Busy    : BOOL;    Error   : BOOL;    ErrorID : UDINT;END_VAR

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘nErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUa

5.1.1.7 UA_NodeGetHandle

This function block retrieves a node handle for a given symbol in UA namespace. The symbol will bespecified by a connection handle and its node ID.

VAR_INPUTVAR_INPUT    Execute       : BOOL;    ConnectionHdl : DWORD;    NodeID        : ST_UANodeID;    Timeout       : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

TF6100 TC3 OPC-UA 161Version: 2.2

Page 162: Manual TF6100 TC3 OPC-UA

PLC libraries

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

Node ID : Node handle, which has been previously acquired by using the function block UA_NodeGetHandle[} 161].

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    NodeHdl    : DWORD;    Done       : BOOL;    Busy       : BOOL;    Error      : BOOL;    ErrorID    : DWORD;END_VAR

NodeHdl : Node handle, which can be used for other function blocks, e.g. UA_Read or UA_Write.

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘ErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.1.8 UA_NodeReleaseHandle

This function block releases a node handle.

VAR_INPUTVAR_INPUT    Execute       : BOOL;    ConnectionHdl : DWORD;    NodeHdl       : DWORD;    Timeout       : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

TF6100 TC3 OPC-UA162 Version: 2.2

Page 163: Manual TF6100 TC3 OPC-UA

PLC libraries

NodeHdl : Node handle that should be released

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    Done    : BOOL;    Busy    : BOOL;    Error   : BOOL;    ErrorID : DWORD;END_VAR

Done : Switches to TRUE if the function block has finished execution.

Busy : This output remains TRUE until the block has executed a command, but at the longest for theduration supplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at theinputs. Please note that it is not the execution of the service but its acceptance whose time is monitored.

Error : This output is switched to TRUE if an error occurs during the execution of a command. Thecommand-specific error code is contained in ‘ErrorID’.

ErrorID : Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.1.9 UA_Read

This function block reads values from a given node and connection handle.

VAR_INPUTVAR_INPUT    Execute          : BOOL;    ConnectionHdl    : DWORD;    NodeHdl          : DWORD;    stNodeAddInfo    : ST_UANodeAdditionalInfo;    pVariable        : PVOID;    cbData           : UDINT;    Timeout          : TIME := DEFAULT_ADS_TIMEOUT;    END_VAR

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

NodeHdl : Node handle, which has been previously acquired by using the function blockUA_NodeGetHandle [} 161].

TF6100 TC3 OPC-UA 163Version: 2.2

Page 164: Manual TF6100 TC3 OPC-UA

PLC libraries

stNodeAddInfo : Defines additional information, e.g. which attribute should be read from UA namespace(by default the 'Value' attribute will be used) or which IndexRange should be used. Will be specified by structST_UANodeAdditionalInfo [} 170].

pVariable : Pointer to data, where the read data will be stored.

cbData : Determines the size of the data that should be read.

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    Done      : BOOL;    Busy      : BOOL;    Error     : BOOL;    ErrorID   : UDINT;    cbData_R  : UDINT;END_VAR

Done: Switches to TRUE if the function block has finished execution.

Busy: This output remains TRUE until the block has executed a command, but at the longest for the durationsupplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at the inputs. Pleasenote that it is not the execution of the service but its acceptance whose time is monitored.

Error: This output is switched to TRUE if an error occurs during the execution of a command. The command-specific error code is contained in ‘nErrorID’.

ErrorID: Contains the command-specific ADS error code of the most recently executed command.

cbData_R: Amount of bytes to read.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.1.10 UA_Write

This function block writes values to a given node and connection handle.

VAR_INPUTVAR_INPUT    Execute          : BOOL;    ConnectionHdl    : DWORD;    NodeHdl          : DWORD;    stNodeAddInfo    : ST_UANodeAdditionalInfo;     pVariable        : PVOID;

TF6100 TC3 OPC-UA164 Version: 2.2

Page 165: Manual TF6100 TC3 OPC-UA

PLC libraries

    cbData           : UDINT;        Timeout          : TIME := DEFAULT_ADS_TIMEOUT; END_VAR

Execute : The command is triggered by a rising edge at this input.

ConnectionHdl : Connection handle, which has been previously acquired by using the function blockUA_Connect [} 155].

NodeHdl : Node handle, which has been previously acquired by using the function blockUA_NodeGetHandle [} 161].

stNodeAddInfo : Defines additional information, e.g. which IndexRange or attribute should be written to (bydefault the 'Value' attribute will be used). Will be specified by struct ST_UANodeAdditionalInfo [} 170].

pVariable : Pointer to the data to be written

cbData : Defines the size of the value to be written.

Timeout : States the time before the function is cancelled. DEFAULT_ADS_TIMEOUT is a global constantset to 5 seconds.

VAR_OUTPUTVAR_OUTPUT    Done     : BOOL;    Busy     : BOOL;    Error    : BOOL;    ErrorID  : DWORD;END_VAR

Done: Switches to TRUE if the function block has finished execution.

Busy: This output remains TRUE until the block has executed a command, but at the longest for the durationsupplied to the ‘Timeout’ input. While Busy = TRUE, no new command will be accepted at the inputs. Pleasenote that it is not the execution of the service but its acceptance whose time is monitored.

Error: This output is switched to TRUE if an error occurs during the execution of a command. The command-specific error code is contained in ‘ErrorID’.

ErrorID: Contains the command-specific ADS error code of the most recently executed command.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2 Data Types

5.1.2.1 E_UAAttributeID

E_UAAttributeID

TYPE E_UAAttributeID:(    eUAAI_NodeID     := 1,    eUAAI_NodeClass    := 2,    eUAAI_BrowseName := 3,    eUAAI_DisplayName := 4,    eUAAI_Description := 5,    eUAAI_WriteMask    := 6,    eUAAI_UserWriteMask := 7,    eUAAI_IsAbstract := 8,    eUAAI_Symmetric    := 9,    eUAAI_InverseName := 10,

TF6100 TC3 OPC-UA 165Version: 2.2

Page 166: Manual TF6100 TC3 OPC-UA

PLC libraries

    eUAAI_ContainsNoLoops := 11,    eUAAI_EventNotifier := 12,    eUAAI_Value     := 13,    eUAAI_DataType     := 14,    eUAAI_ValueRank    := 15,    eUAAI_ArrayDimensions := 16    )DINT;END_TYPE

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.2 E_UADataType

E_UADataType

TYPE E_UADataType:(    eUAType_Undefinied := -1,    eUAType_Null     := 0,    eUAType_Boolean    := 1,    eUAType_SByte     := 2,    eUAType_Byte     := 3,    eUAType_Int16     := 4,    eUAType_UInt16     := 5,    eUAType_Int32     := 6,    eUAType_UInt32     := 7,    eUAType_Int64     := 8,    eUAType_UInt64     := 9,    eUAType_Float     := 10,    eUAType_Double     := 11,    eUAType_String     := 12,    eUAType_DateTime := 13,    eUAType_Guid     := 14,    eUAType_ByteString := 15,    eUAType_XmlElement := 16,    eUAType_NodeId     := 17,    eUAType_ExpandedNodeId := 18,    eUAType_StatusCode := 19,    eUAType_QualifiedName := 20,    eUAType_LocalizedText := 21,    eUAType_ExtensionObject:= 22,    eUAType_DataValue := 23,    eUAType_Variant    := 24,    eUAType_DiagnosticInfo := 25)DINT;END_TYPE

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.3 E_UAIdentifierType

E_UATransportProfile

TYPE E_UAIdentifierType:(    eUAIdentifierType_String := 1,    eUAIdentifierType_Numeric := 2,    eUAIdentifierType_GUID := 3,

TF6100 TC3 OPC-UA166 Version: 2.2

Page 167: Manual TF6100 TC3 OPC-UA

PLC libraries

    eUAIdentifierType_Opaque := 4)DINT;END_TYPE

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.4 E_UASecurityMsgMode

E_UASecurityMsgMode

TYPE E_UASecurityMsgMode:(    eUASecurityMsgMode_BestAvailable := 0,    eUASecurityMsgMode_None     := 1,    eUASecurityMsgMode_Sign     := 2,    eUASecurityMsgMode_Sign_Encrypt := 3)DINT;END_TYPE

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.5 E_UASecurityPolicy

E_UASecurityPolicy

TYPE E_UASecurityPolicy:(    eUASecurityPolicy_BestAvailable := 0    eUASecurityPolicy_None     := 1,    eUASecurityPolicy_Basic128     := 2,    eUASecurityPolicy_Basic128Rsa15 := 3,    eUASecurityPolicy_Basic256     := 4)DINT;END_TYPE

None : a policy used for configurations with lowest security needs

Basic128 : a policy used for low to medium secure configurations.

Basic128Rsa15 : defines a Security Policy for medium to highly secure configurations.

Basic256 : defines a Security Policy for configurations with high security needs

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

TF6100 TC3 OPC-UA 167Version: 2.2

Page 168: Manual TF6100 TC3 OPC-UA

PLC libraries

5.1.2.6 E_UATransportProfile

E_UATransportProfile

TYPE E_UATransportProfile:(    eUATransportProfileUri_UATcp        := 1,    eUATransportProfileUri_WSHttpBinary     := 2,    eUATransportProfileUri_WSHttpXmlOrBinary := 3,    eUATransportProfileUri_WSHttpXml     := 4)DINT;END_TYPE

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.7 ST_UASessionConnectInfo

ST_UASessionConnectInfo

TYPE ST_UASessionConnectInfo:STRUCT    sApplicationUri     : STRING(MAX_STRING_LENGTH);    sApplicationName    : STRING(MAX_STRING_LENGTH);

    eSecurityMode     : E_UASecurityMsgMode;    eSecurityPolicyUri : E_UASecurityPolicy;    eTransportProfileUri : E_UATransportProfile;

    tSessionTimeout     : TIME;    tConnectTimeout     : TIME;END_STRUCTEND_TYPE

sApplicationUri: Application Uri with a maximum string length of 255. Since TcUAClient 2.0.0.14 this will be auto-set from the certificate like defined in PLCOpen specification

sApplicationName: Application name with a maximum string length of 255.

eSecurityMode: Security message mode. See the available modes here E_UASecurityMsgMode [} 167].

eSecurityPolicyUri: Security policy Uri. See the available security policy uri's here E_UASecurityPolicy[} 167].

eTransportProfileUri: Transport profile Uri. See the available transport profile uri's hereE_UATransportProfile [} 168];

nSessionTimeout: Session timeout value.

nConnectTimeout: Connection timeout value.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

TF6100 TC3 OPC-UA168 Version: 2.2

Page 169: Manual TF6100 TC3 OPC-UA

PLC libraries

5.1.2.8 ST_UAIndexRange

ST_UAIndexRange

TYPE ST_UAIndexRange:STRUCT    nStartIndex     : UDINT;    nEndIndex     : UDINT;END_STRUCTEND_TYPE

For each dimension:

• StartIndex and EndIndex are to be assigned• StartIndex must be smaller than EndIndex• To access all the elements in a dimension, it is a must to assign StartIndex and EndIndex depending

on the number of total elements in the dimension• As single elements in a dimension can be selected by specifying the same StartIndex and EndIndex

nStartIndex : Start index of data.

nEndIndex : End index of data.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.9 ST_UAMethodArgInfo

ST_UAMethodArgInfo

TYPE ST_UAMethodArgInfo:STRUCT    DataType     : E_UADataType := -1;    ValueRank    : DINT := 2147483647;    ArrayDimensions : ARRAY[1..3] OF UDINT := [0,0,0];    nLenData     : DINT;END_STRUCTEND_TYPE

Datatype: Specifies the UA data type for the method parameter. (E_UADataType [} 166])

ValueRank: Specifies if the parameter is either a scalar (-1) or an array.

ArrayDimensions: If the parameter is an array, this specifies the dimensions of the array. Each Elementspecifies length per dimension.

nLenData: Specifies the length of the argument. For output information, this is the only required element ofthe struct.

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

TF6100 TC3 OPC-UA 169Version: 2.2

Page 170: Manual TF6100 TC3 OPC-UA

PLC libraries

5.1.2.10 ST_UANodeID

ST_UANodeID

TYPE ST_UANodeID:STRUCT    nNamespaceIndex     : UINT;    nReserved     : ARRAY [1..2] OF BYTE; //fill bytes    sIdentifier     : STRING(MAX_STRING_LENGTH);    eIdentifierType     : E_UAIdentifierType;END_STRUCTEND_TYPE

nNamespaceIndex: NamespaceIndex under which the node is available. Can be determined by functionblock UA_GetNamespaceIndex [} 157].

sIdentifier: Identifier as shown in UA namespace (attribute 'Identifier').

eIdentifierType: Type of variable, described by E_UAIdentifierType [} 166].

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

5.1.2.11 ST_UANodeAdditionalInfo

ST_UANodeAdditionalInfo

TYPE ST_UANodeAdditionalInfo:STRUCT    eAttributeID : E_UAAttributeID;    nIndexRangeCount : UINT;    nReserved     : ARRAY[1..2] OF BYTE; // fill bytes    stIndexRange : ARRAY[1..nMaxIndexRange] OF ST_UAIndexRange;END_STRUCTEND_TYPE

eAttributeID: Specifies the ID of the OPC-UA attribute. By default eUAAI_Value will be used.(E_UAAttributeID [} 165])

nIndexRangeCount: Specifies how many index ranges will be used in stIndexRange.

stIndexRange: Specifies an index range that should be used to read values from an array.(ST_UAIndexRange [} 169])

Requirements

Development environment Target system type PLC libraries to be linkedTwinCAT 3.1 Win32, Win64, CE-X86, CE-ARM Tc3_PLCopen_OpcUaTwinCAT 2.11 R3 Build 2245 Win32, CE-X86, CE-ARM Tc2_PLCopen_OpcUa

TF6100 TC3 OPC-UA170 Version: 2.2

Page 171: Manual TF6100 TC3 OPC-UA

Samples

6 Samples

6.1 OverviewSam-ple

Category TwinCAT ver-sion

Description Download

1 OPC-UA Server TC2 / TC3 Data Access: PLC sample program Sample2 OPC-UA Server TC2 / TC3 Historical Access: PLC sample program Sample3 OPC-UA Client

Tc3_PLCopen_OpcUa

TC3 Samples for UA_Read, UA_Write andUA_MethodCall

Sample

4 OPC-UA ClientTc2_PLCopen_OpcUa

TC2 Samples for UA_Read and UA_Write Sample

TF6100 TC3 OPC-UA 171Version: 2.2

Page 172: Manual TF6100 TC3 OPC-UA

Appendix

7 Appendix

7.1 OPC-UA Server error codesThe table gives an overview of the global OPC-UA error messages.

Hex Description0xE4DD0000 general UA Server error0xE4DA0000 general ADS error0xE4DB0000 general API error0xE4DD0100 Server is already connected0xE4DD0101 general error while establishing a connection to the

UA server0xE4DD0100 Server is already connected0xE4DD0101 general error while establishing a connection to the

UA server0xE4DD0102 failed to setup UA security0xE4DD0103 item ID already exists0xE4DD0104 item does not exist0xE4DD0105 invalid or unsupported item type0xE4DD0106 var types cannot be converted0xE4DD0107 device is suspended0xE4DD0108 vartype conversion is not supported for this type0xE4DD0109 a namespace with the requested name cannot be

found0xE4DD0110 target host not found0xE4DD0111 timeout due to missing reply from target host0xE4DD0112 UA Client session handle is invalid0xE4DD0113 invalid node ID

7.2 OPC-UA Client error codesThe prior described function blocks have output variables indicating an error as well as an ErrorID fordetailed information about the occurred problem.This Error Code list is a list of possible values.

TF6100 TC3 OPC-UA172 Version: 2.2

Page 173: Manual TF6100 TC3 OPC-UA

Appendix

Name Description UpperBytes

LowerBytes

UAC_E_FAIL UA service invocationfailed

0xE4DD 0x0001

UAC_E_CONNECTED Server is alreadyconnected

0x0100

UAC_E_CONNECT General error whileestablishing anconnection

0x0101

UAC_E_UASECURITY failed to setup uasecurity

0x0102

UAC_E_ITEMEXISTS item id already exists 0x0103UAC_E_ITEMNOTFOUND item does not exist 0x0104UAC_E_ITEMTYPE invalid or unsupported

itemtype0x0105

UAC_E_CONVERSION vartypes cannot beconverted

0x0106

UAC_E_SUSPENDED device is suspended.retry later...

0x0107

UAC_E_TYPE_NOT_SUPPORTED vartype conversion isnot supported

0x0108

UAC_E_NSNAME_NOTFOUND A namespace with therequested name couldnot be found

0x0109

UAC_E_CONNECT_NOTFOUND Connect failed: targethost not found

0x0110

UAC_E_TIMEOUT Timeout: i.e. target hostdoes not reply

0x0111

UAC_E_INVALIDHDL Session handle wasinvalid

0x0112

UAC_E_INVALIDNODEID Ua node id wasunknown

0x0113

UAC_E_INVAL_IDENTIFIER_TYPE Identifier type of theUaNodeId is invalid

0x0114

UAC_E_IDENTIFIER_NOTSUPP Identifier type UaNodeIdis not supported

0x0115

UAC_E_INVAL_NODE_HDL Invalid node handle 0x0116UAC_E_UAREADFAILED Ua Read service failed

for unknown reason0x0117

UAC_E_UAWRITEFAILED Ua write service failedfor unknown reason

0x0118

UAC_E_INVAL_NODEMETHOD_HDL Invalid method handle 0x0119UAC_E_CALL_FAILED Call failed; unknown

reason0x011A

UAC_E_CALLDECODE_FAILED Call succeeded, butreturn value decodefailed

0x011B

UAC_E_NOTMAPPEDTYPE Non-mapped datatype inreturn value

0x011C

UAC_E_CALL_FAILED_BADINTERNAL Call failed w/UA_BadInternal

0x011D

UAC_E_METHODIDINVALID Unknown MethodID(returned by Call even ifprovided byGetMethodHdl)

0x011E

TF6100 TC3 OPC-UA 173Version: 2.2

Page 174: Manual TF6100 TC3 OPC-UA

Appendix

Name Description UpperBytes

LowerBytes

UAC_E_TOOMUCHDIM Method Call returned aparameter with morethan 3 dimensions -unsupported

0x011F

UAC_E_CALL_FAILED_INVALIDARG Call failed w/OpcUa_BadInvalidArgument

0x0120

UAC_E_CALL_FAILED_TYPEMISMATCH Call failed w/UAC_E_CALL_FAILED_TYPEMISMATCH

0x0121

UAC_E_CALL_FAILED_OUTOFRANGE Call failed w/UAC_E_CALL_FAILED_OUTOFRANGE

0x0122

UAC_E_CALL_FAILED_BADSTRUCTURE Call failed w/OpcUa_BadStructureMissing

0x0123

UAC_E_CALL_TYPEMISMATCH_OUTPARAM

Call succeeded, buttypemismatch onprovided outputinformation

0x0124

UAC_E_NONVALIDTYPEINFO Node has non-sufficienttype information

0x0125

UAC_E_INVALIDATTRIBID Accessing a invalidattribute of the node

0x0126

DEVICE_INVALIDSIZE parameter size notcorrect

0x705

DEVICE_INVALIDDATA invalid parameter values 0x706

For further return codes please see also ADS return codes [} 174].

7.3 ADS Return CodesError codes: 0x000 [} 175]..., 0x500 [} 175]..., 0x700 [} 176]..., 0x1000 [} 178]...

TF6100 TC3 OPC-UA174 Version: 2.2

Page 175: Manual TF6100 TC3 OPC-UA

Appendix

Global Error CodesHex Dec Description

0x0 0 no error0x1 1 Internal error0x2 2 No Rtime0x3 3 Allocation locked memory error0x4 4 Insert mailbox error0x5 5 Wrong receive HMSG0x6 6 target port not found0x7 7 target machine not found0x8 8 Unknown command ID0x9 9 Bad task ID0xA 10 No IO0xB 11 Unknown ADS command0xC 12 Win 32 error0xD 13 Port not connected0xE 14 Invalid ADS length0xF 15 Invalid ADS Net ID0x10 16 Low Installation level0x11 17 No debug available0x12 18 Port disabled0x13 19 Port already connected0x14 20 ADS Sync Win32 error0x15 21 ADS Sync Timeout0x16 22 ADS Sync AMS error0x17 23 ADS Sync no index map0x18 24 Invalid ADS port0x19 25 No memory0x1A 26 TCP send error0x1B 27 Host unreachable0x1C 28 Invalid AMS fragment

Router Error CodesHex Dec Name Description

0x500 1280 ROUTERERR_NOLOCKEDMEMORY No locked memory can be allocated0x501 1281 ROUTERERR_RESIZEMEMORY The size of the router memory could not be changed0x502 1282 ROUTERERR_MAILBOXFULL The mailbox has reached the maximum number of possible

messages. The current sent message was rejected0x503 1283 ROUTERERR_DEBUGBOXFULL The mailbox has reached the maximum number of possible

messages.The sent message will not be displayed in the debug monitor

0x504 1284 ROUTERERR_UNKNOWNPORTTYPE Unknown port type0x505 1285 ROUTERERR_NOTINITIALIZED Router is not initialized0x506 1286 ROUTERERR_PORTALREADYINUSE The desired port number is already assigned0x507 1287 ROUTERERR_NOTREGISTERED Port not registered0x508 1288 ROUTERERR_NOMOREQUEUES The maximum number of Ports reached0x509 1289 ROUTERERR_INVALIDPORT Invalid port0x50A 1290 ROUTERERR_NOTACTIVATED TwinCAT Router not active

TF6100 TC3 OPC-UA 175Version: 2.2

Page 176: Manual TF6100 TC3 OPC-UA

Appendix

General ADS Error Codes

TF6100 TC3 OPC-UA176 Version: 2.2

Page 177: Manual TF6100 TC3 OPC-UA

Appendix

Hex Dec Name Description0x700 1792 ADSERR_DEVICE_ERROR error class <device error>0x701 1793 ADSERR_DEVICE_SRVNOTSUPP Service is not supported by server0x702 1794 ADSERR_DEVICE_INVALIDGRP invalid index group0x703 1795 ADSERR_DEVICE_INVALIDOFFSET invalid index offset0x704 1796 ADSERR_DEVICE_INVALIDACCESS reading/writing not permitted0x705 1797 ADSERR_DEVICE_INVALIDSIZE parameter size not correct0x706 1798 ADSERR_DEVICE_INVALIDDATA invalid parameter value(s)0x707 1799 ADSERR_DEVICE_NOTREADY device is not in a ready state0x708 1800 ADSERR_DEVICE_BUSY device is busy0x709 1801 ADSERR_DEVICE_INVALIDCONTEXT invalid context (must be in Windows)0x70A 1802 ADSERR_DEVICE_NOMEMORY out of memory0x70B 1803 ADSERR_DEVICE_INVALIDPARM invalid parameter value(s)0x70C 1804 ADSERR_DEVICE_NOTFOUND not found (files, ...)0x70D 1805 ADSERR_DEVICE_SYNTAX syntax error in command or file0x70E 1806 ADSERR_DEVICE_INCOMPATIBLE objects do not match0x70F 1807 ADSERR_DEVICE_EXISTS object already exists0x710 1808 ADSERR_DEVICE_SYMBOLNOTFOUND symbol not found0x711 1809 ADSERR_DEVICE_SYMBOLVERSIONINVAL symbol version invalid

0x712 1810 ADSERR_DEVICE_INVALIDSTATE server is in invalid state0x713 1811 ADSERR_DEVICE_TRANSMODENOTSUPP AdsTransMode not supported0x714 1812 ADSERR_DEVICE_NOTIFYHNDINVALID Notification handle is invalid

0x715 1813 ADSERR_DEVICE_CLIENTUNKNOWN Notification client not registered0x716 1814 ADSERR_DEVICE_NOMOREHDLS no more notification handles0x717 1815 ADSERR_DEVICE_INVALIDWATCHSIZE size for watch too big0x718 1816 ADSERR_DEVICE_NOTINIT device not initialized0x719 1817 ADSERR_DEVICE_TIMEOUT device has a timeout0x71A 1818 ADSERR_DEVICE_NOINTERFACE query interface failed0x71B 1819 ADSERR_DEVICE_INVALIDINTERFACE wrong interface required0x71C 1820 ADSERR_DEVICE_INVALIDCLSID class ID is invalid0x71D 1821 ADSERR_DEVICE_INVALIDOBJID object ID is invalid0x71E 1822 ADSERR_DEVICE_PENDING request is pending0x71F 1823 ADSERR_DEVICE_ABORTED request is aborted0x720 1824 ADSERR_DEVICE_WARNING signal warning0x721 1825 ADSERR_DEVICE_INVALIDARRAYIDX invalid array index0x722 1826 ADSERR_DEVICE_SYMBOLNOTACTIVE symbol not active0x723 1827 ADSERR_DEVICE_ACCESSDENIED access denied0x724 1828 ADSERR_DEVICE_LICENSENOTFOUND missing license0x725 1829 ADSERR_DEVICE_LICENSEEXPIRED license expired0x726 1830 ADSERR_DEVICE_LICENSEEXCEEDED license exceeded0x727 1831 ADSERR_DEVICE_LICENSEINVALID license invalid0x728 1832 ADSERR_DEVICE_LICENSESYSTEMID license invalid system id0x729 1833 ADSERR_DEVICE_LICENSENOTIMELIMIT license not time limited0x72A 1834 ADSERR_DEVICE_LICENSEFUTUREISSUE license issue time in the future0x72B 1835 ADSERR_DEVICE_LICENSETIMETOLONG license time period to long0x72c 1836 ADSERR_DEVICE_EXCEPTION exception occured during system start0x72D 1837 ADSERR_DEVICE_LICENSEDUPLICATED License file read twice0x72E 1838 ADSERR_DEVICE_SIGNATUREINVALID invalid signature0x72F 1839 ADSERR_DEVICE_CERTIFICATEINVALID public key certificate0x740 1856 ADSERR_CLIENT_ERROR Error class <client error>0x741 1857 ADSERR_CLIENT_INVALIDPARM invalid parameter at service0x742 1858 ADSERR_CLIENT_LISTEMPTY polling list is empty0x743 1859 ADSERR_CLIENT_VARUSED var connection already in use0x744 1860 ADSERR_CLIENT_DUPLINVOKEID invoke ID in use0x745 1861 ADSERR_CLIENT_SYNCTIMEOUT timeout elapsed0x746 1862 ADSERR_CLIENT_W32ERROR error in win32 subsystem0x747 1863 ADSERR_CLIENT_TIMEOUTINVALID Invalid client timeout value

TF6100 TC3 OPC-UA 177Version: 2.2

Page 178: Manual TF6100 TC3 OPC-UA

Appendix

Hex Dec Name Description0x748 1864 ADSERR_CLIENT_PORTNOTOPEN ads-port not opened0x750 1872 ADSERR_CLIENT_NOAMSADDR internal error in ads sync0x751 1873 ADSERR_CLIENT_SYNCINTERNAL hash table overflow0x752 1874 ADSERR_CLIENT_ADDHASH key not found in hash0x753 1875 ADSERR_CLIENT_REMOVEHASH no more symbols in cache0x754 1876 ADSERR_CLIENT_NOMORESYM invalid response received0x755 1877 ADSERR_CLIENT_SYNCRESINVALID sync port is locked

RTime Error CodesHex Dec Name Description

0x1000 4096 RTERR_INTERNAL Internal fatal error in the TwinCAT real-time system0x1001 4097 RTERR_BADTIMERPERIODS Timer value not vaild0x1002 4098 RTERR_INVALIDTASKPTR Task pointer has the invalid value ZERO0x1003 4099 RTERR_INVALIDSTACKPTR Task stack pointer has the invalid value ZERO0x1004 4100 RTERR_PRIOEXISTS The demand task priority is already assigned0x1005 4101 RTERR_NOMORETCB No more free TCB (Task Control Block) available. Maximum

number of TCBs is 640x1006 4102 RTERR_NOMORESEMAS No more free semaphores available. Maximum number of

semaphores is 640x1007 4103 RTERR_NOMOREQUEUES No more free queue available. Maximum number of queue is

640x100D 4109 RTERR_EXTIRQALREADYDEF An external synchronization interrupt is already applied0x100E 4110 RTERR_EXTIRQNOTDEF No external synchronization interrupt applied0x100F 4111 RTERR_EXTIRQINSTALLFAILED The apply of the external synchronization interrupt failed0x1010 4112 RTERR_IRQLNOTLESSOREQUAL Call of a service function in the wrong context0x1017 4119 RTERR_VMXNOTSUPPORTED Intel VT-x extension is not supported0x1018 4120 RTERR_VMXDISABLED Intel VT-x extension is not enabled in system BIOS0x1019 4121 RTERR_VMXCONTROLSMISSING Missing function in Intel VT-x extension0x101A 4122 RTERR_VMXENABLEFAILS Enabling Intel VT-x fails

TCP Winsock Error CodesHex Dec Description0x274d 10061 A connection attempt failed because the connected party did not properly respond after a period of time,

or established connection failed because connected host has failed to respond.0x2751 10065 No connection could be made because the target machine actively refused it. This error normally occurs when

you try to connect to a service which is inactive on a different host - a service without a server application.0x274c 10060 No route to a host.

A socket operation was attempted to an unreachable hostFurther Winsock error codes: Win32 Error Codes

TF6100 TC3 OPC-UA178 Version: 2.2

Page 179: Manual TF6100 TC3 OPC-UA

Third party samples

8 Third party samples

8.1 Sample of OPC UA from InosoftDownload Inosoft example "Boiler"

Download PLC demo “Boiler”

Cookbook:1. Load the PLC demo “Boiler” into the TwinCAT PLC2. Install the TwinCAT OPC-UA Server (XP or CE, depending on the platform used)3. Unpack the third-party Inosoft demo4. Open the file “INOSOFT_UABoilerDemo_PC_800_600.vwn” with Notepad5. Search for the line <Channel Name="Ch1" Type="OPCUA" ProgID="Beckhoff OPCUA"

ComputerName="opc.tcp://188.100.13.207:4840">6. Adapt the IP address - the IP address of the device with UA Server must be entered here7. Save the file and start the application “INOSOFT_UABoilerDemo_PC_800_600.exe”8. Confirm the demo mode with OKð the demo is now executable for 1 hour

TF6100 TC3 OPC-UA 179Version: 2.2