0% found this document useful (0 votes)
187 views409 pages

TF6420 TC3 Database Server en

Uploaded by

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

TF6420 TC3 Database Server en

Uploaded by

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

Manual | EN

TF6420
TwinCAT 3 | Database Server

2023-12-20 | Version: 1.13.4


Table of contents

Table of contents
1 Foreword .................................................................................................................................................... 5
1.1 Notes on the documentation ............................................................................................................. 5
1.2 For your safety .................................................................................................................................. 5
1.3 Notes on information security............................................................................................................ 7

2 Overview .................................................................................................................................................... 8

3 Installation ................................................................................................................................................. 9
3.1 System requirements ........................................................................................................................ 9
3.2 Installation ......................................................................................................................................... 9
3.3 Licensing ......................................................................................................................................... 12
3.4 Installation Windows CE ................................................................................................................. 14
3.5 Installing the TwinCAT/BSD ............................................................................................................ 16

4 Technical introduction............................................................................................................................ 17
4.1 Basic concept .................................................................................................................................. 17
4.2 Areas of application and network topologies................................................................................... 18
4.3 Compatibility.................................................................................................................................... 20

5 Configuration........................................................................................................................................... 23
5.1 Configurator .................................................................................................................................... 23
5.1.1 Integration in Visual Studio .............................................................................................. 23
5.1.2 Standalone Configurator ................................................................................................ 101
5.2 Databases ..................................................................................................................................... 123
5.2.1 General Information ....................................................................................................... 124
5.2.2 MS SQL database.......................................................................................................... 126
5.2.3 MS SQL Compact database .......................................................................................... 128
5.2.4 MySQL database ........................................................................................................... 129
5.2.5 Oracle database............................................................................................................. 131
5.2.6 SQLite ............................................................................................................................ 132
5.2.7 ASCII-File....................................................................................................................... 133
5.2.8 XML database ................................................................................................................ 134
5.2.9 ODBC databases ........................................................................................................... 140
5.2.10 MS Access database ..................................................................................................... 147
5.2.11 MS Excel database ........................................................................................................ 148
5.2.12 MongoDB ....................................................................................................................... 149
5.2.13 PostgreSQL.................................................................................................................... 151
5.2.14 InfluxDB.......................................................................................................................... 152
5.2.15 InfluxDB2........................................................................................................................ 153

6 PLC API .................................................................................................................................................. 156


6.1 Tc3_Database ............................................................................................................................... 156
6.1.1 Function blocks .............................................................................................................. 156
6.1.2 Data types ...................................................................................................................... 226
6.1.3 Global constants ............................................................................................................ 246
6.1.4 Obsolete......................................................................................................................... 246
6.2 Tc2_Database ............................................................................................................................... 291
6.2.1 Function blocks .............................................................................................................. 293

TF6420 Version: 1.13.4 3


Table of contents

6.2.2 Data types ...................................................................................................................... 320


6.2.3 Global Constants............................................................................................................ 324

7 Examples ............................................................................................................................................... 326


7.1 Tc3_Database ............................................................................................................................... 326
7.1.1 Scenario examples......................................................................................................... 326
7.1.2 Best practices................................................................................................................. 346
7.2 Tc2_Database ............................................................................................................................... 358
7.2.1 Creating an MS Access database.................................................................................. 359
7.2.2 Starting / stopping, cyclic logging................................................................................... 362
7.2.3 Logging of a PLC variable with FB_DBWrite ................................................................. 363
7.2.4 Example with the FB_DBRecordInsert and FB_DBRecordSelect function blocks......... 367
7.2.5 Stored procedures with FB_DBStoredProceduresRecordArray .................................... 369
7.2.6 Using XML as database ................................................................................................. 372
7.2.7 XPath sample to illustrate the different SELECT types.................................................. 377
7.2.8 XPath sample with XML schema ................................................................................... 380

8 Appendix ................................................................................................................................................ 385


8.1 Error codes.................................................................................................................................... 385
8.1.1 Tc3_Database................................................................................................................ 385
8.1.2 Tc2_Database................................................................................................................ 394
8.2 FAQ - frequently asked questions and answers ........................................................................... 405
8.3 Support and Service...................................................................................................................... 406

4 Version: 1.13.4 TF6420


Foreword

1 Foreword

1.1 Notes on the documentation


This description is intended exclusively for trained specialists in control and automation technology who are
familiar with the applicable national standards.
For installation and commissioning of the components, it is absolutely necessary to observe the
documentation and the following notes and explanations.
The qualified personnel is obliged to always use the currently valid documentation.

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

Disclaimer

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

Trademarks

Beckhoff®, TwinCAT®, TwinCAT/BSD®, TC/BSD®, EtherCAT®, EtherCAT G®, EtherCAT G10®, EtherCAT P®,
Safety over EtherCAT®, TwinSAFE®, XFC®, XTS® and XPlanar® are registered and licensed trademarks of
Beckhoff Automation GmbH.
If third parties make use of designations or trademarks used in this publication for their own purposes, this
could infringe upon the rights of the owners of the said designations.

Patents

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

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

Copyright

© Beckhoff Automation GmbH & Co. KG, Germany.


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

1.2 For your safety


Safety regulations

Read the following explanations for your safety.


Always observe and follow product-specific safety instructions, which you may find at the appropriate places
in this document.

TF6420 Version: 1.13.4 5


Foreword

Exclusion of liability

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

Personnel qualification

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

Signal words

The signal words used in the documentation are classified below. In order to prevent injury and damage to
persons and property, read and follow the safety and warning notices.

Personal injury warnings

DANGER
Hazard with high risk of death or serious injury.

WARNING
Hazard with medium risk of death or serious injury.

CAUTION
There is a low-risk hazard that could result in medium or minor injury.

Warning of damage to property or environment

NOTICE
The environment, equipment, or data may be damaged.

Information on handling the product

This information includes, for example:


recommendations for action, assistance or further information on the product.

6 Version: 1.13.4 TF6420


Foreword

1.3 Notes on information security


The products of Beckhoff Automation GmbH & Co. KG (Beckhoff), insofar as they can be accessed online,
are equipped with security functions that support the secure operation of plants, systems, machines and
networks. Despite the security functions, the creation, implementation and constant updating of a holistic
security concept for the operation are necessary to protect the respective plant, system, machine and
networks against cyber threats. The products sold by Beckhoff are only part of the overall security concept.
The customer is responsible for preventing unauthorized access by third parties to its equipment, systems,
machines and networks. The latter should be connected to the corporate network or the Internet only if
appropriate protective measures have been set up.

In addition, the recommendations from Beckhoff regarding appropriate protective measures should be
observed. Further information regarding information security and industrial security can be found in our
https://www.beckhoff.com/secguide.

Beckhoff products and solutions undergo continuous further development. This also applies to security
functions. In light of this continuous further development, Beckhoff expressly recommends that the products
are kept up to date at all times and that updates are installed for the products once they have been made
available. Using outdated or unsupported product versions can increase the risk of cyber threats.

To stay informed about information security for Beckhoff products, subscribe to the RSS feed at https://
www.beckhoff.com/secinfo.

TF6420 Version: 1.13.4 7


Overview

2 Overview
The TwinCAT Database Server enables data exchange between the TwinCAT system and various database
systems. For small applications it can be used via a configurator, without intervention in the existing program
code. For complex tasks the Database Server offers a large library of PLC function blocks for maximum
flexibility. SQL commands such as Insert or Select can be used directly from the PLC, for example. To take
load off the PLC, if required, procedures can be stored (Stored Procedures) and then called up from the
databases. In this case the parameters transferred by the corresponding PLC function block are used by the
database in conjunction with the Stored Procedure, and results can be returned to the controller.

The TwinCAT Database Server supports a wide range or different database systems, MS SQL, MS SQL
Compact, MS Access, MySQL, PostgreSQL, DB2, Oracle, Interbase, Firebird, ASCII (e.g. .txt or .csv) and
XML files, now also including NoSQL databases, based on support of MongoDB. (See also: Declaration of
the different database types)

Components
• TwinCAT Database Server [} 17]: The service is started and stopped together with TwinCAT. It forms
the link between the TwinCAT system and the database.
• Configurator [} 101]: The TwinCAT Database Server Configurator facilitates visual setting of the
database parameters required for basic communication with the respective database.
• PLC library [} 291]: The PLC library includes various function blocks. They enable establishment of a
database connection, creation of a new table, writing of data into any table structure using Insert
commands, and reading via Select commands. It is also possible to update or delete database entries
and trigger stored procedures. NoSQL databases have their own function blocks that are optimized for
handling flexible JSON documents in the PLC, for example. The principle of operation is identical.

Principle of operation

Within the TwinCAT system the Database Server communicates via ADS. Externally it links to the respective
configured database. Possible network topologies can be found in section "Areas of application and network
technologies [} 18]".

8 Version: 1.13.4 TF6420


Installation

3 Installation

3.1 System requirements


Technical data TF6420 TwinCAT 3 database server
Target systems Windows 10, WinCE, TwinCAT/BSD
x86, x64 and ARM
.NET Framework .Net 4.5.1 or higher
WinCE: .NET 3.5
Min. TwinCAT version 3.1.4018
Min. TwinCAT level TC1200 | TwinCAT 3 PLC

3.2 Installation
The following section describes how to install the TwinCAT 3 Function for Windows-based operating
systems.
ü The TwinCAT 3 Function setup file was downloaded from the Beckhoff website.
1. Run the setup file as administrator. To do this, select the command Run as administrator in the context
menu of the file.
ð The installation dialog opens.
2. Accept the end user licensing agreement and click Next.

TF6420 Version: 1.13.4 9


Installation

3. Enter your user data.

4. If you want to install the full version of the TwinCAT 3 Function, select Complete as installation type. If
you want to install the TwinCAT 3 Function components separately, select Custom.

10 Version: 1.13.4 TF6420


Installation

5. Select Next, then Install to start the installation.

ð A dialog box informs you that the TwinCAT system must be stopped to proceed with the installation.
6. Confirm the dialog with Yes.

TF6420 Version: 1.13.4 11


Installation

7. Select Finish to exit the setup.

ð The TwinCAT 3 Function has been successfully installed and can be licensed (see Licensing [} 12]).

3.3 Licensing
The TwinCAT 3 function can be activated as a full version or as a 7-day test version. Both license types can
be activated via the TwinCAT 3 development environment (XAE).

Licensing the full version of a TwinCAT 3 Function

A description of the procedure to license a full version can be found in the Beckhoff Information System in
the documentation "TwinCAT 3 Licensing".

Licensing the 7-day test version of a TwinCAT 3 Function

A 7-day test version cannot be enabled for a TwinCAT 3 license dongle.

1. Start the TwinCAT 3 development environment (XAE).


2. Open an existing TwinCAT 3 project or create a new project.
3. If you want to activate the license for a remote device, set the desired target system. To do this, select
the target system from the Choose Target System drop-down list in the toolbar.
ð The licensing settings always refer to the selected target system. When the project is activated on
the target system, the corresponding TwinCAT 3 licenses are automatically copied to this system.

12 Version: 1.13.4 TF6420


Installation

4. In the Solution Explorer, double-click License in the SYSTEM subtree.

ð The TwinCAT 3 license manager opens.


5. Open the Manage Licenses tab. In the Add License column, check the check box for the license you
want to add to your project (e.g. "TF4100 TC3 Controller Toolbox").

6. Open the Order Information (Runtime) tab.


ð In the tabular overview of licenses, the previously selected license is displayed with the status
“missing”.

TF6420 Version: 1.13.4 13


Installation

7. Click 7-Day Trial License... to activate the 7-day trial license.

ð A dialog box opens, prompting you to enter the security code displayed in the dialog.

8. Enter the code exactly as it is displayed and confirm the entry.


9. Confirm the subsequent dialog, which indicates the successful activation.
ð In the tabular overview of licenses, the license status now indicates the expiry date of the license.
10. Restart the TwinCAT system.
ð The 7-day trial version is enabled.

3.4 Installation Windows CE


The following section describes how to install a TwinCAT 3 function (TFxxx) on a Beckhoff Embedded PC
with Windows CE.

1. Download and install the setup file [} 14]


2. Transfer the CAB file to the Windows CE device [} 15]
3. Run the CAB file on the Windows CE device [} 15]

If an older TFxxx version is already installed on the Windows CE device, it can be updated:
• Software upgrade [} 15]

Download and install the setup file

The CAB installation file for Windows CE is part of the TFxxx setup. This is made available on the Beckhoff
website www.beckhoff.com and automatically contains all versions for Windows XP, Windows 7 and
Windows CE (x86 and ARM).

Download the TFxxx setup file and install the TwinCAT 3 function as described in the Installation [} 9]
section.

14 Version: 1.13.4 TF6420


Installation

After the installation, the installation folder contains three directories (one directory per hardware platform):
• CE-ARM: ARM-based embedded PCs running Windows CE, e.g. CX8090, CX9020
• CE-X86: X86-based embedded PCs running Windows CE, e.g. CX50xx, CX20x0
• Win32: embedded PCs running Windows XP, Windows 7 or Windows Embedded Standard

The CE-ARM and CE-X86 directories contain the CAB files of the TwinCAT 3 function for Windows CE in
relation to the respective hardware platform of the Windows CE device.

Example: installation folder "TF6310"

Transfer the CAB file to the Windows CE device

Transfer the corresponding CAB file to the Windows CE device.

There are various options for transferring the executable file:


• via network shares
• via the integrated FTP server
• via ActiveSync
• via CF/SD cards

Further information can be found in the Beckhoff Information System in the "Operating Systems"
documentation (Embedded PC > Operating Systems > CE).

Run the CAB file on the Windows CE device

After transferring the CAB file to the Windows CE device, double-click the file there. Confirm the installation
dialog with OK. Then restart the Windows CE device.

After restarting the device, the files of the TwinCAT 3 function (TFxxxx) are automatically loaded in the
background and are then available.

The software is installed in the following directory on the Windows CE device:


\Hard Disk\TwinCAT\Functions\TFxxxx

Software upgrade

If an older version of the TwinCAT 3 function is already installed on the Windows CE device, carry out the
following steps on the Windows CE device to upgrade to a new version:
1. Open the CE Explorer by clicking Start > Run and entering "Explorer".
2. Navigate to \Hard Disk\TwinCAT\Functions\TFxxx\xxxx.
3. Rename the file Tc*.exe to Tc*.old.
4. Restart the Windows CE device.
5. Transfer the new CAB file to the Windows CE device.

TF6420 Version: 1.13.4 15


Installation

6. Run the CAB file on the Windows CE device and install the new version.
7. Delete the file Tc*.old.
8. Restart the Windows CE device.
ð The new version is active after the restart.

3.5 Installing the TwinCAT/BSD


The TwinCAT 3 Database Server is available as a package for TwinCAT/BSD in the package repository.
Under the package name "TF6420-Database-Server" it can be installed via the command
doas pkg install TF6420-Database-Server

Further information about the Package Server can be found in the Embedded PC section of the TwinCAT/
BSD manual.

After a system restart or restart of TwinCAT, the TwinCAT 3 Database Server is also started and can be
configured from a client system via ADS.

Some databases, such as SQLite, can only be used if the corresponding package has been
installed.

16 Version: 1.13.4 TF6420


Technical introduction

4 Technical introduction

4.1 Basic concept


The TwinCAT Database Server is designed to enable a database connection to the controller for all
TwinCAT users, and as conveniently as possible. Notwithstanding the required simplicity, the full flexibility is
to be retained, which is why the TwinCAT Database Server offers four basic categories:
• Configure mode: pure configuration solution
Database connections for simple applications based on graphical configurations without code
implementation.
• PLC Expert mode: programming solution for conventional PLC programmers
Database connection for simple or complex applications based on PLC function blocks, in which the
database commands are largely generated automatically by the Database Server.
• SQL Expert mode: programming solution for conventional PLC programmers and database
experts
Database connection for simple or complex applications based on PLC function blocks and C++
interfaces, in which the database commands are assembled automatically during program execution.
For maximum flexibility.
• NoSQL Expert mode: programming solution for PLC programmers and NoSQL database
experts
Database connection for simple to complex applications with PLC function blocks, in which NoSQL
commands can be created and sent within the program sequence.

Naturally, all four categories can be combined within an application.

The TwinCAT Database Server can be set up via a graphical configurator. The configuration is written to an
XML file, which can then be downloaded to the target system.
On non-Windows CE devices the configuration file is in folder C:\TwinCAT\3.1\Boot, on Windows CE devices
in folder \Hard Disk\TwinCAT\ 3.1\Boot.
Read and write access are available for the different database systems. Deselectable database extensions
are available for this purpose. The supported databases are described in section "Databases [} 123]".

The TwinCAT Database Server service is started together with the TwinCAT system on the respective
control computer. It is the link between the PLC and the database.

TF6420 Version: 1.13.4 17


Technical introduction

Configure Mode

In Configure mode, the bulk of the work is done in the configurator. The configuration has to be set up for the
required database and for the AutoLog group. The target browser can be used for configuring the AutoLog
group, for online access to a target system, and for selecting the variables to be communicated. If the
AutoStart option is used, the communication with the configured database is established directly when
TwinCAT system starts up. If the Manual option is selected, the communication has to be enabled via the
function block FB_PLCDBAutoLog [} 160] or for AutoLog view.

PLC Expert mode

In PLC Expert mode only the database configuration is set in the configurator. Further functionalities are
implemented in the PLC code of the application. With the function block FB_PLCDBCreate [} 171] it is possible
to dispense with the configurator and even configure the database itself from the PLC. Function blocks for
reading and writing are available, if required. The function block FB_PLCDBCmd [} 183] forms the transition
between PLC Expert mode and SQL Expert mode. Here, table structures can easily be mapped as PLC
structures, and an SQL command with placeholders for the current structure values can be transferred to the
TwinCAT Database Server. The TwinCAT Database Server then inserts all values automatically and sends
the command to the database.

SQL Expert Mode

In SQL Expert mode users can assemble the SQL commands for Insert, Select or Update, for example, in
the PLC and send them to the database via the TwinCAT Database Server. This is a very flexible and
powerful option. Stored Procedures [} 201] - in database - can also be called from the PLC.

Logging of structures
Note the corresponding byte alignment when logging structures.

NoSql Expert Mode

In NoSQL Expert mode, the user can compile NoSQL queries such as Insert or Find and many other
database-specific queries and send them to the database via the TwinCAT Database Server. New and more
flexible data schemas, such as hierarchical structures and arrays, are supported.

4.2 Areas of application and network topologies


The TwinCAT Database Server can be used in any control application: reading recipe data in production
machines, labelling products with production data, condition monitoring or machine control, logging of wind
turbine operating states, or building services. The Database Server can be integrated in the existing network
architecture.

The network topology is mostly influenced by the database type, the local conditions and the area of
application. The following illustration shows various network topologies in which the
TwinCAT Database Server can be used.

18 Version: 1.13.4 TF6420


Technical introduction

1. TwinCAT and the TwinCAT Database Server reside on the same computer, together with the
database. The Database Server can act as gateway for many controllers via ADS. The performance
must be taken into account.
2. TwinCAT and the TwinCAT Database Server reside on the same computer, while the database is on
an external device. Here, too, the Database Server can act as gateway for many controllers via ADS.
The performance must be taken into account.
3. The TwinCAT Database Server resides locally on each control device that has a database installed.
Not all databases are suitable for this kind of application.
4. This is the most common use case. The TwinCAT Database Server is installed on each control device,
and the database resides on an external server in the network.
5. Combination of case 3 and case 4. A main database resides on a server in the network, and the
controllers in the field each have a local database, which kicks in when a disconnection is
encountered, for example, and stores the data locally in the first instance. The Database Server is
installed on each control device.

TF6420 Version: 1.13.4 19


Technical introduction

Remote access by the TwinCAT Database Server to a database


For remote access by the TwinCAT Database Server to a database, various aspects have to be
taken into account on the database side:
• Is remote access generally permitted?
• How many simultaneous connections are permitted? (In case the TwinCAT Database Server
needs to open several connections)
• Does the user who wishes to log onto the database with the Database Server have sufficient
rights?
• Is the firewall of the remote system configured appropriately?

More detailed information about the configuration of your database server can be found in the corresponding
database documentation [} 123].

4.3 Compatibility
The TwinCAT Database Server is a tried and tested TwinCAT product that has been around for many years.
The demands on the product are constantly increasing. New developments in the TwinCAT Database Server
are intended to meet these increased requirements.

The TwinCAT database connections have previously been available in versions 3.0.x, 3.1.x and 3.2.x. The
current version is 3.3.x As before, the database server consists of the following components: configurator,
ADS server and PLC library. Version 3.0.x includes the PLC library Tc2_Database.compiled library. The PLC
library in versions 3.1.x and higher is called Tc3_Database.compiled-library.

Overview of released Database Server versions

Database 3.0.23 3.0.26 3.0.27 3.0.28


Server
3.0.x
Database 3.1.29 3.1.30 3.1.31
Server
3.1.x
Database 3.2.32
Server
3.2.x
Database 3.3.33
Server
3.3.x

Notes on the transition from 3.0.x to 3.1.x

In addition to new and higher-performance functions, a key aspect was compatibility between versions 3.0.x
and 3.1.x. For example, old PLC code, in which the Tc2_Database.compiled library is used, can also be
used with the new 3.1.x version ADS server. The old Tc2_Database.compiled library continues to be
installed in version 3.1.x during setup. The XML files created by the configurator for the server differ between
versions 3.0.x and 3.1.x. It is possible to read old configuration files with the new configurator (standalone)
and even to convert them to the new format, if required.

Backup of the old XML configuration


During an update from the TwinCAT Database Server 3.0.x to the new 3.1.x version, the old XML
configuration is saved. It is renamed to "CurrentConfigDataBase_OLD.xml" and remains in the
TwinCAT boot directory.

20 Version: 1.13.4 TF6420


Technical introduction

Notwithstanding the general compatibility referred to above, an old configurator and an old ADS server
(version 3.0.x) cannot be used with the new Tc3_Database.compiled library. The diagram below provides a
compatibility overview.

Notes on the transition from 3.1.x to 3.2.x

The file formats for the configurations are unchanged. The ADS server was merely extended with new
functionalities. All other functions are still available. In version 3.2.x the old Tc2_Database.compiled-library is
installed in parallel with the Tc3_Database.compiled-library during setup. The notes for the transition from
3.0.x to 3.1.x apply.

In the Tc3_Database.compiled-library, all previous function blocks have been updated from version 3.2.x
onwards. The update refers to the I_TcMessage EventLogger interface. To ensure that older applications
continue to function, "Evt" is appended to the names of new function blocks. All old function blocks are still
contained in the library, but are now in the Obsolete folder and are marked accordingly by the compiler.

Example:

In version 3.1.x: FB_SQLCommand

TF6420 Version: 1.13.4 21


Technical introduction

In version 3.2.x: FB_SQLCommandEvt

We recommend using the function blocks with the ending "Evt" for new projects. It should be noted
that the EventLogger itself is only available from TwinCAT 3.1 Build 4022.20, and therefore the
function blocks can only be used from 4022.20.

Notes on the transition from 3.2.x to 3.3.x

With version 3.3.x, the modularization of the TwinCAT Database Server has been further advanced on the
driver side. Full compatibility is ensured. However, some drivers are no longer automatically included in the
setup and must be made available separately by the user. Example: MySQL under Windows CE. For details,
please refer to the settings for the respective database in the Configuration section.

22 Version: 1.13.4 TF6420


Configuration

5 Configuration

5.1 Configurator
The TwinCAT Database Server is set and controlled via the configurator. The tool also offers a range of
development facilities for speeding up the development of the application in the PLC.

The configurator is integrated in Visual Studio, in order to make development as user-friendly as possible.
TwinCAT projects and TwinCAT Database Server projects can be placed in a common solution.
Alternatively, customers can continue to use the standalone configurator, independent of Visual Studio.

5.1.1 Integration in Visual Studio


The TwinCAT Database Server is integrated in Visual Studio 2013 and Visual Studio 2015. This integration
is achieved with the aid of two extensions. The two required extensions are added in the Visual Studio
extension window during the installation, which contain the functionalities of the project system, among other
features.

5.1.1.1 General
This chapter describes the various functions and components of the Visual Studio integration of the
TwinCAT Database Server.

5.1.1.1.1 User interface components


The TwinCAT Database Server is integrated in Visual Studio 2013 and Visual Studio 2015. The TwinCAT
Connectivity extension for Visual Studio offers a new project system. This can be used for creating a file-
based TwinCAT Database Server project, for example. Typical components such as the Properties window,
the Solution Explorer and the error output are supported. In addition, various editors for editing the
configuration files are provided.

TF6420 Version: 1.13.4 23


Configuration

Any number of TwinCAT Database Server projects can be integrated in a TwinCAT connectivity project.

The project icon indicates the state of the set target system:
• Red: The TwinCAT Database Server cannot be reached.
• Blue: The TwinCAT Database Server has no valid license. (See Licensing [} 12])
• Green: The TwinCAT Database Server can be reached and is ready for use.
• Violet: The TwinCAT Database Server is in AutoLog mode. Data are exchanged between PLC and
database.

24 Version: 1.13.4 TF6420


Configuration

The TwinCAT Database projects map a file-based project system. The individual configuration documents
are managed in the Solution Explorer. Any modifications that are pending in the editors are identified with *
in the documents. If changes are made without opening a document (through the Properties window), the
changes are nevertheless registered. Further information on the project system can be found in section
"TwinCAT Database Server project [} 26]".

Toolbar and commands

The toolbar has the following elements:

Toolstrip button Description


Activation of the configuration

Read configuration of the target device

Save configuration in an XML file

Read configuration from an XML file

Add new database configuration

Add new AutoLog group

Event display

Database pool

AutoLog Viewer

InformationLog View

SQL Query Editor

Properties window

The settings for the different project documents can be configured via dedicated editors or via the Properties
window. During this process the file content is modified, but not the metadata in the project file of the
TwinCAT Connectivity project.

The individual properties are described in more detail in the lower part of the Properties window. Note that
some lists can only be edited in the editor.

TF6420 Version: 1.13.4 25


Configuration

Output and error list

Visual Studio features an integrated console output. The TwinCAT Database Server uses this feature to
issue notifications, warnings or error messages. To this end the category "TwinCAT Database Server" can
be selected in the output. It is possible that this category does not yet exist, if there was no previous
message from the TwinCAT Database Server.

In addition, the Visual Studio error list is used for communicating the main information.

Both windows can be opened in Visual Studio via View > Error list/Output.

5.1.1.1.2 TwinCAT Database Server Project

Build Project

The TwinCAT Connectivity extension for Visual Studio provides a new project template. When a new project
is created, the TwinCAT Connectivity Project category appears as an option.

To create a new TwinCAT Connectivity project, select Empty TwinCAT Connectivity Project, specify the
project name and the storage location and click OK to add it to the solution. In this way, TwinCAT
Connectivity projects or TwinCAT Database Server projects can conveniently be created in parallel with
TwinCAT or other Visual Studio projects.

26 Version: 1.13.4 TF6420


Configuration

A new project node appears in the solution. Below the Connectivity project node you can add subprojects for
the supported connectivity functions.

Use Add to add a new TwinCAT Database Server project to the TwinCAT Connectivity project. The
TwinCAT Database Server project can be found in the list of existing Item Templates.

A new TwinCAT Database Server project is created under the TwinCAT Connectivity node.

TF6420 Version: 1.13.4 27


Configuration

This is now used as the basis for the pending configuration of a TwinCAT Database Server. The document
can be edited either via the Properties window or via an editor.

A Connectivity project can be associated with any number of TwinCAT Database Server projects or other
projects, and it may therefore contain several configurations.

Editor for server settings

The Server Settings editor can be used to edit the settings for the TwinCAT Database Server. These are
general settings relating to the corresponding server. In the drop-down menu (1) you can select the target
system via the Ams NetID. To this end you have to create a route to the target system via TwinCAT. When a
finished configuration is transferred, the settings are stored in the TwinCAT Database Server for this target
system.

The settings for logging faults or errors can be configured under Log settings. In the event of a fault or error,
the Database Server generates a detailed entry in a log file. The log file can be read with the Information Log
Viewer [} 49]. Under Log Settings you can specify a path to the file location and the maximum file size.
You can also influence the accuracy of the log. For performance reasons we recommend that logging is
deactivated again after the error analysis, once it is no longer required.

28 Version: 1.13.4 TF6420


Configuration

For network access to file-based databases such as Access or SQL Compact, the Impersonate option must
be set, so that the TwinCAT Database Server can connect to this network drive. This feature is currently
not supported in Windows CE.

Further configuration settings are available to control the read process from the database. These settings
refer to the TwinCAT Database Server on the target system:

MaxStringLength Maximum string length of the variables in the PLC


MaxByteArrayLength Maximum byte array length of the variables in the PLC
DBNullAllowed Indicates whether ZERO values are accepted in the TwinCAT Database Server.
DBConnectionTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection error while attempts are made to establish a connection.
DBCommandTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection fault when a command was sent. If large data quantities are involved,
processing of a command may take quite some time, depending on the database
and the infrastructure.

Supported database types

The installed database types can be selected in the server settings. All installed databases are selected by
default. The TwinCAT 3 Database Server will load the corresponding database interfaces. In this way,
unused databases on the target system can be deselected.

Server settings in the Properties window

The settings for the TwinCAT Database Server can be adjusted in the Editor window or in the Properties
window of the Database Server. These properties also directly affect the configuration file.

TF6420 Version: 1.13.4 29


Configuration

Activating a project

To activate a configured project on the TwinCAT Database Server, use the command Activate
Configuration in the context menu of the TwinCAT Database Server project.

30 Version: 1.13.4 TF6420


Configuration

5.1.1.1.3 Configuring databases


A new database configuration can be added via the command Add New Database in the context menu of a
Database Server project or via the corresponding command in the toolbar.

A new database configuration is added in the form of a file in the project folder and integrated in the project.
As with all Visual Studio projects, the information on the new files is stored in the Connectivity project.

TF6420 Version: 1.13.4 31


Configuration

The new database configuration in the TwinCAT Database Server project can be edited via the Properties
window or a special editor:

The properties dynamically adapt to the selected database types, since the databases have different
parameters. These settings relate to the file contents, not the file properties.

Editor for database configurations

32 Version: 1.13.4 TF6420


Configuration

The database ID, which is required for some function blocks in the PLC, is shown in the upper part of the
editor (1). The database types of the target database can be selected from the drop-down menu (2). Another
option is the ODBC interface for a database, although this is not yet supported. Note that not all functions of
the TwinCAT Database Server can be guaranteed, depending on the database.

As a further option you can select a so-called failover database (3), which is triggered when an error is
encountered in Configure mode. In the event of a network disconnection, this feature can automatically
ensure that data are stored elsewhere and not lost.

For each database [} 123] additional adjustable parameters are available. Depending on the database a
connection string (5) is created, which describes the connection to the database. The intention is to make the
parameters you have set more transparent.

The CREATE (4) button can be used to create a new database. This function is only displayed if the
respective database supports it.

Unknown databases can be configured via an ODBC interface. In the ODBC Type drop-down list select
"Unknown Database" and add parameters via the commands in the context menu. They may contain
passwords, which are stored in encrypted form. The required connection string can be assembled from these
parameters. Note that only limited functions of the TwinCAT Database Server can be used. Only the explicit
function blocks of the SQL Expert mode are supported.

The additional parameters can only be applied via the editor, not via the Properties window.

Copying a database configuration into the database pool

A corresponding command is available in the context menu for copying a database configuration into the
database pool [} 48]. It is also possible to use drag & drop to move database configurations between the
project and the database pool.

TF6420 Version: 1.13.4 33


Configuration

Deactivating database configurations

Individual database configurations can be disabled in the project. These are then marked in red and ignored
when the project is activated.

34 Version: 1.13.4 TF6420


Configuration

5.1.1.1.4 Configuring AutoLog groups


A new AutoLog group for the database configuration can be added via the command Add New
AutologGroup in the context menu of a database configuration or via the toolbar. These AutoLog groups
refer to the parent database.

A new AutoLog group and the corresponding components are added as files to the project folder and
integrated in the project. They include the ADS device, the symbol groups and the table settings. In order to
save these files in the project, you should save the TwinCAT Connectivity project file. The files can then be
edited in editors or in the Properties window.

TF6420 Version: 1.13.4 35


Configuration

StartUp AutoLog mode can be enabled manually (with a command in the PLC or from
the configurator) or automatically during system startup.
Direction The set ADS device is used as data target or data source.
Write mode The data can appended in a database line-by-line, held in a ring buffer on a
temporal or quantitative basis, or simply be updated at the corresponding
position.
Ring buffer parameter Depending on the setting this parameter represent the time or the cycles after
which the ring buffer is updated.
Log mode The variable is written either after a certain cycle time or when a change
occurs.
Cycle Time Cycle time after which the variable is written.

Configuring the ADS device

The ADS device is automatically created under an AutoLog group. In the most frequent use case the ADS
device is the PLC runtime. The following parameters can be set in the editor:

36 Version: 1.13.4 TF6420


Configuration

ADS Device Name of the ADS target device.


AMS NetID Address of the target device in the TwinCAT network.
AMS Port Port of the target device in the TwinCAT network.
Timeout Time after which it is assumed that the connection to the target device is lost.
Connection Type bySymbolName: Connection is established based on the symbol name.
byIndexGroup: Connection is established based on the memory index.

Configuring symbols

The symbols you set here are written to or read from the database, depending on whether the ADS device is
the data target or the data source. The TwinCAT Target browser [} 50] can be used for convenient access.
Here you can search for the symbols on the target and communicate between the two tools via drag & drop.

TF6420 Version: 1.13.4 37


Configuration

Symbols can also be added manually to symbol groups or edited. The information that is required varies,
depending on whether in the ADS device the connection type was selected via the symbol name or the index
groups. The starting point is always the ADS device.

38 Version: 1.13.4 TF6420


Configuration

SymbolName The symbol is addressed based on the set ADS device


Symbol database Name of the variable in the database table
name
DataType PLC data type of the symbol
BitSize Bit size of the symbols (set automatically for the data types)
IndexGroup Index group in the TwinCAT system
IndexOffset Index offset in the TwinCAT system

Configuring a table

The table in a database can be based on a standard table structure or on an individual structure.

The corresponding table can be selected from a list of possible tables. If the table does not yet exist, you can
create it via the SQL Query Editor. If you select the standard table structure, a blue tick indicates whether the
selected table corresponds to this structure.

The specific table type offers the option to distribute the individual symbols that were set in the symbol group
to the table columns in the database as required. When a data set is written to the database in AutoLog
mode, the current values of the symbol group at the sampling time are saved in the corresponding table
column.

TF6420 Version: 1.13.4 39


Configuration

Disabling AutoLog groups

Just like individual database configurations, individual AutoLog groups can also be disabled in the project.
These are then ignored when the project is enabled on the target system. A deactivated AutoLog group is
indicated by a red mark. It can be reactivated with the same command.

40 Version: 1.13.4 TF6420


Configuration

5.1.1.1.5 SQL Query Editor


The SQL Query Editor is a Database Server tool that supports the development of your application. The tool
can be used to test connections and SQL commands and to check the compatibility between PLC and
databases.

TF6420 Version: 1.13.4 41


Configuration

After the TwinCAT Database Server of the target system is selected, the SQL Query Editor loads the current
database configuration and the tables of the successfully connected databases. Depending on whether the
database supports the SQL and the NoSQL interface (from the TwinCAT Database Server), it is listed under
the respective category.

Below the selection of the target system there is a status bar with the available commands:

Table level
Insert working area Opens the Insert working area to write data sets to the selected
table with SQL.
Select working area Opens the Select working area to read data sets from the selected
table with SQL.
Delete/Drop working area Opens the Delete/Drop working area to delete data sets with SQL
from the selected table or to delete entire tables.
NoSQL working area Opens the NoSQL working area to execute NoSQL-specific
queries.
Database level
Stored Procedure working area Opens the Stored Procedure working area to execute stored
procedures of the database.
Tables working area Opens the Tables working area to create new tables in the selected
database.
Update tables Updates the available tables of the selected database.
General
Update databases Updates the entire database tree.

The working areas are opened to the right of the tree under the corresponding tab. Also from the same table
several tabs can be opened at one time.

Insert working area

The Insert working area enables data to be written to the selected table via the TwinCAT Database Server
interface for SQL function blocks.

In the lower area (2) there is a table with the individual data symbols in the data set to be written. The name,
PLC data type, the byte length as well as the value can be determined here. The entered values are then
used via the command to generate the SQL statement.

This SQL statement is then made available in a text field (3). Depending on the syntax of the database, the
content may vary.

The upper status bar contains the commands for interacting with the TwinCAT Database Server (1).

42 Version: 1.13.4 TF6420


Configuration

Command Description
Read tables schema Reads out the table schema of the table of the working area.
Generate SQL statement Generates the SQL statement from the present table depending on the
database syntax.
Execution Executes the statement in the text field (3) via the respective interface of
the TwinCAT Database Server.
Copy the statement Copies the statement in the text field (3) as TwinCAT compatible syntax.
Export as structure Exports the structure of the table of input values to a TwinCAT 3
compatible DUT.

Select working area

The Select working area allows reading data into the selected table via the TwinCAT Database Server
interface for SQL function blocks.

In the lower area (2) there is a table with the individual data symbols in the data set to be read. The name,
PLC data type, as well as the byte length can be determined here. This information is then needed to
interpret the data.

This SQL statement is then made available in a text field (3). Depending on the syntax of the database, the
content may vary.

The result field (4) displays the data after the statement has been executed. If several results are returned,
they can be switched through the pages.

The upper status bar contains the commands for interacting with the TwinCAT Database Server (1).

Command Description
Read tables schema Reads out the table schema of the table of the working area.
Generate SQL statement Generates the SQL statement from the present table depending on the
database syntax.
Execution Executes the statement in the text field (3) via the respective interface of
the TwinCAT Database Server.
Copy the statement Copies the statement in the text field (3) as TwinCAT compatible syntax.
Export as structure Exports the structure of the table of input values to a TwinCAT 3
compatible DUT.

Delete/Drop working area

The Delete/Drop working area provides the option to issue SQL statements to delete either data from a table
or the entire table from the database.

TF6420 Version: 1.13.4 43


Configuration

For this purpose, you can choose between the two options in the status bar. The syntax corresponding to the
database is then generated in the statement field. To execute this with the TwinCAT Database Server
interface, the switch FB_SQLCommandEvt.Execute is available.

NoSql working area

The NoSql working area supports the special functions of NoSql databases or the TwinCAT Database
Server NoSQL interface.

ID Name Function
1 Filter/Document Depending on which function is used, this input field acts as a document
or as a filter in JSON format. If you want to execute a Find operation and
also carry out a projection or sort operation, you can fill these fields with
Options(Find) below.
2 Options (Find) Describes additional parameters for the Find function, such as the
projection or sorting.
3 Control elements Control elements for interaction with the TwinCAT Database Server
interface for NoSQL.
4 Data display List of returned data. Navigation allows iteration through the available
pages.

44 Version: 1.13.4 TF6420


Configuration

Find: executes a search query with the filter entered in the text field (1). Optionally, a projection or sorting
operation can also be executed via the Options(Find) fields. Data is returned and listed in the data display
(4). The syntax of the filters is database-specific.

Aggregate: executes an aggregation with the parameters entered in the text field (1). Data is returned and
listed in the data display (4). The syntax of the filters is database-specific.

Insert: executes an insert query of the (JSON) document or document array entered in the text field (1).
These are then written to the collection.

Delete: executes a delete query on the data found with the filter in the text field (1). Any data that is found is
deleted from the collection.

Validate: if this option is selected, the data queries are not automatically parsed according to their own
schema, but an attempt is made to map these data to the structure of the symbol from the PLC, which was
specified via these parameters.

With the latter function, a Find query may lead to conflicts. In contrast to structures in the PLC process
image, data sets in NoSQL databases do not have to follow a fixed schema. It is possible that queried
documents do not have data for a specific element in the PLC structure. Or the data set carries data that
does not occur in the PLC structure. These data are assigned via the name or the attribute "ElementName"
in the PLC.

The differences in the data can be examined via the Schema Compare tab. In the above example it can be
seen that in the case of the returned document in the PLC structure, the variable "Name" has a different data
type length than that of the database. The corresponding colors show the weighting of the conflict:

Red: too many or too few data available.

Yellow: the byte length of the data set does not match, or underlying data sets are left over or missing.

Green: no conflicts

TF6420 Version: 1.13.4 45


Configuration

These conflicts are also listed under the Issue Tracker tab. It can also be read into the PLC as a string
array, if required.

The Remaining Json tab returns any remaining data sets as JSON. This information can also be read into
the PLC as a string.

The control elements in the status bar can be used to iterate through the data, as known from the other
displayed data. The number of data sets displayed simultaneously can be specified.

Stored Procedure working area

The TwinCAT Database Server supports "Stored Procedures", which provide numerous databases for
processing more complex queries at the database level or to make a simplified interface available.

If Stored Procedures are present in the database, they will be listed in the dropdown list of the status bar
(4).

Below is the table for the input parameters (1), and for the output schema (2). In addition, there is a view for
the output results (3). If the Stored Procedure is executed successfully, the results are displayed here.

The status bar has the following commands:

Command Description
Read stored procedure input Reads out the input parameter schema. The results are shown in Table
schema 1.
Read Stored Procedure output Reads out the output parameter schema. The results are shown in Table
schema 2. Info: This requires the execution of the Stored Procedure. Depending
on the programming, data can be changed here.
Design Executes the Stored Procedure via the respective interface of the
TwinCAT Database Server.
Export as structure Exports the structure of the table to a TwinCAT 3 compatible DUT.

Table working area

The Table working area is used to create new tables.

46 Version: 1.13.4 TF6420


Configuration

Here, the table structure (1) can be created and an SQL statement can be generated from it in the
corresponding field (2). The status bar (3) with the following commands can be used for this purpose:

Command Description
Table name Specifies the table name of the new table.
Generate SQL statement Generates the SQL statement from the present table depending on the
database syntax.
Execution Executes the Stored Procedure via the respective interface of the
TwinCAT Database Server.
Copy the statement Copies the statement in the text field (2) as TwinCAT compatible syntax.

5.1.1.1.6 AutoLog view


The AutoLog Viewer of the TwinCAT Database Server is a tool for controlling and monitoring the AutoLog
mode. You can log into a target system, similar to the TwinCAT PLC. In logged-in state the AutoLog mode
can be started or stopped. Information on the current state of the logging is shown in the lower part of the
window. When an AutoLog group is selected, further information is displayed via the logged symbols.

TF6420 Version: 1.13.4 47


Configuration

ID Name Function
1 Target system Choose Target System with installed TwinCAT Database Server
2 Start Manual start of the AutoLog mode
3 Login Logging into the active AutoLog process
4 Logout Logging out of the active AutoLog process
5 Stop Manual stop of the AutoLog mode
6 AutoLog groups List of configured AutoLog groups on the target system
7 Symbols List of configured symbols for the selected AutoLog group

5.1.1.1.7 Database configuration pool


The database configuration pool is a global repository for database configurations on the development
system. It is used by developers as storage location for project-independent database configurations or
templates for repeatedly used configurations. This pool uses the same user-specific storage location for the
Visual Studio integration and for the standalone configurator. The files are retained when the
TwinCAT Database Server is uninstalled.

48 Version: 1.13.4 TF6420


Configuration

5.1.1.1.8 InformationLog View


InformationLog View is a tool for reading log files from the TwinCAT Database Server. Recorded information
is displayed with a timestamp, IDs and error messages in plain text.

The log files can not only be viewed or emptied via direct file access, but also directly via the target. This is
particularly advantageous with distributed Database Servers in a network, for quick and easy access to the
log file. For this access a route to the target device must exist.

TF6420 Version: 1.13.4 49


Configuration

5.1.1.1.9 TwinCAT Target Browser


The TwinCAT Target Browser is the central data management interface in the TwinCAT 3 Engineering. It can
provide data from various TwinCAT target systems live via ADS or access historic data in databases.
Depending on what TwinCAT 3 functions are installed on an engineering system, the ADS standard
extension of the TwinCAT Target Browser is extended by further extensions (see Extensions [} 51]).

Call options

The Target Browser can be called via the Scope menu in Visual Studio®. Due to its ever increasing use in
the TwinCAT system, it can also be opened via the TwinCAT menu under the item Target Browser.

In addition, it is possible that the various tools that use the Target Browser will provide additional calls. For
example, some products do this via the context menu on their respective project nodes.

Architecture

Within Microsoft Visual Studio® the TwinCAT Target Browser is a tool window that is subdivided into two
sections. Target systems are displayed on the left-hand side ("Specific Target Area"). You can switch
between the various extensions via the tabs. The details of the respective target system or the selected
object respectively are displayed on the right-hand side ("Common Symbol Area").

Many extensions support a "Value Preview" for variables. This means that if you select a variable and press
and hold the space bar, a small chart appears. In this way you can determine whether data have arrived or
exist in a database. A search bar above the right-hand section enables the filtering/reduction of the visible
symbols. The entry must be confirmed with the [Enter] key.

A breadcrumb navigation bar shows the current location.

50 Version: 1.13.4 TF6420


Configuration

Extensions

The following table shows an overview of the current extensions and the product from which they were
installed. Further information on the extensions can be found in the associated document sections.

Extension name Products


ADS [} 51] TwinCAT XAE, TwinCAT Scope, TwinCAT IoT Data Agent, TwinCAT Data
base Server, TwinCAT Analytics Service Tool
OPC UA [} 53] TwinCAT Scope, TwinCAT IoT Data Agent
TcAnalytics [} 55] TwinCAT Analytics Workbench and Service Tool, TwinCAT Scope
TcAnalytics File [} 57] TwinCAT Analytics Workbench and Service Tool, TwinCAT Scope
TcDBSrv [} 58] TwinCAT Scope

5.1.1.1.9.1 Extension – ADS


The TwinCAT Target Browser ADS extension is used most frequently within the TwinCAT system.

Specific Target Area

All target systems registered to the local TwinCAT 3 Engineering are displayed in a tree structure in the left-
hand area of the TwinCAT Target Browser (ADS). In first place is the local system, followed by the target
systems such as Industrial PCs or Embedded PCs in the order of registration. The prefixed screen symbol
indicates the state of the system (green: run mode, blue: config mode, red: stop mode or unreachable). The
available default ADS ports are listed below a target system. If you select a port, the available symbols/
variables are displayed in the Common Symbol Area on the right-hand side of the TwinCAT Target Browser.

Toolbar

The toolbar of the ADS extension makes the following functions available:

TF6420 Version: 1.13.4 51


Configuration

Ports If an ADS port is not displayed by default, further ports can be added to a selection via this
command.

Edit Routes If an ADS route to a target system is missing, further target systems can be added via this
button.

Refresh The display of the target system states can be manually updated with this button.

Common Symbol Area

The ADS symbols available at the selected port are displayed in the right-hand area of the
TwinCAT Target Browser. The addresses and the attributes, for example, are also displayed in addition to
the name, the data type, the size and the symbol name. Special attributes, such as those of the units, are
interpreted and output in their own columns.

52 Version: 1.13.4 TF6420


Configuration

5.1.1.1.9.2 Extension - OPC UA


The TwinCAT Target Browser OPC UA extension offers a standardized way into the
TwinCAT 3 Engineering.

Specific Target Area

All OPC UA Servers that have been added using the Add command in the toolbar are displayed in a tree
structure in the left-hand area of the TwinCAT Target Browser (OpcUa). The screen symbol in front of the
server designation at the first level of the tree structure indicates the connection status. Below the server the
created end points are subdivided into "Anonym" (anonymous) and "Authenticated" (user mode). The
encryption method is displayed in brackets for each end point. If you select an end point, the available
OPC UA Nodes are displayed on the right-hand side of the TwinCAT Target Browser (see also: Displaying
OPC UA Nodes [} 54])

Toolbar

The toolbar of the OPC UA extension makes the following functions available:

Add New connections to existing OPC UA Servers can be established with this command (see
also: Adding OPC UA Servers [} 53])

Remove A registered server can be removed with this command.

Refresh The display in the Target Browser tree can be manually updated with this button.

Common Symbol Area

The available OPC UA Nodes are displayed on the right-hand side of the TwinCAT Target Browser. These
reflect the hierarchical structure of the PLC project. The node class and the identifier, for example, are also
displayed in addition to the name, the data type, the size and the full object name.

Adding OPC UA Servers


1. Click on Add in the OPC UA toolbar.

TF6420 Version: 1.13.4 53


Configuration

ð The dialog OpcUa EndPoint Selection opens.

2. Enter the URL of the server.


3. Select the end point from the drop-down list. With OPC UA you can determine via the corresponding end
points whether and which method of encryption is used. It is also possible to add several end points to a
server. To do this, execute the Add command again.

4. Select whether the access is anonymous or authenticated. If the access is authenticated, enter a user
name and password. Authenticated access may be required if a password-protected user management
has been set up for the OPC UA server (e.g. different user accounts with different rights).
5. Confirm the dialog.
ð The OPC UA Server is added to the tree structure in the Target Browser with the selected end points.

Displaying OPC UA Nodes

In order to display the available OPC UA Nodes, select the respective end point in the tree structure on the
left-hand side. If you select an end point without certified access, the nodes will be displayed directly. If the
selected end point is certified, you must first trust the server certificate in a corresponding dialog.

54 Version: 1.13.4 TF6420


Configuration

You can trust the certificate in a single case (until the Visual Studio instance is closed) or add it to the list of
trusted certificates via the check box Save Certificate to Trustlist.

During the first attempt to connect to an OPC UA Server it is additionally necessary to trust the certificate of
the client (Target Browser) on the server side. To do this, copy the respective certificate in the certificate
directory of the OPC UA Server from the "rejected" folder to the "trusted" folder.

5.1.1.1.9.3 Extension – TcAnalytics


With the help of the TcAnalytics Extension of the TwinCAT Target Browser, MQTT data streams from
different brokers and topics can be displayed and made available for different measurement products. All
you have to do is drag and drop the desired stream symbols into the corresponding engineering tools.

Specific Target Area

In the left area of the TwinCAT Target Browser (TcAnalytics) all brokers and their data streams are displayed
in a tree structure. In addition, historical data streams are also displayed. The current status of the system or
the data stream is indicated by the preceding symbols (green: available, red: unreachable, gray: unknown
status).

Toolbar

The toolbar of the TcAnalytics extension provides the following functions:

TF6420 Version: 1.13.4 55


Configuration

Add broker This button can be used to add broker connections.


connection

Delete broker This button can be used to delete existing connections to a broker from the tree.
connection

Refresh The display of the target system states can be manually updated with this button.

Edit This button can be used to subsequently change the connection parameters.
connection

Machine This button opens the machine administration page. The incoming data streams of the
Administration various "machines" can be managed via this page.

Page

Common Symbol Area

The symbols of the different data streams are displayed in the right-hand area of the
TwinCAT Target Browser (TcAnalytics). In addition to the name, data type, size and symbol name, attributes
are also displayed, for example. Special attributes, such as those of the units, are interpreted and output in
their own columns. If a historized data stream is selected, the individual recordings and their time ranges are
also displayed.

56 Version: 1.13.4 TF6420


Configuration

5.1.1.1.9.4 Extension – TcAnalytics File


With the help of the TcAnalytics Extension of the TwinCAT Target Browser, MQTT data streams from
different brokers and topics can be displayed and made available for different measurement products. All
you have to do is drag and drop the desired stream symbols into the corresponding engineering tools.

Specific Target Area

In the left area of the TwinCAT Target Browser (TcAnalyticsFile) all folders are displayed in which a search
for AnalyticsFile folders is to take place. Any AnalyticsFile folders that are found are then displayed in a tree
structure.

Toolbar

The toolbar of the TcAnalyticsFile extension provides the following functions:

New folder This button can be used to add folder paths in which a search for AnalyticsFile folders is to
take place.

Delete folder This button can be used to delete the selected folder from the tree.

Refresh This button can be used to manually update the displays.

This button can be used to customize various properties of the TcAnalyticsFile extension.
Properties

TF6420 Version: 1.13.4 57


Configuration

Common Symbol Area

The symbols of the different AnalyticsFiles are displayed on the right in the TwinCAT Target Browser
(TcAnalyticsFile). In addition to the name, data type, size and symbol name, attributes are also displayed, for
example. Special attributes, such as those of the units, are interpreted and output in their own columns. In
addition, the individual recordings and their time ranges are displayed.

5.1.1.1.9.5 Extension – TcDBSrv


The TcDBSrv extension of the TwinCAT Target Browser can be used to display data sets from databases in
TwinCAT Scope via the TwinCAT Database Server. Only the desired columns of the tables have to be
dragged into TwinCAT Scope. A corresponding SQL command is generated automatically, which can of
course still be customized manually.

Specific Target Area

All target systems registered to the local TwinCAT 3 Engineering are displayed in a tree structure in the left-
hand area of the TwinCAT Target Browser (TcDBSrv). In first place is the local system, followed by the target
systems such as Industrial PCs or Embedded PCs in the order of registration. The prefixed screen symbol
indicates the state of the system (green: run mode, blue: config mode, red: stop mode or unreachable). The
available TwinCAT Database Server instances are listed below a target system. Below you will find all
configured databases with their accessible tables. If a table node is selected, the individual table columns
are displayed in the "Common Symbol Area".

Toolbar

The toolbar of the TcDBSrv extension provides the following functions:

58 Version: 1.13.4 TF6420


Configuration

Edit Routes If an ADS route to a target system is missing, further target systems can be added via this
button.

If the filter is active, only those routes are displayed where a TwinCAT Database Server is
Filter installed and accessible.
Add database This button can be used to create database configurations. Databases from the database
pool or new configurations can be created on the TwinCAT Database Server. The familiar
configuration editors open.
Delete This button can be used to delete the selected database configuration from the TwinCAT
Database Server.
database
Refresh The display of the target system states can be manually updated with this button.

Set timestamp This button or the corresponding context menu item in the table node can be used to specify
a column as timestamp; the time range of the table is read out based on this column.
column

Common Symbol Area

The tables are displayed with their columns in the right-hand area of the TwinCAT Target Browser
(TcDBSrv). In addition to the name and the data type, the size of the columns is also displayed. If a column
is defined as a timestamp column, the time range of the data is displayed

TF6420 Version: 1.13.4 59


Configuration

5.1.1.1.10 Support Information Report


The Support Information Report is a tool for collecting product information for submission to Beckhoff
technical support. Collecting product-related data such as TwinCAT version/build, product version, image
version and device type reduces email traffic significantly and enables more efficient advice.

Plug-in mechanism

Various Beckhoff products interface with the Support Information Report via a plug-in mechanism. These
products, such as the TwinCAT Database Server, have a Support Information Report entry in the
corresponding product menu.

Creating and submitting a Support Information Report


ü A Support Information Report is open.
1. Use the Behaviour text field to describe the behavior that occurred in as much detail as possible.
2. In the Attachment area, you can add files (screenshots etc.) to the report via the Add Attachment
button, if required. Files can optionally be selected via remote access. To do this, select a target from the
Remote System dropdown list. Depending on the selected target, it may be possible to browse Windows
CE devices.
3. Enter your contact details and select a Beckhoff subsidiary for your country.
This information is obligatory for submitting the Support Information Report.
4. You will be offered the option to store your contact details for future Support Information Reports. To do
this, tick the Store personal data check box.
5. The product-specific plug-ins can be found in the lower section of the Support Information Report. Tick
the Include in report check box. The information required for the product is added automatically, if it is
available. The screenshot shows the current configuration of a TwinCAT Database Server in the form of
an XML file as an example.
6. Submitting the Support Information Report:
• If the device has an email connection, you can submit the Support Information Report directly to the
Beckhoff subsidiary for your country via the Send Report button.
• If the device does not have an email connection, you can save the Support Information Report locally
as a .zip file via the Save .zip button and then make it available via FTP, USB etc.

60 Version: 1.13.4 TF6420


Configuration

5.1.1.2 Configure mode


This chapter is a compilation of all the information required for using the Configure mode of the
TwinCAT Database Server. It deals with the following topics:
• Creating a project
• Creating and setting up a database configuration
• Creating and setting up AutoLog groups
• Activating a Database Server project
• Monitoring and controlling automatic logging

Configure Mode

In Configure mode, the bulk of the work is done in the configurator. The configuration has to be set up for the
required database and for the AutoLog group. The target browser can be used for configuring the AutoLog
group, for online access to a target system, and for selecting the variables to be communicated. If the
AutoStart option is used, the communication with the configured database is established directly when
TwinCAT system starts up. If the Manual option is selected, the communication has to be enabled via the
function block FB_PLCDBAutoLog [} 160] or for AutoLog view.

Build Project

The TwinCAT Connectivity extension for Visual Studio provides a new project template. When a new project
is created, the TwinCAT Connectivity Project category appears as an option.

TF6420 Version: 1.13.4 61


Configuration

To create a new TwinCAT Connectivity project, select Empty TwinCAT Connectivity Project, specify the
project name and the storage location and click OK to add it to the solution. In this way, TwinCAT
Connectivity projects or TwinCAT Database Server projects can conveniently be created in parallel with
TwinCAT or other Visual Studio projects.

A new project node appears in the solution. Below the Connectivity project node you can add subprojects for
the supported connectivity functions.

Use Add to add a new TwinCAT Database Server project to the TwinCAT Connectivity project. The
TwinCAT Database Server project can be found in the list of existing Item Templates.

A new TwinCAT Database Server project is created under the TwinCAT Connectivity node.

62 Version: 1.13.4 TF6420


Configuration

This is now used as the basis for the pending configuration of a TwinCAT Database Server. The document
can be edited either via the Properties window or via an editor.

A Connectivity project can be associated with any number of TwinCAT Database Server projects or other
projects, and it may therefore contain several configurations.

Editor for server settings

The Server Settings editor can be used to edit the settings for the TwinCAT Database Server. These are
general settings relating to the corresponding server. In the drop-down menu (1) you can select the target
system via the Ams NetID. To this end you have to create a route to the target system via TwinCAT. When a
finished configuration is transferred, the settings are stored in the TwinCAT Database Server for this target
system.

The settings for logging faults or errors can be configured under Log settings. In the event of a fault or error,
the Database Server generates a detailed entry in a log file. The log file can be read with the Information Log
Viewer [} 49]. Under Log Settings you can specify a path to the file location and the maximum file size. You
can also influence the accuracy of the log. For performance reasons we recommend that logging is
deactivated again after the error analysis, once it is no longer required.

TF6420 Version: 1.13.4 63


Configuration

For network access to file-based databases such as Access or SQL Compact, the Impersonate option must
be set, so that the TwinCAT Database Server can connect to this network drive. This feature is currently
not supported in Windows CE.

Further configuration settings are available to control the read process from the database. These settings
refer to the TwinCAT Database Server on the target system:

MaxStringLength Maximum string length of the variables in the PLC


MaxByteArrayLength Maximum byte array length of the variables in the PLC
DBNullAllowed Indicates whether ZERO values are accepted in the TwinCAT Database Server.
DBConnectionTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection error while attempts are made to establish a connection.
DBCommandTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection fault when a command was sent. If large data quantities are involved,
processing of a command may take quite some time, depending on the database
and the infrastructure.

Supported database types

The installed database types can be selected in the server settings. All installed databases are selected by
default. The TwinCAT 3 Database Server will load the corresponding database interfaces. In this way,
unused databases on the target system can be deselected.

Adding a new database configuration

The database configuration is required for furnishing the Database Server with all the information required
for the database connection.

A new database configuration can be added via the command Add New Database in the context menu of a
Database Server project or via the corresponding command in the toolbar.

64 Version: 1.13.4 TF6420


Configuration

A new database configuration is added in the form of a file in the project folder and integrated in the project.
As with all Visual Studio projects, the information on the new files is stored in the Connectivity project.

Editor for database configurations

The database ID, which is required for some function blocks in the PLC, is shown in the upper part of the
editor (1). The database types of the target database can be selected from the drop-down menu (2). Another
option is the ODBC interface for a database, although this is not yet supported. Note that not all functions of
the TwinCAT Database Server can be guaranteed, depending on the database.

As a further option you can select a so-called failover database (3), which is triggered when an error is
encountered in Configure mode. In the event of a network disconnection, this feature can automatically
ensure that data are stored elsewhere and not lost.

TF6420 Version: 1.13.4 65


Configuration

For each database [} 123] additional adjustable parameters are available. Depending on the database a
connection string (5) is created, which describes the connection to the database. The intention is to make the
parameters you have set more transparent.

The CREATE (4) button can be used to create a new database. This function is only displayed if the
respective database supports it.

Unknown databases can be configured via an ODBC interface. In the ODBC Type drop-down list select
"Unknown Database" and add parameters via the commands in the context menu. They may contain
passwords, which are stored in encrypted form. The required connection string can be assembled from these
parameters. Note that only limited functions of the TwinCAT Database Server can be used. Only the explicit
function blocks of the SQL Expert mode are supported.

Failover database
The TwinCAT 3 Database Server has a failover database function. This function offers an option to
switch to another database in the event of a connection loss or other problems with the database
that was set up, in order to avoid possible data loss. This function is only supported by the
Configure mode. In the case of automatic writing, the corresponding alternative database is used in
the event of an error. The table of the first database must match the second.

Adding a new AutoLog group

The AutoLog groups contain information on which variables of the PLC are to be synchronized with which
variables from the databases. In addition, information about the synchronization times and the type of
synchronization are stored here.

A new AutoLog group for the database configuration can be added via the command Add New
AutologGroup in the context menu of a database configuration or via the toolbar. These AutoLog groups
refer to the parent database.

66 Version: 1.13.4 TF6420


Configuration

A new AutoLog group and the corresponding components are added as files to the project folder and
integrated in the project. They include the ADS device, the symbol groups and the table settings. In order to
save these files in the project, you should save the TwinCAT Connectivity project file. The files can then be
edited in editors or in the Properties window.

TF6420 Version: 1.13.4 67


Configuration

StartUp AutoLog mode can be enabled manually (with a command in the PLC or from
the configurator) or automatically during system startup.
Direction The set ADS device is used as data target or data source.
Write mode The data can appended in a database line-by-line, held in a ring buffer on a
temporal or quantitative basis, or simply be updated at the corresponding
position.
Ring buffer parameter Depending on the setting this parameter represent the time or the cycles after
which the ring buffer is updated.
Log mode The variable is written either after a certain cycle time or when a change
occurs.
Cycle Time Cycle time after which the variable is written.

Configuring the ADS device

The ADS device is automatically created under an AutoLog group. In the most frequent use case the ADS
device is the PLC runtime. The following parameters can be set in the editor:

68 Version: 1.13.4 TF6420


Configuration

ADS Device Name of the ADS target device.


AMS NetID Address of the target device in the TwinCAT network.
AMS Port Port of the target device in the TwinCAT network.
Timeout Time after which it is assumed that the connection to the target device is lost.
Connection Type bySymbolName: Connection is established based on the symbol name.
byIndexGroup: Connection is established based on the memory index.

Configuring symbols

The symbols you set here are written to or read from the database, depending on whether the ADS device is
the data target or the data source. The TwinCAT Target browser [} 50] can be used for convenient access.
Here you can search for the symbols on the target and communicate between the two tools via drag & drop.

Symbols can also be added manually to symbol groups or edited. The information that is required varies,
depending on whether in the ADS device the connection type was selected via the symbol name or the index
groups. The starting point is always the ADS device.

TF6420 Version: 1.13.4 69


Configuration

SymbolName The symbol is addressed based on the set ADS device


Symbol database Name of the variable in the database table
name
DataType PLC data type of the symbol
BitSize Bit size of the symbols (set automatically for the data types)
IndexGroup Index group in the TwinCAT system
IndexOffset Index offset in the TwinCAT system

Configuring a table

The table in a database can be based on a standard table structure or on an individual structure.

The corresponding table can be selected from a list of possible tables. If the table does not yet exist, you can
create it via the SQL Query Editor. If you select the standard table structure, a blue tick indicates whether the
selected table corresponds to this structure.

70 Version: 1.13.4 TF6420


Configuration

The specific table type offers the option to distribute the individual symbols that were set in the symbol group
to the table columns in the database as required. When a data set is written to the database in AutoLog
mode, the current values of the symbol group at the sampling time are saved in the corresponding table
column.

TF6420 Version: 1.13.4 71


Configuration

Activating a project

To activate a configured project on the TwinCAT Database Server, use the command Activate
Configuration in the context menu of the TwinCAT Database Server project.

72 Version: 1.13.4 TF6420


Configuration

Logging of the variable starts when the TwinCAT system starts, depending on which startup behavior was
specified in the AutoLog group. The mode can be started manually via the following AutoLog Viewer or with
the corresponding function block from the PLC.

AutoLog Viewer

The AutoLog Viewer of the TwinCAT Database Server is a tool for controlling and monitoring the AutoLog
mode. You can log into a target system, similar to the TwinCAT PLC. In logged-in state the AutoLog mode
can be started or stopped. Information on the current state of the logging is shown in the lower part of the
window. When an AutoLog group is selected, further information is displayed via the logged symbols.

TF6420 Version: 1.13.4 73


Configuration

ID Name Function
1 Target system Choose Target System with installed TwinCAT Database Server
2 Start Manual start of the AutoLog mode
3 Login Logging into the active AutoLog process
4 Logout Logging out of the active AutoLog process
5 Stop Manual stop of the AutoLog mode
6 AutoLog groups List of configured AutoLog groups on the target system
7 Symbols List of configured symbols for the selected AutoLog group

The AutoLog Viewer can be used to start and monitor the configured application. Depending on setting, after
login and startup the incrementing cycle counter of the AutoLog group is visible according to the update
times. Update errors are also shown here. For more detailed handling we recommend the InformationLog
View.

More detailed error handling with the InformationLog View

InformationLog View is a tool for reading log files from the TwinCAT Database Server. Recorded information
is displayed with a timestamp, IDs and error messages in plain text.

The log files can not only be viewed or emptied via direct file access, but also directly via the target. This is
particularly advantageous with distributed Database Servers in a network, for quick and easy access to the
log file. For this access a route to the target device must exist.

74 Version: 1.13.4 TF6420


Configuration

5.1.1.3 PLC Expert mode


This chapter is a compilation of all the information required for using the PLC Expert mode of the TwinCAT
Database Server. In contrast to the Configure mode, in this mode data are not written or read based on
cycles or events, but at specific times within the program sequence. This requires knowledge of the SQL
language.

PLC Expert mode

In PLC Expert mode only the database configuration is set in the configurator. Further functionalities are
implemented in the PLC code of the application. With the function block FB_PLCDBCreate [} 171] it is possible
to dispense with the configurator and even configure the database itself from the PLC. Function blocks for
reading and writing are available, if required. The function block FB_PLCDBCmd [} 183] forms the transition
between PLC Expert mode and SQL Expert mode. Here, table structures can easily be mapped as PLC
structures, and an SQL command with placeholders for the current structure values can be transferred to the
TwinCAT Database Server. The TwinCAT Database Server then inserts all values automatically and sends
the command to the database.

Build Project

The TwinCAT Connectivity extension for Visual Studio provides a new project template. When a new project
is created, the TwinCAT Connectivity Project category appears as an option.

TF6420 Version: 1.13.4 75


Configuration

To create a new TwinCAT Connectivity project, select Empty TwinCAT Connectivity Project, specify the
project name and the storage location and click OK to add it to the solution. In this way, TwinCAT
Connectivity projects or TwinCAT Database Server projects can conveniently be created in parallel with
TwinCAT or other Visual Studio projects.

A new project node appears in the solution. Below the Connectivity project node you can add subprojects for
the supported connectivity functions.

Use Add to add a new TwinCAT Database Server project to the TwinCAT Connectivity project. The
TwinCAT Database Server project can be found in the list of existing Item Templates.

A new TwinCAT Database Server project is created under the TwinCAT Connectivity node.

76 Version: 1.13.4 TF6420


Configuration

This is now used as the basis for the pending configuration of a TwinCAT Database Server. The document
can be edited either via the Properties window or via an editor.

A Connectivity project can be associated with any number of TwinCAT Database Server projects or other
projects, and it may therefore contain several configurations.

Editor for server settings

The Server Settings editor can be used to edit the settings for the TwinCAT Database Server. These are
general settings relating to the corresponding server. In the drop-down menu (1) you can select the target
system via the Ams NetID. To this end you have to create a route to the target system via TwinCAT. When a
finished configuration is transferred, the settings are stored in the TwinCAT Database Server for this target
system.

The settings for logging faults or errors can be configured under Log settings. In the event of a fault or error,
the Database Server generates a detailed entry in a log file. The log file can be read with the Information Log
Viewer [} 49]. Under Log Settings you can specify a path to the file location and the maximum file size. You
can also influence the accuracy of the log. For performance reasons we recommend that logging is
deactivated again after the error analysis, once it is no longer required.

TF6420 Version: 1.13.4 77


Configuration

For network access to file-based databases such as Access or SQL Compact, the Impersonate option must
be set, so that the TwinCAT Database Server can connect to this network drive. This feature is currently
not supported in Windows CE.

Further configuration settings are available to control the read process from the database. These settings
refer to the TwinCAT Database Server on the target system:

MaxStringLength Maximum string length of the variables in the PLC


MaxByteArrayLength Maximum byte array length of the variables in the PLC
DBNullAllowed Indicates whether ZERO values are accepted in the TwinCAT Database Server.
DBConnectionTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection error while attempts are made to establish a connection.
DBCommandTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection fault when a command was sent. If large data quantities are involved,
processing of a command may take quite some time, depending on the database
and the infrastructure.

Supported database types

The installed database types can be selected in the server settings. All installed databases are selected by
default. The TwinCAT 3 Database Server will load the corresponding database interfaces. In this way,
unused databases on the target system can be deselected.

Adding a database configuration

A new database configuration can be added via the command Add New Database in the context menu of a
Database Server project or via the corresponding command in the toolbar.

78 Version: 1.13.4 TF6420


Configuration

A new database configuration is added in the form of a file in the project folder and integrated in the project.
As with all Visual Studio projects, the information on the new files is stored in the Connectivity project.

Editor for database configurations

The database ID, which is required for some function blocks in the PLC, is shown in the upper part of the
editor (1). The database types of the target database can be selected from the drop-down menu (2). Another
option is the ODBC interface for a database, although this is not yet supported. Note that not all functions of
the TwinCAT Database Server can be guaranteed, depending on the database.

As a further option you can select a so-called failover database (3), which is triggered when an error is
encountered in Configure mode. In the event of a network disconnection, this feature can automatically
ensure that data are stored elsewhere and not lost.

TF6420 Version: 1.13.4 79


Configuration

For each database [} 123] additional adjustable parameters are available. Depending on the database a
connection string (5) is created, which describes the connection to the database. The intention is to make the
parameters you have set more transparent.

The CREATE (4) button can be used to create a new database. This function is only displayed if the
respective database supports it.

Unknown databases can be configured via an ODBC interface. In the ODBC Type drop-down list select
"Unknown Database" and add parameters via the commands in the context menu. They may contain
passwords, which are stored in encrypted form. The required connection string can be assembled from these
parameters. Note that only limited functions of the TwinCAT Database Server can be used. Only the explicit
function blocks of the SQL Expert mode are supported.

No additional AutoLog group configuration is required in this mode, since writing and reading between the
database and the PLC is called manually by the PLC programmer. The configuration part is now complete.

Activating a project

To activate a configured project on the TwinCAT Database Server, use the command Activate
Configuration in the context menu of the TwinCAT Database Server project.

80 Version: 1.13.4 TF6420


Configuration

Once the project has been activated, the can be used for further development steps, such as creating
databases or tables, generating structures for the PLC, which match the corresponding table structure of the
database, or testing connections to the database with the implemented information.

The PLC programmer can use the available PLC API [} 164] function blocks to communicate with the
TwinCAT Database Server.

5.1.1.4 SQL Expert mode


This chapter describes all the steps required for using the SQL Expert mode. This mode is tailored for users
with individual requirements. The following topics will be discussed:

1. Creating a project
2. Creating and setting up a database configuration
3. Activating a Database Server project
4. Creating SQL commands with the SQL Query Editor

SQL Expert Mode

In SQL Expert mode users can assemble the SQL commands for Insert, Select or Update, for example, in
the PLC and send them to the database via the TwinCAT Database Server. This is a very flexible and
powerful option. Stored Procedures [} 201] - in database - can also be called from the PLC.

Build Project

The TwinCAT Connectivity extension for Visual Studio provides a new project template. When a new project
is created, the TwinCAT Connectivity Project category appears as an option.

TF6420 Version: 1.13.4 81


Configuration

To create a new TwinCAT Connectivity project, select Empty TwinCAT Connectivity Project, specify the
project name and the storage location and click OK to add it to the solution. In this way, TwinCAT
Connectivity projects or TwinCAT Database Server projects can conveniently be created in parallel with
TwinCAT or other Visual Studio projects.

A new project node appears in the solution. Below the Connectivity project node you can add subprojects for
the supported connectivity functions.

Use Add to add a new TwinCAT Database Server project to the TwinCAT Connectivity project. The
TwinCAT Database Server project can be found in the list of existing Item Templates.

A new TwinCAT Database Server project is created under the TwinCAT Connectivity node.

82 Version: 1.13.4 TF6420


Configuration

This is now used as the basis for the pending configuration of a TwinCAT Database Server. The document
can be edited either via the Properties window or via an editor.

A Connectivity project can be associated with any number of TwinCAT Database Server projects or other
projects, and it may therefore contain several configurations.

Editor for server settings

The Server Settings editor can be used to edit the settings for the TwinCAT Database Server. These are
general settings relating to the corresponding server. In the drop-down menu (1) you can select the target
system via the Ams NetID. To this end you have to create a route to the target system via TwinCAT. When a
finished configuration is transferred, the settings are stored in the TwinCAT Database Server for this target
system.

The settings for logging faults or errors can be configured under Log settings. In the event of a fault or error,
the Database Server generates a detailed entry in a log file. The log file can be read with the Information Log
Viewer [} 49]. Under Log Settings you can specify a path to the file location and the maximum file size. You
can also influence the accuracy of the log. For performance reasons we recommend that logging is
deactivated again after the error analysis, once it is no longer required.

TF6420 Version: 1.13.4 83


Configuration

For network access to file-based databases such as Access or SQL Compact, the Impersonate option must
be set, so that the TwinCAT Database Server can connect to this network drive. This feature is currently
not supported in Windows CE.

Further configuration settings are available to control the read process from the database. These settings
refer to the TwinCAT Database Server on the target system:

MaxStringLength Maximum string length of the variables in the PLC


MaxByteArrayLength Maximum byte array length of the variables in the PLC
DBNullAllowed Indicates whether ZERO values are accepted in the TwinCAT Database Server.
DBConnectionTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection error while attempts are made to establish a connection.
DBCommandTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection fault when a command was sent. If large data quantities are involved,
processing of a command may take quite some time, depending on the database
and the infrastructure.

Supported database types

The installed database types can be selected in the server settings. All installed databases are selected by
default. The TwinCAT 3 Database Server will load the corresponding database interfaces. In this way,
unused databases on the target system can be deselected.

Adding a database configuration

A new database configuration can be added via the command Add New Database in the context menu of a
Database Server project or via the corresponding command in the toolbar.

84 Version: 1.13.4 TF6420


Configuration

A new database configuration is added in the form of a file in the project folder and integrated in the project.
As with all Visual Studio projects, the information on the new files is stored in the Connectivity project.

Editor for database configurations

The database ID, which is required for some function blocks in the PLC, is shown in the upper part of the
editor (1). The database types of the target database can be selected from the drop-down menu (2). Another
option is the ODBC interface for a database, although this is not yet supported. Note that not all functions of
the TwinCAT Database Server can be guaranteed, depending on the database.

As a further option you can select a so-called failover database (3), which is triggered when an error is
encountered in Configure mode. In the event of a network disconnection, this feature can automatically
ensure that data are stored elsewhere and not lost.

TF6420 Version: 1.13.4 85


Configuration

For each database [} 123] additional adjustable parameters are available. Depending on the database a
connection string (5) is created, which describes the connection to the database. The intention is to make the
parameters you have set more transparent.

The CREATE (4) button can be used to create a new database. This function is only displayed if the
respective database supports it.

Unknown databases can be configured via an ODBC interface. In the ODBC Type drop-down list select
"Unknown Database" and add parameters via the commands in the context menu. They may contain
passwords, which are stored in encrypted form. The required connection string can be assembled from these
parameters. Note that only limited functions of the TwinCAT Database Server can be used. Only the explicit
function blocks of the SQL Expert mode are supported.

Activating a project

To activate a configured project on the TwinCAT Database Server, use the command Activate
Configuration in the context menu of the TwinCAT Database Server project.

86 Version: 1.13.4 TF6420


Configuration

SQL Query Editor

The SQL Query Editor is a Database Server tool that supports the development of your application. The tool
can be used to test connections and SQL commands and to check the compatibility between PLC and
databases.

TF6420 Version: 1.13.4 87


Configuration

ID Name Function
1 Target system Choose Target System with installed TwinCAT Database Server
2 Database Selecting the configured database connection
3 Table Selecting the existing tables in the database
4 Copying for PLC Copying the SQL command to the PLC string. This can be copied into the
PLC source code. Special characters are automatically captured and
formatted.
5 Export TC3 Exporting the table schema into a PLC structure. This can be used in the
program for SQL commands, for example.
6 Get Table Schema Reading the table structure
7 Create Cmd Creating an SQL command, based on the table structure
8 Execute Executing the SQL command

First select the target system from the routes of your TwinCAT system (1). The TwinCAT Database Server
must be installed on the target system. If a NoSQL database is stored in the configuration, an additional
NoSQL tab is visible. You will find the documentation in a subitem below.

All configured databases (2) are displayed, once you have activated the database configurations on the
target system. You can also select one of the available tables (3) from the database. Based on this table,
you can generate SQL commands from the SQL Query Editor and send them to the database. The SQL
commands have different syntax, depending on database type.

Three commands are available for generating the individual SQL commands:
• Get Table Schema: Calls up the structure of the selected table.
◦ Information such as the column name, PLC data type and size of variables is displayed. The
retrieved structure can also be prepared for your PLC application via the commands Copy for
PLC (4) or Export TC3 (5).
• Create Cmd: An SQL command is generated in the command text box, depending on the selected tab.
The command syntax may differ, depending on the database type. The previously read table schema is
used here.
◦ The created SQL command can optionally be modified.
• Execute: The SQL command shown in the text box is executed and returns values, if applicable.

The differences in the individual SQL commands are explained below.

Comment: Since the syntax of SQL commands often collides with the syntax in the ST code of TwinCAT, the
SQL Query Editor offers the command "Copy for PLC" (4). The command is used to copy the created and
tested SQL commands with the correct formatting for special characters for the ST program code into the
cache.

Create Table command

The CREATE TABLE tab can be used to create tables within the database. Further columns can be added
to the table with (+), as required. Once you have specified the column name and type, you can specify
additional properties, in order to generate automatic IDs, for example.

The table name can be determined by executing the command. The table with the configured table structure
is created.

88 Version: 1.13.4 TF6420


Configuration

Insert command

The Insert command gives the opportunity to write records into the table. The values under "Value" can be
modified once the table structure has been retrieved. If the command is then generated, the values in the
Insert command will automatically be in the right format. These values are written into the table when the
command is executed.

This value cannot be customized if automatic ID generation is used.

TF6420 Version: 1.13.4 89


Configuration

Select command

Select commands can be created and sent via the SELECT tab. Select commands give the opportunity to
read records from the databases. After executing the command, values are returned if they exist in the table.
They are listed under "Value" in the table structure display. Use the arrows under the display to navigate
through the individual records.

90 Version: 1.13.4 TF6420


Configuration

Delete command

The Delete command has two functions.

1. DELETE Records: Deletes the contents of a table.


2. DROP table: Deletes the whole table.

This SQL command can also be customized, in order to delete only a particular section of the table, for
example.

TF6420 Version: 1.13.4 91


Configuration

Stored Procedures

The TwinCAT Database Server supports "Stored Procedures", which provide numerous databases for
processing more complex queries at the database level or to make a simplified interface available.

If Stored Procedures are available in the database and the table, you can list and select them (1). The input
and output parameters can be picked up automatically (2) and transferred to the tables in the display (3)(4).

The parameter type, name and data type are displayed there. In addition you can insert values here, in order
to execute the Stored Procedures with the input values via "Execute". The result is displayed in the output
values (4). If several records are returned, the arrow keys can be used to switch between them. This
functionality serves as development aid for the call in the PLC. The results are returned there by calling the
corresponding function block [} 201].

92 Version: 1.13.4 TF6420


Configuration

InformationLog View for diagnostics

The InformationLog View is available for troubleshooting.

InformationLog View is a tool for reading log files from the TwinCAT Database Server. Recorded information
is displayed with a timestamp, IDs and error messages in plain text.

The log files can not only be viewed or emptied via direct file access, but also directly via the target. This is
particularly advantageous with distributed Database Servers in a network, for quick and easy access to the
log file. For this access a route to the target device must exist.

TF6420 Version: 1.13.4 93


Configuration

5.1.1.5 NoSql Expert Mode


NoSQL

NoSQL databases (not only Sequel) differ from conventional relational data storage.

Document-based databases:

Records are stored as documents in the database. This offers the advantage of being able to archive data in
a more flexible and hierarchical manner.

94 Version: 1.13.4 TF6420


Configuration

If a record consists of more than one flat structure of basic data types, it can no longer be mapped directly
via a relational database. NoSQL databases offer this flexibility. Changes in the program code and the
corresponding structures can also be easily adopted without having to create a new table.

Document-based databases usually save the data as JSON-formatted records. The records can all be
different.

Build Project

The TwinCAT Connectivity extension for Visual Studio provides a new project template. When a new project
is created, the TwinCAT Connectivity Project category appears as an option.

To create a new TwinCAT Connectivity project, select Empty TwinCAT Connectivity Project, specify the
project name and the storage location and click OK to add it to the solution. In this way, TwinCAT
Connectivity projects or TwinCAT Database Server projects can conveniently be created in parallel with
TwinCAT or other Visual Studio projects.

TF6420 Version: 1.13.4 95


Configuration

A new project node appears in the solution. Below the Connectivity project node you can add subprojects for
the supported connectivity functions.

Use Add to add a new TwinCAT Database Server project to the TwinCAT Connectivity project. The
TwinCAT Database Server project can be found in the list of existing Item Templates.

A new TwinCAT Database Server project is created under the TwinCAT Connectivity node.

96 Version: 1.13.4 TF6420


Configuration

This is now used as the basis for the pending configuration of a TwinCAT Database Server. The document
can be edited either via the Properties window or via an editor.

A Connectivity project can be associated with any number of TwinCAT Database Server projects or other
projects, and it may therefore contain several configurations.

Editor for server settings

The Server Settings editor can be used to edit the settings for the TwinCAT Database Server. These are
general settings relating to the corresponding server. In the drop-down menu (1) you can select the target
system via the Ams NetID. To this end you have to create a route to the target system via TwinCAT. When a
finished configuration is transferred, the settings are stored in the TwinCAT Database Server for this target
system.

The settings for logging faults or errors can be configured under Log settings. In the event of a fault or error,
the Database Server generates a detailed entry in a log file. The log file can be read with the Information Log
Viewer [} 49]. Under Log Settings you can specify a path to the file location and the maximum file size. You
can also influence the accuracy of the log. For performance reasons we recommend that logging is
deactivated again after the error analysis, once it is no longer required.

TF6420 Version: 1.13.4 97


Configuration

For network access to file-based databases such as Access or SQL Compact, the Impersonate option must
be set, so that the TwinCAT Database Server can connect to this network drive. This feature is currently
not supported in Windows CE.

Further configuration settings are available to control the read process from the database. These settings
refer to the TwinCAT Database Server on the target system:

MaxStringLength Maximum string length of the variables in the PLC


MaxByteArrayLength Maximum byte array length of the variables in the PLC
DBNullAllowed Indicates whether ZERO values are accepted in the TwinCAT Database Server.
DBConnectionTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection error while attempts are made to establish a connection.
DBCommandTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection fault when a command was sent. If large data quantities are involved,
processing of a command may take quite some time, depending on the database
and the infrastructure.

Supported database types

The installed database types can be selected in the server settings. All installed databases are selected by
default. The TwinCAT 3 Database Server will load the corresponding database interfaces. In this way,
unused databases on the target system can be deselected.

Adding a database configuration

A new database configuration can be added via the command Add New Database in the context menu of a
Database Server project or via the corresponding command in the toolbar.

98 Version: 1.13.4 TF6420


Configuration

A new database configuration is added in the form of a file in the project folder and integrated in the project.
As with all Visual Studio projects, the information on the new files is stored in the Connectivity project.

Editor for database configurations

The database ID, which is required for some function blocks in the PLC, is shown in the upper part of the
editor (1). The database types of the target database can be selected from the drop-down menu (2). Another
option is the ODBC interface for a database, although this is not yet supported. Note that not all functions of
the TwinCAT Database Server can be guaranteed, depending on the database.

As a further option you can select a so-called failover database (3), which is triggered when an error is
encountered in Configure mode. In the event of a network disconnection, this feature can automatically
ensure that data are stored elsewhere and not lost.

For each database [} 123] additional adjustable parameters are available. Depending on the database a
connection string (5) is created, which describes the connection to the database. The intention is to make the
parameters you have set more transparent.

The CREATE (4) button can be used to create a new database. This function is only displayed if the
respective database supports it. CHECK can be used to check the connection to the database.

NoSQL databases can also be selected from the target databases. If you activate the project with a NoSQL
database, a NoSQL tab is enabled in the SQL query editor to facilitate the use of NoSQL-specific functions.

TF6420 Version: 1.13.4 99


Configuration

Activating a project

To activate a configured project on the TwinCAT Database Server, use the command Activate
Configuration in the context menu of the TwinCAT Database Server project.

MongoDB in PLC Expert/Configure mode

PLC Expert and Configure mode use the predefined database schema in their processes. Normally, the
schema of the structures used will not change during operation. In order to nevertheless be able to use the
function blocks, the TwinCAT 3 Database Server requires a description of the table schema. For MongoDB a
table is therefore simulated.
In the SQL Query Editor, use the SQL tab and the CREATE TABLE subcategory to create a table, or in this
case a collection. In addition, unlike for relational databases, an entry is created in a metadata collection.
Information on the table schema for the TwinCAT 3 Database Server is stored here.

In order to use advanced functionality, e.g. structures of any hierarchy or flexible records, we recommend
using the NoSQL function blocks.

InformationLog View for diagnostics

The InformationLog View is available for troubleshooting.

InformationLog View is a tool for reading log files from the TwinCAT Database Server. Recorded information
is displayed with a timestamp, IDs and error messages in plain text.

The log files can not only be viewed or emptied via direct file access, but also directly via the target. This is
particularly advantageous with distributed Database Servers in a network, for quick and easy access to the
log file. For this access a route to the target device must exist.

100 Version: 1.13.4 TF6420


Configuration

5.1.2 Standalone Configurator

5.1.2.1 General

5.1.2.1.1 Interface and basic functions


The TwinCAT 3 Database Server is configured via an XML configuration file.
The settings in the configuration file can easily be created and modified with the help of the XML
configuration file editor. New configuration files can be created, and existing configuration files can be read
and revised.

TF6420 Version: 1.13.4 101


Configuration

Toolbar and commands

The toolbar has the following elements:

102 Version: 1.13.4 TF6420


Configuration

Toolstrip button Description


Activation of the configuration

Read configuration of the target device

Save configuration in an XML file

Read configuration from an XML file

Add new database configuration

Add new AutoLog group

Event display

Database pool

AutoLog Viewer

InformationLog View

SQL Query Editor

TF6420 Version: 1.13.4 103


Configuration

5.1.2.1.2 Project properties

Editor for server settings

The Server Settings editor can be used to edit the settings for the TwinCAT Database Server. These are
general settings relating to the corresponding server. In the drop-down menu (1) you can select the target
system via the Ams NetID. To this end you have to create a route to the target system via TwinCAT. When a
finished configuration is transferred, the settings are stored in the TwinCAT Database Server for this target
system.

The settings for logging faults or errors can be configured under Log settings. In the event of a fault or error,
the Database Server generates a detailed entry in a log file. The log file can be read with the Information Log
Viewer [} 49]. Under Log Settings you can specify a path to the file location and the maximum file size. You
can also influence the accuracy of the log. For performance reasons we recommend that logging is
deactivated again after the error analysis, once it is no longer required.

For network access to file-based databases such as Access or SQL Compact, the Impersonate option must
be set, so that the TwinCAT Database Server can connect to this network drive. This feature is currently
not supported in Windows CE.

Further configuration settings are available to control the read process from the database. These settings
refer to the TwinCAT Database Server on the target system:

MaxStringLength Maximum string length of the variables in the PLC


MaxByteArrayLength Maximum byte array length of the variables in the PLC
DBNullAllowed Indicates whether ZERO values are accepted in the TwinCAT Database Server.
DBConnectionTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection error while attempts are made to establish a connection.
DBCommandTimeout Indicates the time after which the TwinCAT Database Server assumes a
connection fault when a command was sent. If large data quantities are involved,
processing of a command may take quite some time, depending on the database
and the infrastructure.

104 Version: 1.13.4 TF6420


Configuration

Supported database types

The installed database types can be selected in the server settings. All installed databases are selected by
default. The TwinCAT 3 Database Server will load the corresponding database interfaces. In this way,
unused databases on the target system can be deselected.

TF6420 Version: 1.13.4 105


Configuration

5.1.2.1.3 Configuring databases

Editor for database configurations

The database ID, which is required for some function blocks in the PLC, is shown in the upper part of the
editor (1). The database types of the target database can be selected from the drop-down menu (2). Another
option is the ODBC interface for a database, although this is not yet supported. Note that not all functions of
the TwinCAT Database Server can be guaranteed, depending on the database.

As a further option you can select a so-called failover database (3), which is triggered when an error is
encountered in Configure mode. In the event of a network disconnection, this feature can automatically
ensure that data are stored elsewhere and not lost.

For each database [} 123] additional adjustable parameters are available. Depending on the database a
connection string (5) is created, which describes the connection to the database. The intention is to make the
parameters you have set more transparent.

The CREATE (4) button can be used to create a new database. This function is only displayed if the
respective database supports it.

106 Version: 1.13.4 TF6420


Configuration

Unknown databases can be configured via an ODBC interface. In the ODBC Type drop-down list select
"Unknown Database" and add parameters via the commands in the context menu. They may contain
passwords, which are stored in encrypted form. The required connection string can be assembled from these
parameters. Note that only limited functions of the TwinCAT Database Server can be used. Only the explicit
function blocks of the SQL Expert mode are supported.

5.1.2.1.4 Configuring AutoLog groups

Configuring the ADS device

The ADS device is automatically created under an AutoLog group. In the most frequent use case the ADS
device is the PLC runtime. The following parameters can be set in the editor:

TF6420 Version: 1.13.4 107


Configuration

ADS Device Name of the ADS target device.


AMS NetID Address of the target device in the TwinCAT network.
AMS Port Port of the target device in the TwinCAT network.
Timeout Time after which it is assumed that the connection to the target device is lost.
Connection Type bySymbolName: Connection is established based on the symbol name.
byIndexGroup: Connection is established based on the memory index.

108 Version: 1.13.4 TF6420


Configuration

StartUp AutoLog mode can be enabled manually (with a command in the PLC or from
the configurator) or automatically during system startup.
Direction The set ADS device is used as data target or data source.
Write mode The data can appended in a database line-by-line, held in a ring buffer on a
temporal or quantitative basis, or simply be updated at the corresponding
position.
Ring buffer parameter Depending on the setting this parameter represent the time or the cycles after
which the ring buffer is updated.
Log mode The variable is written either after a certain cycle time or when a change
occurs.
Cycle Time Cycle time after which the variable is written.

A new AutoLog group for the database configuration can be added via the command Add New
AutologGroup in the context menu of a database configuration or via the toolbar. These AutoLog groups
refer to the parent database.

Configuring symbols

The symbols you set here are written to or read from the database, depending on whether the ADS device is
the data target or the data source. The TwinCAT Target browser [} 50] can be used for convenient access.
Here you can search for the symbols on the target and communicate between the two tools via drag & drop.

TF6420 Version: 1.13.4 109


Configuration

Symbols can also be added manually to symbol groups or edited. The information that is required varies,
depending on whether in the ADS device the connection type was selected via the symbol name or the index
groups. The starting point is always the ADS device.

110 Version: 1.13.4 TF6420


Configuration

SymbolName The symbol is addressed based on the set ADS device


Symbol database Name of the variable in the database table
name
DataType PLC data type of the symbol
BitSize Bit size of the symbols (set automatically for the data types)
IndexGroup Index group in the TwinCAT system
IndexOffset Index offset in the TwinCAT system

Configuring a table

The table in a database can be based on a standard table structure or on an individual structure.

The corresponding table can be selected from a list of possible tables. If the table does not yet exist, you can
create it via the SQL Query Editor. If you select the standard table structure, a blue tick indicates whether the
selected table corresponds to this structure.

The specific table type offers the option to distribute the individual symbols that were set in the symbol group
to the table columns in the database as required. When a data set is written to the database in AutoLog
mode, the current values of the symbol group at the sampling time are saved in the corresponding table
column.

TF6420 Version: 1.13.4 111


Configuration

5.1.2.1.4.1 Write direction mode


The TwinCAT Database Server has four different write direction modes. These are explained below.

DB_TO_ADS

This write mode is used to cyclically read variable values from a database and write the read values into PLC
variables.

ADS_TO_DB_APPEND

This write mode is used to cyclically write variable values from the PLC into a database. Each time a new
record is created and appended at the end of the table/file.

ADS_TO_DB_UPDATE

This write mode is used to cyclically read variable values from the PLC and compare the read values with
the database records. If differences are detected, the corresponding record is modified with the new value.

ADS_TO_DB_RINGBUFFER

This write mode can be used to specify the number of records or the age of records.
This write mode is available during cyclic logging via the symbol groups and during logging with the function
block FB_DBWrite.
The RingBuffer mode is available for all database types. This mode can also be used to influence logging in
ASCII files.

112 Version: 1.13.4 TF6420


Configuration

RingBuffer-Arten

The RingBuffer can be used in two different ways:


• "RingBuffer_Time"
• "RingBuffer_Count"

RingBuffer Time

In this mode a time can be specified for the maximum age of the record. If this age is exceeded, the
corresponding record is deleted.

RingBuffer Count

In this mode a maximum number of records can be specified. When the maximum number is reached, the
oldest records are deleted in order to make room for the new ones.

Declaring the RingBuffer mode in the XML configuration file editor

RingBuffer_Time:

The time is specified in milliseconds.

RingBuffer_Count:

Declaring the RingBuffer mode in FB_DBWrite:

RingBuffer_Time:

TF6420 Version: 1.13.4 113


Configuration

RingBuffer_Count:

5.1.2.1.5 SQL Query Editor


The SQL Query Editor is a Database Server tool that supports the development of your application. The tool
can be used to test connections and SQL commands and to check the compatibility between PLC and
databases.

114 Version: 1.13.4 TF6420


Configuration

After the TwinCAT Database Server of the target system is selected, the SQL Query Editor loads the current
database configuration and the tables of the successfully connected databases. Depending on whether the
database supports the SQL and the NoSQL interface (from the TwinCAT Database Server), it is listed under
the respective category.

Below the selection of the target system there is a status bar with the available commands:

Table level
Insert working area Opens the Insert working area to write data sets to the selected
table with SQL.
Select working area Opens the Select working area to read data sets from the selected
table with SQL.
Delete/Drop working area Opens the Delete/Drop working area to delete data sets with SQL
from the selected table or to delete entire tables.
NoSQL working area Opens the NoSQL working area to execute NoSQL-specific
queries.
Database level
Stored Procedure working area Opens the Stored Procedure working area to execute stored
procedures of the database.
Tables working area Opens the Tables working area to create new tables in the selected
database.
Update tables Updates the available tables of the selected database.
General
Update databases Updates the entire database tree.

The working areas are opened to the right of the tree under the corresponding tab. Also from the same table
several tabs can be opened at one time.

Insert working area

The Insert working area enables data to be written to the selected table via the TwinCAT Database Server
interface for SQL function blocks.

TF6420 Version: 1.13.4 115


Configuration

In the lower area (2) there is a table with the individual data symbols in the data set to be written. The name,
PLC data type, the byte length as well as the value can be determined here. The entered values are then
used via the command to generate the SQL statement.

This SQL statement is then made available in a text field (3). Depending on the syntax of the database, the
content may vary.

The upper status bar contains the commands for interacting with the TwinCAT Database Server (1).

Command Description
Read tables schema Reads out the table schema of the table of the working area.
Generate SQL statement Generates the SQL statement from the present table depending on the
database syntax.
Execution Executes the statement in the text field (3) via the respective interface of
the TwinCAT Database Server.
Copy the statement Copies the statement in the text field (3) as TwinCAT compatible syntax.
Export as structure Exports the structure of the table of input values to a TwinCAT 3
compatible DUT.

Select working area

The Select working area allows reading data into the selected table via the TwinCAT Database Server
interface for SQL function blocks.

116 Version: 1.13.4 TF6420


Configuration

In the lower area (2) there is a table with the individual data symbols in the data set to be read. The name,
PLC data type, as well as the byte length can be determined here. This information is then needed to
interpret the data.

This SQL statement is then made available in a text field (3). Depending on the syntax of the database, the
content may vary.

The result field (4) displays the data after the statement has been executed. If several results are returned,
they can be switched through the pages.

The upper status bar contains the commands for interacting with the TwinCAT Database Server (1).

Command Description
Read tables schema Reads out the table schema of the table of the working area.
Generate SQL statement Generates the SQL statement from the present table depending on the
database syntax.
Execution Executes the statement in the text field (3) via the respective interface of
the TwinCAT Database Server.
Copy the statement Copies the statement in the text field (3) as TwinCAT compatible syntax.
Export as structure Exports the structure of the table of input values to a TwinCAT 3
compatible DUT.

Delete/Drop working area

The Delete/Drop working area provides the option to issue SQL statements to delete either data from a table
or the entire table from the database.

TF6420 Version: 1.13.4 117


Configuration

For this purpose, you can choose between the two options in the status bar. The syntax corresponding to the
database is then generated in the statement field. To execute this with the TwinCAT Database Server
interface, the switch FB_SQLCommandEvt.Execute is available.

NoSql working area

The NoSql working area supports the special functions of NoSql databases or the TwinCAT Database
Server NoSQL interface.

ID Name Function
1 Filter/Document Depending on which function is used, this input field acts as a document
or as a filter in JSON format. If you want to execute a Find operation and
also carry out a projection or sort operation, you can fill these fields with
Options(Find) below.
2 Options (Find) Describes additional parameters for the Find function, such as the
projection or sorting.
3 Control elements Control elements for interaction with the TwinCAT Database Server
interface for NoSQL.
4 Data display List of returned data. Navigation allows iteration through the available
pages.

118 Version: 1.13.4 TF6420


Configuration

Find: executes a search query with the filter entered in the text field (1). Optionally, a projection or sorting
operation can also be executed via the Options(Find) fields. Data is returned and listed in the data display
(4). The syntax of the filters is database-specific.

Aggregate: executes an aggregation with the parameters entered in the text field (1). Data is returned and
listed in the data display (4). The syntax of the filters is database-specific.

Insert: executes an insert query of the (JSON) document or document array entered in the text field (1).
These are then written to the collection.

Delete: executes a delete query on the data found with the filter in the text field (1). Any data that is found is
deleted from the collection.

Validate: if this option is selected, the data queries are not automatically parsed according to their own
schema, but an attempt is made to map these data to the structure of the symbol from the PLC, which was
specified via these parameters.

With the latter function, a Find query may lead to conflicts. In contrast to structures in the PLC process
image, data sets in NoSQL databases do not have to follow a fixed schema. It is possible that queried
documents do not have data for a specific element in the PLC structure. Or the data set carries data that
does not occur in the PLC structure. These data are assigned via the name or the attribute "ElementName"
in the PLC.

The differences in the data can be examined via the Schema Compare tab. In the above example it can be
seen that in the case of the returned document in the PLC structure, the variable "Name" has a different data
type length than that of the database. The corresponding colors show the weighting of the conflict:

Red: too many or too few data available.

Yellow: the byte length of the data set does not match, or underlying data sets are left over or missing.

Green: no conflicts

TF6420 Version: 1.13.4 119


Configuration

These conflicts are also listed under the Issue Tracker tab. It can also be read into the PLC as a string
array, if required.

The Remaining Json tab returns any remaining data sets as JSON. This information can also be read into
the PLC as a string.

The control elements in the status bar can be used to iterate through the data, as known from the other
displayed data. The number of data sets displayed simultaneously can be specified.

Stored Procedure working area

The TwinCAT Database Server supports "Stored Procedures", which provide numerous databases for
processing more complex queries at the database level or to make a simplified interface available.

If Stored Procedures are present in the database, they will be listed in the dropdown list of the status bar
(4).

Below is the table for the input parameters (1), and for the output schema (2). In addition, there is a view for
the output results (3). If the Stored Procedure is executed successfully, the results are displayed here.

The status bar has the following commands:

Command Description
Read stored procedure input Reads out the input parameter schema. The results are shown in Table
schema 1.
Read Stored Procedure output Reads out the output parameter schema. The results are shown in Table
schema 2. Info: This requires the execution of the Stored Procedure. Depending
on the programming, data can be changed here.
Design Executes the Stored Procedure via the respective interface of the
TwinCAT Database Server.
Export as structure Exports the structure of the table to a TwinCAT 3 compatible DUT.

Table working area

The Table working area is used to create new tables.

120 Version: 1.13.4 TF6420


Configuration

Here, the table structure (1) can be created and an SQL statement can be generated from it in the
corresponding field (2). The status bar (3) with the following commands can be used for this purpose:

Command Description
Table name Specifies the table name of the new table.
Generate SQL statement Generates the SQL statement from the present table depending on the
database syntax.
Execution Executes the Stored Procedure via the respective interface of the
TwinCAT Database Server.
Copy the statement Copies the statement in the text field (2) as TwinCAT compatible syntax.

5.1.2.1.6 AutoLog Live View


The AutoLog Viewer of the TwinCAT Database Server is a tool for controlling and monitoring the AutoLog
mode. You can log into a target system, similar to the TwinCAT PLC. In logged-in state the AutoLog mode
can be started or stopped. Information on the current state of the logging is shown in the lower part of the
window. When an AutoLog group is selected, further information is displayed via the logged symbols.

TF6420 Version: 1.13.4 121


Configuration

ID Name Function
1 Target system Choose Target System with installed TwinCAT Database Server
2 Start Manual start of the AutoLog mode
3 Login Logging into the active AutoLog process
4 Logout Logging out of the active AutoLog process
5 Stop Manual stop of the AutoLog mode
6 AutoLog groups List of configured AutoLog groups on the target system
7 Symbols List of configured symbols for the selected AutoLog group

5.1.2.1.7 InformationLog View


InformationLog View is a tool for reading log files from the TwinCAT Database Server. Recorded information
is displayed with a timestamp, IDs and error messages in plain text.

The log files can not only be viewed or emptied via direct file access, but also directly via the target. This is
particularly advantageous with distributed Database Servers in a network, for quick and easy access to the
log file. For this access a route to the target device must exist.

122 Version: 1.13.4 TF6420


Configuration

5.2 Databases
The TwinCAT Database Server is the link between the TwinCAT PLC and database systems. It supports a
wide range of databases. In addition to conventional databases such as Microsoft SQL or Oracle, XML and
ASCII files can also be used as databases. With ODBC databases it is even possible to enter database
connection strings for communication with databases that are not listed as supported database types.

The two tables below show an overview of which databases are supported on which operating system
platforms and which databases are available for data export and import for the TwinCAT Scope.

Platform support

Overview of which database connections are supported by which platform.

TF6420 Version: 1.13.4 123


Configuration

Database Windows Windows CE TwinCAT/BSD


Local Remote Local Remote Local Remote
MS SQL X X - X - X
MS SQL X - X - - -
Compact
MySQL X X - X* X X
Oracle DB X X - - - -
SQLite X - X** - X* -
ASCII-File X - X - X -
XML X - X - X -
ODBC X* X* - - X* X*
MS Access X* - - - - -
MS Excel X* - - - - -
MongoDB X X - - X X
PostgreSQL X X - - - X
InfluxDB X X - - X X

*additional server or client drivers for the database must be installed on the device

**applies only to devices with ARM architecture

TwinCAT Scope support

Overview of which databases are supported for data import and export in TwinCAT Scope. The TwinCAT
Scope always works together with the TwinCAT Database Server.

Database Scope Export Scope Import


MS SQL X X
MS SQL Compact - X
MySQL - X
Oracle DB - X
SQLite - X
ASCII-File X X
XML - X
ODBC - X
MS Access - X
MS Excel - X
MongoDB - -
PostgreSQL - X
InfluxDB - X

The configuration of the individual databases and mapping of the data sets in the PLC is explained on the
following sections.

5.2.1 General Information


On the following pages you will find some general information about the supported databases. This
information is generic, i.e. not limited to a specific database, and covers topics such as network access, data
type support and operating system support.

5.2.1.1 WString support


WSTRING is available for using the Unicode character set.

124 Version: 1.13.4 TF6420


Configuration

This data type must be activated in the server settings so that it can be written to the database using the
TwinCAT Database Server in PLC Expert mode.

This data type requires two bytes per character. Please keep this in mind when creating the table structure.
To be able to save it in the database in UTF16 format, the column must be created according to the
character set. The SQL Query Editor can also be used for this purpose.

TF6420 Version: 1.13.4 125


Configuration

The following databases are supported with the Database Server:

Database UTF8 UTF16 Character set definition Performance impairment


MySQL x x column-specific x
MSSQL x x column-specific
Oracle x x column-specific
PostgreSQL x x cross-database x
Others x

Performance impairment
Some databases cause performance problems, because additional SQL commands have to be sent
in order to read the character set.

WString support is available from version 3.1.31.4.

5.2.1.2 BULK support


The TwinCAT Database Server also supports so-called BULK commands for a selection of databases. BULK
commands are SQL statements that insert collected data into multiple rows of a table. Using BULK insert
commands usually results in better performance than processes that send a single insert statement to the
database for each row to be added.

Currently, BULK commands via the FB_PLCDBCmdEvt function block are supported by the TwinCAT
Database Server for Microsoft SQL databases.

Example command: 'SQLBULK<INSERT>#MyTable‘

5.2.2 MS SQL database


This section contains information on the configuration and the data type mapping of
Microsoft SQL databases.

Compatible versions: Microsoft SQL database 20xx.

126 Version: 1.13.4 TF6420


Configuration

Declaration in the TwinCAT Database Server Configurator

Microsoft SQL database


Database Type Select "Microsoft SQL Server" from the drop-down menu.
Provider "SQLOLEDB"or the provider of the SQL Native Client, e.g. "SQLNCLI10"
Server Enter the name of your SQL server here. Example:
"TESTSERVER\SQLEXPRESS"
Database Enter the name of the database. If the database does not yet exist, it can
be created with the Create button. Corresponding permissions must
exist.
Authentication Option for logging into the database as a particular user.
User name Enter the user name here.
Password Enter the corresponding password.

Windows CE support
This database is also supported by the Windows CE version of the TwinCAT Database Server. The
interfacing is not local, but can be established via a network connection.

Data type mapping between DB and PLC

E_ColumnTypes MS SQL TwinCAT PLC


BigInt bigint T_ULARGE_INTEGER
(TcUtilities.lib)
Integer integer DINT
SmallInt smallint INT
TinyInt tinyint SINT
Bit_ bit BYTE
Money money LREAL
Float float LREAL
Real_ real REAL
DateTime datetime DT
NText ntext STRING
NChar nchar STRING
Image image ARRAY OF BYTE
NVarChar nvarchar STRING
Binary binary ARRAY OF BYTE
VarBinary varbinary ARRAY OF BYTE

Data type support


This database supports the data type WSTRING. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

TF6420 Version: 1.13.4 127


Configuration

5.2.2.1 Notes on the Microsoft SQL Server

Logs in the Windows Eventlog

Error Event In the SQL Configuration Manager under SQL Server 2005 stop
"Report Server Windows Service the SQL Server Reporting Services (SQLEXPRESS) and set the
(SQLEXPRESS) cannot be connected to Start Mode to "manual". The Database Server doesn't need the
the report server database." Reporting Service.
Information event Open the Properties via the context menu in SQL Server
"'TcDataLogger' database is started" Management Studio Express under Databases/TcDataLogger
and under Options set the option Close automatically to FALSE.
This option is not required because the Database Server opens
and closes the database automatically.

It is possible to suppress logging to the Windows Eventlog. Events are then no longer logged. No distinction
can be made between the different types of event.

Select the SQL Server (SQLEXPRESS) in the SQL configuration manager under SQL Server 2005 Services
and open the Properties via the context menu. The Advanced tab contains a Startup parameters subitem.
The individual parameters are separated by semicolons. Add the parameter "-n" and restart the service.

From this point onwards no further events will be logged by the SQL Server.

5.2.3 MS SQL Compact database


This section contains information on the configuration and the data type mapping of
Microsoft SQL Compact databases. MS SQL Compact is an ideal database for embedded applications. It
has a small footprint but nevertheless provides the required functionality for relational databases.

Compatible versions: Microsoft SQL Compact database 3.5

Declaration in the TwinCAT Database Server Configurator

Microsoft SQL Compact database


Database Type Select "Microsoft Compact SQL" from the drop-down menu.
Database URL Enter the name and path of the database. If the database does not yet exist,
it can be created with the Create button. Corresponding permissions must
exist.
Authentication Option for logging into the database with a password.
Password Enter the password.

Windows CE support
This database is also supported by the Windows CE version of the TwinCAT Database Server. The
connection can be established locally.

128 Version: 1.13.4 TF6420


Configuration

Data type mapping between DB and PLC

E_ColumnTypes MS SQL Compact TwinCAT PLC


BigInt bigint T_ULARGE_INTEGER
(TcUtilities.lib)
Integer integer DINT
SmallInt smallint INT
TinyInt tinyint SINT
Bit_ bit BYTE
Money money LREAL
Float float LREAL
Real_ real REAL
DateTime datetime DT
NText ntext STRING
NChar nchar STRING
Image image ARRAY OF BYTE
NVarChar nvarchar STRING
Binary binary ARRAY OF BYTE
VarBinary varbinary ARRAY OF BYTE

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.4 MySQL database


This section contains information on the configuration and the data type mapping of MySQL databases.

Declaration in the TwinCAT Database Server Configurator

MySQL database
Database type Select "MySQL" from the drop-down menu.
Server Enter the name or IP address of your server here.
Database Enter the name of the database. If the database does not yet exist, it can be
created with the Create button. Corresponding permissions must exist.
Port Enter the port for communicating with the MySQL database here. Default:
3306.
User name Enter the user name here.
Password Enter the corresponding password.

TF6420 Version: 1.13.4 129


Configuration

Windows CE support
This database is also supported by the Windows CE version of the TwinCAT Database Server. The
interfacing is not local, but can be established via a network connection.
The installation of the necessary components is not automatic and must be performed manually. To
this end, additionally copy version 6.7.8.0 of the library "MySql.Data.CF.dll" into the TwinCAT
Database Server folder of the CE device. (\Hard Disk\TwinCAT\Functions\TF6420-Database-
Server\Server)

Data type mapping between DB and PLC

E_ColumnTypes MySQL TwinCAT PLC


BigInt BIGINT T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INT DINT
SmallInt SMALLINT INT
TinyInt TINYINT SINT
Bit_ CHAR(1) STRING
Money DECIMAL(18,4) LREAL
Float DOUBLE LREAL
Real_ FLOAT REAL
DateTime DATETIME DT
NText TEXT STRING
NChar CHAR STRING
Image BLOB ARRAY OF BYTE
NVarChar VARCHAR STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

Drivers for "big Windows" systems

The used MySQLConnector is under MIT licence and under Copyright:

Copyright (c) 2016 Bradley Grainger

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Data type support


This database supports the data type WSTRING. (See WString support [} 124])

130 Version: 1.13.4 TF6420


Configuration

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.5 Oracle database


This section contains information on the configuration and the data type mapping of Oracle databases. For
interfacing with an Oracle database the so-called ODP driver is used.

Compatible versions: Oracle 9i, 10g, 11g and higher

The TwinCAT Database Server requires the 32-bit version of the .NET ODP components.

Declaration in the TwinCAT Database Server Configurator

Oracle database
Database Type Select "Oracle ODP" from the drop-down menu.
Host Enter the IP or host name of the database.
Service name Enter the name of the service or the database.
Port Enter the communication port (optional). Default: 1521.
Protocol Enter the protocol (optional). Default: TCPIP.
Scheme Enter the database schema.
User name Enter the user name here.
Password Enter the corresponding password.

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

Data type mapping between DB and PLC

E_ColumnTypes Oracle TwinCAT PLC


BigInt DECIMAL(15,0) T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INTEGER DINT
SmallInt SMALLINT INT
TinyInt SMALLINT SINT
Bit_ CHAR(1) BYTE
Money DECIMAL(18,4) LREAL
Float DOUBLE PRECISION LREAL
Real_ FLOAT REAL
DateTime DATE DT
NText VARCHAR(254) STRING
NChar CHAR(254) STRING
Image BLOB ARRAY OF BYTE
NVarChar NVARCHAR(254) STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

TF6420 Version: 1.13.4 131


Configuration

Data type support


This database supports the data type WSTRING. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.6 SQLite
This section contains information on the configuration and the data type mapping of SQLite databases.
SQLite is an ideal database for embedded applications. This file-based SQL database requires no
installation, since it is already integrated in the TwinCAT Database Server. The relational database offers
most of the features of SQL databases and supports the commands of the SQL92 standard. The database
enables reliable and fast data storage. However, the database does not allow distinction of users. It is
therefore particularly suitable for safe storage of variables on the local system.

Declaration in the TwinCAT Database Server Configurator

SQLite database
Database Type Select "SQLite" from the drop-down menu.
SQLite database file Enter the name and path of the database. You can also use the browser
dialog. If the database does not yet exist, it can be created with the Create
button. Corresponding permissions must exist.
Authentication An option for logging into the database as a particular user.
Password Enter the corresponding password.

Windows CE support
The database is also supported by the Windows CE version of the TwinCAT Database Server, but
only on devices with ARM processor. The connection can be established locally.

TwinCAT/BSD support
This database is supported by the TwinCAT Database Server on TwinCAT/BSD. In addition,
however, the installation of the package "sqlite3" from the package repository is required for use.

Data type mapping between DB and PLC

SQLite has five internal basic data types. For more precise interpretation of the data, additional data types
are supported, which are listed in the documentation of the database manufacturer.

132 Version: 1.13.4 TF6420


Configuration

E_ColumnTypes SQLite TwinCAT PLC


BigInt BIGINT T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INT DINT
SmallInt SMALLINT INT
TinyInt TINYINT BYTE
Bit_ BOOLEAN BOOL
Money DOUBLE LREAL
Float FLOAT LREAL
Real_ REAL REAL
DateTime DATETIME DT
NText TEXT STRING
NChar NCHAR STRING
Image BLOB ARRAY OF BYTE
NVarChar NVARCHAR STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

Special feature: string or binary data types are unlimited in Sqlite. However, the TwinCAT 3 Database Server
requires fixed limits, which can be set in the general server settings.

Incompatible data types


It is possible that incompatible data type designations are created in the database by third-party
software, which the TwinCAT3 Database Server cannot interpret. In this case it is helpful to use the
SQL Query Builder.

Data type support


This database supports the data type WSTRING. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.7 ASCII-File
Information on configuring ASCII files as databases. The file is generated automatically by the
TwinCAT Database Server. A Create Database procedure is not required. The created file can be imported
and processed in other spreadsheet programs such as Microsoft Excel.

TF6420 Version: 1.13.4 133


Configuration

Declaration in the TwinCAT Database Server Configurator

ASCII file as database


Database Type Select "ASCII" from the drop-down menu.
ASCII File Enter the path for the ASCII file. The file is generated automatically by
the TwinCAT Database Server.
Value separator Here you can specify the separator for the values, i.e. for the columns.
Default: ";"
Old ASCII DB format For compatibility reasons you can optionally switch to the old ASCII
format used by the TwinCAT Database Server 3.0.x versions. Use the
default table structure.
DBValue Type Only active if Old ASCII DB format is enabled. You can select BYTES
or DOUBLE. With DOUBLE the values are in plain text, with BYTES they
form a byte stream.

Functions that are not supported

Automatic ID generation is not supported by this database. If the standard table structure is used in
Configure mode, the value of the ID is not set.

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

Windows CE support
This database is also supported by the Windows CE version of the TwinCAT Database Server. The
connection can be established locally.

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.8 XML database


This section contains information on the configuration and the data type mapping of XML files as databases.
The database structure, tables and columns are defined in an XSD file. The XML file, the XSD file and an
XSL file containing style information are created with the TwinCAT Database Server configurator (Create
command). Based on the XSL file the XML file can be opened in a web browser, where a graphical enhance
view of the database or the table is presented.

Further information on working with XML files as databases can be found in section "XML - information
[} 135]".

Declaration in the TwinCAT Database Server Configurator

XML database
Database Type Select "XML" from the drop-down menu.
XML Database File Enter the name and path of the XML file.
XML Schema File Enter the name and path of the XSD file.
Database Enter the name of the database. If the database does not yet exist, it can be
created with the Create button. Corresponding permissions must exist. In the
case of XML databases, the XML, XSD and XSL files are created automatically.

134 Version: 1.13.4 TF6420


Configuration

Windows CE support
This database is also supported by the Windows CE version of the TwinCAT Database Server. The
connection can be established locally.

Data type mapping between DB and PLC

E_ColumnTypes XML TwinCAT PLC


BigInt bigint T_ULARGE_INTEGER
(TcUtilities.lib)
Integer integer DINT
SmallInt smallint INT
TinyInt tinyint BYTE
Bit_ bit BOOL
Money money LREAL
Float float LREAL
Real_ real LREAL
DateTime datetime DT
NText ntext STRING
NChar nchar STRING
Image image ARRAY OF BYTE
NVarChar nvarchar STRING
Binary binary ARRAY OF BYTE
VarBinary varbinary ARRAY OF BYTE

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.8.1 XML - information


1. Using an XML file as a database with the TwinCAT 3 Database Server

2. Apply XPath queries to an XML file with the TwinCAT 3 Database Server

Further information about XML schemas can be found here: http://www.edition-w3.de/TR/2001/REC-


xmlschema-0-20010502/

1. XML as database

XSD schema for standard table structure:


<?xmlversion="1.0"?>
<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:simpleTypename="bigint">
<xsd:restrictionbase="xsd:long" />
</xsd:simpleType>
<xsd:simpleTypename="datetime">
<xsd:restrictionbase="xsd:dateTime" />
</xsd:simpleType>
<xsd:simpleTypename="ntext_80">
<xsd:restrictionbase="xsd:string">

TF6420 Version: 1.13.4 135


Configuration

<xsd:maxLengthvalue="80" />
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleTypename="float">
<xsd:restrictionbase="xsd:double" />
</xsd:simpleType>
<xsd:complexTypename="myTable_Double_Type">
<xsd:sequence>
<xsd:elementminOccurs="0"maxOccurs="unbounded"name="row">
<xsd:complexType>
<xsd:attributename="ID"type="bigint" />
<xsd:attributename="Timestamp"type="datetime" />
<xsd:attributename="Name"type="ntext_80" />
<xsd:attributename="Value" type="float" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:elementname="TestDB_XML">
<xsd:complexType>
<xsd:sequenceminOccurs="1"maxOccurs="1">
<xsd:elementname="myTable_Double"type="myTable_Double_Type" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

XML file for standard table structure (example):


<?xmlversion="1.0"encoding="UTF-8"?>
<TestDB_XMLxmlns:xs="http://www.w3.org/2001/XMLSchema-
nstance"xs:noNamespaceSchemaLocation="TestDB_XML.xsd">
<myTable_Double>
<rowID="1"Timestamp="2012-03-08T12:45:08"Name="TestValue1"Value="222.222" />
<rowID="2"Timestamp="2012-03-08T12:45:14"Name="TestValue1"Value="222.222" />
<rowID="3"Timestamp="2012-03-08T12:45:18"Name="TestValue1"Value="222.222" />
<rowID="4"Timestamp="2012-03-08T12:45:22"Name="TestValue1"Value="222.222" />
<rowID="5"Timestamp="2012-03-08T12:45:23"Name="TestValue1"Value="222.222" />
</myTable_Double>
</TestDB_XML>

Data types for XML tables:


<xsd:simpleTypename="bigint">
<xsd:restrictionbase="xsd:long" />
</xsd:simpleType>

<xsd:simpleTypename="datetime">
<xsd:restrictionbase="xsd:dateTime" />
</xsd:simpleType>

<xsd:simpleTypename="ntext_80"> //Länge kann individuell angegeben werden


<xsd:restrictionbase="xsd:string">
<xsd:maxLengthvalue="80" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleTypename="float">
<xsd:restrictionbase="xsd:double" />
</xsd:simpleType>

<xsd:simpleTypename="binary_1"> //Länge kann individuell angegeben werden


<xsd:restrictionbase="xsd:hexBinary">
<xsd:maxLengthvalue="1" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleTypename="bit">
<xsd:restrictionbase="xsd:boolean" />
</xsd:simpleType>

<xsd:simpleTypename="image_1"> //Länge kann individuell angegeben werden


<xsd:restrictionbase="xsd:hexBinary">
<xsd:maxLengthvalue="1" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleTypename="integer">
<xsd:restrictionbase="xsd:int" />
</xsd:simpleType>

136 Version: 1.13.4 TF6420


Configuration

<xsd:simpleTypename="money">
<xsd:restrictionbase="xsd:double" />
</xsd:simpleType>

<xsd:simpleTypename="nchar_50"> //Länge kann individuell angegeben werden


<xsd:restrictionbase="xsd:string">
<xsd:maxLengthvalue="50" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleTypename="nvarchar_50"> //Länge kann individuell angegeben


werden
<xsd:restrictionbase="xsd:string">
<xsd:maxLengthvalue="50" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleTypename="real">
<xsd:restrictionbase="xsd:double" />
</xsd:simpleType>

<xsd:simpleTypename="smallint">
<xsd:restrictionbase="xsd:short" />
</xsd:simpleType>

<xsd:simpleTypename="tinyint">
<xsd:restrictionbase="xsd:byte" />
</xsd:simpleType>

<xsd:simpleTypename="varbinary_1"> //Länge kann individuell angegeben werden


<xsd:restrictionbase="xsd:hexBinary">
<xsd:maxLengthvalue="1" />
</xsd:restriction>
</xsd:simpleType>

Data type mapping between DB and PLC

E_ColumnTypes XML TwinCAT PLC


BigInt bigint T_ULARGE_INTEGER
(TcUtilities.lib)
Integer integer DINT
SmallInt smallint INT
TinyInt tinyint BYTE
Bit_ bit BOOL
Money money LREAL
Float float LREAL
Real_ real LREAL
DateTime datetime DT
NText ntext STRING
NChar nchar STRING
Image image ARRAY OF BYTE
NVarChar nvarchar STRING
Binary binary ARRAY OF BYTE
VarBinary varbinary ARRAY OF BYTE

Creating/reading of records in/from the XML file

Standard SQL commands can be used for generating records. The TwinCAT Database Server interprets
SQL INSERT commands and converts them for the XML file in the form of XML nodes. The TwinCAT
Database Server converts SQL SELECT commands for the XML file in the form of XPath queries.

Samples for supported INSERT commands:


• INSERT INTO myTable_Double (ID, Timestamp, Name, Value) VALUES(1, CURRENT_TIMESTAMP,
'TestValue1' , 1234.5678)

TF6420 Version: 1.13.4 137


Configuration

• INSERT INTO myTable_Double (Timestamp, Name) VALUES(CURRENT_TIMESTAMP,


'TestValue1');
• INSERT INTO myTable_Double VALUES(1, CURRENT_TIMESTAMP, 'TestValue1', 1234.5678);
• INSERT INTO myTable_Double VALUES(1, '2010-01-06 12:13:14', 'TestValue1', 1234.5678);

Samples for supported SELECT commands:


• SELECTID, Timestamp, Name, Value FROM myTable_Double;
• SELECT* FROM myTable_Double;
• SELECTTimestamp, Name FROM myTable_Double
• SELECT* FROM myTable_Double WHERE Name = 'TestValue1';
• SELECT* FROM myTable_Double WHERE ID > 1;

Supported function blocks:


• FB_DBCreate
• FB_DBCyclicRdWrt
• FB_DBRead
• FB_DBRecordArraySelect
• FB_DBRecordDelete
• FB_DBRecordInsert
• FB_DBRecordInsert_EX
• FB_DBRecordSelect
• FB_DBRecordSelect_EX
• FB_DBTableCreate
• FB_DBWrite

2. XML standard XPath function

XPath types

The syntax of the prefixes of the XPaths in the TwinCAT Database Server is as follows:
XPATH_[Type]<[Position]>#[Path]

There are 4 different types of XPath:


• SEL
◦ Reads data from the XML and returns them to the PLC
• ADD
◦ Appends the transferred data to the XML at the selected position.
• UPD
◦ Replaces the existing XML information at the selected position with the new data.
• DEL
◦ Deletes the data in the XML at the selected position.

There are 3 different data available for the positions:


• ATTR
◦ Applies to all attribute values from the selected XML tag.
• TAG
◦ Applies to the InnerText value of the selected XML tag.
• SUBTAG
◦ Applies to the InnerText value of all subtags of the selected XML tag.
◦ If an XML Schema exists, the attributes are converted to the correct data types.
If no XML Schema exists, the attributes are returned as T_MaxString.

138 Version: 1.13.4 TF6420


Configuration

Samples:

XML file:
<?xmlversion="1.0"encoding="utf-8" ?>
<TestXML>
<Nodeattr1="1"attr2="Node1">
<SubNode1>SubNodeWert1</SubNode1>
<SubNode2>200</SubNode2>
<SubNode3>SubNodeWert3</SubNode3>
<SubNode4>400.5</SubNode4>
<SubNode5>SubNodeWert5</SubNode5>
</Node>
<Nodeattr1="2"attr2="Node2">
<SubNode1>SubNodeWert1</SubNode1>
<SubNode2>200</SubNode2>
<SubNode3>SubNodeWert3</SubNode3>
<SubNode4>400.5</SubNode4>
<SubNode5>SubNodeWert5</SubNode5>
</Node>
</TestXML>

XML Schema:
<?xmlversion="1.0"encoding="utf-8"?>
<xs:schemaattributeFormDefault="unqualified"elementFormDefault="qualified"xmlns:xs="http://
www.w3.org/2001/XMLSchema">
<xs:elementname="TestXML">
<xs:complexType>
<xs:sequence>
<xs:elementmaxOccurs="unbounded"name="Node">
<xs:complexType>
<xs:sequence>
<xs:elementname="SubNode1"type="xs:string" />
<xs:elementname="SubNode2"type="xs:short" />
<xs:elementname="SubNode3"type="xs:string" />
<xs:elementname="SubNode4"type="xs:double" />
<xs:elementname="SubNode5"type="xs:string" />
</xs:sequence>
<xs:attributename="attr1" type="xs:integer"use="required" />
<xs:attributename="attr2" type="xs:string"use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Sample for XPATH<ATTR>

XPath => XPATH_SEL<ATTR>#TestXML/Node[@attr1=2]

Returned structure if no schema exists:


TYPEST_Record :
STRUCT
attr1 : T_MaxString := ‘2’;
attr2 : T_MaxString := ‘Node2’;
END_STRUCT
END_TYPE

Returned structure if one schema exists:


TYPEST_Record :
STRUCT
attr1 : DINT := 2;
attr2 : T_MaxString := ‘Node2’;
END_STRUCT
END_TYPE

Sample for XPATH<TAG>

XPath => XPATH_SEL<TAG>#TestXML/Node[@attr1=2]/SubNode2

Returned value if no schema exists: SubNode2 : T_MaxString := ‘200’;

Returned value if one schema exists: SubNode2 : INT := 200;

Sample for XPATH<SUBTAG>

TF6420 Version: 1.13.4 139


Configuration

XPath => XPATH_SEL<SUBTAG>#TestXML/Node[@attr1=2]

Returned structure if no schema exists:


TYPEST_Record :
STRUCT
SubNode1 : T_MaxString := ‘SubNodeWert1’;
SubNode2 : T_MaxString := ‘200’;
SubNode3 : T_MaxString := ‘SubNodeWert3’;
SubNode4 : T_MaxString := ‘400.5’;
SubNode5 : T_MaxString := ‘SubNodeWert5’;
END_STRUCT
END_TYPE

Returned structure if one schema exists:


TYPEST_Record :
STRUCT
SubNode1 : T_MaxString := ‘SubNodeWert1’;
SubNode2 : INT := 200;
SubNode3 : T_MaxString := ‘SubNodeWert3’;
SubNode4 : LREAL := 400.5;
SubNode5 : T_MaxString := ‘SubNodeWert5’;
END_STRUCT
END_TYPE

Special feature of the use of the FB_PLCDBCmd:

Unlike the usual implementation of the FB_PLCDBCmd, the set parameters (ST_ExpParameter) do not
specify the placeholders for the respective instruction, but the scheme of the transferred or returned data.

Supported function blocks


• FB_DBRecordSelect
• FB_DBRecordSelect_EX
• FB_DBRecordArraySelect

5.2.9 ODBC databases


Many databases offer ODBC interfaces. The TwinCAT Database Server also has this interface. In the
TwinCAT Database Configurator it is therefore generally possible to select an ODBC database in the
database configuration menu. So-called "Free Connection Strings [} 140]" can be used to form your own
connection strings with Add additional parameter.

Further known and regularly used ODBC databases are available as templates. These include:
• MySQL [} 141]
• Oracle [} 142]
• PostgreSQL [} 143]
• IBM DB2 [} 144]
• Firebird [} 146]

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

5.2.9.1 Free connection string


To use a database with ODBC interface that is not supported by the TwinCAT Database Server by default,
you can select "Unknown Database" as ODBC type.

140 Version: 1.13.4 TF6420


Configuration

Declaration in the TwinCAT Database Server Configurator

ODBC Free Connection String database


Database Type "Odbc_Database"
ODBC Type Select "Unknown Database" from the drop-down menu.

Simply find the connection string for the ODBC database and remodel it in the configuration window of the
TwinCAT Database Server.

Two commands are available in the context menu for this purpose:
• Add additional Parameter
Adds a general parameter for the connection string. This can have any name, as required by the
connection string.
• Add additional Password Parameter
Adds a special password parameter, the value of which is not readable (encrypted) in the configurator
and in the configuration file.

Operating principle with Free Connection String


To ensure that the TwinCAT Database Server can work with a Free Connection String, the
corresponding driver must be installed on the target system of the TwinCAT Database Server. Only
"SQL Expert mode [} 17]" can be used!

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.9.2 MySQL
This section contains information on the configuration and the data type mapping of MySQL databases with
ODBC.

TF6420 Version: 1.13.4 141


Configuration

Declaration in the TwinCAT Database Server Configurator

ODBC MySQL database


Database Type “Odbc_Database”
ODBC Type Select "MySQL" from the drop-down menu.
Driver Enter the actually installed driver.
Server Enter the name or IP address of your server.
Database Enter the name of the database.
Port Enter the port for communicating with the MySQL database here. Default:
3306.
Option Default: 2 “Return matched rows instead of affected rows”
Uid Enter the user name.
Pwd Enter the corresponding password.

Data type mapping between DB and PLC

E_ColumnTypes MySQL TwinCAT PLC


BigInt BIGINT T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INT DINT
SmallInt SMALLINT INT
TinyInt TINYINT SINT
Bit_ CHAR(1) STRING
Money DECIMAL(18,4) LREAL
Float DOUBLE LREAL
Real_ FLOAT REAL
DateTime DATETIME DT
NText TEXT STRING
NChar CHAR STRING
Image BLOB ARRAY OF BYTE
NVarChar VARCHAR STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

Data type support


This database supports the data type WSTRING. (See WString support [} 124])

Functioning
All functions of the TwinCAT Database Server can be applied to the ODBC templates. This does
not apply to the "Free Connection String [} 140]".

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.9.3 Oracle
This section contains information on the configuration and the data type mapping of Oracle databases with
ODBC.

142 Version: 1.13.4 TF6420


Configuration

Declaration in the TwinCAT Database Server Configurator

ODBC Oracle database


Database Type "Odbc_Database"
ODBC Type Select "Oracle" from the drop-down menu.
Driver Select here the actually installed driver.
Server Enter the name or IP address of your server.
Uid Enter the user name here.
Pwd Enter the corresponding password.

Data type mapping between DB and PLC

E_ColumnTypes Oracle TwinCAT PLC


BigInt DECIMAL(15,0) T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INTEGER DINT
SmallInt SMALLINT INT
TinyInt SMALLINT SINT
Bit_ CHAR(1) BYTE
Money DECIMAL(18,4) LREAL
Float DOUBLE PRECISION LREAL
Real_ FLOAT REAL
DateTime DATE DT
NText VARCHAR(254) STRING
NChar CHAR(254) STRING
Image BLOB ARRAY OF BYTE
NVarChar NVARCHAR(254) STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

Data type support


This database supports the data type WSTRING. (See WString support [} 124])

Functioning
All functions of the TwinCAT Database Server can be applied to the ODBC templates. This does
not apply to the "Free Connection String [} 140]".

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.9.4 PostgreSQL
This section contains information on the configuration and the data type mapping of PostgreSQL databases
with ODBC.

TF6420 Version: 1.13.4 143


Configuration

Declaration in the TwinCAT Database Server Configurator

ODBC PostgreSQL database


Database Type "Odbc_Database"
ODBC Type Select "PostgreSQL" from the drop-down menu.
Driver Select here the actually installed driver.
Server Enter the name or IP address of your server.
Database Enter the name of the database.
Port Enter the port for communicating with the PostgreSQL database. Default:
5432.
Uid Enter the user name here.
Pwd Enter here the corresponding password.

Data type mapping between DB and PLC

E_ColumnTypes PostgreSQL TwinCAT PLC


BigInt BIGINT T_ULARGE_INTEGER
(TcUtilities.lib)
Integer integer DINT
SmallInt smallint INT
TinyInt smallint INT
Bit_ bit BYTE
Money money LREAL
Float Double precision LREAL
Real_ real REAL
DateTime timestamp DT
NText text STRING
NChar character STRING
Image byte ARRAY OF BYTE
NVarChar Character varying STRING
Binary byte ARRAY OF BYTE
VarBinary byte ARRAY OF BYTE

Data type support


This database supports the data type WSTRING. The character set must be set up when the
database is created.

Functioning
All functions of the TwinCAT Database Server can be applied to the ODBC templates. This does
not apply to the "Free Connection String [} 140]".

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.9.5 IBM DB2


This section contains information on the configuration and the data type mapping of IBM DB2 databases with
ODBC.

144 Version: 1.13.4 TF6420


Configuration

Declaration in the TwinCAT Database Server Configurator

ODBC IBM DB2 database


Database Type "Odbc_Database"
ODBC Type Select "IBM DB2" from the drop-down menu.
Driver Enter here the actually installed driver.
Host name Enter the name or IP address of your server.
Database Enter the name of the database.
Port Enter the port for communicating with the IBM DB2 database. Default:
50000.
Protocol Default: TCPIP
Uid Enter the user name here.
Pwd Enter here the corresponding password.
LONGDATACOMPAT Default: 1

Data type mapping between DB and PLC

E_ColumnTypes IBM DB2 TwinCAT PLC


BigInt BIGINT T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INT DINT
SmallInt SMALLINT INT
TinyInt SMALLINT INT
Bit_ VARCHAR(1) STRING(1)
Money DECIMAL(18,4) LREAL
Float DOUBLE PRECISION LREAL
Real_ FLOAT LREAL
DateTime TIMESTAMP DT
NText LONG VARCHAR STRING
NChar CHAR(254) STRING
Image BLOB ARRAY OF BYTE
NVarChar NVARCHAR(254) STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

Functioning
All functions of the TwinCAT Database Server can be applied to the ODBC templates. This does
not apply to the "Free Connection String [} 140]".

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

TF6420 Version: 1.13.4 145


Configuration

5.2.9.6 Firebird
This section contains information on the configuration and the data type mapping of Firebird databases with
ODBC.

Declaration in the TwinCAT Database Server Configurator

ODBC Firebird database


Database Type "Odbc_Database"
ODBC Type Select "Firebird" from the drop-down menu.
Driver Select here the actually installed driver.
Database Enter the name of the database.
Client
Uid Enter the user name here.
Pwd Enter the corresponding password.

Data type mapping between DB and PLC

E_ColumnTypes Firebird TwinCAT PLC


BigInt BIGINT T_ULARGE_INTEGER
(TcUtilities.lib)
Integer INTEGER DINT
SmallInt SMALLINT INT
TinyInt TINYINT INT
Bit_ CHAR(1) STRING
Money DECIMAL(18,4) LREAL
Float FLOAT REAL
Real_ DOUBLE PRECISION LREAL
DateTime TIMESTAMP DT
NText VARCHAR(254) STRING
NChar CHAR(254) STRING
Image BLOB ARRAY OF BYTE
NVarChar VARCHAR(254) STRING
Binary BLOB ARRAY OF BYTE
VarBinary BLOB ARRAY OF BYTE

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

Functioning
All functions of the TwinCAT Database Server can be applied to the ODBC templates. This does
not apply to the "Free Connection String [} 140]".

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

146 Version: 1.13.4 TF6420


Configuration

5.2.10 MS Access database


The values of the variables are saved in a Microsoft Access database.

Access 2000 and Access 2003 (*.mdb) database files are compatible, as are Access 2007 (*.accdb) files. All
you have to do is specify different providers in the declaration in the XML configuration file.

Declaration in the TwinCAT Database Server Configurator

Microsoft Access database


DBValueType Select "Double" to limit logging to alphanumeric and Boolean data types.
Select "Bytes" to also log structures and strings.
DBType Select "MS Access". PLC: eDBType_Access.
DBServer Not required.
DBProvider Access 2000 - Access 2003:
The provider is "Microsoft.Jet.OLEDB.4.0".
Access 2007:
The provider is "Microsoft.ACE.OLEDB.12.0".
DBUrl DBUrl contains the path to the MDB file.
e.g. C:\TwinCAT\TcDatabaseSrv\Samples\TestDB.mdb
DBTable DBTable contains the name of the table.

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

TwinCAT/BSD support
This database is not supported by the TwinCAT Database Server on the TwinCAT/BSD platform.

Data type mapping between DB and PLC

E_DBColumnTypes MS Access PLC Control


eDBColumn_BigInt Integer4 DINT
eDBColumn_Integer Integer2 INT
eDBColumn_SmallInt Integer2 SINT
eDBColumn_TinyInt Integer1 SINT
eDBColumn_Bit YESNO BYTE
eDBColumn_Money Currency LREAL
eDBColumn_Float Double LREAL
eDBColumn_Real Single REAL
eDBColumn_DateTime DATETIME DT
eDBColumn_NText Text STRING
eDBColumn_NChar VarChar STRING
eDBColumn_Image OLEOBJECT ARRAY OF BYTE
eDBColumn_NVarChar VarChar STRING
eDBColumn_Binary OLEOBJECT ARRAY OF BYTE
eDBColumn_VarBinary OLEOBJECT ARRAY OF BYTE

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

TF6420 Version: 1.13.4 147


Configuration

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.11 MS Excel database


The variable values are stored in a Microsoft Excel database.

Declaration in the TwinCAT Database Server Configurator

Microsoft Excel database


DBValueType Select "Double" to limit logging to alphanumeric and Boolean data types.
Select "Bytes" to also log structures and strings.
DBType Select "MS Excel". PLC: eDBType_MSExcel.
DBServer Not required.
DBProvider "Microsoft.Jet.OLEDB.4.0" or "Microsoft.ACE.OLEDB.12.0"
DBUrl DBUrl contains the path to the Excel file.
e.g. C:\TwinCAT\TcDatabaseSrv\Samples\TestDB.xls
DBTable DBTable contains the name of the table.

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

TwinCAT/BSD support
This database is not supported by the TwinCAT Database Server on the TwinCAT/BSD platform.

Data type mapping between DB and PLC

E_DBColumnTypes MS Excel PLC Control


eDBColumn_BigInt Number LREAL
eDBColumn_Integer Number LREAL
eDBColumn_SmallInt Number LREAL
eDBColumn_TinyInt Number LREAL
eDBColumn_Bit BOOLEAN BOOL
eDBColumn_Money Currency LREAL
eDBColumn_Float Number LREAL
eDBColumn_Real Number LREAL
eDBColumn_DateTime Date DT
eDBColumn_NText Text STRING(255)
eDBColumn_NChar Text STRING(255)
eDBColumn_NVarChar Text STRING(255)

Functions that are not supported

Automatic ID generation is not supported by this database. If the standard table structure is used in
Configure mode, the value of the ID is not set.

148 Version: 1.13.4 TF6420


Configuration

Non-supported data types


Binary, VarBinary and Image are not supported with Excel databases.

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.12 MongoDB
This section contains information on the configuration and the data type mapping of MongoDB databases.

Declaration in the TwinCAT Database Server Configurator

MongoDB
Database Type Select "MongoDB" from the drop-down menu.
Server Enter the name of your MongoDB server.
Database Enter the name of the database. If the database does not yet exist, it is
created the first time it is accessed.
Authentication None: No authentication
User name/password: Login with user name and password
x509 certificate:
User name: ID of the certificate user
Certificate Authority: path to signing certificate (*.crt)
Client Certificate: path to client certificate (*.pfx)
Client Private Key: password for the client certificate
GSSAPI/Kerberos: Login with user name and password
LDAP(PLAIN): Login with user name and password
(Since the user name and password are transmitted in plain text, this
option is not recommended)

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

TF6420 Version: 1.13.4 149


Configuration

Data type mapping between DB and PLC

MongoDB TwinCAT PLC


long LINT
int DINT
bool BYTE
double LREAL
timestamp DT
string STRING
binData ARRAY OF BYTE
objectId T_ObjectId_MongoDB
array ARRAY
object STRUCT

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

MongoDB in PLC Expert/Configure mode

PLC Expert and Configure mode use the predefined database schema in their processes. Normally, the
schema of the structures used will not change during operation. In order to nevertheless be able to use the
function blocks, the TwinCAT 3 Database Server requires a description of the table schema. For MongoDB a
table is therefore simulated.
In the SQL Query Editor, use the SQL tab and the CREATE TABLE subcategory to create a table, or in this
case a collection. In addition, unlike for relational databases, an entry is created in a metadata collection.
Information on the table schema for the TwinCAT 3 Database Server is stored here.

In order to use advanced functionality, e.g. structures of any hierarchy or flexible records, we recommend
using the NoSQL function blocks.

Use of certificates

Among other things, MongoDB supports authentication by means of certificates. To this end, select the 'x509
certificate' method under Authentication. The following fields appear:

User name User name of the corresponding certificate


Certificate Authority Path to the SSL certificate of the certificate authority. This may be a self-signed
certificate.
Client Certificate Client certificate signed by the SSL certificate.
Client Certificate Password of the client certificate.
Password

Configuring the database connection to MongoDB using certificates:

150 Version: 1.13.4 TF6420


Configuration

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.13 PostgreSQL
This section provides information about configuration and application of the PostgreSql database.
PostgreSQL is an object-relational open source database with a client-server infrastructure. The TwinCAT 3
database server uses the Npgsql API for connection.

Declaration in the TwinCAT Database Server Configurator

PostgreSql database
Database type Select "PostgreSql" from the drop-down menu.
Server Name or IP of the database server
Database Name of the database on the server
Port Port of the database
Authentication Database authentication method
User name Enter the user name.
Password Enter the corresponding password.
Client Certificate Path to used client certificate (.pfx)
Client Certificate Password Password of the referenced client certificate

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

TF6420 Version: 1.13.4 151


Configuration

Data type mapping between DB and PLC

E_ColumnTypes PostgreSQL TwinCAT PLC


BigInt Bigint T_ULARGE_INTEGER
(TcUtilities.lib)
Integer Integer DINT
SmallInt Smallint INT
TinyInt SINT
Bit_ Bit BYTE
Money Money LREAL
Float Double precision LREAL
Real_ Real REAL
DateTime Timestamp without time zone DT
NText Text STRING
NChar Character STRING
Image ARRAY OF BYTE
NVarChar Character varying STRING
Binary Bytea ARRAY OF BYTE
VarBinary ARRAY OF BYTE

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

5.2.14 InfluxDB
This section contains information about the configuration and the data type mapping of InfluxDB.

Supported version: 1.7.x, 1.8.x

Declaration in the TwinCAT Database Server Configurator

InfluxDB
Database type Select "InfluxDB" from the drop-down menu.
Server Enter the address of the desired database server here.
Database Enter the name of the database. If the database does not yet exist, you
can create it with "Create".
Authentication None: No authentication
User name/password: Login with user name and password

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

152 Version: 1.13.4 TF6420


Configuration

Data type mapping between DB and PLC

E_ColumnTypes InfluxDB TwinCAT PLC


BigInt Integer LINT
Integer Integer DINT
SmallInt Integer INT
TinyInt Integer BYTE
Bit_ Boolean BOOL
Money Float LREAL
Float Float LREAL
Real_ Float LREAL
DateTime DT
NText String STRING
NChar String STRING
Image ARRAY OF BYTE
NVarChar String STRING
Binary ARRAY OF BYTE
VarBinary ARRAY OF BYTE
Tag STRING
"time" LINT

Time

As a time series database, InfluxDB has some special features. Each measurement (table) of a series
contains the time column, tag columns and field columns. The time column is stored in the database as
UNIX epoch time. The function blocks of the database server use the TwinCAT time (number of 100 ns steps
since January 1, 1601). They are converted to UNIX epoch time. The FB_SQLDBCommand is excluded from
this conversion. Here you can transfer your own free timestamps without conversion. The precision is set to
"ns" accuracy. Times are unique in InfluxDB as ID together with the tag columns. If the tags and the time are
identical, a data set is overwritten.

Standard table structure

The standard table structure for InfluxDB looks like this in the PLC:

ColumnName InfluxDB TwinCAT PLC


time Integer LINT
Name Tag T_MaxString
Value Float LREAL

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

5.2.15 InfluxDB2
This section contains information about the configuration and the data type mapping of InfluxDB2.

TF6420 Version: 1.13.4 153


Configuration

Supported version: 2.x

Declaration in the TwinCAT Database Server Configurator

InfluxDB
Database Type Select "InfluxDB2" from the drop-down menu.
Server Enter the address of the desired database server here.
Database Enter the name of the database. If the database does not yet exist, you
can create it with "Create".
Authentication None: no authentication
User name/password: Login with username and password
Token Access token for accessing the database. This can be created with the
necessary rights in the database software.

Windows CE support
Under Windows CE this database is not supported by the TwinCAT Database Server.

Data type mapping between DB and PLC

E_ColumnTypes InfluxDB2 TwinCAT PLC


BigInt Integer LINT
Integer Integer DINT
SmallInt Integer INT
TinyInt Integer BYTE
Bit_ Boolean BOOL
Money Float LREAL
Float Float LREAL
Real_ Float LREAL
DateTime DateTime DT
NText String STRING
NChar String STRING
Image - ARRAY OF BYTE
NVarChar String STRING
Binary - ARRAY OF BYTE
VarBinary - ARRAY OF BYTE
Tag Tag STRING
BigInt "_time" LINT

Time

As a time series database, InfluxDB2 has some special features. Each measurement (table) of a series
contains the time column, tag columns and field columns. The time column is stored in the database as
UNIX epoch time. The function blocks of the database server use the TwinCAT time (number of 100 ns steps
since January 1, 1601). They are converted to UNIX epoch time. The FB_SQLDBCommand is excluded from
this conversion. Here you can transfer your own free timestamps without conversion. The precision is set to
"ns" accuracy. Times are unique in InfluxDB as ID together with the tag columns. If the tags and the time are
identical, a data set is overwritten.

Data type support


WSTRING is not supported by this database. (See WString support [} 124])

154 Version: 1.13.4 TF6420


Configuration

NOTICE
Data security
In flash memory devices the number of write access operations is limited. The flash memory devices can
fail, with a risk of data loss.
• Make regular backups of your system. Use the IPC diagnostics in order to determine the status of the
flash memory devices.

TF6420 Version: 1.13.4 155


PLC API

6 PLC API

6.1 Tc3_Database

6.1.1 Function blocks


The function blocks of the Tc3_Database.compiled library are split into three sections, based on the basic
concept [} 17]:
• Configure Mode:
Contains function blocks for controlling reading and writing of AutoLog groups defined in the
configurator.
• PLC Expert Mode:
Contains function blocks for conventional PLC programmers.
• SQL Expert mode:
IT and PLC experts with advanced database knowledge can use these function blocks to assemble
SQL commands in the PLC.
• NoSql Expert Mode:
These function blocks can be used by IT and PLC experts with extended database knowledge to
create commands via NoSQL databases and send them to the database.

Using the Tc3_Eventlogger

The TwinCAT 3 Database Server supports the Tc3_Eventlogger API. Further information can be found under
Support for the Tc3_EventLogger [} 219]

6.1.1.1 Configure mode

6.1.1.1.1 FB_ConfigTcDBSrvEvt

Function block for creating, reading and deleting configuration entries for the TwinCAT Database Server.

Syntax

Definition:
FUNCTION_BLOCK FB_ConfigTcDBSrvEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

156 Version: 1.13.4 TF6420


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Create [} 157] Local Creates new entries in the XML configuration file for the
TwinCAT Database Server
Read [} 158] Local Reads the current configuration of the TwinCAT Database Server
Delete [} 159] Local Deletes the database and AutoLog groups from the configuration
of the TwinCAT Database Server

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.1.1.1 Create
This method creates new entries in the XML configuration file for the TwinCAT Database Server. Optionally
the TwinCAT Database Server can use a new entry on a temporary basis. In this case no data is written to
the XML file.

Syntax
METHOD Create : BOOL
VAR_INPUT
pTcDBSrvConfig: POINTER TO BYTE;
cbTcDBSrvConfig: UDINT;
bTemporary: BOOL := TRUE;
pConfigID: POINTER TO UDINT;
END_VAR

TF6420 Version: 1.13.4 157


PLC API

Inputs

Name Type Description


pTcDBSrvConfig POINTER TO BYTE Pointer of the configuration structure to be created.
cbTcDBSrvConfig UDINT Length of the configuration structure
bTemporary BOOL Indicates whether the configuration is to be stored in the
XML file.
pConfigID POINTER TO UDINT Return pointer of the configuration ID (hDBID or
hAutoLogGrpID)

Creating AutoLog groups is currently not supported.

Return value

Name Type Description


Create BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
// Any other ConfigType can be used here
stConfigDB : T_DBConfig_MsCompactSQL;
tcMessage : I_TcMessage;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Recipes.sdf';

IF fbConfigTcDBSrv.Create(
pTcDBSrvConfig:= ADR(stConfigDB),
cbTcDBSrvConfig:= SIZEOF(stConfigDB),
bTemporary:= TRUE,
pConfigID:= ADR(myConfigHandle))
THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.1.1.2 Read
This method can be used to read the current configurations of the TwinCAT Database Server. Any
temporary configurations that may be included are marked accordingly.

Syntax
METHOD Read : BOOL
VAR_INPUT
pDBConfig: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_ConfigDB;
cbDBConfig: UDINT;
pAutoLogGrpConfig: POINTER TO ARRAY[1..MAX_CONFIGURATIONS] OF
ST_ConfigAutoLogGrp;
cbAutoLogGrpConfig: UDINT;
pDBCount: POINTER TO UDINT;
pAutoLogGrpCount: POINTER TO UDINT;
END_VAR

158 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


pDBConfig POINTER TO ARRAY [1..MA Pointer address of the array into which the database
X_CONFIGURATIONS configurations are to be written.
[} 246]] OF ST_ConfigDB
[} 228]
cbDBConfig UDINT Length of the database configuration array
pAutoLogGrpConfig POINTER TO ARRAY[1..MAX Pointer address of the array into which the
_CONFIGURATIONS AutoLogGrp configurations are to be written.
[} 246]] OF
ST_ConfigAutoLogGrp [} 227]
cbAutoLogGrpConfig UDINT Length of the AutoLogGrp configuration array
pDBCount POINTER TO UDINT Pointer address for storing the number of database
configurations.
pAutoLogGrpCount POINTER TO UDINT Pointer address for storing the number of AutoLogGrp
configurations.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
aDBConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigDB;
aAutoGrpConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigAutoLogGrp;
nDbCount : UDINT;
nAutoGrpCount : UDINT;
tcMessage : I_TcMessage;
END_VAR
IF fbConfigTcDBSrv.Read(
pDBConfig := ADR(aDBConfig),
cbDBConfig := SIZEOF(aDBConfig),
pAutologGrpConfig := ADR(aAutoGrpConfig),
cbAutoLogGrpConfig := SIZEOF(aAutoGrpConfig),
pDBCount := ADR(nDbCount),
pAutoLogGrpCount := ADR(nAutoGrpCount))
THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.1.1.3 Delete
This method can be used to delete databases and AutoLog groups from the configuration of the
TwinCAT Database Server.

Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR

TF6420 Version: 1.13.4 159


PLC API

Inputs

Name Type Description


eTcDBSrvConfigType E_TcDBSrvConfigType Type of the configuration to be deleted (database /
AutoLog group)
hConfigID UDINT ID of the configuration to be deleted (hDBID or
hAutoLogGrpID)

Return value

Name Type Description


Delete BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
tcMessage : I_TcMessage;
END_VAR
IF fbConfigTcDBSrv.Delete(
eTcDBSrvConfigType := E_TcDBSrvConfigType.Database,
hConfigID := myConfigHandle) THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.1.2 FB_PLCDBAutoLogEvt

Function block with four methods for starting and stopping of defined AutoLog groups and for reading of the
corresponding group status.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBAutoLogEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage;
bBusy_Status: BOOL;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

160 Version: 1.13.4 TF6420


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active, except for the Status method.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage Result interface with detailed information on
the return value.
bBusy_Status BOOL The Status method can be executed
independently of the other three methods of
the function block and therefore has its own
Busy flag. Is TRUE as soon as the Status
method is active.

Methods

Name Definition loca- Description


tion
RunOnce Local Executes the AutoLog group once
[} 161]
Start [} 162] Local Starts AutoLog mode with the corresponding configured AutoLog groups
Status [} 162] Local Queries the status of the AutoLog groups.
Stop [} 163] Local Stops AutoLog mode

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.1.2.1 RunOnce
This method can be used to execute an AutoLog group once, for example based on an event in the
controller.

Syntax
METHOD RunOnce : BOOL
VAR_INPUT
hAutoLogGrpID: UDINT;
bAll: BOOL;
END_VAR

Inputs

Name Type Description


hAutoLogGrpID UDINT ID of the AutoLog group to be executed once.
bAll BOOL If TRUE, all AutoLog groups are executed once.

Return value

Name Type Description


RunOnce BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

TF6420 Version: 1.13.4 161


PLC API

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.RunOnce(hAutologGrpID := 1, bAll := FALSE) THEN
; // ...
END_IF

6.1.1.1.2.2 Start
This method starts the AutoLog mode with the corresponding configured AutoLog groups.

Syntax
METHOD Start : BOOL

Return value

Name Type Description


Start BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Start() THEN
; // ...
END_IF

6.1.1.1.2.3 Status
This method can be used to query the status of the AutoLog groups. A separate busy flag is provided in the
body of the function block for this method, since it can be called independently of the other methods of the
function block: bBusy_Status.

Syntax
METHOD Status : BOOL
VAR_INPUT
tCheckCycle: TIME;
pError: POINTER TO BOOL;
pAutoLogGrpStatus: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
cbAutoLogGrpStatus: UDINT;
END_VAR

Inputs

Name Type Description


tCheckCycle TIME Interval time at which the status array is
updated.
pError POINTER TO BOOL TRUE, if an error has occurred in AutoLog
mode.
pAutoLogStatus POINTER TO ARRAY Address of the status array that contains all
[1..MAX_CONFIGURATIONS [} 246]] OF groups.
ST_AutoLogGrpStatus [} 243]
cbAutoLogStatus UDINT Length of the status array

162 Version: 1.13.4 TF6420


PLC API

Return value

Name Type Description


Status BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt(sNetID:='', tTimeout := T#5S);
bError : BOOL;
aAutologGrpStatus : ARRAY[0..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
END_VAR
IF fbPLCDBAutoLog.Status(tCheckCycle := T#30S, ADR(bError), ADR(aAutologGrpStatus), SIZEOF(aAutologG
rpStatus)) THEN
; // ...
END_IF

6.1.1.1.2.4 Stop
This method stops the AutoLog mode.

Syntax
METHOD Stop : BOOL

Return value

Name Type Description


Stop BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF

TF6420 Version: 1.13.4 163


PLC API

6.1.1.2 PLC Expert mode

6.1.1.2.1 FB_ConfigTcDBSrvEvt

Function block for creating, reading and deleting configuration entries for the TwinCAT Database Server.

Syntax

Definition:
FUNCTION_BLOCK FB_ConfigTcDBSrvEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage;
END_VAR

164 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Create [} 165] Local Creates new entries in the XML configuration file for the
TwinCAT Database Server
Read [} 166] Local Reads the current configuration of the TwinCAT Database Server
Delete [} 167] Local Deletes the database and AutoLog groups from the configuration
of the TwinCAT Database Server

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.2.1.1 Create
This method creates new entries in the XML configuration file for the TwinCAT Database Server. Optionally
the TwinCAT Database Server can use a new entry on a temporary basis. In this case no data is written to
the XML file.

Syntax
METHOD Create : BOOL
VAR_INPUT
pTcDBSrvConfig: POINTER TO BYTE;
cbTcDBSrvConfig: UDINT;
bTemporary: BOOL := TRUE;
pConfigID: POINTER TO UDINT;
END_VAR

TF6420 Version: 1.13.4 165


PLC API

Inputs

Name Type Description


pTcDBSrvConfig POINTER TO BYTE Pointer of the configuration structure to be created.
cbTcDBSrvConfig UDINT Length of the configuration structure
bTemporary BOOL Indicates whether the configuration is to be stored in the
XML file.
pConfigID POINTER TO UDINT Return pointer of the configuration ID (hDBID or
hAutoLogGrpID)

Creating AutoLog groups is currently not supported.

Return value

Name Type Description


Create BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
// Any other ConfigType can be used here
stConfigDB : T_DBConfig_MsCompactSQL;
tcMessage : I_TcMessage;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Recipes.sdf';

IF fbConfigTcDBSrv.Create(
pTcDBSrvConfig:= ADR(stConfigDB),
cbTcDBSrvConfig:= SIZEOF(stConfigDB),
bTemporary:= TRUE,
pConfigID:= ADR(myConfigHandle))
THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.2.1.2 Read
This method can be used to read the current configurations of the TwinCAT Database Server. Any
temporary configurations that may be included are marked accordingly.

Syntax
METHOD Read : BOOL
VAR_INPUT
pDBConfig: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_ConfigDB;
cbDBConfig: UDINT;
pAutoLogGrpConfig: POINTER TO ARRAY[1..MAX_CONFIGURATIONS] OF
ST_ConfigAutoLogGrp;
cbAutoLogGrpConfig: UDINT;
pDBCount: POINTER TO UDINT;
pAutoLogGrpCount: POINTER TO UDINT;
END_VAR

166 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


pDBConfig POINTER TO ARRAY [1..MA Pointer address of the array into which the database
X_CONFIGURATIONS configurations are to be written.
[} 246]] OF ST_ConfigDB
[} 228]
cbDBConfig UDINT Length of the database configuration array
pAutoLogGrpConfig POINTER TO ARRAY[1..MAX Pointer address of the array into which the
_CONFIGURATIONS AutoLogGrp configurations are to be written.
[} 246]] OF
ST_ConfigAutoLogGrp [} 227]
cbAutoLogGrpConfig UDINT Length of the AutoLogGrp configuration array
pDBCount POINTER TO UDINT Pointer address for storing the number of database
configurations.
pAutoLogGrpCount POINTER TO UDINT Pointer address for storing the number of AutoLogGrp
configurations.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
aDBConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigDB;
aAutoGrpConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigAutoLogGrp;
nDbCount : UDINT;
nAutoGrpCount : UDINT;
tcMessage : I_TcMessage;
END_VAR
IF fbConfigTcDBSrv.Read(
pDBConfig := ADR(aDBConfig),
cbDBConfig := SIZEOF(aDBConfig),
pAutologGrpConfig := ADR(aAutoGrpConfig),
cbAutoLogGrpConfig := SIZEOF(aAutoGrpConfig),
pDBCount := ADR(nDbCount),
pAutoLogGrpCount := ADR(nAutoGrpCount))
THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.2.1.3 Delete
This method can be used to delete databases and AutoLog groups from the configuration of the
TwinCAT Database Server.

Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR

TF6420 Version: 1.13.4 167


PLC API

Inputs

Name Type Description


eTcDBSrvConfigType E_TcDBSrvConfigType Type of the configuration to be deleted (database /
AutoLog group)
hConfigID UDINT ID of the configuration to be deleted (hDBID or
hAutoLogGrpID)

Return value

Name Type Description


Delete BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
tcMessage : I_TcMessage;
END_VAR
IF fbConfigTcDBSrv.Delete(
eTcDBSrvConfigType := E_TcDBSrvConfigType.Database,
hConfigID := myConfigHandle) THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.2.2 FB_PLCDBAutoLogEvt

Function block with four methods for starting and stopping of defined AutoLog groups and for reading of the
corresponding group status.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBAutoLogEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage;
bBusy_Status: BOOL;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

168 Version: 1.13.4 TF6420


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active, except for the Status method.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage Result interface with detailed information on
the return value.
bBusy_Status BOOL The Status method can be executed
independently of the other three methods of
the function block and therefore has its own
Busy flag. Is TRUE as soon as the Status
method is active.

Methods

Name Definition loca- Description


tion
RunOnce Local Executes the AutoLog group once
[} 169]
Start [} 170] Local Starts AutoLog mode with the corresponding configured AutoLog groups
Status [} 170] Local Queries the status of the AutoLog groups.
Stop [} 171] Local Stops AutoLog mode

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.2.2.1 RunOnce
This method can be used to execute an AutoLog group once, for example based on an event in the
controller.

Syntax
METHOD RunOnce : BOOL
VAR_INPUT
hAutoLogGrpID: UDINT;
bAll: BOOL;
END_VAR

Inputs

Name Type Description


hAutoLogGrpID UDINT ID of the AutoLog group to be executed once.
bAll BOOL If TRUE, all AutoLog groups are executed once.

Return value

Name Type Description


RunOnce BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

TF6420 Version: 1.13.4 169


PLC API

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.RunOnce(hAutologGrpID := 1, bAll := FALSE) THEN
; // ...
END_IF

6.1.1.2.2.2 Start
This method starts the AutoLog mode with the corresponding configured AutoLog groups.

Syntax
METHOD Start : BOOL

Return value

Name Type Description


Start BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Start() THEN
; // ...
END_IF

6.1.1.2.2.3 Status
This method can be used to query the status of the AutoLog groups. A separate busy flag is provided in the
body of the function block for this method, since it can be called independently of the other methods of the
function block: bBusy_Status.

Syntax
METHOD Status : BOOL
VAR_INPUT
tCheckCycle: TIME;
pError: POINTER TO BOOL;
pAutoLogGrpStatus: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
cbAutoLogGrpStatus: UDINT;
END_VAR

Inputs

Name Type Description


tCheckCycle TIME Interval time at which the status array is
updated.
pError POINTER TO BOOL TRUE, if an error has occurred in AutoLog
mode.
pAutoLogStatus POINTER TO ARRAY Address of the status array that contains all
[1..MAX_CONFIGURATIONS [} 246]] OF groups.
ST_AutoLogGrpStatus [} 243]
cbAutoLogStatus UDINT Length of the status array

170 Version: 1.13.4 TF6420


PLC API

Return value

Name Type Description


Status BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt(sNetID:='', tTimeout := T#5S);
bError : BOOL;
aAutologGrpStatus : ARRAY[0..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
END_VAR
IF fbPLCDBAutoLog.Status(tCheckCycle := T#30S, ADR(bError), ADR(aAutologGrpStatus), SIZEOF(aAutologG
rpStatus)) THEN
; // ...
END_IF

6.1.1.2.2.4 Stop
This method stops the AutoLog mode.

Syntax
METHOD Stop : BOOL

Return value

Name Type Description


Stop BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF

6.1.1.2.3 FB_PLCDBCreateEvt

Function block with two methods. One method can be used to create databases from the PLC on a database
server specified in the PLC. The other method can be used to generate a new table in a specified database.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBCreateEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

TF6420 Version: 1.13.4 171


PLC API

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Database Local Creates a new database
[} 172]
Table [} 173] Local Creates a new table with a structure that is defined via an array with x
elements or x columns in the PLC.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.2.3.1 Database
This method creates a new database. Optionally you can specify whether the created database should also
be used for the configuration of the TwinCAT Database Server.

Syntax
METHOD Database : BOOL
VAR_INPUT
pDatabaseConfig: POINTER TO BYTE;
cbDatabaseConfig: UDINT;
bCreateXMLConfig: BOOL;
pDBID: POINTER TO UDINT;
END_VAR

172 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


pDatabaseConfig POINTER TO BYTE Address of the database configuration structure [} 229]
cbDatabaseConfig UDINT Length of the database configuration structure
bCreateXMLConfig BOOL Indicates whether the newly created database should be
entered as new configuration entry in the XML file.
pDBID UDINT Returns the hDBID if/when a new configuration entry was
created.

Return value

Name Type Description


Database BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBCreate : FB_PLCDBCreateEvt(sNetID := '', tTimeout := T#5S);
stConfigDB : T_DBConfig_MsCompactSQL;
hDBID : UDINT;
tcMessage : I_TcMessage;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Test.sdf';

IF fbPLCDBCreate.Database(
pDatabaseConfig:= ADR(stConfigDB),
cbDatabaseConfig := SIZEOF(stConfigDB),
bCreateXMLConfig := TRUE,
pDBID := ADR(hDBID))
THEN
IF fbPLCDBCreate.bError THEN
tcMessage := fbPLCDBCreate.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.2.3.2 Table
This method creates a new table with a structure that is defined through an array with x elements or x
columns in the PLC.

Syntax
METHOD Table : BOOL
VAR_INPUT
hDBID : UDINT;
sTableName : T_MaxString;
pTableCfg : POINTER TO ARRAY[0..MAX_DBCOLUMNS] OF ST_ColumnInfo;
cbTableCfg : UDINT;
END_VAR

TF6420 Version: 1.13.4 173


PLC API

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName MaxString Name of the table to be created.
pTableCfg POINTER TO Indicates the pointer address of the table structure
ARRAY[0..MAX_DBCOLUMNS array. The individual columns are written in this array.
[} 246]] OF ST_ColumnInfo
[} 243]
cbTableCfg UDINT Indicates the length of the array in which the columns
are configured.

Return value

Name Type Description


Table BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBCreate : FB_PLCDBCreateEvt(sNetID := '', tTimeout := T#5S);
ColumnInfo : ARRAY [0..14] OF ST_ColumnInfo;
tcMessage : I_TcMessage;
END_VAR
ColumnInfo[0].sName := 'colBigInt'; ColumnInfo[0].eType := E_ColumnType.BigInt; ColumnInfo[0
].nLength := 8; ColumnInfo[0].sProperty := 'IDENTITY(1,1)';
ColumnInfo[1].sName := 'colInteger'; ColumnInfo[1].eType := E_ColumnType.Integer; ColumnInfo[1
].nLength := 4;
ColumnInfo[2].sName := 'colSmallInt'; ColumnInfo[2].eType := E_ColumnType.SmallInt; ColumnInfo[2
].nLength := 2;
ColumnInfo[3].sName := 'colTinyInt'; ColumnInfo[3].eType := E_ColumnType.TinyInt; ColumnInfo[3
].nLength := 1;
ColumnInfo[4].sName := 'colBit'; ColumnInfo[4].eType := E_ColumnType.BIT_; ColumnInfo[4
].nLength := 1;
ColumnInfo[5].sName := 'colMoney'; ColumnInfo[5].eType := E_ColumnType.Money; ColumnInfo[5
].nLength := 8;
ColumnInfo[6].sName := 'colFloat'; ColumnInfo[6].eType := E_ColumnType.Float; ColumnInfo[6
].nLength := 8;
ColumnInfo[7].sName := 'colReal'; ColumnInfo[7].eType := E_ColumnType.REAL_; ColumnInfo[7
].nLength := 4;
ColumnInfo[8].sName := 'colDateTime'; ColumnInfo[8].eType := E_ColumnType.DateTime; ColumnInfo[8
].nLength := 4;
ColumnInfo[9].sName := 'colNText'; ColumnInfo[9].eType := E_ColumnType.NText; ColumnInfo[9
].nLength := 256;
ColumnInfo[10].sName := 'colNChar'; ColumnInfo[10].eType := E_ColumnType.NChar; ColumnInfo[1
0].nLength := 10;
ColumnInfo[11].sName := 'colImage'; ColumnInfo[11].eType := E_ColumnType.Image; ColumnInfo[1
1].nLength := 256;
ColumnInfo[12].sName := 'colNVarChar'; ColumnInfo[12].eType := E_ColumnType.NVarChar; ColumnInfo[1
2].nLength := 50;
ColumnInfo[13].sName := 'colBinary'; ColumnInfo[13].eType := E_ColumnType.Binary; ColumnInfo[1
3].nLength := 30;
ColumnInfo[14].sName := 'colVarBinary'; ColumnInfo[14].eType := E_ColumnType.VarBinary; ColumnInfo[1
4].nLength := 20;

IF fbPLCDBCreate.Table(
hDBID:= 1,
sTableName:= 'myNewTable',
pTableCfg:= ADR(ColumnInfo),
cbTableCfg:= SIZEOF(ColumnInfo))
THEN
IF fbPLCDBCreate.bError THEN
TcMessage:= fbPLCDBCreate.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

174 Version: 1.13.4 TF6420


PLC API

6.1.1.2.4 FB_PLCDBReadEvt

Function block for reading records from a database.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBReadEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Description


nRecords UDINT Outputs the maximum number of records that could be collected
depending on sDBSymbolName.
eTraceLevel TcEventSeverity Specifies the weighting of the events. Only events with a weighting
[} 225] higher than this value are sent to the TwinCAT system.

Methods

Name Definition location Description


Read [} 176] Local Reads a specified number of records from a database table with the
standard table structure specified by Beckhoff.
ReadStruct [} 177] Local Reads a specified number of records from a database table with any
table structure.

TF6420 Version: 1.13.4 175


PLC API

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.2.4.1 Read
This method reads a specified number of records from a database table with the standard table structure
specified by Beckhoff. The standard table structure is used in AutoLog mode and in the FB_DBWriteEvt
function block, for example.

Syntax
METHOD Read : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
sDBSymbolName: T_MaxString;
eOrderBy: E_OrderColumn := E_OrderColumn.eColumnID;
eOrderType: E_OrderType := E_OrderType.eOrder_ASC;
nStartIndex: UDINT;
nRecordCount: UDINT;
pData: POINTER TO ST_StandardRecord;
cbData: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
sDBSymbolName T_MaxString Symbol name to be read from the standard table
structure.
eOrderBy E_OrderColumn.eColumnID Sorting column (ID, timestamp, name or value)
eOrderType E_OrderType.eOrder_ASC Sorting direction (ASC or DESC)
nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO ST_StandardRecord Address of the structure array into which the
records are to be written.
cbData UDINT Indicates the size of the structure array in bytes.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the method execution is
finished, even in the event of an error.

Sample
VAR
fbPLCDBRead : FB_PLCDBReadEvt (sNetID := '', tTimeout := T#5S);
ReadStruct : ST_StandardRecord;
tcMessage : I_TcMessage;
END_VAR
IF fbPLCDBRead.Read(
hDBID:= 1,
sTableName:= 'MyTable_WithLReal',
sDBSymbolName:= 'MyValue',
eOrderBy:= E_OrderColumn.ID,
eOrderType:= E_OrderType.DESC,
nStartIndex:= 0,
nRecordCount:= 1,
pData:= ADR(ReadStruct),
cbData:= SIZEOF(ReadStruct))

176 Version: 1.13.4 TF6420


PLC API

THEN
IF fbPLCDBRead.bError THEN
tcMessage := fbPLCDBRead.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the PLC:

6.1.1.2.4.2 ReadStruct
This method reads a specified number of records from a database table with any table structure.

Syntax
METHOD ReadStruct : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
pColumnNames: POINTER TO ARRAY [0..MAX_DBCOLUMNS] OF STRING(50);
cbColumnNames: UDINT;
sOrderByColumn: STRING(50);
eOrderType: E_OrderType := E_OrderType.eOrder_ASC
nStartIndex: UDINT;
nRecordCount: UDINT;
pData: POINTER TO BYTE;
cbData: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
pColumnNames POINTER TO ARRAY [0..MAX_D Address of the array containing the column name
BCOLUMNS] OF STRING(50) to be read.
cbColumnNames UDINT Length of the column name array
sOrderByColumn STRING(50) Name the sorting column
eOrderType E_OrderType Sorting direction (ASC or DESC)
nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO BYTE Address of the structure array into which the
records are to be written.
cbData UDINT Indicates the size of the structure array in bytes.

Return value

Name Type Description


ReadStruct BOOL Displays the status of the method. Returns TRUE as soon as the method execution is
finished, even in the event of an error.

TF6420 Version: 1.13.4 177


PLC API

Sample
VAR
fbPLCDBRead : FB_PLCDBReadEvt (sNetID := '', tTimeout := T#5S);
myCustomStruct : ST_Record;
tcMessage : I_TcMessage;
END_VAR
TYPE ST_Record :
STRUCT
nID : LINT;
dtTimestamp: DATE_AND_TIME;
sName : STRING;
nSensor1 : LREAL;
nSensor2 : LREAL;
END_STRUCT
END_TYPE
// set columnnames
ColumnNames[0] := 'ID';
ColumnNames[1] := 'Timestamp';
ColumnNames[2] := 'Name';
ColumnNames[3] := 'Sensor1';
ColumnNames[4] := 'Sensor2';

IF fbPLCDBRead.ReadStruct(
hDBID:= 1,
sTableName:= 'MyTable_Struct',
pColumnNames:= ADR(ColumnNames),
cbColumnNames:= SIZEOF(ColumnNames),
sOrderByColumn:= ColumnNames[0],
eOrderType:= E_OrderType.DESC,
nStartIndex:= 0,
nRecordCount:= 1,
pData:= ADR(myCustomStruct),
cbData:= SIZEOF(myCustomStruct))
THEN
IF fbPLCDBRead.bError THEN
tcMessage:= fbPLCDBRead.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the PLC:

6.1.1.2.5 FB_PLCDBWriteEvt

Function block for writing of records into a database.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBWriteEvt
VAR_INPUT
sNetID: T_AmsNetID := '';

178 Version: 1.13.4 TF6420


PLC API

tTimeout: TIME := T#5S;


END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Write [} 179] Local Creates a record in the standard table structure specified by
Beckhoff.
WriteBySymbol Local Reads the value of a specified ADS symbol and saves it in the
[} 181] standard table structure specified by Beckhoff.
WriteStruct [} 182] Local Creates a record with any table structure.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.2.5.1 Write
This method creates a record in the standard table structure specified by Beckhoff.

Syntax
METHOD Write : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;

TF6420 Version: 1.13.4 179


PLC API

pValue: POINTER TO BYTE;


cbValue: UDINT;
sDBSymbolName: T_MaxString;
eDBWriteMode: E_WriteMode := E_WriteMode.eADS_TO_DB_Append;
nRingBuffParameter: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
pValue POINTER TO BYTE Address of the variable to be logged in the standard table
structure.
cbValue UDINT Length of the variable to be logged.
sDBSymbolName T_MaxString Name that is logged in the table.
eDBWriteMode E_WriteMode Indicates the write mode. (append, update, ring buffer)
nRingBuffParameter UDINT Additional parameter(s) for the "ring buffer" write mode.

Return value

Name Type Description


Write BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

This sample shows how to use the FB_PLCDBWriteEvt.Write method:


VAR
fbPLCDBWrite : FB_PLCDBWriteEvt(sNetID := '', tTimeout := T#5S);
myValue : LREAL := 43.23;
tcMessage : I_TcMessage;
END_VAR
IF fbPLCDBWrite.Write(
hDBID:= 1,
sTableName:= 'myTable_WithLReal',
pValue:= ADR(myValue),
cbValue:= SIZEOF(myValue),
sDBSymbolName:= 'MyValue',
eDBWriteMode:= E_WriteMode.eADS_TO_DB_RingBuff_Count,
nRingBuffParameter:= 3)
THEN
IF fbPLCDBWrite.bError THEN
tcMessage := fbPLCDBWrite.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the database:

ID Timestamp Name Value


27 Has been dropped
28 '2018-01-30 14:04:19' 'MyValue' 41.23
29 '2018-01-30 14:04:29' 'MyValue' 42.23
30 '2018-01-30 14:04:39' 'MyValue' 43.23

With the ring buffer option, only three entries of this name are in the database at any one time. Older entries
are deleted.

180 Version: 1.13.4 TF6420


PLC API

6.1.1.2.5.2 WriteBySymbol
This method reads the value of a specified ADS symbol and saves it in the standard table structure specified
by Beckhoff. ADS symbols from other ADS devices can also be read.

Syntax
METHOD WriteBySymbol : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
stADSDevice: ST_ADSDevice;
stSymbol: ST_Symbol;
eDBWriteMode: E_WriteMode := E_WriteMode.eADS_TO_DB_Append;
nRingBuffParameter: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
stADSDevice ST_ADSDevice ADS device from which a symbol is to be logged in the standard
table structure.
stSymbol ST_Symbol Symbol name of the variable to be written
eDBWriteMode E_WriteMode Indicates the write mode. (append, update, ring buffer)
nRingBuffParameter UDINT Additional parameter(s) for the "ring buffer" write mode

Return value

Name Type Description


WriteBySymbol BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

This sample shows how to use the FB_PLCDBWriteEvt.WriteBySymbol method:


VAR
fbPLCDBWrite : FB_PLCDBWriteEvt(sNetID := '', tTimeout := T#5S);
myValue : LREAL := 43.23;
myAdsDevice : ST_ADSDevice;
mySymbol : ST_Symbol;
tcMessage : I_TcMessage;
END_VAR
// Set ADSDevice Information
myAdsDevice.sDevNetID := '127.0.0.1.1.1';
myAdsDevice.nDevPort := 851;
myAdsDevice.eADSRdWrtMode := E_ADSRdWrtMode.bySymbolName;
myAdsDevice.tTimeout := T#5S;

// Set Symbol Information


mySymbol.eDataType := E_PLCDataType.eType_LREAL;
mySymbol.sDBSymbolName := 'MySymbol';
mySymbol.sSymbolName := 'MAIN.myValue';
mySymbol.nBitSize := 8;

// Call Functionblock
IF fbPLCDBWrite.WriteBySymbol(
hDBID:= 1,
sTableName:= 'myTable_WithLReal',
stADSDevice:= myAdsDevice,
stSymbol:= mySymbol,
eDBWriteMode:= E_WriteMode.eADS_TO_DB_Append,
nRingBuffParameter:= 1)
THEN
IF fbPLCDBWrite.bError THEN
tcMessage := fbPLCDBWrite.ipTcResult;

TF6420 Version: 1.13.4 181


PLC API

nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the database:

ID Timestamp Name Value


28 '2018-01-30 14:04:19' 'MyValue' 41.23
29 '2018-01-30 14:04:29' 'MyValue' 42.23
30 '2018-01-30 14:04:39' 'MyValue' 43.23
31 '2018-01-30 14:06:12’ ‘MySymbol’ 86.2

6.1.1.2.5.3 WriteStruct
This method creates a record with a freely selectable table structure.

Syntax
METHOD WriteStruct : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
pRecord: POINTER TO BYTE;
cbRecord: UDINT;
pColumnNames: POINTER TO ARRAY [0..MAX_DBCOLUMNS] OF STRING(50);
cbColumnNames: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
pRecord POINTER TO BYTE Address of a structure that is to be logged in a freely
selectable table structure.
cbRecord UDINT Length of the structure to be written
pColumnNames POINTER TO ARRAY [ Address of the array containing the column name to be filled.
0..MAX_DBCOLUMNS
] OF STRING(50)
cbColumnNames UDINT Length of the column name array

Return value

Name Type Description


WriteStruct BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

This sample shows how to use the method FB_PLCDBWriteEvt.WriteStruct:


VAR
fbPLCDBWrite : FB_PLCDBWriteEvt(sNetID := '', tTimeout := T#5S);
myRecord : ST_Record;
ColumnNames : ARRAY[0..4] OF STRING(50);

systime : GETSYSTEMTIME;
currentTime : T_FILETIME;
tcMessage : I_TcMessage;
END_VAR

182 Version: 1.13.4 TF6420


PLC API

TYPE ST_Record :
STRUCT
nID : LINT;
dtTimestamp: DATE_AND_TIME;
sName : STRING;
nSensor1 : LREAL;
nSensor2 : LREAL;
END_STRUCT
END_TYPE
// set Values
systime(timeLoDw => currentTime.dwLowDateTime, timeHiDW => currentTime.dwHighDateTime );
myRecord.dtTimestamp := FILETIME_TO_DT(currentTime);
myRecord.sName := 'MyStructVal';
myRecord.nSensor1 := 12.34;
myRecord.nSensor2 := 102.5;

// set columnnames
ColumnNames[0] := 'ID';
ColumnNames[1] := 'Timestamp';
ColumnNames[2] := 'Name';
ColumnNames[3] := 'Sensor1';
ColumnNames[4] := 'Sensor2';

// Call Functionblock
IF fbPLCDBWrite.WriteStruct(
hDBID:= 1,
sTableName:= 'myTable_Struct',
pRecord:= ADR(myRecord),
cbRecord:= SIZEOF(myRecord),
pColumnNames:= ADR(ColumnNames) ,
cbColumnNames:= SIZEOF(ColumnNames))
THEN
IF fbPLCDBWrite.bError THEN
tcMessage := fbPLCDBWrite.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the database:

ID Timestamp Name Sensor1 Sensor2


5 '2018-01-30 ‘MyStructVal’ 12.34 102.5
15:23:26'

6.1.1.2.6 FB_PLCDBCmdEvt

Function block with two methods. Users can define and transfer their own SQL commands. Placeholders in
the SQL command can correlate with structures in the PLC, which reflect the table structure. The database
server enters the current data of the structure into the SQL command.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBCmdEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

TF6420 Version: 1.13.4 183


PLC API

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Execute [} 184] Local Sends any SQL commands to the database.
Returned records cannot be read.
ExecuteDataReturn Local Sends any SQL commands to the database.
[} 186] A specified number of records can be read.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.2.6.1 Execute
This method can be used to send SQL commands to the database. The database connection is opened with
each call and then closed again. It is possible to define placeholders in the command, which are replaced by
the TwinCAT Database Server with the corresponding values before the execution. Returned records cannot
be read.

Syntax
METHOD Execute : BOOL
VAR_INPUT
hDBID: UDINT;
pExpression: POINTER TO BYTE;
cbExpression: UDINT;
pData: POINTER TO BYTE;
cbData: UDINT;
pParameter: POINTER TO ARRAY[0..MAX_DBCOLUMNS] OF ST_ExpParameter;
cbParameter: UDINT;
END_VAR

184 Version: 1.13.4 TF6420


PLC API

Sample
VAR
fbPLCDBCmd : FB_PLCDBCmdEvt(sNetID := '', tTimeout := T#5S);
sCmd : STRING (1000);
myStruct : ST_DataAll;
aPara : ARRAY[0..14] OF ST_ExpParameter;
tcMessage : I_TcMessage;
END_VAR
TYPE ST_DataAll :
STRUCT
colBigInt: LINT;
colInteger: DINT;
colSmallInt: INT;
colTinyInt: BYTE;
colBit: BOOL;
colMoney: LREAL;
colFloat: LREAL;
colReal: REAL;
colDateTime: DT;
colNText: STRING(255);
colNChar: STRING(10);
colImage: ARRAY[0..255] OF BYTE;
colNVarChar: STRING(50);
colBinary: ARRAY[0..29] OF BYTE;
colVarBinary: ARRAY[0..19] OF BYTE;
END_STRUCT
END_TYPE
// set Parameter configuration
aPara[0].sParaName := 'colBigInt'; aPara[0].eParaType :=
E_ExpParameterType.Int64; aPara[0].nParaSize := 8;
aPara[1].sParaName := 'colInteger'; aPara[1].eParaType :=
E_ExpParameterType.Int32; aPara[1].nParaSize := 4;
aPara[2].sParaName := 'colSmallInt'; aPara[2].eParaType :=
E_ExpParameterType.Int16; aPara[2].nParaSize := 2;
aPara[3].sParaName := 'colTinyInt'; aPara[3].eParaType :=
E_ExpParameterType.Byte_; aPara[3].nParaSize := 1;
aPara[4].sParaName := 'colBit'; aPara[4].eParaType :=
E_ExpParameterType.Boolean; aPara[4].nParaSize := 1;
aPara[5].sParaName := 'colMoney'; aPara[5].eParaType :=
E_ExpParameterType.Double64; aPara[5].nParaSize := 8;
aPara[6].sParaName := 'colFloat'; aPara[6].eParaType :=
E_ExpParameterType.Double64; aPara[6].nParaSize := 8;
aPara[7].sParaName := 'colReal'; aPara[7].eParaType :=
E_ExpParameterType.Float32; aPara[7].nParaSize := 4;
aPara[8].sParaName := 'colDateTime'; aPara[8].eParaType :=
E_ExpParameterType.DateTime; aPara[8].nParaSize := 4;
aPara[9].sParaName := 'colNText'; aPara[9].eParaType :=
E_ExpParameterType.STRING_; aPara[9].nParaSize := 256;
aPara[10].sParaName:= 'colNChar'; aPara[10].eParaType :=
E_ExpParameterType.STRING_; aPara[10].nParaSize := 10;
aPara[11].sParaName:= 'colImage'; aPara[11].eParaType :=
E_ExpParameterType.ByteArray; aPara[11].nParaSize := 256;
aPara[12].sParaName:= 'colNVarChar'; aPara[12].eParaType :=
E_ExpParameterType.STRING_; aPara[12].nParaSize := 50;
aPara[13].sParaName:= 'colBinary'; aPara[13].eParaType :=
E_ExpParameterType.ByteArray; aPara[13].nParaSize := 30;
aPara[14].sParaName:= 'colVarBinary'; aPara[14].eParaType :=
E_ExpParameterType.ByteArray; aPara[14].nParaSize := 20;

// set command
sCmd := 'INSERT INTO MyTableName (colInteger, colSmallInt, colTinyInt, colBit, colMoney, colFloat,
colReal, colDateTime, colNText, colNChar, colImage, colNVarChar, colBinary, colVarBinary) VALUES
({colInteger}, {colSmallInt}, {colTinyInt}, {colBit}, {colMoney}, {colFloat}, {colReal},
{colDateTime}, {colNText}, {colNChar}, {colImage}, {colNVarChar}, {colBinary}, {colVarBinary})';

// call functionblock
IF fbPLCDBCmd.Execute(
hDBID:= 1,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(myStruct),
cbData:= SIZEOF(myStruct),
pParameter:= ADR(aPara),
cbParameter:= SIZEOF(aPara))
THEN
IF fbPLCDBCmd.bError THEN
tcMessage := fbPLCDBCmd.ipTcResult;
nState := 255;

TF6420 Version: 1.13.4 185


PLC API

ELSE
nState := 0;
END_IF
END_IF

6.1.1.2.6.2 ExecuteDataReturn
This method can be used to send SQL commands to the database. The database connection is opened with
each call and then closed again. It is possible to define placeholders in the command, which are replaced by
the TwinCAT Database Server with the corresponding values before the execution. A specified number of
records can be read.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
hDBID: UDINT;
pExpression: POINTER TO BYTE;
cbExpression: UDINT;
pData: POINTER TO BYTE;
cbData: UDINT;
pParameter: POINTER TO ARRAY[0..MAX_DBCOLUMNS] OF ST_ExpParameter;
cbParameter: UDINT;
nStartIndex: UDINT;
nRecordCount: UDINT;
pReturnData: POINTER TO BYTE;
cbReturnData: UDINT;
pRecords: POINTER TO UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
pExpression POINTER TO BYTE Address of the string variable with the SQL command
cbExpression UDINT Length of the string variable with the SQL command
pData POINTER TO BYTE Address of the structure with the parameter values
cbData UDINT Length of the structure with the parameter values
pParameter POINTER TO ARRAY[0..MAX_ Address of the structure array with the parameter
DBCOLUMNS] OF ST_ExpPar information
ameter
cbParameter UDINT Length of the structure array with the parameter
information
nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pReturnData POINTER TO BYTE Address of the structure array into which the records are
to be written.
cbReturnData UDINT Indicates the size of the structure array in bytes.
pRecords POINTER TO BYTE Number of read records.

Return value

Name Type Description


ExecuteDataReturn BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

186 Version: 1.13.4 TF6420


PLC API

Parameterizing the command


The column names for the individual parameters are specified in curly brackets in the SQL
command.
Sample: ‚SELECT * FROM MyHouse_Temperatures WHERE Room = {SelectedRoom}’.
Accordingly, SelectedRoom has to be specified as parameter name in the structure
ST_ExpParameter.

Some databases do not support the parameterization of SQL clauses. (TOP/LIMIT/ROWNUM/...)


Parameterizable table names are not usually supported.

Sample
VAR
fbPLCDBCmd : FB_PLCDBCmdEvt(sNetID := '', tTimeout := T#5S);
sCmd : STRING (1000);
stPara : ST_ExpParameter;
RecordAmt : ULINT := 3;
ReturnDataStruct : ARRAY [0..9] OF ST_DataAll;
nRecords : UDINT;
tcMessage : I_TcMessage;
END_VAR
// set Parameter configuration
stPara.eParaType := E_ExpParameterType.Int64;
stPara.nParaSize := 8;
stPara.sParaName := 'RecordAmt';

// set command with placeholder


sCmd := 'SELECT TOP ({RecordAmt}) * FROM MyTableName';

// call functionblock
IF fbPLCDBCmd.ExecuteDataReturn(
hDBID:= 1,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(RecordAmt),
cbData:= SIZEOF(RecordAmt),
pParameter:= ADR(stPara),
cbParameter:= SIZEOF(stPara),
nStartIndex:= 0,
nRecordCount:= 10,
pReturnData:= ADR(ReturnDataStruct),
cbReturnData:= SIZEOF(ReturnDataStruct),
pRecords:= ADR(nRecords))
THEN
IF fbPLCDBCmd.bError THEN
tcMessage := fbPLCDBCmd.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

TF6420 Version: 1.13.4 187


PLC API

6.1.1.3 SQL Expert mode

6.1.1.3.1 FB_ConfigTcDBSrvEvt

Function block for creating, reading and deleting configuration entries for the TwinCAT Database Server.

Syntax

Definition:
FUNCTION_BLOCK FB_ConfigTcDBSrvEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage;
END_VAR

188 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Create [} 189] Local Creates new entries in the XML configuration file for the
TwinCAT Database Server
Read [} 190] Local Reads the current configuration of the TwinCAT Database Server
Delete [} 191] Local Deletes the database and AutoLog groups from the configuration
of the TwinCAT Database Server

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.3.1.1 Create
This method creates new entries in the XML configuration file for the TwinCAT Database Server. Optionally
the TwinCAT Database Server can use a new entry on a temporary basis. In this case no data is written to
the XML file.

Syntax
METHOD Create : BOOL
VAR_INPUT
pTcDBSrvConfig: POINTER TO BYTE;
cbTcDBSrvConfig: UDINT;
bTemporary: BOOL := TRUE;
pConfigID: POINTER TO UDINT;
END_VAR

TF6420 Version: 1.13.4 189


PLC API

Inputs

Name Type Description


pTcDBSrvConfig POINTER TO BYTE Pointer of the configuration structure to be created.
cbTcDBSrvConfig UDINT Length of the configuration structure
bTemporary BOOL Indicates whether the configuration is to be stored in the
XML file.
pConfigID POINTER TO UDINT Return pointer of the configuration ID (hDBID or
hAutoLogGrpID)

Creating AutoLog groups is currently not supported.

Return value

Name Type Description


Create BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
// Any other ConfigType can be used here
stConfigDB : T_DBConfig_MsCompactSQL;
tcMessage : I_TcMessage;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Recipes.sdf';

IF fbConfigTcDBSrv.Create(
pTcDBSrvConfig:= ADR(stConfigDB),
cbTcDBSrvConfig:= SIZEOF(stConfigDB),
bTemporary:= TRUE,
pConfigID:= ADR(myConfigHandle))
THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.3.1.2 Read
This method can be used to read the current configurations of the TwinCAT Database Server. Any
temporary configurations that may be included are marked accordingly.

Syntax
METHOD Read : BOOL
VAR_INPUT
pDBConfig: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_ConfigDB;
cbDBConfig: UDINT;
pAutoLogGrpConfig: POINTER TO ARRAY[1..MAX_CONFIGURATIONS] OF
ST_ConfigAutoLogGrp;
cbAutoLogGrpConfig: UDINT;
pDBCount: POINTER TO UDINT;
pAutoLogGrpCount: POINTER TO UDINT;
END_VAR

190 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


pDBConfig POINTER TO ARRAY [1..MA Pointer address of the array into which the database
X_CONFIGURATIONS configurations are to be written.
[} 246]] OF ST_ConfigDB
[} 228]
cbDBConfig UDINT Length of the database configuration array
pAutoLogGrpConfig POINTER TO ARRAY[1..MAX Pointer address of the array into which the
_CONFIGURATIONS AutoLogGrp configurations are to be written.
[} 246]] OF
ST_ConfigAutoLogGrp [} 227]
cbAutoLogGrpConfig UDINT Length of the AutoLogGrp configuration array
pDBCount POINTER TO UDINT Pointer address for storing the number of database
configurations.
pAutoLogGrpCount POINTER TO UDINT Pointer address for storing the number of AutoLogGrp
configurations.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
aDBConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigDB;
aAutoGrpConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigAutoLogGrp;
nDbCount : UDINT;
nAutoGrpCount : UDINT;
tcMessage : I_TcMessage;
END_VAR
IF fbConfigTcDBSrv.Read(
pDBConfig := ADR(aDBConfig),
cbDBConfig := SIZEOF(aDBConfig),
pAutologGrpConfig := ADR(aAutoGrpConfig),
cbAutoLogGrpConfig := SIZEOF(aAutoGrpConfig),
pDBCount := ADR(nDbCount),
pAutoLogGrpCount := ADR(nAutoGrpCount))
THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.3.1.3 Delete
This method can be used to delete databases and AutoLog groups from the configuration of the
TwinCAT Database Server.

Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR

TF6420 Version: 1.13.4 191


PLC API

Inputs

Name Type Description


eTcDBSrvConfigType E_TcDBSrvConfigType Type of the configuration to be deleted (database /
AutoLog group)
hConfigID UDINT ID of the configuration to be deleted (hDBID or
hAutoLogGrpID)

Return value

Name Type Description


Delete BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrvEvt(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
tcMessage : I_TcMessage;
END_VAR
IF fbConfigTcDBSrv.Delete(
eTcDBSrvConfigType := E_TcDBSrvConfigType.Database,
hConfigID := myConfigHandle) THEN
IF fbConfigTcDBSrv.bError THEN
tcMessage := fbConfigTcDBSrv.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.1.3.2 FB_SQLDatabaseEvt

Function block for opening, closing and managing a database connection.

Syntax

Definition:
FUNCTION BLOCK FB_SQLDatabaseEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

192 Version: 1.13.4 TF6420


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Connect [} 193] Local Opens a connection to a declared database.
CreateCmd [} 194] Local Initializes an instance of the function block FB_SQLCommandEvt
[} 196] with the already open database connection of the
function block FB_SQLDatabaseEvt.
CreateSP [} 195] Local Initializes an instance of the function block
FB_SQLStoredProcedureEvt [} 201] with the already open
database connection of the function block
FB_SQLDatabaseEvt.
Disconnect [} 195] Local Closes the connection to the database that was opened by this
function block instance.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.3.2.1 Connect
This method opens a connection to a declared database.

Syntax
METHOD Connect : BOOL
VAR_INPUT
hDBID: UDINT := 1;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.

TF6420 Version: 1.13.4 193


PLC API

Return value

Name Type Description


Connect BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
END_VAR
// open connection
IF fbSqlDatabase.Connect(1) THEN
IF fbSqlDatabase.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

6.1.1.3.2.2 CreateCmd
This method is used to initialize an instance of the function block FB_SQLCommand with the already open
database connection of the function block FB_SQLDatabase. The function block FB_SQLCommand only
uses the database connection it was assigned via the CreateCmd method. Several instances of the function
block FB_SQLCommand can be initialized with the same database connection.

The initialization of the function block FB_SQLCommand is completed in the same cycle. This means that
neither the Busy flag of the function block nor the method return value of the CreateCmd method have to be
checked.

Syntax
METHOD CreateCmd : BOOL
VAR_INPUT
pSQLCommand: POINTER TO FB_SQLCommandEvt;
END_VAR

Inputs

Name Type Description


pSQLCommand POINTER TO FB_SQLCommand Returns a new instance of the function block
FB_SQLCommandEvt.

Return value

Name Type Description


CreateCmd BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
END_VAR
// create a command reference
IF fbSqlDatabase.CreateCmd(ADR(fbSqlCommand)) THEN
IF fbSqlDatabase.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

FB_SQLCommandEvt [} 196] can then be used for the execution.

194 Version: 1.13.4 TF6420


PLC API

6.1.1.3.2.3 CreateSP
This method is used to initialize an instance of the function block FB_SQLStoredProcedureEvt with the
already open database connection of the function block FB_SQLDatabaseEvt. The function block
FB_SQLStoredProcedureEvt only uses the database connection it was assigned via the CreateCmd method.
Several instances of the function block FB_SQLStoredProcedureEvt can be initialized with the same
database connection.

The initialization of the function block FB_SQLStoredProcedureEvt may take several cycles. The Busy flag of
the function block or the method return value of the CreateCmd method have to be checked before the
function block can be used.

Syntax
METHOD CreateSP : BOOL
VAR_INPUT
sProcedureName: T_MaxString;
pParameterInfo: POINTER TO ARRAY [0..MAX_SPPARAMETER] OF ST_SQLSPParameter;
cbParameterInfo: UDINT;
pSQLProcedure: POINTER TO FB_SQLStoredProcedureEvt;
END_VAR

Inputs

Name Type Description


sProcedureName T_MaxString Indicates the name of the procedure to be
executed.
pParameterInfo POINTER TO ARRAY [0..MAX_SPPAR Pointer address for the parameter info list.
AMETER] OF ST_SQLSPParameter
cbParameterInfo UDINT Indicates the length of the parameter info list.
pSQLProcedure POINTER TO FB_SQLStoredProcedure Returns a new instance of the function block
Evt FB_SQLStoredProcedureEvt.

Return value

Name Type Description


CreateSP BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
ParaInfo : ST_SQLSPParameter;
END_VAR
ParaInfo.sParameterName := '@Customer_ID';
ParaInfo.eParameterType := E_SPParameterType.Input;
ParaInfo.eParameterDataType := E_ColumnType.BigInt;
ParaInfo.nParameterSize := 8;

IF fbSQLDatabase.CreateSP('dbo.SP_GetCustomerPositions', ADR(ParaInfo), SIZEOF(ParaInfo), ADR(fbSQLS


toredProcedure)) THEN
IF fbSQLDatabase.bError THEN
nState:=255;
ELSE
nState:= nState+1;
END_IF
END_IF

Subsequently, the FB_SQLStoredProcedureEvt [} 201] can be used to execute the stored procedure.

6.1.1.3.2.4 Disconnect
This method closes the connection to the database that was opened by this function block instance.

TF6420 Version: 1.13.4 195


PLC API

Syntax
METHOD Disconnect : BOOL

Return value

Name Type Description


Disconnect BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
END_VAR
// disconnect from database
IF fbSqlDatabase.Disconnect() THEN
IF fbSqlDatabase.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

6.1.1.3.3 FB_SQLCommandEvt

Function block for executing SQL commands. Before it can be used it has to be initialized with the function
block FB_SQLDatabaseEvt.

Syntax

Definition:
FUNCTION BLOCK FB_SQLCommandEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

196 Version: 1.13.4 TF6420


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Execute [} 197] Local Sends the specified SQL command to the database via the
database connection already opened by the function block
FB_SQLDatabaseEvt [} 192].
ExecuteDataReturn Local Sends the specified SQL command to the database via the
[} 198] database connection already opened by the function block
FB_SQLDatabaseEvt [} 192].
An instance of the function block FB_SQLResultEvt [} 199] can
be transferred for reading the returned records.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.3.3.1 Execute
This method sends the specified SQL command to the database via the database connection already
opened by the function block FB_SQLDatabase.

Syntax
METHOD Execute : BOOL
VAR_INPUT
pSQLCmd: POINTER TO BYTE;
cbSQLCmd: UDINT;
END_VAR

Inputs

Name Type Description


pSQLCmd POINTER TO BYTE Indicates the pointer address of a string variable with the SQL
command to be executed.
cbSQLCmd UDINT Indicates the length of a SQL command to be executed.

TF6420 Version: 1.13.4 197


PLC API

Return value

Name Type Description


Execute POINTER TO BYTE Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

Uses the command created by FB_SQLDatabaseEvt.CreateCmd() [} 192].


VAR
fbSqlCommand : FB_SQLCommandEvt(sNetID := '', tTimeout := T#5S);
tcMessage : I_TcMessage;
END_VAR
// you can generate this with the SQL Query Editor
sCmd := 'INSERT INTO myTable_Double ( Timestamp, Name, Value) VALUES ( $'2018-01-31 14:59:27$', $'Te
mperature$', 21.3)';

// call sql command


IF fbSQLCommand.Execute(ADR(sCmd), SIZEOF(sCmd)) THEN
IF fbSQLCommand.bError THEN
tcMessage := fbSQLCommand.ipTcResult;
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

6.1.1.3.3.2 ExecuteDataReturn
This method sends the specified SQL command to the database via the database connection already
opened by the function block FB_SQLDatabase. An instance of the function block FB_SQLResult can be
transferred for reading the returned records.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
pSQLCmd: POINTER TO BYTE;
cbSQLCmd: UDINT;
pSQLDBResult: POINTER TO FB_SQLResult;
END_VAR

Inputs

Name Type Description


pSQLCmd POINTER TO BYTE Indicates the pointer address of a string variable with
the SQL command to be executed.
cbSQLCmd UDINT Indicates the length of a SQL command to be executed.
pSQLDBResult POINTER TO FB_SQLResult Returns a new instance of the function block
[} 199] FB_SQLResult.

Return value

Name Type Description


ExecuteDataReturn POINTER TO BYTE Displays the status of the method. Returns TRUE as soon
as the method execution is finished, even in the event of an
error.

Sample

Uses the command created by FB_SQLDatabaseEvt.CreateCmd() [} 192].

198 Version: 1.13.4 TF6420


PLC API

VAR
fbSqlCommand : FB_SQLCommandEvt(sNetID := '', tTimeout := T#5S);
tcMessage : I_TcMessage;
END_VAR
// you can generate this with the SQL Query Editor
sCmd := 'SELECT ID, Timestamp, Name, Value FROM myTable_Double';

// call sql command


IF fbSQLCommand.ExecuteDataReturn(ADR(sCmd), SIZEOF(sCmd), ADR(fbSqlResult)) THEN
IF fbSQLCommand.bError THEN
nState := 255;
ELSE
tcMessage := fbSQLCommand.ipTcResult;
nState := nState+1;
END_IF
END_IF

FB_SQLResultEvt [} 199] can then be used to read the data.

6.1.1.3.4 FB_SQLResultEvt

The function block is used for reading the cached records.

Syntax

Definition:
FUNCTION BLOCK FB_SQLResultEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

TF6420 Version: 1.13.4 199


PLC API

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Read [} 200] Local Reads a specified number of records from the result data
cached in the TwinCAT Database Server.
Release [} 201] Local Releases data buffered by the TwinCAT Database Server.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.3.4.1 Read
This method reads a specified number of records from the result data cached in the
TwinCAT Database Server.

Syntax
METHOD Read : BOOL
VAR_INPUT
nStartIndex: UDINT := 0;
nRecordCount: UDINT := 1;
pData: POINTER TO BYTE;
cbData: UDINT;
bWithVerifying: BOOL := FALSE;
bDataRelease: BOOL := TRUE;
END_VAR

Inputs

Name Type Description


nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO BYTE Address of the structure array into which the records are to be
written.
cbData UDINT Indicates the size of the structure array in bytes.
bWithVerifying BOOL Return data are compared with the pData structure array and
adjusted if necessary.
bDataRelease BOOL Releases the cached data.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

200 Version: 1.13.4 TF6420


PLC API

Sample
VAR
fbSqlResult : FB_SQLResultEvt(sNetID:='', tTimeout := T#5S);
aReadStruct : ARRAY[1..5] OF ST_StandardRecord;
END_VAR
// get values from internal tc db srv storage
IF fbSqlResult.Read(2, 3, ADR(aReadStruct), SIZEOF(aReadStruct), FALSE, TRUE) THEN
IF fbSqlResult.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

Result in the PLC:

6.1.1.3.4.2 Release
This method can be used to release data cached by the TwinCAT Database Server.

Syntax
METHOD Release : BOOL

Return value

Name Type Description


Release BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

6.1.1.3.5 FB_SQLStoredProcedureEvt

Function block for executing stored procedures of the database. Before it can be used it has to be initialized
with the function block FB_SQLDatabaseEvt.

Syntax

Definition:
FUNCTION BLOCK FB_SQLStoredProcedureEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;

TF6420 Version: 1.13.4 201


PLC API

END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Methods

Name Definition loca- Description


tion
Execute [} 202] Local Sends the call of the specified stored procedure to the
database via the database connection already opened by the
function block FB_SQLDatabaseEvt [} 192].
ExecuteDataReturn Local Sends the call of the specified stored procedure to the
[} 203] database via the database connection already opened by the
function block FB_SQLDatabaseEvt [} 192].
An instance of the function block FB_SQLResultEvt [} 199] can
be transferred for reading the returned records.
Release [} 204] Local Releases the parameter information of the stored procedure
that was transferred during initialization.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.3.5.1 Execute
This method sends the call of the specified stored procedure to the database via the database connection
already opened by the function block FB_SQLDatabaseEvt.

202 Version: 1.13.4 TF6420


PLC API

Syntax
METHOD Execute : BOOL
VAR_INPUT
pParameterStrc: POINTER TO BYTE;
cbParameterStrc: UDINT;
END_VAR

Inputs

Name Type Description


pParameterStrc POINTER TO BYTE Pointer address to the parameter structure that is transferred to
the procedure.
cbParameterStrc UDINT Length of the parameter structure.

Return value

Name Type Description


Execute BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

Uses the stored procedure previously created with FB_SQLDatabaseEvt.CreateSP() [} 192].


VAR
fbSQLStoredProcedure : FB_SQLStoredProcedureEvt(sNetID:='', tTimeout := T#5S);
Customer_ID : LINT;
tcMessage : I_TcMessage;
END_VAR
IF fbSQLStoredProcedure.Execute(pParameterStrc := ADR(Customer_ID) , cbParameterStrc:= SIZEOF(Custom
er_ID)) THEN
IF fbSQLStoredProcedure.bError THEN
tcMessage := fbSQLStoredProcedure.ipTcResult;
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

6.1.1.3.5.2 ExecuteDataReturn
This method sends the call of the specified stored procedure to the database via the database connection
already opened by the function block FB_SQLDatabase. An instance of the FB_SQLResult function block
can be transferred for reading the returned records.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
pParameterStrc: POINTER TO BYTE;
cbParameterStrc: UDINT;
pSQLDBResult: POINTER TO FB_SQLDBResultEvt;
END_VAR

Inputs

Name Type Description


pParameterStrc POINTER TO BYTE
Pointer address to the parameter structure that is transferred to
the procedure.
cbParameterStrc UDINT Length of the parameter structure
pSQLDBResult POINTER TO FB_SQL Returns a new instance of the function block
DBResultEvt FB_SQLDBResultEvt.

TF6420 Version: 1.13.4 203


PLC API

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

Uses the stored procedure previously created with FB_SQLDatabaseEvt.CreateSP() [} 192].


VAR
fbSQLStoredProcedure : FB_SQLStoredProcedureEvt(sNetID:='', tTimeout := T#5S);
Customer_ID : LINT;
tcMessage : I_TcMessage;
END_VAR
IF fbSQLStoredProcedure.ExecuteDataReturn(pParameterStrc := ADR(Customer_ID), cbParameterStrc:= SIZE
OF(Customer_ID), pSQLDBResult := ADR(fbSqlResult)) THEN
IF fbSQLStoredProcedure.bError THEN
tcMessage := fbSQLStoredProcedure.ipTcResult;
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

FB_SQLResultEvt [} 199] can then be used to read the data.

6.1.1.3.5.3 Release
This method releases the parameter information of the stored procedure, which was transferred during
initialization.

Syntax
METHOD Release : BOOL

Return value

Name Type Description


Release BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

204 Version: 1.13.4 TF6420


PLC API

6.1.1.4 NoSQL Expert Mode

6.1.1.4.1 Query Builder


In order to support as many NoSQL databases as possible, there are query function blocks that offer
different parameterizations for queries. These function blocks are then passed as an interface to the
methods of the FB_NoSQLQuery.

6.1.1.4.1.1 FB_NoSQLQueryBuilder_DocumentDB

Function block for defining a query for the database. The query is sent with FB_NoSQLQueryEvt [} 208]. It is
not necessary to call the Build method.

Syntax

Definition:

TF6420 Version: 1.13.4 205


PLC API

FUNCTION BLOCK FB_NoSQLQueryBuilder_DocumentDB


VAR_INPUT
eQueryType : E_DocumentDbQueryType;
sCollectionName : T_MAXSTRING;
pQueryOptions: POINTER TO BYTE;
cbQueryOptions : UDINT;
END_VAR
VAR_OUTPUT
END_VAR

Inputs

Name Type Description


eQueryType E_DocumentDb Type of query sent to the database.
QueryType
[} 233]
sCollectionNa T_ Name of the collection that is the target of the query.
me MAXSTRING
pQueryOption POINTER TO Specifies the address for the query options [} 234].
s BYTE
cbQueryOptio UDINT Length of the query options.
nsr

Methods

Name Definition loca- Description


tion
Build [} 206] Local [optional] This method generates a query for the function block
FB_NoSQLQueryEvt [} 208] from the set parameters.

Sample:
VAR
fbNoSQLQueryBuilder_DocumentDB: FB_NoSQLQueryBuilder_DocumentDB;
sFilter : T_MAXSTRING;
stOptions : T_QueryOptionDocumentDB_Find;
END_VAR
// Set your settings before you run the query
stOptions.pFilter:= ADR(sFilter);
stOptions.cbFilter:= SIZEOF(sFilter);

fbNoSQLQueryBuilder_DocumentDB.eQueryType:=E_DocumentDbQueryType.Find;
fbNoSQLQueryBuilder_DocumentDB.sCollectionName:= 'MyCollectionName';
fbNoSQLQueryBuilder_DocumentDB.pQueryOptions:= ADR(stOptions);
fbNoSQLQueryBuilder_DocumentDB.cbQueryOptions:= SIZEOF(stOptions);

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.4.1.1.1 Build
This method is called automatically in case of a FB_NoSQLQuery [} 208]Evt (either with Execute or
ExecuteDataReturn) before the query is sent. It creates a TwinCAT 3 Database Server-specific query from
the specified parameters of the QueryBuilder.

206 Version: 1.13.4 TF6420


PLC API

6.1.1.4.1.2 FB_NoSQLQueryBuilder_TimeSeriesDB

Function block for defining a query for a TimeSeries database. The query is sent with FB_NoSQLQueryEvt
[} 208]. It is not necessary to call the Build method. Data structures [} 357] can be described with attributes
to affect individual settings.

Inputs

Name Type Description


pQueryOption POINTER TO Specifies the address for the query options [} 236].
s BYTE
cbQueryOptio UDINT Length of the query options.
ns

Syntax

Definition:
FUNCTION BLOCK FB_NoSQLQueryBuilder_TimeSeriesDB
VAR_INPUT
pQueryOptions : POINTER TO BYTE;
cbQueryOptions : UDINT;
END_VAR
VAR_OUTPUT
END_VAR

Methods

Name Definition loca- Description


tion
Build [} 206] Local [optional] This method generates a query for the function block
FB_NoSQLQueryEvt [} 208] from the set parameters.

Example:
VAR
fbNoSQLQueryBuilder_TimeSeriesDB : FB_NoSQLQueryBuilder_TimeSeriesDB;
QueryOption_TSDB_Insert : T_QueryOptionTimeSeriesDB_Insert;
fbNoSqlQueryEvt : FB_NoSQLQueryEvt(sNetID := '', tTimeout := T#15S);
MyStructArray: ARRAY[1..1000] OF MyStruct;
END_VAR
CASE nState OF
1: // init
fbNoSQLQueryBuilder_TimeSeriesDB.pQueryOptions := ADR(QueryOption_TSDB_Insert);
fbNoSQLQueryBuilder_TimeSeriesDB.cbQueryOptions := SIZEOF(QueryOption_TSDB_Insert);

QueryOption_TSDB_Insert.sTableName := 'MeasurementName';
QueryOption_TSDB_Insert.sDataType := 'MyStruct';
QueryOption_TSDB_Insert.pSymbol := ADR(MyStructArray);
QueryOption_TSDB_Insert.cbSymbol := SIZEOF(MyStructArray);
QueryOption_TSDB_Insert.nDataCount := 1000; // ArrayLength
QueryOption_TSDB_Insert.nStartTimestamp := F_GetSystemTime(); // get current twincat time
QueryOption_TSDB_Insert.nCycleTime := 1000; // equivalent to 1 ms

2: // write values
IF fbNoSqlQueryEvt.Execute(dbid, fbNoSQLQueryBuilder_TimeSeriesDB) THEN
IF fbNoSqlQueryEvt.bError THEN
// do some error handling here
ELSE
// success
END_IF
END_IF
END_CASE

TF6420 Version: 1.13.4 207


PLC API

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.4.1.2.1 Build
This method is called automatically in case of a FB_NoSQLQuery [} 208]Evt (either with Execute or
ExecuteDataReturn) before the query is sent. It creates a TwinCAT 3 Database Server-specific query from
the specified parameters of the QueryBuilder.

6.1.1.4.2 FB_NoSQLQueryEvt

Function block for executing NoSQL database queries. A QueryBuilder function block that describes the
query is used as the input parameter for the methods.

Syntax

Definition:
FUNCTION BLOCK FB_NoSQLQueryEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

208 Version: 1.13.4 TF6420


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Methods

Name Definition loca- Description


tion
Execute [} 209] Local Sends the query created by the QueryBuilder function block to
the database.
ExecuteDataReturn Local Sends the query created by the QueryBuilder function block to
[} 210] the database.
An instance of the FB_NoSqlResultEvt [} 211] function block can
be transferred for reading the returned records.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.4.2.1 Execute
This method sends a query to the NoSQL database, which was previously set with the I_NoSQLQueryBuilder
[} 205] function block.

Syntax
METHOD Execute : BOOL
VAR_INPUT
hDBID: UDINT;
iNoSQLQueryBuilder: I_NoSQLQueryBuilder;
END_VAR

Inputs

Name Type Description


hDBID UDINT ID of the set database configuration
iNoSSQLQuery I_NoSQLQueryBuilde Pre-parameterized QueryBuilder function block. This varies
Builder r depending on the database.

Return value

Name Type Description


Execute BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Uses the QueryBuilder to execute the corresponding query.


VAR
fbNoSQLQuery : FB_NoSQLQueryEvt(sNetID := '', tTimeout := T#5S);
fbNoSQLQueryBuilder_DocumentDB: FB_NoSQLQueryBuilder_DocumentDB;
InsertQueryOptions: T_QueryOptionDocumentDB_Insert;
myDBID : UDINT := 1;

TF6420 Version: 1.13.4 209


PLC API

sDocument : STRING(1000);
TcMessage : I_TcMessage;
END_VAR
// set QueryInputs
fbNoSQLQueryBuilder_DocumentDB.eQueryType := E_DocumentDbQueryType.InsertOne;
fbNoSQLQueryBuilder_DocumentDB.pQueryOptions := ADR(InsertQueryOptions);
fbNoSQLQueryBuilder_DocumentDB.cbQueryOptions := SIZEOF(InsertQueryOptions);

// set insert parameter:


sDocument := '{Name : „MyValue“, Value : 123.456}';
InsertQueryOptions.pDocuments:= ADR(sDocument);
InsertQueryOptions.cbDocuments:= SIZEOF(sDocument);

// call nosql command


IF fbNoSQLQuery.Execute(myDBID, fbNoSQLQueryBuilder_DocumentDB) THEN
IF fbNoSQLQuery .bError THEN
TcMessage := fbNoSQLQuery.ipTcResult
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

First, the FB_NoSQLQueryEvt function block is parameterized via the FB_NoSQLQueryBuilder_DocumentDB


[} 205] function block. Depending on the query type there are various options, such as
T_QueryOptionDocumentDB_Insert [} 235], for setting the document to be inserted.

6.1.1.4.2.2 ExecuteDataReturn
This method executes a query to a NoSQL database that was previously set using the
I_NoSQLQueryBuilder function block. The transferred instance of type FB_NoSQLResultEvt is filled with
return values.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
hDBID : UDINT;
iNoSSQLQueryBuilder: I_NoSQLQueryBuilder;
pNoSQLResult: POINTER TO FB_NoSQLResultEvt;
END_VAR

Inputs

Name Type Description


hDBID UDINT ID of the set database configuration
iNoSQLQueryBuil I_NoSQLQueryBuilder Preconfigured QueryBuilder function block that defines
der the query to be sent.
pNoSQLResult POINTER TO Specifies the address for the FB_NoSQLResultEvt
FB_NoSSQLResultEvt function block, which can be used to read the results.

Return value

Name Type Description


ExecuteDataReturn BOOL Displays the status of the method. Returns TRUE as soon
as the method execution is finished, even in the event of an
error.
nDataCount UDINT [optional] Number of records returned

Uses the QueryBuilder to execute the corresponding query.


VAR
fbNoSqlQuery : FB_NoSQLQueryEvt(sNetID := '', tTimeout := T#5S);
fbNoSQLQueryBuilder_DocumentDB: FB_NoSQLQueryBuilder_DocumentDB
FindQueryOptions : T_QueryOptionDocumentDB_Find;
fbNoSqlResult : FB_NoSQLResultEvt(sNetID := '', tTimeout := T#5S);
myDBID : UDINT := 1;

210 Version: 1.13.4 TF6420


PLC API

sFilter : STRING(255);
sSort: STRING(255);
sProjection: STRING(255);
TcMessage : I_TcMessage;
END_VAR
// set QueryInputs:
fbNoSQLQueryBuilder_DocumentDB.eQueryType := E_DocumentDbQueryType.Find;
fbNoSQLQueryBuilder_DocumentDB.pQueryOptions := ADR(FindQueryOptions);
fbNoSQLQueryBuilder_DocumentDB.cbQueryOptions := SIZEOF(FindQueryOptions);

//set Find Parameter ([optional] sort, projection):


sFilter := '{}'; // read all data from database
FindQueryOptions.pFilter:= ADR(sFilter);
FindQueryOptions.cbFilter:= SIZEOF(sFilter);

// call nosql query:


IF fbNoSqlQuery.ExecuteDataReturn(myDBID, fbNoSqlQuery, ADR(fbNoSqlResult)) THEN
IF fbNoSqlQuery.bError THEN
TcMessage := fbNoSqlQuery.ipTcResult;
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

First, the FB_NoSQLQueryEvt function block is parameterized via the FB_NoSQLQueryBuilder_DocumentDB


[} 205] function block. Depending on the query type there are various options, such as
T_QueryOptionDocumentDB_Find [} 234], for defining the filter, sorting or projection.

6.1.1.4.3 FB_NoSQLResultEvt

Function block for reading buffered records.

The records must first be retrieved from the database using the function block FB_NoSQLQueryEvt [} 208]
when the ExecuteDataReturn [} 210] method is called. The function block FB_NoSQLResultEvt is specified
for initialization. They can then be read out either as a PLC structure or as a string.

Syntax

Definition:
FUNCTION BLOCK FB_SQLResultEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

TF6420 Version: 1.13.4 211


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Description


eTraceLevel TcEventSeverity Specifies the weighting of the events. Only events with a weighting
[} 225] higher than this value are sent to the TwinCAT system.
nDataCount UDINT Indicates the number of returned records available from the call of
the function block FB_NoSQLQueryEvt.ExecuteDataReturn() [} 210].

Methods

Name Definition loca- Description


tion
ReadAsString [} 212] Local Reads a specified number of records from the result data
cached in the TwinCAT Database Server as JSON string.
ReadAsStruct [} 213] Local Reads a specified number of records from the result data
cached in the TwinCAT Database Server into the specified
structure.
Release [} 214] Local Releases data buffered by the TwinCAT Database Server.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.4.3.1 ReadAsString
This method reads a specified number of records from the result data cached in the
TwinCAT Database Server. An array of strings is specified into which this data is to be copied as JSON.

Syntax
METHOD ReadAsString : BOOL
VAR_INPUT
nStartIndex: UDINT := 0;
nRecordCount: UDINT := 1;
pData: POINTER TO BYTE;
cbData: UDINT;
nMaxDocumentSize : UDINT;
bDataRelease: BOOL := TRUE;
END_VAR

212 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO BYTE Indicates the address of the string array into which the records
are to be written.
cbData UDINT Indicates the size of the string array in bytes.
nMaxDocumentSi UDINT Indicates the maximum size of a single JSON document from
ze pData.
bDataRelease BOOL Releases the cached data.

Return value

Name Type Description


ReadAsString BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample:
VAR
fbNoSqlResult : FB_NoSQLResultEvt(sNetID := '', tTimeout := T#5S);
aRead_Json : ARRAY[0..2] OF STRING(1000);
TcMessage : I_TcMessage;
END_VAR
IF fbNoSqlResult.ReadAsString(
nStartIndex:= 0,
nRecordCount:= 3,
pData:= ADR(aRead_Json),
cbData:= SIZEOF(aRead_Json),
MaxDocumentSize:= SIZEOF(aRead_Json[0]),
bDataRelease:= TRUE)
THEN
IF fbNoSqlResult.bError THEN
TcMessage := fbNoSqlResult.ipTcResult;
nstate := 255;
ELSE
nstate := nstate+1;
END_IF
END_IF

6.1.1.4.3.2 ReadAsStruct
This method reads a specified number of records from the buffered result data. A structure or an array of a
structure is specified in which the data is to be written. The data type schema of this structure should
correspond as closely as possible to that of the read data. The variable names are compared with those of
the record. A validation makes it possible to detect deviations and respond to them.

If there is a requirement to use different names in the database and in the PLC, the names can be described
in the structure with the attribute 'ElementName' with the assigned name from the database.

Syntax
METHOD ReadAsStruct: BOOL
VAR_INPUT
nStartIndex: UDINT := 0;
nRecordCount: UDINT := 1;
pData: POINTER TO BYTE;
cbData: UDINT;
bValidate: BOOL := FALSE;
pNoSQLValidation : POINTER TO FB_NoSQLValidationEvt;
bDataRelease: BOOL := TRUE;
END_VAR

TF6420 Version: 1.13.4 213


PLC API

Inputs

Name Type Description


nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO BYTEAddress of the structure array into which the records are to be
written.
cbData UDINT Indicates the size of the structure array in bytes.
bValidate BOOL Return data are compared with the pData structure array and
adjusted if necessary.
pNoSQLValidatio POINTER TO Address of the function block FB_NoSQLValidationEvt that
n FB_NoSQLValidationE provides further information for validating the call.
vt
bDataRelease BOOL Releases the cached data.

Return value

Name Type Description


ReadAsStruct BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample:
VAR
fbNoSQLResult: FB_NoSQLResultEvt(sNetID := '', tTimeout := T#5S);
aRead : ARRAY[0..2] OF ST_MyDataStruct;
fbNoSQLValidation : FB_NoSQLValidationEvt(sNetID := '', tTimeout := #5S);
END_VAR
IF fbNoSQLResult.ReadAsStruct(
nStartIndex:= 0,
nRecordCount:= 3,
pData:= ADR(aRead),
cbData:= SIZEOF(aRead),
bValidate:= TRUE,
pNoSQLValidation:= ADR(fbNoSQLValidation),
bDataRelease:= TRUE)
THEN
IF fbNoSQLResult.bError THEN
TcMessage := fbNoSQLResult.ipTcResult;
nstate := 255;
ELSE
nstate := nstate+1;
END_IF
END_IF

6.1.1.4.3.3 Release
This method can be used to release data cached by the TwinCAT Database Server.

Syntax
METHOD Release : BOOL

Return value

Name Type Description


Release BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

214 Version: 1.13.4 TF6420


PLC API

6.1.1.4.4 FB_NoSQLValidationEvt

Function block for reading the validation events and results that occurred when reading the data with
FB_NoSQLResultEvt [} 211]. This function block is initialized via the CreateValidation method of the
NoSQLResult. It refers to the last call of the ReadAsStruct [} 213] method.

Syntax

Definition:
FUNCTION BLOCK FB_NoSQLValidationEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResult Tc3_EventLogger.I_TcMessage [} 224] Message interface from the TwinCAT 3
EventLogger, which provides details on the
return value.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

TF6420 Version: 1.13.4 215


PLC API

Methods

Name Definition loca- Description


tion
GetIssues [} 216] Local Reads a list of validation events as a string array.
GetRemainingData Local Reads the data as a string which could not be assigned to any
[} 217] element in the structure in the PLC.
Release [} 217] Local Releases the buffered data in the TwinCAT Database Server.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.4.4.1 GetIssues
Reads the validation events that occurred into an array of type T_MAXSTRING. These contain information
about remaining or unassigned records or which elements of the PLC structure were not filled.

Syntax
METHOD GetIssues : BOOL
VAR_INPUT
pData : POINTER TO BYTE;
cbData: UDINT;
bDataRelease : BOOL;
END_VAR

Inputs

Name Type Description


pData POINTER TO BYTE Address of the array of type T_MAXSTRING in which the
records are to be written.
cbData UDINT Indicates the size of the string array in bytes.
bDataRelease BOOL Releases the cached data.

Return value

Name Type Description


ReadAsString BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample:
VAR
fbNoSqlValidation : FB_NoSQLValidation(sNetID := '', tTimeout := t#15S);
aIssues : ARRAY[0..1000] OF T_MAXSTRING;
END_VAR
IF fbNoSqlValidation.GetIssues(
pData:= ADR(aIssues),
cbData:= SIZEOF(aIssues),
bDataRelease:= TRUE)
THEN
IF fbNoSqlValidation.bError THEN
TcMessage := fbNoSqlValidation.ipTcResult;
nstate := 255;
ELSE
nstate := nstate+1;
END_IF
END_IF

216 Version: 1.13.4 TF6420


PLC API

6.1.1.4.4.2 GetRemainingData
This method can be used to read the remaining data in JSON format after the validation. This includes
records which could not be assigned to the PLC structure, for example.

Syntax
METHOD GetRemainingData : BOOL
VAR_INPUT
pData : POINTER TO BYTE;
cbData : UDINT;
cbDocument : UDINT;
bDataRelease : BOOL;
END_VAR

Inputs

Name Type Description


pData POINTER TO BYTE Indicates the address of the string array into which the records
are to be written.
cbData UDINT Indicates the size of the string array in bytes.
cbDocument UDINT Specifies the length of the string in the array.
bDataRelease BOOL Releases the cached data.

Return value

Name Type Description


GetRemainingDat BOOL Displays the status of the method. Returns TRUE as soon as the
a method execution is finished, even in the event of an error.

Sample:
VAR CONSTANT
cDocumentSize : UDINT := 1000;
END_VAR
VAR
fbNoSqlValidation : FB_NoSQLValidation(sNetID := '', tTimeout := t#15S);
aRemainingData : ARRAY[0..1000] OF STRING(cDocumentSize);
END_VAR
IF fbNoSqlValidation.GetRemainingData(
pData:= ADR(aRemainingData),
cbData:= SIZEOF(aRemainingData),
cbDocument:= cDocumentSize,
bDataRelease:= TRUE)
THEN
IF fbNoSqlValidation.bError THEN
TcMessage := fbNoSqlValidation.ipTcResult;
nstate := 255;
ELSE
nstate := nstate+1;
END_IF
END_IF

6.1.1.4.4.3 Release
Releases the validation results in the memory.

Syntax
METHOD Release : BOOL

TF6420 Version: 1.13.4 217


PLC API

Return value

Name Type Description


Release BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

6.1.1.4.5 Helper
These function blocks offer useful functions for dealing with data types, for example.

6.1.1.4.5.1 FB_NoSQLObjectId_MongoDB

The function block for parsing the ObjectId from the MongoDB. In the PLC it is described by the data type
T_ObjectId_MongoDB [} 233].

Syntax
FUNCTION_BLOCK FB_NoSQLObjectId_MongoDB
VAR_INPUT
ObjectId : T_ObjectId_MongoDB;
END_VAR

Inputs

Name Type Description


ObjectId T_ObjectId_Mongo 12-byte data type for describing the ObjectId.
DB

Properties

Name Type Description


eTraceLevel TcEventSeverity Specifies the weighting of the events. Only events with a weighting
higher than this value are sent to the TwinCAT system.
nId UDINT Non-unique, sequential number
nMachineId UDINT Identification of the machine
nProcessId UINT Identification of the writing process
tTimestamp DATE_AND_TIME Time stamp of the record

Methods

Name Definition loca- Return value Description


tion
ToString Local STRING(36) Returns the ID as a string with type
designation.
Example:
‚ObjectId(„5be15c11afa6ec72b107dafaf“)‘
ValueOf Local STRING(24) Returns only the ID as a string.
Example: ‚5be15c11afa6ec72b107dafaf‘

218 Version: 1.13.4 TF6420


PLC API

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.1.5 Support of the Tc3_Eventlogger


The TwinCAT 3 Database Server supports the TwinCAT 3 EventLogger (TwinCAT 3 Version 4022.20). This
makes it possible to read out details of function block events via an interface. Further information on the
EventLogger can be found in the TwinCAT 3 basic libraries.

All function blocks of the TwinCAT 3 Database Server support the interface of the Tc3 EventLogger. The
interface Tc3_Eventlogger.I_TcMessage [} 224] is used as the return value of the function blocks. In addition
to the return value, the eTraceLevel property is available to determine the event weighting.

Properties

Name Type Access Description


eTraceLe TcEventSev Get, Set Specifies the weighting of the events.
vel erity Only events with a weighting higher than
this value are sent to the TwinCAT
[} 225]
system.

Sample:

As an example, the following weighting is specified for the function block FB_PLCDBWrite:
fbPLCDBWriteEvt.eTraceLevel := TcEventSeverity.Warning;

All events that represent at least a warning are now sent here. Events of the "Information" weighting are
ignored in this case.

The Tc3_Database function blocks themselves have the output ipTcResult of data type
Tc3_Eventlogger.I_TcMessage. All functions of this interface that are offered can be used.

In this sample, the function block is called first.


1: // Call Functionblock
IF fbPLCDBWriteEvt.WriteStruct(
hDBID:= 1,
sTableName:= 'myTable_Struct',
pRecord:= ADR(myRecord),
cbRecord:= SIZEOF(myRecord),
pColumnNames:= ADR(ColumnNames) ,
cbColumnNames:= SIZEOF(ColumnNames))
THEN
IF fbPLCDBWriteEvt.bError THEN
myTcMessage := fbPLCDBWriteEvt.ipTcResult
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

If an error occurs, we now want to request the event text in the runtime environment. The RequestEventText
method can be used for this purpose. Use nLangId =1031 to read the error code in German. This is one of
the many functions of the Tc3_Eventlogger.I_TcMessage [} 224] interface.
255://Request EventText
IF myTcMessage.RequestEventText(1031,
ADR(MyEventString),
SIZEOF(MyEventString))THEN
nState := 0;
END_IF

TF6420 Version: 1.13.4 219


PLC API

6.1.1.5.1 I_TcEventBase
Methods and properties of an event are defined in this basic interface.

Methods

Name Description
EqualsTo [} 220] Compares the event with another instance.
EqualsToEventClass [} 221] Compares the event class of the event with another event class.
EqualsToEventEntryEx Compares the event definition of the event with another event definition.
[} 222]
GetJsonAttribute [} 222] Returns the Json attribute.
RequestEventClassName Requests the name of the event class.
[} 223]
RequestEventText [} 224] Returns the text for the event.

Properties

Name Type Access Description


eSeverity TcEventSeverity Get Returns the severity.
[} 225]
EventClass GUID Get Returns the GUID of the event
class.
ipSourceInfo I_TcSourceInfo Get Returns a pointer to the source
definition.
nEventId UDINT Get Returns the ID of the event.
stEventEntry TcEventEntry Get Returns the event definition.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1.4022.20 PC or CX (x64, x86, ARM) Tc3_EventLogger

6.1.1.5.1.1 EqualsTo

This method carries out a comparison with another event specified at the input.

Syntax
METHOD EqualsTo : BOOL
VAR_INPUT
ipOther : I_TcEventBase;
END_VAR

Inputs

Name Type Description


ipOther I_TcEventBase Event to be compared

220 Version: 1.13.4 TF6420


PLC API

Return value

Name Type Description


EqualsTo BOOL Returns TRUE if the events match.

6.1.1.5.1.2 EqualsToEventClass

This method carries out a comparison with another event class specified at the input.

Syntax
METHOD EqualsToEventClass : BOOL
VAR_INPUT
OtherEventClass : GUID
END_VAR

Inputs

Name Type Description


OtherEventClass GUID Event class to be compared.

Return value

Name Type Description


EqualsToEventClass BOOL Returns TRUE if the event classes match.

6.1.1.5.1.3 EqualsToEventEntry

This method carries out a comparison with another event specified at the input.

Syntax
METHOD EqualsToEventEntry : BOOL
VAR_INPUT
OtherEventClass : GUID;
nOtherEventID : UDINT;
eOtherSeverity : TcEventSeverity;
END_VAR

Inputs

Name Type Description


OtherEventClass GUID Event class of the event to be compared.
nOtherEventID UDINT Event ID of the event to be compared.
eOtherSeverity TcEventSeverity Event severity of the event to be compared.

TF6420 Version: 1.13.4 221


PLC API

Return value

Name Type Description


EqualsToEventEntry BOOL Returns TRUE if the events match.

6.1.1.5.1.4 EqualsToEventEntryEx

This method carries out a comparison with another event specified at the input.

Syntax
METHOD EqualsToEventEntryEx : BOOL
VAR_INPUT
stOther : TcEventEntry;
END_VAR

Inputs

Name Type Description


stOther TcEventEntry Event to be compared.

Return value

Name Type Description


EqualsToEventEntryEx BOOL Returns TRUE if the events match.

6.1.1.5.1.5 GetJsonAttribute

This method returns the Json attribute.

Syntax
METHOD GetJsonAttribute : HRESULT
VAR_INPUT
sJsonAttribute : REFERENCE TO STRING;
nJsonAttribute : UDINT;
END_VAR

Inputs

Name Type Description


sJsonAttribute REFERENCE TO STRING Reference to a variable of the type String
nJsonAttribute UDINT Length of the String variable

222 Version: 1.13.4 TF6420


PLC API

Return value

Name Type Description


GetJsonAttribute HRESULT Returns S_OK if the method call was successful.
Returns ERROR_BAD_LENGTH if the length of the variable is too
small.
Otherwise HRESULT is returned as error code.

6.1.1.5.1.6 RequestEventClassName

This method returns the name of the event class.

Syntax
METHOD RequestEventClassName : BOOL
VAR_INPUT
nLangId : DINT;
sResult : REFERENCE TO STRING;
nResultSize : UDINT;
END_VAR
VAR_OUTPUT
bError : BOOL;
hrErrorCode : HRESULT;
END_VAR

Inputs

Name Type Description


nLangId DINT Specifies the language ID
English (en-US) = 1033
German (de-DE) = 1031

sResult REFERENCE TO STRING Reference to a variable of the type String
nResultSize UDINT Size of the String variable in bytes

Return value

Name Type Description


RequestEventClassName BOOL Returns TRUE as soon as the request has been terminated.
Returns FALSE if the asynchronous request is still active. The
method must be called until the return value is TRUE.

Outputs

Name Type Description


bError BOOL Returns FALSE if the method call was successful. Returns TRUE if
an error has occurred.
hrErrorCode HRESULT Returns S_OK if the method call was successful. An error code is
output in case of an error.

TF6420 Version: 1.13.4 223


PLC API

6.1.1.5.1.7 RequestEventText

This method returns the event text.

Syntax
METHOD RequestEventText : BOOL
VAR_INPUT
nLangId : DINT;
sResult : REFERENCE TO STRING;
nResultSize : UDINT;
END_VAR
VAR_OUTPUT
bError : BOOL;
hrErrorCode : HRESULT;
END_VAR

Inputs

Name Type Description


nLangId DINT Specifies the language ID
English (en-US) = 1033
German (de-DE) = 1031

sResult REFERENCE TO STRING Reference to a variable of the type String
nResultSize UDINT Size of the String variable in bytes

Return value

Name Type Description


RequestEventText BOOL Returns TRUE as soon as the request has been terminated.
Returns FALSE if the asynchronous request is still active. The
method must be called until the return value is TRUE.

Outputs

Name Type Description


bError BOOL Returns FALSE if the method call was successful. Returns TRUE if
an error has occurred.
hrErrorCode HRESULT Returns S_OK if the method call was successful. An error code is
output in case of an error.

6.1.1.5.2 I_TcMessage
This interface provides methods and properties for the message handling.

Inheritance hierarchy

I_TcEventBase [} 220]

I_TcMessage

224 Version: 1.13.4 TF6420


PLC API

Methods

Name Description
Send [} 225] Sends a message

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1.4022.20 PC or CX (x64, x86, ARM) Tc3_EventLogger

6.1.1.5.2.1 Send

This method sends the message.

Syntax
METHOD Send : HRESULT
VAR_INPUT
nTimeStamp: ULINT;
END_VAR

Inputs

Name Type Description


nTimeStamp ULINT 0: Current time stamp is used
> 0: External time stamp in 100 nanoseconds since January 1st,
1601 (UTC).

Return value

Name Type Description


Send FB_ HRESULT Returns S_OK if the method call was successful, otherwise
HRESULT as error code

6.1.1.5.3 Data types

6.1.1.5.3.1 TcEventSeverity
Defines the severity of the event.

Syntax

Definition:
{attribute 'qualified_only'}
TYPE TcEventSeverity : (
Verbose := 0,
Info := 1,
Warning := 2,
Error := 3,
Critical := 4);
END_TYPE

TF6420 Version: 1.13.4 225


PLC API

6.1.2 Data types

6.1.2.1 Config

6.1.2.1.1 E_DatabaseType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_DatabaseType :
(
MS_Compact_SQL := 0,
MS_Access := 1,
MS_SQL := 2,
ASCII := 3,
ODBC_MySQL := 4,
ODBC_PostgreSQL := 5,
ODBC_Oracle := 6,
ODBC_DB2 := 7,
ODBC_InterBase := 8,
ODBC_Firebird := 9,
XML := 10,
OCI_Oracle := 11,
NET_MySQL := 12,
AzureSQL := 13,
MS_Excel := 14,
AS400ISeries := 15,
OleDB_Database := 16,
Odbc_Database := 17,
SQLite:=18,
ODP_Oracle := 19
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.2 E_DBAuthentication

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_DBAuthentication:
(
None:= 0,
UserNamePassword := 1,
x509Cert := 2,
GSSAPI := 3,
LDAP := 4
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

226 Version: 1.13.4 TF6420


PLC API

6.1.2.1.3 E_OdbcSubType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_OdbcSubType:
(
Unknown:= 0,
MySQL := 1,
Oracle := 2,
Postgre := 3,
DB2 := 4
Firebird := 5
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.4 E_TcDBSrvConfigType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_TcDBSrvConfigType :
(
Database := 0,
AutoLogGroup := 1,
DBSrvSettings := 2,
Symbol := 3,
ADSDevice := 4,
Table := 5,
SymbolList := 6
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.5 ST_ConfigAutoLogGrp
This structure is used for the Read method of the function block FB_ConfigTcDBSrvEvt [} 156]. All configured
AutoLog groups are read into the PLC in an array of this structure.

Syntax

Definition:
TYPE ST_ConfigAutoLogGrp :
STRUCT
sName: T_MaxString;
hAutoLogGrpID: UDINT;
hDBID: UDINT;
sTableName: T_MaxString;
stADSDev: ST_ADSDevice;
eWriteMode: E_WriteMode;
nCycleTime: TIME;
nSymbolCount: UDINT;
END_STRUCT
END_TYPE

TF6420 Version: 1.13.4 227


PLC API

Parameter

Name Type Description


sName T_MaxString Group name
hAutoLogGrpID UDINT ID of the declared AutoLog group
hDBID UDINT ID of the assigned database
sTableName T_MaxString Table name
stADSDev ST_ADSDevice [} 242] ADS device information
eWriteMode E_WriteMode [} 242] Write mode
nCycleTime TIME Cycle time
nSymbolCount UDINT Number of symbols

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.6 ST_ConfigDB
This structure is used for the Read method of the function block FB_ConfigTcDBSrvEvt [} 156]. All configured
database connections are read into the PLC in an array of this structure.

Syntax

Definition:
TYPE ST_ConfigDB :
STRUCT
sName: T_MaxString;
hDBID: DINT;
eDBType: E_DatabaseType;
sServer: STRING(80);
sDatabase: STRING(80);
bTemp: BOOL;
END_STRUCT
END_TYPE

Name Type Parameter


sName T_MaxString Connection name
hDBID DINT ID of the declared database
eDBType E_DatabaseType Database type
[} 226]
sServer STRING (80) Server name
sDatabase STRING (80) Database name
bTemp BOOL TRUE if the connection was only stored temporarily.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.7 ST_ConnStringParameter

Syntax

Definition:
TYPE ST_ConnStringParameter
STRUCT
sName: T_MaxString;

228 Version: 1.13.4 TF6420


PLC API

sValue: T_MaxString;
END_STRUCT
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8 ConfigType
Different database configuration structures are provided for the supported database types.

6.1.2.1.8.1 T_DBConfig_ASCII
Describes the database configuration structure for the ASCII file.

Syntax

Definition:
TYPE T_DBConfig_ASCII
STRUCT
sServer: T_MaxString;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Path to the ASCII file

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.2 T_DBConfig_MSAccess
Describes the database configuration structure for a Microsoft Access database.

Syntax

Definition:
TYPE T_DBConfig_MSAccess
STRUCT
sServer: T_MaxString;
sProvider: T_MaxString;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Path to the Access databases
sProvider T_MaxString Access 2000 – Access 2003: "Microsoft.Jet.OLEDB.4.0"
Access 2007: "Microsoft.ACE.OLEDB.12.0"

TF6420 Version: 1.13.4 229


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.3 T_DBConfig_MsCompactSQL
Describes the database configuration structure for a Microsoft Compact SQL database.

Syntax

Definition:
TYPE T_DBConfig_MsCompactSQL
STRUCT
sServer: T_MaxString;
sPassword: T_MaxString;
bAuthentification: BOOL;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Path to the Microsoft Compact SQL file (*.sdf)
sPassword T_MaxString Password for the database
bAuthentification BOOL TRUE if the database is password-protected.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.4 T_DBConfig_MsExcel
Describes the database configuration structure for a Microsoft Excel file.

Syntax

Definition:
TYPE T_DBConfig_MsExcel
STRUCT
sServer: T_MaxString;
sProvider: T_MaxString;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Path to the Microsoft Excel file
sProvider T_MaxString "Microsoft.Jet.OLEDB.4.0" or "Microsoft.ACE.OLEDB.12.0"

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.5 T_DBConfig_MsSQL
Describes the database configuration structure for a Microsoft SQL database.

230 Version: 1.13.4 TF6420


PLC API

Syntax

Definition:
TYPE T_DBConfig_MsSQL
STRUCT
sServer: T_MaxString;
sProvider: T_MaxString;
sDatabase: T_MaxString;
sUserID: T_MaxString;
sPassword: T_MaxString;
bAuthentification: BOOL;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Enter the name of your SQL server here.
Example: "TESTSERVER\SQLEXPRESS"
sProvider T_MaxString "SQLOLEDB" or the provider of the SQL native client, e.g.
"SQLNCLI10"
Database T_MaxString Enter the desired database name here.
sUserID T_MaxString Enter the user name here.
sPassword T_MaxString Enter the user password here.
bAuthentification BOOL Set this variable to TRUE to activate authentication based on user
ID and password.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.6 T_DBConfig_Odbc
Describes the database configuration structure for a database with ODBC interface.

Syntax

Definition:
TYPE T_DBConfig_NET_MySQL
STRUCT
eOdbcSubType: E_OdbcSubType
nParameterCount: UINT;
arrParameter: ARRAY [0..MAX_CONFIGPARAMETER] OF ST_ConnStringParameter;
END_STRUCT
END_TYPE

Parameter

Name Type Description


eOdbcSubType E_OdbcSubType [} 227] Describes an ODBC database [} 227]
that is supported with full functionality.
nParameterCount UINT Number of parameters for the
connection strings
arrParameter ARRAY [0..MAX_CONFIGPARAMETER] OF Array of parameters for the connection
ST_ConnStringParameter [} 228]; string of type ST_ConnStringParameter
[} 228].

TF6420 Version: 1.13.4 231


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.7 T_DBConfig_SQLite
Describes the database configuration structure for an SQLite database.

Syntax

Definition:
TYPE T_DBConfig_SQLite
STRUCT
sServer: T_MaxString;
sPassword: T_MaxString;
bAuthentification: BOOL;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Path to the SQLite file
sPassword T_MaxString Password for the database
bAuthentification BOOL TRUE if the database is password-protected.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.1.8.8 T_DBConfig_XML
Describes the database configuration structure for an XML file in the customized database format.

Syntax

Definition:
TYPE T_DBConfig_XML
STRUCT
sServer: T_MaxString;
sSchema: T_MaxString;
sDatabase: T_MaxString;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sServer T_MaxString Name and path of the XML file
sSchema T_MaxString Name and path of the XSD file
sDatabase T_MaxString Describes the name of the database. The XML, XSD and XSL files
are created automatically for this database type.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

232 Version: 1.13.4 TF6420


PLC API

6.1.2.2 NoSQL

6.1.2.2.1 E_NoSQLDatabaseType

Syntax
{attribute 'qualified_only'}
TYPE E_NoSQLDatabaseType :
(
UnknownType := 0,
DocumentDB := 1,
Binary := 2,
TimeSeriesDB := 3
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.2.2 E_DocumentDBQueryType

Syntax
{attribute 'qualified_only'}
TYPE E_DocumentDbQueryType :
(
InsertOne := 1,
InsertMany := 2,
UpdateOne := 3,
UpdateMany := 4 ,
Find := 5,
Aggregation := 6,
Delete := 7,
DeleteMany := 8,
CreateCollection := 9,
DropCollection := 10
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.2.3 T_ObjectId_MongoDB
A data type that maps the database-specific "ObjectId" data type. It consists of 12 bytes with different
meanings:

Table 1: ObjectId at byte level

1 2 3 4 5 6 7 8 9 10 11 12
Timestamp MachineId ProcessId Id

The function block FB_NoSQLObjecId_MongoDB [} 218] is available for parsing out the individual elements.

Syntax
TYPE T_ObjectId_MongoDB : ARRAY[0..11] OF BYTE;
END_TYPE

TF6420 Version: 1.13.4 233


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.2.4 QueryOptions

6.1.2.2.4.1 DocumentDB

6.1.2.2.4.1.1 T_QueryOptionDocumentDB_Find

Syntax

Definition:
TYPE T_QueryOptionDocumentDB_Find
STRUCT
pFilter: POINTER TO BYTE;
cbFilter: UDINT;
pSort: POINTER TO BYTE;
cbSort: UDINT;
pProjection: POINTER TO BYTE;
cbProjection: UDINT;
END_STRUCT
END_TYPE

Parameter

Name Type Description


pFilter POINTER TO Specifies the address of the search filter based on which the
BYTE collection is to be searched.
cbFilter UDINT Length of the search filter.
pSort POINTER TO Specifies the sort address based on which the collection is to be
BYTE sorted.
cbSort UDINT Length of sorting
pProjection POINTER TO Specifies the address of the display and how the collection data is
BYTE to be displayed.
cbProjection UDINT Length of the display.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.4.1.2 T_QueryOptionDocumentDB_Aggregate

Syntax

Definition:
TYPE T_QueryOptionDocumentDB_Aggregate
STRUCT
pPipeStages: POINTER TO BYTE;
cbPipeStages: UDINT;
END_STRUCT
END_TYPE

234 Version: 1.13.4 TF6420


PLC API

Parameter

Name Type Description


pPipeStages POINTER TO Specifies the address of the stage document. Several stages can
BYTE be defined in this.
cbPipeStages UDINT Length of the stage document.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.4.1.3 T_QueryOptionDocumentDB_Insert

Syntax

Definition:
TYPE T_QueryOptionDocumentDB_Insert
STRUCT
pDocuments: POINTER TO BYTE;
cbDocuments: UDINT;
END_STRUCT
END_TYPE

Parameter

Name Type Description


pDocuments POINTER TO Specifies the address of one or more documents to add to a
BYTE collection.
cbDocuments UDINT Length of the document.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.4.1.4 T_QueryOptionDocumentDB_Update

Syntax

Definition:
TYPE T_QueryOptionDocumentDB_Update
STRUCT
pFilter: POINTER TO BYTE;
cbFilter: UDINT;
pDocuments: POINTER TO BYTE;
cbDocuments: UDINT;
END_STRUCT
END_TYPE

Parameter

Name Type Description


pFilter POINTER TO Specifies the address of the search filter based on which the
BYTE collection is to be searched.
cbFilter UDINT Length of the search filter.
pDocuments POINTER TO Specifies the address of the documents whose values are to be
BYTE transferred to the collection.
cbDocuments UDINT Length of the documents

TF6420 Version: 1.13.4 235


PLC API

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.4.1.5 T_QueryOptionDocumentDB_Delete

Syntax

Definition:
TYPE T_QueryOptionDocumentDB_Delete
STRUCT
pFilter: POINTER TO BYTE;
cbFilter: UDINT;
END_STRUCT
END_TYPE

Parameter

Name Type Description


pFilter POINTER TO Specifies the address of the search filter based on which the
BYTE collection is to be searched.
cbFilter UDINT Length of the search filter.

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.4.2 TimeSeriesDB

6.1.2.2.4.2.1 T_QueryOptionTimeSeriesDB_Insert
This structure is used to write data to a time series database. An array of a structure can be specified as a
symbol. Each individual array element is mapped as a row with a unique timestamp in the database. The
timestamps of the individual series are generated by specifying a start timestamp and the time cycle
between the data sets.

Syntax

Definition:
TYPE T_QueryOptionTimeSeriesDB_Insert
STRUCT
pSymbol : PVOID;
cbSymbol : UDINT;
sDataType : STRING;
nDataCount : UDINT := 1;
sTableName : T_MaxString;
nCycleTime : UDINT := 100000;
nStartTimestamp : ULINT := 0;
END_STRUCT
END_TYPE

236 Version: 1.13.4 TF6420


PLC API

Parameter

Name Type Description


pSymbol POINTER TO Pointer to the symbol that is to be written to the database
BYTE
cbSymbol UDINT Length of the specified symbol pointer
sDataType STRING (Simple) type designation of the specified symbol
nDataCount UDINT Number of data sets in the transferred array symbol
sTableName T_MaxString Name of the table or table equivalent
nCycleTime UDINT Time interval of the cyclic data sets
nStartTimestamp ULINT Time stamp of the first data set in TwinCAT time: Number of 100
ns intervals since January 1, 1601.
Further: Reading the current TwinCAT time

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.4.2.2 T_QueryOptionTimeSeriesDB_Query
This structure is used to read data from a time series database. The query is passed as a string and can
then be passed to the FB_NoSQLQueryBuilder_TimeSeriesDB [} 207].

Syntax

Definition:
TYPE T_QueryOptionDocumentDB_Find
STRUCT
pQuery: POINTER TO BYTE;
cbQuery: UDINT;
END_STRUCT
END_TYPE

Parameter

Name Type Description


pQuery POINTER TO Specifies the pointer to the query (string)
BYTE
cbQuery UDINT Specifies the length of the query pointer

Requirements

Development environment Target platform PLC libraries to include


TwinCAT v3.1 Build 4022.20 PC or CX (x86) Tc3_Database

6.1.2.2.5 E_TimeSeriesDbQueryType

Syntax
{attribute 'qualified_only'}
TYPE E_ TimeSeriesDbQueryType:
(
Insert := 1,
Query := 2
);
END_TYPE

TF6420 Version: 1.13.4 237


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.3 SQL

6.1.2.3.1 E_ColumnType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_ColumnType :
(
BigInt := 0,
Integer := 1,
SmallInt := 2,
TinyInt := 3,
BIT_ := 4,
Money := 5,
Float := 6,
REAL_ := 7,
DateTime := 8,
NText := 9,
NChar := 10,
Image := 11,
NVarChar := 12,
Binary := 13,
VarBinary := 14
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.3.2 E_SPParameterType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_SPParameterType :
(
Input := 0,
Output := 1,
InputOutput := 2,
ReturnValue := 3,
OracleCursor := 4
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.3.3 E_VerifyResult

Syntax

Definition:

238 Version: 1.13.4 TF6420


PLC API

{attribute 'qualified_only'}
TYPE E_VerifyResult:
(
check_None:= 0,
check_OK := 1,
check_Error:= 2,
check_TypeWarning:= 3,
check_TypeError := 4,
check_DataLengthWarning := 5,
check_DataLengthError := 6
);
END_TYPE

Values

Name Description
check_None PLC structure is not verified.
check_OK No differences between PLC structure and database table structure
check_TypeWarning Different data types with regard to the sign between PLC and database data
types, e.g. UINT <> INT
check_TypeError Different data types with regard to the sign between PLC structure and
database table structure
check_DataLengthWarning Different length between PLC structure and database table structure. The
record can nevertheless be mapped, although data may be lost.
check_DataLengthError Different length between PLC structure and database table structure. The
record cannot be mapped.

6.1.2.3.4 ST_SQLSPParameter
This structure is required for the function block FB_SQLStoredProcedureEvt [} 201] to describe the different
parameters of the procedure to be executed.

Syntax

Definition:
TYPE ST_SQLSPParameter :
STRUCT
eParameterType: E_SPParameterType;
eParameterDataType: E_ColumnType;
nParameterSize: UDINT;
sParameterName: STRING(50);
END_STRUCT
END_TYPE

Name Type Description


eParameterType E_SPParameterType [} 238] Parameter type (INPUT,
OUTPUT ..)
eParameterDataType E_ColumnType [} 238] Parameter type
nParameterSize UDINT Parameter length
sParameterName STRING (50) Parameter name

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

TF6420 Version: 1.13.4 239


PLC API

6.1.2.4 PLC

6.1.2.4.1 E_ADSRdWrtMode

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_ADSRdWrtMode :
(
bySymbolName := 1,
IGroup_IOffset := 2
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.2 E_ErrorType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_ErrorType :
(
noError := 0,
InternalError,
DataBaseError,
ADSError
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.3 E_ExpParameterType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_ExpParameterType :
(
NULL := 0,
Boolean := 1,
Byte_ := 2,
Int16 := 3,
Int32 := 4,
Int64 := 5,
UInt16 := 6,
UInt32 := 7,
UInt64 := 8,
DateTime := 9,
Float32 := 10,
Double64 := 11,
STRING_ := 12,
ByteArray := 13,
Struct_ := 14,
XMLTAGName := 15
);
END_TYPE

240 Version: 1.13.4 TF6420


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.4 E_OrderColumn

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_OrderColumn :
(
ID := 0,
Timestamp := 1,
Name := 2,
Value := 3
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.5 E_OrderType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_OrderType :
(
ASC := 0,
DESC := 1
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.6 E_PLCDataType

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_PLCDataType :
(
eType_BOOL := 0,
eType_BYTE := 1,
eType_SINT := 2,
eType_INT := 3,
eType_DINT := 4,
eType_UINT := 5,
eType_UDINT := 6,
eType_WORD := 7,
eType_DWORD := 8,
eType_LREAL := 9,
eType_REAL := 10,
eType_LINT := 11,
eType_ULINT := 12,

TF6420 Version: 1.13.4 241


PLC API

eType_BigType := 13
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.7 E_WriteMode

Syntax

Definition:
{attribute 'qualified_only'}
TYPE E_WriteMode :
(
eADS_TO_DB_Update := 0,
eADS_TO_DB_Append := 1,
eADS_TO_DB_RingBuff_Time := 2,
eADS_TO_DB_RingBuff_Count := 3
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.8 ST_ADSDevice
Describes the ADS device, which has to be specified for methods of the function block FB_PLCDBWriteEvt
[} 178].

Syntax

Definition:
TYPE ST_ADSDevice :
STRUCT
sDevNetID: T_AmsNetId;
nDevPort: T_AmsPort;
eADSRdWrtMode: E_ADSRdWrtMode;
tTimeout: TIME;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sDevNetID T_AmsNetId NetID of the ADS device
nDevPort T_AmsPort AMS Port
eADSRdWrtMod E_ADSRdWrtMode Connection mode IGroup_IOffset / bySymbol
e [} 240]
tTimeout TIME ADS connection timeout

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

242 Version: 1.13.4 TF6420


PLC API

6.1.2.4.9 ST_AutoLogGrpStatus
Provides information about the respective AutoLog group.

Syntax

Definition:
TYPE ST_AutoLogGrpStatus :
STRUCT
hAutoLogGrpID: UDINT;
nCycleCount: UDINT;
hrErrorCode: HRESULT;
eErrorType: E_ErrorType;
bError: BOOL;
END_STRUCT
END_TYPE

Parameter

Parameter

Name Type Description


hAutoLogGrpID UDINT ID of the declared AutoLog group
nCycleCount UDINT Number of executed cycles
hrErrorCode HRESULT HRESULT error code
eErrorType E_ErrorType Error type
[} 240]
bError BOOL TRUE if an error has occurred.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.10 ST_ColumnInfo

Syntax

Definition:
TYPE ST_ColumnInfo :
STRUCT
sName: STRING(50);
sProperty: STRING;
nLength: UDINT;
eType: E_ColumnType;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sName STRING (50) Name of the column
sProperty STRING String for additional column properties
nLength UDINT Maximum length (for strings and byte streams)
eType E_ColumnType Column type
[} 238]

TF6420 Version: 1.13.4 243


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.11 ST_ExpParameter
This structure is required for the function block FB_PLCCmd [} 183], for making the description of the different
parameters (placeholders) available in the SQL command.

Syntax

Definition:
TYPE ST_ExpParameter:
STRUCT
sParaName : T_MaxString;
nParaSize : UDINT;
eParaType : E_ExpParameterType;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sParaName T_MaxString Name of the parameter (placeholder)
nParaSize UDINT Length of the parameter value
eParaType E_ExpParameterTy Data type of the parameter
pe [} 240]

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.12 ST_StandardRecord
This structure can be used in the PLC if you want to work with the standard table structure of the TwinCAT
Database Server.

This structure cannot be used with Microsoft Access databases, since this database type does not support
the 64-bit integer data type. In this case the structure ST_StandardRecord_MSAccess [} 245] should be used.

Syntax

Definition:
TYPE ST_StandardRecord :
STRUCT
nID: LINT;
dtTimestamp: DT;
sName: STRING(80);
rValue: LREAL;
END_STRUCT
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

244 Version: 1.13.4 TF6420


PLC API

6.1.2.4.13 ST_StandardRecord_MSAccess
This structure can be used in the PLC if you want to work with the standard table structure of the TwinCAT
Database Server. This structure is specifically intended for Microsoft Access databases, since this database
type does not support the 64-bit integer data type.

Syntax

Definition:
TYPE ST_StandardRecord_MSAccess:
STRUCT
nID: DINT;
dtTimestamp: DT;
sName: STRING(80);
rValue: LREAL;
END_STRUCT
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.2.4.14 ST_Symbol
Describes the ADS symbol, which has to be specified for methods of the function block FB_PLCDBWriteEvt
[} 178].

Syntax

Definition:
TYPE ST_Symbol :
STRUCT
sSymbolName: T_MaxString;
sDBSymbolName: T_MaxString;
nIGroup: UDINT;
nIOffset: UDINT;
nBitSize: UDINT;
eDataType: E_PLCDataType;
END_STRUCT
END_TYPE

Parameter

Name Type Description


sSymbolName T_MaxString Symbol name
sDBSymbolName T_MaxString Name to be written to the database.
nIGroup UDINT Index Group (only for ADSRdWrtMode
"eADSMode_IGroup_IOffset")
nIOffset UDINT Index Offset (only for ADSRdWrtMode
"eADSMode_IGroup_IOffset")
nBitSize UDINT Length in bits (only for ADSRdWrtMode
"eADSMode_IGroup_IOffset")
eDataType E_PLCDataType Data type (only for ADSRdWrtMode
[} 241] "eADSMode_IGroup_IOffset")

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

TF6420 Version: 1.13.4 245


PLC API

6.1.3 Global constants

6.1.3.1 Constants

VAR_GLOBAL CONSTANT GVL


AMSPORT_DBSRV : UINT := 21372;
MAX_DBCONNECTIONS : UDINT := 255;
MAX_DBCOLUMNS : UDINT := 255;
MAX_SPPARAMETER : UDINT := 255;
MAX_CONFIGURATIONS : UDINT := 255;
MAX_RECORDS : UDINT := 255;

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4 Obsolete

6.1.4.1 Configure mode

6.1.4.1.1 FB_ConfigTcDBSrv

Function block for creating, reading and deleting configuration entries for the TwinCAT Database Server.

Syntax

Definition:
FUNCTION_BLOCK FB_ConfigTcDBSrv
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on
the return value.

246 Version: 1.13.4 TF6420


PLC API

Methods

Name Definition loca- Description


tion
Create [} 157] Local Creates new entries in the XML configuration file for the
TwinCAT Database Server
Read [} 158] Local Reads the current configuration of the TwinCAT Database Server
Delete [} 159] Local Deletes the database and AutoLog groups from the configuration
of the TwinCAT Database Server

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.1.1.1 Create
This method creates new entries in the XML configuration file for the TwinCAT Database Server. Optionally
the TwinCAT Database Server can use a new entry on a temporary basis. In this case no data is written to
the XML file.

Syntax
METHOD Create : BOOL
VAR_INPUT
pTcDBSrvConfig: POINTER TO BYTE;
cbTcDBSrvConfig: UDINT;
bTemporary: BOOL := TRUE;
pConfigID: POINTER TO UDINT;
END_VAR

Inputs

Name Type Description


pTcDBSrvConfig POINTER TO BYTE Pointer of the configuration structure to be created.
cbTcDBSrvConfig UDINT Length of the configuration structure
bTemporary BOOL Indicates whether the configuration is to be stored in the
XML file.
pConfigID POINTER TO UDINT Return pointer of the configuration ID (hDBID or
hAutoLogGrpID)

Creating AutoLog groups is currently not supported.

Return value

Name Type Description


Create BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
// Any other ConfigType can be used here
stConfigDB : T_DBConfig_MsCompactSQL;
END_VAR

TF6420 Version: 1.13.4 247


PLC API

stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Recipes.sdf';

IF fbConfigTcDBSrv.Create(
pTcDBSrvConfig:= ADR(stConfigDB),
cbTcDBSrvConfig:= SIZEOF(stConfigDB),
bTemporary:= TRUE,
pConfigID:= ADR(myConfigHandle))
THEN
IF fbSQLStoredProcedure.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.1.1.2 Read
This method can be used to read the current configurations of the TwinCAT Database Server. Any
temporary configurations that may be included are marked accordingly.

Syntax
METHOD Read : BOOL
VAR_INPUT
pDBConfig: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_ConfigDB;
cbDBConfig: UDINT;
pAutoLogGrpConfig: POINTER TO ARRAY[1..MAX_CONFIGURATIONS] OF
ST_ConfigAutoLogGrp;
cbAutoLogGrpConfig: UDINT;
pDBCount: POINTER TO UDINT;
pAutoLogGrpCount: POINTER TO UDINT;
END_VAR

Inputs

Name Type Description


pDBConfig POINTER TO ARRAY [1..MA Pointer address of the array into which the database
X_CONFIGURATIONS] OF S configurations are to be written.
T_ConfigDB [} 228]
cbDBConfig UDINT Length of the database configuration array
pAutoLogGrpConfig POINTER TO ARRAY[1..MAX Pointer address of the array into which the
_CONFIGURATIONS] OF AutoLogGrp configurations are to be written.
ST_ConfigAutoLogGrp [} 227]
cbAutoLogGrpConfig UDINT Length of the AutoLogGrp configuration array
pDBCount POINTER TO UDINT Pointer address for storing the number of database
configurations.
pAutoLogGrpCount POINTER TO UDINT Pointer address for storing the number of AutoLogGrp
configurations.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
aDBConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigDB;
aAutoGrpConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigAutoLogGrp;
nDbCount : UDINT;
nAutoGrpCount : UDINT;
END_VAR

248 Version: 1.13.4 TF6420


PLC API

IF fbConfigTcDBSrv.Read(
pDBConfig := ADR(aDBConfig),
cbDBConfig := SIZEOF(aDBConfig),
pAutologGrpConfig := ADR(aAutoGrpConfig),
cbAutoLogGrpConfig := SIZEOF(aAutoGrpConfig),
pDBCount := ADR(nDbCount),
pAutoLogGrpCount := ADR(nAutoGrpCount))
THEN
IF fbConfigTcDBSrv.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.1.1.3 Delete
This method can be used to delete databases and AutoLog groups from the configuration of the
TwinCAT Database Server.

Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR

Inputs

Name Type Description


eTcDBSrvConfigType E_TcDBSrvConfigType Type of the configuration to be deleted (database /
AutoLog group)
hConfigID UDINT ID of the configuration to be deleted (hDBID or
hAutoLogGrpID)

Return value

Name Type Description


Delete BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
END_VAR
IF fbConfigTcDBSrv.Delete(
eTcDBSrvConfigType := E_TcDBSrvConfigType.Database,
hConfigID := myConfigHandle) THEN
IF fbConfigTcDBSrv.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.1.2 FB_PLCDBAutoLog

TF6420 Version: 1.13.4 249


PLC API

Function block with four methods for starting and stopping of defined AutoLog groups and for reading of the
corresponding group status.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBAutoLog
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent;
bBusy_Status: BOOL;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active, except for the Status method.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on
the return value.
bBusy_Status BOOL The Status method can be executed
independently of the other three methods of
the function block and therefore has its own
Busy flag. Is TRUE as soon as the Status
method is active.

Methods

Name Definition loca- Description


tion
RunOnce Local Executes the AutoLog group once
[} 161]
Start [} 162] Local Starts AutoLog mode with the corresponding configured AutoLog groups
Status [} 162] Local Queries the status of the AutoLog groups.
Stop [} 163] Local Stops AutoLog mode

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.1.2.1 RunOnce
This method can be used to execute an AutoLog group once, for example based on an event in the
controller.

250 Version: 1.13.4 TF6420


PLC API

Syntax
METHOD RunOnce : BOOL
VAR_INPUT
hAutoLogGrpID: UDINT;
bAll: BOOL;
END_VAR

Inputs

Name Type Description


hAutoLogGrpID UDINT ID of the AutoLog group to be executed once.
bAll BOOL If TRUE, all AutoLog groups are executed once.

Return value

Name Type Description


RunOnce BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.RunOnce(hAutologGrpID := 1, bAll := FALSE) THEN
; // ...
END_IF

6.1.4.1.2.2 Start
This method starts the AutoLog mode with the corresponding configured AutoLog groups.

Syntax
METHOD Start : BOOL

Return value

Name Type Description


Start BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Start() THEN
; // ...
END_IF

6.1.4.1.2.3 Status
This method can be used to query the status of the AutoLog groups. A separate busy flag is provided in the
body of the function block for this method, since it can be called independently of the other methods of the
function block: bBusy_Status.

Syntax
METHOD Status : BOOL
VAR_INPUT
tCheckCycle: TIME;
pError: POINTER TO BOOL;

TF6420 Version: 1.13.4 251


PLC API

pAutoLogGrpStatus: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;


cbAutoLogGrpStatus: UDINT;
END_VAR

Inputs

Name Type Description


tCheckCycle TIME Interval time at which the status array is
updated.
pError POINTER TO BOOL TRUE, if an error has occurred in AutoLog
mode.
pAutoLogStatus POINTER TO ARRAY Address of the status array that contains all
[1..MAX_CONFIGURATIONS] OF groups.
ST_AutoLogGrpStatus
cbAutoLogStatus UDINT Length of the status array

Return value

Name Type Description


Status BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog(sNetID:='', tTimeout := T#5S);
bError : BOOL;
aAutologGrpStatus : ARRAY[0..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
END_VAR
IF fbPLCDBAutoLog.Status(tCheckCycle := T#30S, ADR(bError), ADR(aAutologGrpStatus), SIZEOF(aAutologG
rpStatus)) THEN
; // ...
END_IF

6.1.4.1.2.4 Stop
This method stops the AutoLog mode.

Syntax
METHOD Stop : BOOL

Return value

Name Type Description


Stop BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF

252 Version: 1.13.4 TF6420


PLC API

6.1.4.2 PLC Expert mode

6.1.4.2.1 FB_ConfigTcDBSrv

Function block for creating, reading and deleting configuration entries for the TwinCAT Database Server.

Syntax

Definition:
FUNCTION_BLOCK FB_ConfigTcDBSrv
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on
the return value.

Methods

Name Definition loca- Description


tion
Create [} 254] Local Creates new entries in the XML configuration file for the
TwinCAT Database Server
Read [} 254] Local Reads the current configuration of the TwinCAT Database Server
Delete [} 255] Local Deletes the database and AutoLog groups from the configuration
of the TwinCAT Database Server

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

TF6420 Version: 1.13.4 253


PLC API

6.1.4.2.1.1 Create
This method creates new entries in the XML configuration file for the TwinCAT Database Server. Optionally
the TwinCAT Database Server can use a new entry on a temporary basis. In this case no data is written to
the XML file.

Syntax
METHOD Create : BOOL
VAR_INPUT
pTcDBSrvConfig: POINTER TO BYTE;
cbTcDBSrvConfig: UDINT;
bTemporary: BOOL := TRUE;
pConfigID: POINTER TO UDINT;
END_VAR

Inputs

Name Type Description


pTcDBSrvConfig POINTER TO BYTE Pointer of the configuration structure to be created.
cbTcDBSrvConfig UDINT Length of the configuration structure
bTemporary BOOL Indicates whether the configuration is to be stored in the
XML file.
pConfigID POINTER TO UDINT Return pointer of the configuration ID (hDBID or
hAutoLogGrpID)

Creating AutoLog groups is currently not supported.

Return value

Name Type Description


Create BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
// Any other ConfigType can be used here
stConfigDB : T_DBConfig_MsCompactSQL;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Recipes.sdf';

IF fbConfigTcDBSrv.Create(
pTcDBSrvConfig:= ADR(stConfigDB),
cbTcDBSrvConfig:= SIZEOF(stConfigDB),
bTemporary:= TRUE,
pConfigID:= ADR(myConfigHandle))
THEN
IF fbSQLStoredProcedure.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.2.1.2 Read
This method can be used to read the current configurations of the TwinCAT Database Server. Any
temporary configurations that may be included are marked accordingly.

254 Version: 1.13.4 TF6420


PLC API

Syntax
METHOD Read : BOOL
VAR_INPUT
pDBConfig: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_ConfigDB;
cbDBConfig: UDINT;
pAutoLogGrpConfig: POINTER TO ARRAY[1..MAX_CONFIGURATIONS] OF
ST_ConfigAutoLogGrp;
cbAutoLogGrpConfig: UDINT;
pDBCount: POINTER TO UDINT;
pAutoLogGrpCount: POINTER TO UDINT;
END_VAR

Inputs

Name Type Description


pDBConfig POINTER TO ARRAY [1..MA Pointer address of the array into which the database
X_CONFIGURATIONS] OF S configurations are to be written.
T_ConfigDB [} 228]
cbDBConfig UDINT Length of the database configuration array
pAutoLogGrpConfig POINTER TO ARRAY[1..MAX Pointer address of the array into which the
_CONFIGURATIONS] OF AutoLogGrp configurations are to be written.
ST_ConfigAutoLogGrp [} 227]
cbAutoLogGrpConfig UDINT Length of the AutoLogGrp configuration array
pDBCount POINTER TO UDINT Pointer address for storing the number of database
configurations.
pAutoLogGrpCount POINTER TO UDINT Pointer address for storing the number of AutoLogGrp
configurations.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
aDBConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigDB;
aAutoGrpConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigAutoLogGrp;
nDbCount : UDINT;
nAutoGrpCount : UDINT;
END_VAR
IF fbConfigTcDBSrv.Read(
pDBConfig := ADR(aDBConfig),
cbDBConfig := SIZEOF(aDBConfig),
pAutologGrpConfig := ADR(aAutoGrpConfig),
cbAutoLogGrpConfig := SIZEOF(aAutoGrpConfig),
pDBCount := ADR(nDbCount),
pAutoLogGrpCount := ADR(nAutoGrpCount))
THEN
IF fbConfigTcDBSrv.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.2.1.3 Delete
This method can be used to delete databases and AutoLog groups from the configuration of the
TwinCAT Database Server.

TF6420 Version: 1.13.4 255


PLC API

Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR

Inputs

Name Type Description


eTcDBSrvConfigType E_TcDBSrvConfigType Type of the configuration to be deleted (database /
AutoLog group)
hConfigID UDINT ID of the configuration to be deleted (hDBID or
hAutoLogGrpID)

Return value

Name Type Description


Delete BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
END_VAR
IF fbConfigTcDBSrv.Delete(
eTcDBSrvConfigType := E_TcDBSrvConfigType.Database,
hConfigID := myConfigHandle) THEN
IF fbConfigTcDBSrv.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.2.2 FB_PLCDBAutoLog

Function block with four methods for starting and stopping of defined AutoLog groups and for reading of the
corresponding group status.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBAutoLog
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent;
bBusy_Status: BOOL;
END_VAR

256 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active, except for the Status method.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on
the return value.
bBusy_Status BOOL The Status method can be executed
independently of the other three methods of
the function block and therefore has its own
Busy flag. Is TRUE as soon as the Status
method is active.

Methods

Name Definition loca- Description


tion
RunOnce Local Executes the AutoLog group once
[} 161]
Start [} 162] Local Starts AutoLog mode with the corresponding configured AutoLog groups
Status [} 162] Local Queries the status of the AutoLog groups.
Stop [} 163] Local Stops AutoLog mode

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.2.2.1 RunOnce
This method can be used to execute an AutoLog group once, for example based on an event in the
controller.

Syntax
METHOD RunOnce : BOOL
VAR_INPUT
hAutoLogGrpID: UDINT;
bAll: BOOL;
END_VAR

Inputs

Name Type Description


hAutoLogGrpID UDINT ID of the AutoLog group to be executed once.
bAll BOOL If TRUE, all AutoLog groups are executed once.

TF6420 Version: 1.13.4 257


PLC API

Return value

Name Type Description


RunOnce BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.RunOnce(hAutologGrpID := 1, bAll := FALSE) THEN
; // ...
END_IF

6.1.4.2.2.2 Start
This method starts the AutoLog mode with the corresponding configured AutoLog groups.

Syntax
METHOD Start : BOOL

Return value

Name Type Description


Start BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Start() THEN
; // ...
END_IF

6.1.4.2.2.3 Status
This method can be used to query the status of the AutoLog groups. A separate busy flag is provided in the
body of the function block for this method, since it can be called independently of the other methods of the
function block: bBusy_Status.

Syntax
METHOD Status : BOOL
VAR_INPUT
tCheckCycle: TIME;
pError: POINTER TO BOOL;
pAutoLogGrpStatus: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
cbAutoLogGrpStatus: UDINT;
END_VAR

258 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


tCheckCycle TIME Interval time at which the status array is
updated.
pError POINTER TO BOOL TRUE, if an error has occurred in AutoLog
mode.
pAutoLogStatus POINTER TO ARRAY Address of the status array that contains all
[1..MAX_CONFIGURATIONS] OF groups.
ST_AutoLogGrpStatus
cbAutoLogStatus UDINT Length of the status array

Return value

Name Type Description


Status BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog(sNetID:='', tTimeout := T#5S);
bError : BOOL;
aAutologGrpStatus : ARRAY[0..MAX_CONFIGURATIONS] OF ST_AutoLogGrpStatus;
END_VAR
IF fbPLCDBAutoLog.Status(tCheckCycle := T#30S, ADR(bError), ADR(aAutologGrpStatus), SIZEOF(aAutologG
rpStatus)) THEN
; // ...
END_IF

6.1.4.2.2.4 Stop
This method stops the AutoLog mode.

Syntax
METHOD Stop : BOOL

Return value

Name Type Description


Stop BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF

6.1.4.2.3 FB_PLCDBCreate

TF6420 Version: 1.13.4 259


PLC API

Function block with two methods. One method can be used to create databases from the PLC on a database
server specified in the PLC. The other method can be used to generate a new table in a specified database.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBCreate
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block is
active.
bError BOOL TRUE when an error occurs.
ipTcResultEve Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on the return
nt value.

Methods

Name Definition loca- Description


tion
Database Local Creates a new database
[} 260]
Table [} 261] Local Creates a new table with a structure that is defined via an array with x
elements or x columns in the PLC.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.2.3.1 Database
This method creates a new database. Optionally you can specify whether the created database should also
be used for the configuration of the TwinCAT Database Server.

Syntax
METHOD Database : BOOL
VAR_INPUT
pDatabaseConfig: POINTER TO BYTE;
cbDatabaseConfig: UDINT;
bCreateXMLConfig: BOOL;
pDBID: POINTER TO UDINT;
END_VAR

260 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


pDatabaseConfig POINTER TO BYTE Address of the database configuration structure [} 229]
cbDatabaseConfig UDINT Length of the database configuration structure
bCreateXMLConfig BOOL Indicates whether the newly created database should be
entered as new configuration entry in the XML file.
pDBID UDINT Returns the hDBID if/when a new configuration entry was
created.

Return value

Name Type Description


Database BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBCreate : FB_PLCDBCreateEvt(sNetID := '', tTimeout := T#5S);
stConfigDB : T_DBConfig_MsCompactSQL;
hDBID : UDINT;
tcMessage : I_TcMessage;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Test.sdf';

IF fbPLCDBCreate.Database(
pDatabaseConfig:= ADR(stConfigDB),
cbDatabaseConfig := SIZEOF(stConfigDB),
bCreateXMLConfig := TRUE,
pDBID := ADR(hDBID))
THEN
IF fbPLCDBCreate.bError THEN
tcMessage := fbPLCDBCreate.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.2.3.2 Table
This method creates a new table with a structure that is defined through an array with x elements or x
columns in the PLC.

Syntax
METHOD Table : BOOL
VAR_INPUT
hDBID : UDINT;
sTableName : T_MaxString;
pTableCfg : POINTER TO ARRAY[0..MAX_DBCOLUMNS] OF ST_ColumnInfo;
cbTableCfg : UDINT;
END_VAR

TF6420 Version: 1.13.4 261


PLC API

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName MaxString Name of the table to be created.
pTableCfg POINTER TO Indicates the pointer address of the table structure
ARRAY[0..MAX_DBCOLUMNS] array. The individual columns are written in this array.
OF ST_ColumnInfo [} 243]
cbTableCfg UDINT Indicates the length of the array in which the columns
are configured.

Return value

Name Type Description


Table BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbPLCDBCreate : FB_PLCDBCreateEvt(sNetID := '', tTimeout := T#5S);
ColumnInfo : ARRAY [0..14] OF ST_ColumnInfo;
tcMessage : I_TcMessage;
END_VAR
ColumnInfo[0].sName := 'colBigInt'; ColumnInfo[0].eType := E_ColumnType.BigInt; ColumnInfo[0
].nLength := 8; ColumnInfo[0].sProperty := 'IDENTITY(1,1)';
ColumnInfo[1].sName := 'colInteger'; ColumnInfo[1].eType := E_ColumnType.Integer; ColumnInfo[1
].nLength := 4;
ColumnInfo[2].sName := 'colSmallInt'; ColumnInfo[2].eType := E_ColumnType.SmallInt; ColumnInfo[2
].nLength := 2;
ColumnInfo[3].sName := 'colTinyInt'; ColumnInfo[3].eType := E_ColumnType.TinyInt; ColumnInfo[3
].nLength := 1;
ColumnInfo[4].sName := 'colBit'; ColumnInfo[4].eType := E_ColumnType.BIT_; ColumnInfo[4
].nLength := 1;
ColumnInfo[5].sName := 'colMoney'; ColumnInfo[5].eType := E_ColumnType.Money; ColumnInfo[5
].nLength := 8;
ColumnInfo[6].sName := 'colFloat'; ColumnInfo[6].eType := E_ColumnType.Float; ColumnInfo[6
].nLength := 8;
ColumnInfo[7].sName := 'colReal'; ColumnInfo[7].eType := E_ColumnType.REAL_; ColumnInfo[7
].nLength := 4;
ColumnInfo[8].sName := 'colDateTime'; ColumnInfo[8].eType := E_ColumnType.DateTime; ColumnInfo[8
].nLength := 4;
ColumnInfo[9].sName := 'colNText'; ColumnInfo[9].eType := E_ColumnType.NText; ColumnInfo[9
].nLength := 256;
ColumnInfo[10].sName := 'colNChar'; ColumnInfo[10].eType := E_ColumnType.NChar; ColumnInfo[1
0].nLength := 10;
ColumnInfo[11].sName := 'colImage'; ColumnInfo[11].eType := E_ColumnType.Image; ColumnInfo[1
1].nLength := 256;
ColumnInfo[12].sName := 'colNVarChar'; ColumnInfo[12].eType := E_ColumnType.NVarChar; ColumnInfo[1
2].nLength := 50;
ColumnInfo[13].sName := 'colBinary'; ColumnInfo[13].eType := E_ColumnType.Binary; ColumnInfo[1
3].nLength := 30;
ColumnInfo[14].sName := 'colVarBinary'; ColumnInfo[14].eType := E_ColumnType.VarBinary; ColumnInfo[1
4].nLength := 20;

IF fbPLCDBCreate.Table(
hDBID:= 1,
sTableName:= 'myNewTable',
pTableCfg:= ADR(ColumnInfo),
cbTableCfg:= SIZEOF(ColumnInfo))
THEN
IF fbPLCDBCreate.bError THEN
TcMessage:= fbPLCDBCreate.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

262 Version: 1.13.4 TF6420


PLC API

6.1.4.2.4 FB_PLCDBRead

Function block for reading records from a database.

Syntax
FUNCTION_BLOCK FB_PLCDBRead
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on the
return value.

Methods

Name Definition location Description


Read [} 263] Local Reads a specified number of records from a database table with the
standard table structure specified by Beckhoff.
ReadStruct [} 265] Local Reads a specified number of records from a database table with any
table structure.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.2.4.1 Read
This method reads a specified number of records from a database table with the standard table structure
specified by Beckhoff. (The standard table structure is used in AutoLog mode and in the FB_DBWrite
function block, for example).

Syntax
METHOD Read : BOOL
VAR_INPUT
hDBID: UDINT;

TF6420 Version: 1.13.4 263


PLC API

sTableName: T_MaxString;
sDBSymbolName: T_MaxString;
eOrderBy: E_OrderColumn := E_OrderColumn.eColumnID;
eOrderType: E_OrderType := E_OrderType.eOrder_ASC;
nStartIndex: UDINT;
nRecordCount: UDINT;
pData: POINTER TO ST_StandardRecord;
cbData: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
sDBSymbolName T_MaxString Symbol name to be read from the standard table
structure.
eOrderBy E_OrderColumn.eColumnID Sorting column (ID, timestamp, name or value)
eOrderType E_OrderType.eOrder_ASC Sorting direction (ASC or DESC)
nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO ST_StandardRecord Address of the structure array into which the
records are to be written.
cbData UDINT Indicates the size of the structure array in bytes.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the method execution is
finished, even in the event of an error.

Sample
VAR
fbPLCDBRead : FB_PLCDBReadEvt (sNetID := '', tTimeout := T#5S);
ReadStruct : ST_StandardRecord;
tcMessage : I_TcMessage;
END_VAR
IF fbPLCDBRead.Read(
hDBID:= 1,
sTableName:= 'MyTable_WithLReal',
sDBSymbolName:= 'MyValue',
eOrderBy:= E_OrderColumn.ID,
eOrderType:= E_OrderType.DESC,
nStartIndex:= 0,
nRecordCount:= 1,
pData:= ADR(ReadStruct),
cbData:= SIZEOF(ReadStruct))
THEN
IF fbPLCDBRead.bError THEN
tcMessage := fbPLCDBRead.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the PLC:

264 Version: 1.13.4 TF6420


PLC API

6.1.4.2.4.2 ReadStruct
This method reads a specified number of records from a database table with any table structure.

Syntax
METHOD ReadStruct : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
pColumnNames: POINTER TO ARRAY [0..MAX_DBCOLUMNS] OF STRING(50);
cbColumnNames: UDINT;
sOrderByColumn: STRING(50);
eOrderType: E_OrderType := E_OrderType.eOrder_ASC
nStartIndex: UDINT;
nRecordCount: UDINT;
pData: POINTER TO BYTE;
cbData: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
pColumnNames POINTER TO ARRAY [0..MAX_D Address of the array containing the column name
BCOLUMNS] OF STRING(50) to be read.
cbColumnNames UDINT Length of the column name array
sOrderByColumn STRING(50) Name the sorting column
eOrderType E_OrderType Sorting direction (ASC or DESC)
nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO BYTE Address of the structure array into which the
records are to be written.
cbData UDINT Indicates the size of the structure array in bytes.

Return value

Name Type Description


ReadStruct BOOL Displays the status of the method. Returns TRUE as soon as the method execution is
finished, even in the event of an error.

Sample
VAR
fbPLCDBRead : FB_PLCDBReadEvt (sNetID := '', tTimeout := T#5S);
myCustomStruct : ST_Record;
tcMessage : I_TcMessage;
END_VAR
TYPE ST_Record :
STRUCT
nID : LINT;
dtTimestamp: DATE_AND_TIME;

TF6420 Version: 1.13.4 265


PLC API

sName : STRING;
nSensor1 : LREAL;
nSensor2 : LREAL;
END_STRUCT
END_TYPE
// set columnnames
ColumnNames[0] := 'ID';
ColumnNames[1] := 'Timestamp';
ColumnNames[2] := 'Name';
ColumnNames[3] := 'Sensor1';
ColumnNames[4] := 'Sensor2';

IF fbPLCDBRead.ReadStruct(
hDBID:= 1,
sTableName:= 'MyTable_Struct',
pColumnNames:= ADR(ColumnNames),
cbColumnNames:= SIZEOF(ColumnNames),
sOrderByColumn:= ColumnNames[0],
eOrderType:= E_OrderType.DESC,
nStartIndex:= 0,
nRecordCount:= 1,
pData:= ADR(myCustomStruct),
cbData:= SIZEOF(myCustomStruct))
THEN
IF fbPLCDBRead.bError THEN
tcMessage:= fbPLCDBRead.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the PLC:

6.1.4.2.5 FB_PLCDBWrite

Function block for writing of records into a database.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBWrite
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

266 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block
is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on the
return value.

Methods

Name Definition loca- Description


tion
Write [} 267] Local Creates a record in the standard table structure specified by
Beckhoff.
WriteBySymbol Local Reads the value of a specified ADS symbol and saves it in the
[} 268] standard table structure specified by Beckhoff.
WriteStruct [} 270] Local Creates a record with any table structure

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.2.5.1 Write
This method creates a record in the standard table structure specified by Beckhoff.

Syntax
METHOD Write : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
pValue: POINTER TO BYTE;
cbValue: UDINT;
sDBSymbolName: T_MaxString;
eDBWriteMode: E_WriteMode := E_WriteMode.eADS_TO_DB_Append;
nRingBuffParameter: UDINT;
END_VAR

TF6420 Version: 1.13.4 267


PLC API

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
pValue POINTER TO BYTE Address of the variable to be logged in the standard table
structure.
cbValue UDINT Length of the variable to be logged.
sDBSymbolName T_MaxString Name that is logged in the table.
eDBWriteMode E_WriteMode Indicates the write mode. (append, update, ring buffer)
nRingBuffParameter UDINT Additional parameter(s) for the "ring buffer" write mode.

Return value

Name Type Description


Write BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

This sample shows how to use the FB_PLCDBWriteEvt.Write method:


VAR
fbPLCDBWrite : FB_PLCDBWriteEvt(sNetID := '', tTimeout := T#5S);
myValue : LREAL := 43.23;
tcMessage : I_TcMessage;
END_VAR
IF fbPLCDBWrite.Write(
hDBID:= 1,
sTableName:= 'myTable_WithLReal',
pValue:= ADR(myValue),
cbValue:= SIZEOF(myValue),
sDBSymbolName:= 'MyValue',
eDBWriteMode:= E_WriteMode.eADS_TO_DB_RingBuff_Count,
nRingBuffParameter:= 3)
THEN
IF fbPLCDBWrite.bError THEN
tcMessage := fbPLCDBWrite.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the database:

ID Timestamp Name Value


27 Has been dropped
28 '2018-01-30 14:04:19' 'MyValue' 41.23
29 '2018-01-30 14:04:29' 'MyValue' 42.23
30 '2018-01-30 14:04:39' 'MyValue' 43.23

With the ring buffer option, only three entries of this name are in the database at any one time. Older entries
are deleted.

6.1.4.2.5.2 WriteBySymbol
This method reads the value of a specified ADS symbol and saves it in the standard table structure specified
by Beckhoff. ADS symbols from other ADS devices can also be read.

268 Version: 1.13.4 TF6420


PLC API

Syntax
METHOD WriteBySymbol : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
stADSDevice: ST_ADSDevice;
stSymbol: ST_Symbol;
eDBWriteMode: E_WriteMode := E_WriteMode.eADS_TO_DB_Append;
nRingBuffParameter: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
stADSDevice ST_ADSDevice ADS device from which a symbol is to be logged in the standard
table structure.
stSymbol ST_Symbol Symbol name of the variable to be written
eDBWriteMode E_WriteMode Indicates the write mode. (append, update, ring buffer)
nRingBuffParameter UDINT Additional parameter(s) for the "ring buffer" write mode

Return value

Name Type Description


WriteBySymbol BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

This sample shows how to use the FB_PLCDBWriteEvt.WriteBySymbol method:


VAR
fbPLCDBWrite : FB_PLCDBWriteEvt(sNetID := '', tTimeout := T#5S);
myValue : LREAL := 43.23;
myAdsDevice : ST_ADSDevice;
mySymbol : ST_Symbol;
tcMessage : I_TcMessage;
END_VAR
// Set ADSDevice Information
myAdsDevice.sDevNetID := '127.0.0.1.1.1';
myAdsDevice.nDevPort := 851;
myAdsDevice.eADSRdWrtMode := E_ADSRdWrtMode.bySymbolName;
myAdsDevice.tTimeout := T#5S;

// Set Symbol Information


mySymbol.eDataType := E_PLCDataType.eType_LREAL;
mySymbol.sDBSymbolName := 'MySymbol';
mySymbol.sSymbolName := 'MAIN.myValue';
mySymbol.nBitSize := 8;

// Call Functionblock
IF fbPLCDBWrite.WriteBySymbol(
hDBID:= 1,
sTableName:= 'myTable_WithLReal',
stADSDevice:= myAdsDevice,
stSymbol:= mySymbol,
eDBWriteMode:= E_WriteMode.eADS_TO_DB_Append,
nRingBuffParameter:= 1)
THEN
IF fbPLCDBWrite.bError THEN
tcMessage := fbPLCDBWrite.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the database:

TF6420 Version: 1.13.4 269


PLC API

ID Timestamp Name Value


28 '2018-01-30 14:04:19' 'MyValue' 41.23
29 '2018-01-30 14:04:29' 'MyValue' 42.23
30 '2018-01-30 14:04:39' 'MyValue' 43.23
31 '2018-01-30 14:06:12’ ‘MySymbol’ 86.2

6.1.4.2.5.3 WriteStruct
This method creates a record with a freely selectable table structure.

Syntax
METHOD WriteStruct : BOOL
VAR_INPUT
hDBID: UDINT;
sTableName: T_MaxString;
pRecord: POINTER TO BYTE;
cbRecord: UDINT;
pColumnNames: POINTER TO ARRAY [0..MAX_DBCOLUMNS] OF STRING(50);
cbColumnNames: UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
sTableName T_MaxString Name of the table that is to be read.
pRecord POINTER TO BYTE Address of a structure that is to be logged in a freely
selectable table structure.
cbRecord UDINT Length of the structure to be written
pColumnNames POINTER TO ARRAY [ Address of the array containing the column name to be filled.
0..MAX_DBCOLUMNS
] OF STRING(50)
cbColumnNames UDINT Length of the column name array

Return value

Name Type Description


WriteStruct BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

This sample shows how to use the method FB_PLCDBWriteEvt.WriteStruct:


VAR
fbPLCDBWrite : FB_PLCDBWriteEvt(sNetID := '', tTimeout := T#5S);
myRecord : ST_Record;
ColumnNames : ARRAY[0..4] OF STRING(50);

systime : GETSYSTEMTIME;
currentTime : T_FILETIME;
tcMessage : I_TcMessage;
END_VAR
TYPE ST_Record :
STRUCT
nID : LINT;
dtTimestamp: DATE_AND_TIME;
sName : STRING;
nSensor1 : LREAL;
nSensor2 : LREAL;
END_STRUCT
END_TYPE

270 Version: 1.13.4 TF6420


PLC API

// set Values
systime(timeLoDw => currentTime.dwLowDateTime, timeHiDW => currentTime.dwHighDateTime );
myRecord.dtTimestamp := FILETIME_TO_DT(currentTime);
myRecord.sName := 'MyStructVal';
myRecord.nSensor1 := 12.34;
myRecord.nSensor2 := 102.5;

// set columnnames
ColumnNames[0] := 'ID';
ColumnNames[1] := 'Timestamp';
ColumnNames[2] := 'Name';
ColumnNames[3] := 'Sensor1';
ColumnNames[4] := 'Sensor2';

// Call Functionblock
IF fbPLCDBWrite.WriteStruct(
hDBID:= 1,
sTableName:= 'myTable_Struct',
pRecord:= ADR(myRecord),
cbRecord:= SIZEOF(myRecord),
pColumnNames:= ADR(ColumnNames) ,
cbColumnNames:= SIZEOF(ColumnNames))
THEN
IF fbPLCDBWrite.bError THEN
tcMessage := fbPLCDBWrite.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

Result in the database:

ID Timestamp Name Sensor1 Sensor2


5 '2018-01-30 ‘MyStructVal’ 12.34 102.5
15:23:26'

6.1.4.2.6 FB_PLCDBCmd

Function block with two methods. Users can define and transfer their own SQL commands. Placeholders in
the SQL command can correlate with structures in the PLC, which reflect the table structure. The Database
Server ultimately enters the current data of the structure into the SQL command.

Syntax

Definition:
FUNCTION_BLOCK FB_PLCDBCmd
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

TF6420 Version: 1.13.4 271


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on
the return value.

Methods

Name Definition loca- Description


tion
Execute [} 272] Local Sends any SQL commands to the database.
Returned records cannot be read.
ExecuteDataReturn Local Sends any SQL commands to the database.
[} 273] A specified number of records can be read.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.2.6.1 Execute
This method can be used to send SQL commands to the database. The database connection is opened with
each call and then closed again. It is possible to define placeholders in the command, which are then
replaced by the TwinCAT Database Server with the corresponding values before the execution. Returned
records cannot be read.

Syntax
METHOD Execute : BOOL
VAR_INPUT
hDBID: UDINT;
pExpression: POINTER TO BYTE;
cbExpression: UDINT;
pData: POINTER TO BYTE;
cbData: UDINT;
pParameter: POINTER TO ARRAY[0..MAX_DBCOLUMNS] OF ST_ExpParameter;
cbParameter: UDINT;
END_VAR

Sample
VAR
fbPLCDBCmd : FB_PLCDBCmdEvt(sNetID := '', tTimeout := T#5S);
sCmd : STRING (1000);
myStruct : ST_DataAll;
aPara : ARRAY[0..14] OF ST_ExpParameter;
tcMessage : I_TcMessage;
END_VAR
TYPE ST_DataAll :
STRUCT
colBigInt: LINT;
colInteger: DINT;
colSmallInt: INT;
colTinyInt: BYTE;
colBit: BOOL;
colMoney: LREAL;
colFloat: LREAL;
colReal: REAL;
colDateTime: DT;
colNText: STRING(255);
colNChar: STRING(10);
colImage: ARRAY[0..255] OF BYTE;

272 Version: 1.13.4 TF6420


PLC API

colNVarChar: STRING(50);
colBinary: ARRAY[0..29] OF BYTE;
colVarBinary: ARRAY[0..19] OF BYTE;
END_STRUCT
END_TYPE
// set Parameter configuration
aPara[0].sParaName := 'colBigInt'; aPara[0].eParaType :=
E_ExpParameterType.Int64; aPara[0].nParaSize := 8;
aPara[1].sParaName := 'colInteger'; aPara[1].eParaType :=
E_ExpParameterType.Int32; aPara[1].nParaSize := 4;
aPara[2].sParaName := 'colSmallInt'; aPara[2].eParaType :=
E_ExpParameterType.Int16; aPara[2].nParaSize := 2;
aPara[3].sParaName := 'colTinyInt'; aPara[3].eParaType :=
E_ExpParameterType.Byte_; aPara[3].nParaSize := 1;
aPara[4].sParaName := 'colBit'; aPara[4].eParaType :=
E_ExpParameterType.Boolean; aPara[4].nParaSize := 1;
aPara[5].sParaName := 'colMoney'; aPara[5].eParaType :=
E_ExpParameterType.Double64; aPara[5].nParaSize := 8;
aPara[6].sParaName := 'colFloat'; aPara[6].eParaType :=
E_ExpParameterType.Double64; aPara[6].nParaSize := 8;
aPara[7].sParaName := 'colReal'; aPara[7].eParaType :=
E_ExpParameterType.Float32; aPara[7].nParaSize := 4;
aPara[8].sParaName := 'colDateTime'; aPara[8].eParaType :=
E_ExpParameterType.DateTime; aPara[8].nParaSize := 4;
aPara[9].sParaName := 'colNText'; aPara[9].eParaType :=
E_ExpParameterType.STRING_; aPara[9].nParaSize := 256;
aPara[10].sParaName:= 'colNChar'; aPara[10].eParaType :=
E_ExpParameterType.STRING_; aPara[10].nParaSize := 10;
aPara[11].sParaName:= 'colImage'; aPara[11].eParaType :=
E_ExpParameterType.ByteArray; aPara[11].nParaSize := 256;
aPara[12].sParaName:= 'colNVarChar'; aPara[12].eParaType :=
E_ExpParameterType.STRING_; aPara[12].nParaSize := 50;
aPara[13].sParaName:= 'colBinary'; aPara[13].eParaType :=
E_ExpParameterType.ByteArray; aPara[13].nParaSize := 30;
aPara[14].sParaName:= 'colVarBinary'; aPara[14].eParaType :=
E_ExpParameterType.ByteArray; aPara[14].nParaSize := 20;

// set command
sCmd := 'INSERT INTO MyTableName (colInteger, colSmallInt, colTinyInt, colBit, colMoney, colFloat,
colReal, colDateTime, colNText, colNChar, colImage, colNVarChar, colBinary, colVarBinary) VALUES
({colInteger}, {colSmallInt}, {colTinyInt}, {colBit}, {colMoney}, {colFloat}, {colReal},
{colDateTime}, {colNText}, {colNChar}, {colImage}, {colNVarChar}, {colBinary}, {colVarBinary})';

// call functionblock
IF fbPLCDBCmd.Execute(
hDBID:= 1,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(myStruct),
cbData:= SIZEOF(myStruct),
pParameter:= ADR(aPara),
cbParameter:= SIZEOF(aPara))
THEN
IF fbPLCDBCmd.bError THEN
tcMessage := fbPLCDBCmd.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.2.6.2 ExecuteDataReturn
This method can be used to send SQL commands to the database. The database connection is opened with
each call and then closed again. It is possible to define placeholders in the command, which are then
replaced by the TwinCAT Database Server with the corresponding values before the execution. A specified
number of records can be read.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
hDBID: UDINT;
pExpression: POINTER TO BYTE;
cbExpression: UDINT;
pData: POINTER TO BYTE;
cbData: UDINT;

TF6420 Version: 1.13.4 273


PLC API

pParameter: POINTER TO ARRAY[0..MAX_DBCOLUMNS] OF ST_ExpParameter;


cbParameter: UDINT;
nStartIndex: UDINT;
nRecordCount: UDINT;
pReturnData: POINTER TO BYTE;
cbReturnData: UDINT;
pRecords: POINTER TO UDINT;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.
pExpression POINTER TO BYTE Address of the string variable with the SQL command.
cbExpression UDINT Length of the string variable with the SQL command.
pData POINTER TO BYTE Address of the structure with the parameter values
cbData UDINT Length of the structure with the parameter values
pParameter POINTER TO ARRAY[0..MAX_ Address of the structure array with the parameter
DBCOLUMNS] OF ST_ExpPar information.
ameter
cbParameter UDINT Length of the structure array with the parameter
information.
nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pReturnData POINTER TO BYTE Address of the structure array into which the records are
to be written.
cbReturnData UDINT Indicates the size of the structure array in bytes.
pRecords POINTER TO BYTE Number of read records.

Return value

Name Type Description


ExecuteDataReturn BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Parameterizing the command


The column names for the individual parameters are specified in curly brackets in the SQL
command.
Sample: ‚SELECT * FROM MyHouse_Temperatures WHERE Room = {SelectedRoom}’.
Accordingly, SelectedRoom has to be specified as parameter name in the structure
ST_ExpParameter.

Some databases do not support the parameterization of SQL clauses. (TOP/LIMIT/ROWNUM/...)


Parameterizable table names are not usually supported.

Sample
VAR
fbPLCDBCmd : FB_PLCDBCmdEvt(sNetID := '', tTimeout := T#5S);
sCmd : STRING (1000);
stPara : ST_ExpParameter;
RecordAmt : ULINT := 3;
ReturnDataStruct : ARRAY [0..9] OF ST_DataAll;
nRecords : UDINT;
tcMessage : I_TcMessage;
END_VAR
// set Parameter configuration
stPara.eParaType := E_ExpParameterType.Int64;
stPara.nParaSize := 8;
stPara.sParaName := 'RecordAmt';

// set command with placeholder

274 Version: 1.13.4 TF6420


PLC API

sCmd := 'SELECT TOP ({RecordAmt}) * FROM MyTableName';

// call functionblock
IF fbPLCDBCmd.ExecuteDataReturn(
hDBID:= 1,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(RecordAmt),
cbData:= SIZEOF(RecordAmt),
pParameter:= ADR(stPara),
cbParameter:= SIZEOF(stPara),
nStartIndex:= 0,
nRecordCount:= 10,
pReturnData:= ADR(ReturnDataStruct),
cbReturnData:= SIZEOF(ReturnDataStruct),
pRecords:= ADR(nRecords))
THEN
IF fbPLCDBCmd.bError THEN
tcMessage := fbPLCDBCmd.ipTcResult;
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.3 SQL Expert mode

6.1.4.3.1 FB_ConfigTcDBSrv

Function block for creating, reading and deleting configuration entries for the TwinCAT Database Server.

TF6420 Version: 1.13.4 275


PLC API

Syntax

Definition:
FUNCTION_BLOCK FB_ConfigTcDBSrv
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent;
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function
block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResultEvent Result interface with detailed information on
the return value.

Methods

Name Definition loca- Description


tion
Create [} 157] Local Creates new entries in the XML configuration file for the
TwinCAT Database Server
Read [} 158] Local Reads the current configuration of the TwinCAT Database Server
Delete [} 159] Local Deletes the database and AutoLog groups from the configuration
of the TwinCAT Database Server

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.3.1.1 Create
This method creates new entries in the XML configuration file for the TwinCAT Database Server. Optionally
the TwinCAT Database Server can use a new entry on a temporary basis. In this case no data is written to
the XML file.

Syntax
METHOD Create : BOOL
VAR_INPUT
pTcDBSrvConfig: POINTER TO BYTE;
cbTcDBSrvConfig: UDINT;
bTemporary: BOOL := TRUE;
pConfigID: POINTER TO UDINT;
END_VAR

276 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


pTcDBSrvConfig POINTER TO BYTE Pointer of the configuration structure to be created.
cbTcDBSrvConfig UDINT Length of the configuration structure
bTemporary BOOL Indicates whether the configuration is to be stored in the
XML file.
pConfigID POINTER TO UDINT Return pointer of the configuration ID (hDBID or
hAutoLogGrpID)

Creating AutoLog groups is currently not supported.

Return value

Name Type Description


Create BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
// Any other ConfigType can be used here
stConfigDB : T_DBConfig_MsCompactSQL;
END_VAR
stConfigDB.bAuthentification := FALSE;
stConfigDB.sServer := 'C:\Recipes.sdf';

IF fbConfigTcDBSrv.Create(
pTcDBSrvConfig:= ADR(stConfigDB),
cbTcDBSrvConfig:= SIZEOF(stConfigDB),
bTemporary:= TRUE,
pConfigID:= ADR(myConfigHandle))
THEN
IF fbSQLStoredProcedure.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.3.1.2 Read
This method can be used to read the current configurations of the TwinCAT Database Server. Any
temporary configurations that may be included are marked accordingly.

Syntax
METHOD Read : BOOL
VAR_INPUT
pDBConfig: POINTER TO ARRAY [1..MAX_CONFIGURATIONS] OF ST_ConfigDB;
cbDBConfig: UDINT;
pAutoLogGrpConfig: POINTER TO ARRAY[1..MAX_CONFIGURATIONS] OF
ST_ConfigAutoLogGrp;
cbAutoLogGrpConfig: UDINT;
pDBCount: POINTER TO UDINT;
pAutoLogGrpCount: POINTER TO UDINT;
END_VAR

TF6420 Version: 1.13.4 277


PLC API

Inputs

Name Type Description


pDBConfig POINTER TO ARRAY [1..MA Pointer address of the array into which the database
X_CONFIGURATIONS] OF S configurations are to be written.
T_ConfigDB [} 228]
cbDBConfig UDINT Length of the database configuration array
pAutoLogGrpConfig POINTER TO ARRAY[1..MAX Pointer address of the array into which the
_CONFIGURATIONS] OF AutoLogGrp configurations are to be written.
ST_ConfigAutoLogGrp [} 227]
cbAutoLogGrpConfig UDINT Length of the AutoLogGrp configuration array
pDBCount POINTER TO UDINT Pointer address for storing the number of database
configurations.
pAutoLogGrpCount POINTER TO UDINT Pointer address for storing the number of AutoLogGrp
configurations.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
aDBConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigDB;
aAutoGrpConfig : ARRAY[0..MAX_CONFIGURATIONS] OF ST_ConfigAutoLogGrp;
nDbCount : UDINT;
nAutoGrpCount : UDINT;
END_VAR
IF fbConfigTcDBSrv.Read(
pDBConfig := ADR(aDBConfig),
cbDBConfig := SIZEOF(aDBConfig),
pAutologGrpConfig := ADR(aAutoGrpConfig),
cbAutoLogGrpConfig := SIZEOF(aAutoGrpConfig),
pDBCount := ADR(nDbCount),
pAutoLogGrpCount := ADR(nAutoGrpCount))
THEN
IF fbConfigTcDBSrv.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.3.1.3 Delete
This method can be used to delete databases and AutoLog groups from the configuration of the
TwinCAT Database Server.

Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR

278 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


eTcDBSrvConfigType E_TcDBSrvConfigType Type of the configuration to be deleted (database /
AutoLog group)
hConfigID UDINT ID of the configuration to be deleted (hDBID or
hAutoLogGrpID)

Return value

Name Type Description


Delete BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbConfigTcDBSrv : FB_ConfigTcDBSrv(sNetId := '', tTimeout:=T#5S);
myConfigHandle : INT;
END_VAR
IF fbConfigTcDBSrv.Delete(
eTcDBSrvConfigType := E_TcDBSrvConfigType.Database,
hConfigID := myConfigHandle) THEN
IF fbConfigTcDBSrv.bError THEN
nState := 255;
ELSE
nState := 0;
END_IF
END_IF

6.1.4.3.2 FB_SQLDatabase

Function block for opening, closing and managing a database connection.

Syntax

Definition:
FUNCTION BLOCK FB_SQLDatabase
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

TF6420 Version: 1.13.4 279


PLC API

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResult Result interface with detailed information on the return
Event value.

Methods

Name Definition loca- Description


tion
Connect [} 280] Local Opens a connection to a declared database.
CreateCmd [} 281] Local Initializes an instance of the function block FB_SQLCommand
with the already open database connection of the function block
FB_SQLDatabase.
CreateSP [} 281] Local Initializes an instance of the function block
FB_SQLStoredProcedure with the already open database
connection of the function block FB_SQLDatabase.
Disconnect [} 282] Local Closes the connection to the database that was opened by this
function block instance.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.3.2.1 Connect
This method opens a connection to a declared database.

Syntax
METHOD Connect : BOOL
VAR_INPUT
hDBID: UDINT := 1;
END_VAR

Inputs

Name Type Description


hDBID UDINT Indicates the ID of the database to be used.

Return value

Name Type Description


Connect BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
END_VAR
// open connection
IF fbSqlDatabase.Connect(1) THEN
IF fbSqlDatabase.bError THEN
nState := 255;
ELSE

280 Version: 1.13.4 TF6420


PLC API

nState := nState+1;
END_IF
END_IF

6.1.4.3.2.2 CreateCmd
This method is used to initialize an instance of the function block FB_SQLCommand with the already open
database connection of the function block FB_SQLDatabase. The function block FB_SQLCommand only
uses the database connection it was assigned via the CreateCmd method. Several instances of the function
block FB_SQLCommand can be initialized with the same database connection.

The initialization of the function block FB_SQLCommand is completed in the same cycle. This means that
neither the Busy flag of the function block nor the method return value of the CreateCmd method have to be
checked.

Syntax
METHOD CreateCmd : BOOL
VAR_INPUT
pSQLCommand: POINTER TO FB_SQLCommand;
END_VAR

Inputs

Name Type Description


pSQLCommand POINTER TO FB_SQLCommand Returns a new instance of the function block
FB_SQLCommand.

Return value

Name Type Description


CreateCmd BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
END_VAR
// create a command reference
IF fbSqlDatabase.CreateCmd(ADR(fbSqlCommand)) THEN
IF fbSqlDatabase.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

FB_SQLCommandEvt [} 196] can then be used for the execution.

6.1.4.3.2.3 CreateSP
This method is used to initialize an instance of the function block FB_SQLStoredProcedure with the already
open database connection of the function block FB_SQLDatabase. The function block
FB_SQLStoredProcedure only uses the database connection it was assigned via the CreateCmd method.
Several instances of the function block FB_SQLStoredProcedure can be initialized with the same database
connection.

The initialization of the function block FB_SQLStoredProcedure may take several cycles. The Busy flag of
the function block or the method return value of the CreateCmd method have to be checked before the
function block can be used.

TF6420 Version: 1.13.4 281


PLC API

Syntax
METHOD CreateSP : BOOL
VAR_INPUT
sProcedureName: T_MaxString;
pParameterInfo: POINTER TO ARRAY [0..MAX_SPPARAMETER] OF ST_SQLSPParameter;
cbParameterInfo: UDINT;
pSQLProcedure: POINTER TO FB_SQLStoredProcedure;
END_VAR

Inputs

Name Type Description


sProcedureName T_MaxString Indicates the name of the procedure to be
executed.
pParameterInfo POINTER TO ARRAY [0..MAX_SPPAR Pointer address for the parameter info list.
AMETER] OF ST_SQLSPParameter
cbParameterInfo UDINT Indicates the length of the parameter info list.
pSQLProcedure POINTER TO FB_SQLStoredProcedure Returns a new instance of the function block
FB_SQLStoredProcedure.

Return value

Name Type Description


CreateSP BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
ParaInfo : ST_SQLSPParameter;
END_VAR
ParaInfo.sParameterName := '@Customer_ID';
ParaInfo.eParameterType := E_SPParameterType.Input;
ParaInfo.eParameterDataType := E_ColumnType.BigInt;
ParaInfo.nParameterSize := 8;

IF fbSQLDatabase.CreateSP('dbo.SP_GetCustomerPositions', ADR(ParaInfo), SIZEOF(ParaInfo), ADR(fbSQLS


toredProcedure)) THEN
IF fbSQLDatabase.bError THEN
nState:=255;
ELSE
nState:= nState+1;
END_IF
END_IF

Subsequently, the FB_SQLStoredProcedureEvt [} 201] can be used to execute the stored procedure.

6.1.4.3.2.4 Disconnect
This method closes the connection to the database that was opened by this function block instance.

Syntax
METHOD Disconnect : BOOL

Return value

Name Type Description


Disconnect BOOL Displays the status of the method. Returns TRUE as soon as the method
execution is finished, even in the event of an error.

282 Version: 1.13.4 TF6420


PLC API

Sample
VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
END_VAR
// disconnect from database
IF fbSqlDatabase.Disconnect() THEN
IF fbSqlDatabase.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

6.1.4.3.3 FB_SQLCommand

Function block for executing SQL commands. Before it can be used it has to be initialized with the function
block FB_SQLDatabase.

Syntax

Definition:
FUNCTION BLOCK FB_SQLCommand
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcResult Result interface with detailed information on the return
Event value.

TF6420 Version: 1.13.4 283


PLC API

Methods

Name Definition loca- Description


tion
Execute [} 284] Local Sends the specified SQL command to the database via the
database connection already opened by the function block
FB_SQLDatabase.
ExecuteDataReturn Local Sends the specified SQL command to the database via the
[} 285] database connection already opened by the function block
FB_SQLDatabase.
An instance of the function block FB_SQLResult can be
transferred for reading the returned records.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.3.3.1 Execute
This method sends the specified SQL command to the database via the database connection already
opened by the function block FB_SQLDatabase.

Syntax
METHOD Execute : BOOL
VAR_INPUT
pSQLCmd: POINTER TO BYTE;
cbSQLCmd: UDINT;
END_VAR

Inputs

Name Type Description


pSQLCmd POINTER TO BYTE Indicates the pointer address of a string variable with the SQL
command to be executed.
cbSQLCmd UDINT Indicates the length of a SQL command to be executed.

Return value

Name Type Description


Execute POINTER TO BYTE Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

Uses the command created by FB_SQLDatabaseEvt.CreateCmd() [} 192].


VAR
fbSqlCommand : FB_SQLCommandEvt(sNetID := '', tTimeout := T#5S);
tcMessage : I_TcMessage;
END_VAR
// you can generate this with the SQL Query Editor
sCmd := 'INSERT INTO myTable_Double ( Timestamp, Name, Value) VALUES ( $'2018-01-31 14:59:27$', $'Te
mperature$', 21.3)';

// call sql command


IF fbSQLCommand.Execute(ADR(sCmd), SIZEOF(sCmd)) THEN
IF fbSQLCommand.bError THEN
tcMessage := fbSQLCommand.ipTcResult;
nState := 255;
ELSE

284 Version: 1.13.4 TF6420


PLC API

nState := nState+1;
END_IF
END_IF

6.1.4.3.3.2 ExecuteDataReturn
This method sends the specified SQL command to the database via the database connection already
opened by the function block FB_SQLDatabase. An instance of the function block FB_SQLResult can be
transferred for reading the returned records.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
pSQLCmd: POINTER TO BYTE;
cbSQLCmd: UDINT;
pSQLDBResult: POINTER TO FB_SQLResult;
END_VAR

Inputs

Name Type Description


pSQLCmd POINTER TO BYTE Indicates the pointer address of a string variable with
the SQL command to be executed.
cbSQLCmd UDINT Indicates the length of a SQL command to be executed.
pSQLDBResult POINTER TO FB_SQLResult Returns a new instance of the function block
[} 285] FB_SQLResult.

Return value

Name Type Description


ExecuteDataReturn POINTER TO BYTE Displays the status of the method. Returns TRUE as soon
as the method execution is finished, even in the event of an
error.

Sample

Uses the command created by FB_SQLDatabaseEvt.CreateCmd() [} 192].


VAR
fbSqlCommand : FB_SQLCommandEvt(sNetID := '', tTimeout := T#5S);
tcMessage : I_TcMessage;
END_VAR
// you can generate this with the SQL Query Editor
sCmd := 'SELECT ID, Timestamp, Name, Value FROM myTable_Double';

// call sql command


IF fbSQLCommand.ExecuteDataReturn(ADR(sCmd), SIZEOF(sCmd), ADR(fbSqlResult)) THEN
IF fbSQLCommand.bError THEN
nState := 255;
ELSE
tcMessage := fbSQLCommand.ipTcResult;
nState := nState+1;
END_IF
END_IF

FB_SQLResultEvt [} 199] can then be used to read the data.

6.1.4.3.4 FB_SQLResult

TF6420 Version: 1.13.4 285


PLC API

The function block is used for reading the cached records.

Syntax

Definition:
FUNCTION BLOCK FB_SQLResult
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcRes Result interface with detailed information on the return value.
ultEvent

Methods

Name Definition loca- Description


tion
Read [} 286] Local Reads a specified number of records from the result data
cached in the TwinCAT Database Server.
Release [} 287] Local Releases data buffered by the TwinCAT Database Server.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.3.4.1 Read
This method reads a specified number of records from the result data cached in the
TwinCAT Database Server.

Syntax
METHOD Read : BOOL
VAR_INPUT
nStartIndex: UDINT := 0;
nRecordCount: UDINT := 1;
pData: POINTER TO BYTE;
cbData: UDINT;
bWithVerifying: BOOL := FALSE;
bDataRelease: BOOL := TRUE;
END_VAR

286 Version: 1.13.4 TF6420


PLC API

Inputs

Name Type Description


nStartIndex UDINT Indicates the index of the first record to be read.
nRecordCount UDINT Indicates the number of records to be read.
pData POINTER TO BYTE Address of the structure array into which the records are to be
written.
cbData UDINT Indicates the size of the structure array in bytes.
bWithVerifying BOOL Return data are compared with the pData structure array and
adjusted if necessary.
bDataRelease BOOL Releases the cached data.

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample
VAR
fbSqlResult : FB_SQLResultEvt(sNetID:='', tTimeout := T#5S);
aReadStruct : ARRAY[1..5] OF ST_StandardRecord;
END_VAR
// get values from internal tc db srv storage
IF fbSqlResult.Read(2, 3, ADR(aReadStruct), SIZEOF(aReadStruct), FALSE, TRUE) THEN
IF fbSqlResult.bError THEN
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

Result in the PLC:

6.1.4.3.4.2 Release
This method can be used to release data cached by the TwinCAT Database Server.

Syntax
METHOD Release : BOOL

TF6420 Version: 1.13.4 287


PLC API

Return value

Name Type Description


Release BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

6.1.4.3.5 FB_SQLStoredProcedure

Function block for executing stored procedures of the database. Before it can be used it has to be initialized
with the function block "FB_SQLDatabase".

Syntax

Definition:
FUNCTION BLOCK FB_SQLStoredProcedure
VAR_INPUT
sNetID: T_AmsNetID := '';
tTimeout: TIME := T#5S;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResultEvent: Tc3_EventLogger.I_TcResultEvent
END_VAR

Inputs

Name Type Description


sNetID T_AmsNetID AMS network ID of the target device at which the ADS command is
directed.
tTimeout TIME Indicates the time before the function is cancelled.

Outputs

Name Type Description


bBusy BOOL TRUE as soon as a method of the function block is active.
bError BOOL TRUE when an error occurs.
ipTcResultEvent Tc3_EventLogger.I_TcR Result interface with detailed information on the return value.
esultEvent

288 Version: 1.13.4 TF6420


PLC API

Methods

Name Definition loca- Description


tion
Execute [} 289] Local Sends the call of the specified stored procedure to the
database via the database connection already opened by the
function block FB_SQLDatabase.
ExecuteDataReturn Local Sends the call of the specified stored procedure to the
[} 290] database via the database connection already opened by the
function block FB_SQLDatabase.
An instance of the FB_SQLResult function block can be
transferred for reading the returned records.
Release [} 290] Local Releases the parameter information of the stored procedure
that was transferred during initialization.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.1 Build 4020.10 PC or CX (x86) Tc3_Database

6.1.4.3.5.1 Execute
This method sends the call of the specified stored procedure to the database via the database connection
already opened by the function block FB_SQLDatabase.

Syntax
METHOD Execute : BOOL
VAR_INPUT
pParameterStrc: POINTER TO BYTE;
cbParameterStrc: UDINT;
END_VAR

Inputs

Name Type Description


pParameterStrc POINTER TO BYTE Pointer address to the parameter structure that is transferred to
the procedure.
cbParameterStrc UDINT Length of the parameter structure

Return value

Name Type Description


Execute BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

Uses the stored procedure previously created with FB_SQLDatabaseEvt.CreateSP() [} 192].


VAR
fbSQLStoredProcedure : FB_SQLStoredProcedureEvt(sNetID:='', tTimeout := T#5S);
Customer_ID : LINT;
tcMessage : I_TcMessage;
END_VAR
IF fbSQLStoredProcedure.Execute(pParameterStrc := ADR(Customer_ID) , cbParameterStrc:= SIZEOF(Custom
er_ID)) THEN
IF fbSQLStoredProcedure.bError THEN
tcMessage := fbSQLStoredProcedure.ipTcResult;
nState := 255;
ELSE

TF6420 Version: 1.13.4 289


PLC API

nState := nState+1;
END_IF
END_IF

6.1.4.3.5.2 ExecuteDataReturn
This method sends the call of the specified stored procedure to the database via the database connection
already opened by the function block FB_SQLDatabase. An instance of the FB_SQLResult function block
can be transferred for reading the returned records.

Syntax
METHOD ExecuteDataReturn : BOOL
VAR_INPUT
pParameterStrc: POINTER TO BYTE;
cbParameterStrc: UDINT;
pSQLDBResult: POINTER TO FB_SQLDBResult;
END_VAR

Inputs

Name Type Description


pParameterStrc POINTER TO BYTE
Pointer address to the parameter structure that is transferred to
the procedure.
cbParameterStrc UDINT Length of the parameter structure
pSQLDBResult POINTER TO FB_SQL Returns a new instance of the function block FB_SQLDBResult.
DBResult

Return value

Name Type Description


Read BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

Sample

Uses the stored procedure previously created with FB_SQLDatabaseEvt.CreateSP() [} 192].


VAR
fbSQLStoredProcedure : FB_SQLStoredProcedureEvt(sNetID:='', tTimeout := T#5S);
Customer_ID : LINT;
tcMessage : I_TcMessage;
END_VAR
IF fbSQLStoredProcedure.ExecuteDataReturn(pParameterStrc := ADR(Customer_ID), cbParameterStrc:= SIZE
OF(Customer_ID), pSQLDBResult := ADR(fbSqlResult)) THEN
IF fbSQLStoredProcedure.bError THEN
tcMessage := fbSQLStoredProcedure.ipTcResult;
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

FB_SQLResultEvt [} 199] can then be used to read the data.

6.1.4.3.5.3 Release
This method releases the parameter information of the stored procedure, which was transferred during
initialization.

Syntax
METHOD Release : BOOL

290 Version: 1.13.4 TF6420


PLC API

Return value

Name Type Description


Release BOOL Displays the status of the method. Returns TRUE as soon as the
method execution is finished, even in the event of an error.

6.2 Tc2_Database
Overview

The Tc2_Database library contains function blocks for controlling and configuring the TwinCAT 3 database
server.

TF6420 Version: 1.13.4 291


PLC API

Function blocks

Name Description
FB_GetStateTcDatabase [} 293] Retrieves status information.

FB_DBConnectionAdd [} 295] Adds database connections to the XML configuration


file.
FB_DBAuthentificationAdd [} 314] Adds authentication information for the respective
database connection to the XML configuration file.
FB_DBOdbcConnectionAdd [} 296] Adds an ODBC database connection to the XML
configuration file.
FB_AdsDeviceConnectionAdd [} 298] Adds an ADS device to the XML configuration file.

FB_DBReloadConfig [} 294] Reloads the XML configuration file


FB_GetDBXMLConfig [} 299] Reads all database configurations from the XML
configuration file.
FB_GetAdsDevXMLConfig [} 299] Reads all ADS device configurations from the XML
configuration file.

FB_DBConnectionOpen [} 300] Opens a connection to a database.


FB_DBConnectionClose [} 301] Closes a connection to a database.

FB_DBCreate [} 302] Creates a new database


FB_DBTableCreate [} 303] Creates a table with any desired table structure

FB_DBRead [} 305] Reads one value out of the database


FB_DBWrite [} 306] Writes one variable value, with timestamp, into a
database
FB_DBCyclicRdWrt [} 304] Starts or stops the logging/writing of variables

FB_DBRecordSelect [} 316] Reads a data record out of a table


FB_DBRecordSelect_EX [} 318] Reads a data record out of a table (command length
less than 10,000 characters)
FB_DBRecordArraySelect [} 309] Reads several records from a table.
FB_DBRecordInsert [} 315] Creates a new data record.
FB_DBRecordInsert_EX [} 308] Creates a new data record. (command length less
than 10,000 characters)
FB_DBRecordDelete [} 307] Deletes a record from a table.

FB_DBStoredProcedures [} 311] Executes a stored procedure.


FB_DBStoredProceduresRecordReturn [} 319] Executes a stored procedure and returns a record.
FB_DBStoredProceduresRecordArray [} 312] Executes a stored procedure and returns several
records.

292 Version: 1.13.4 TF6420


PLC API

Data Types

Name
ST_DBColumnCfg [} 320]
ST_DBXMLCfg [} 320]
ST_ADSDevXMLCfg [} 321]
ST_DBSQLError [} 321]
ST_DBParameter [} 321]
E_DbColumnTypes [} 322]
E_DBTypes [} 323]
E_DBValueType [} 323]
E_DBWriteModes [} 323]
E_DBParameterTypes [} 323]

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1 Function blocks

6.2.1.1 FB_GetStateTcDatabase

The function block allows to get the current state of the Twincat Database Server.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

bExecute: The command is executed with the rising edge.

tTimeout: Indicates the timeout time.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
nAdsSta : UINT;
nDevState : UINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

TF6420 Version: 1.13.4 293


PLC API

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

nAdsState: Contains the state identification code of the ADS target device. The codes returned here are
specified for all ADS servers:
• ADSSTATE_INVALID =0 ;
• ADSSTATE_IDLE =1 ;
• ADSSTATE_RESET =2 ;
• ADSSTATE_INIT =3 ;
• ADSSTATE_START =4 ;
• ADSSTATE_RUN =5 ;
• ADSSTATE_STOP =6 ;
• ADSSTATE_SAVECFG =7 ;
• ADSSTATE_LOADCFG =8 ;
• ADSSTATE_POWERFAILURE =9 ;
• ADSSTATE_POWERGOOD =10 ;
• ADSSTATE_ERROR =11;

nDevState: Contains the specific state identification code of the ADS target device. The codes returned here
are supplementary information specific to the ADS device.
• 1 = TwinCAT Database Server started
• 2 = cyclic reading or writing started

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.2 FB_DBReloadConfig

With the FB_DBReloadConfig function block the XML configuration file can be reloaded.
If the XML configuration file was modified, the Database Server must be notified of the modifications with the
aid of FB_DBReloadConfig.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

bExecute: The command is executed with a rising edge.

tTimeout: States the length of the timeout that may not be exceeded by execution of the ADS command.

294 Version: 1.13.4 TF6420


PLC API

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.3 FB_DBConnectionAdd

The FB_DBConnectionAdd function block permits additional database connections to be added to the XML
configuration file.

VAR_INPUT
VAR_INPUT
sNetID :T_AmsNetId;
eDBType :E_DBTypes;
eDBValueType :E_DBValueType;
sDBServer :T_MaxString;
sDBProvider :T_MaxString;
sDBUrl :T_MaxString;
sDBSystemDB :T_MaxString;
sDBUserId :T_MaxString;
sDBPassword :T_MaxString;
sDBTable :T_MaxString;
bExecute :BOOL;
tTimeout :TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

eDBType: Indicates the type of the database, e.g. 'Mobile server'.

eDBValueType: Indicates the form in which the values are or will be stored.

sDBServer: Provides the name of the server: Optional.

sDBProvider: Gives the provider of the database: Optional.

sDBUrl: Gives the path to the database.

TF6420 Version: 1.13.4 295


PLC API

sSystemDB: Only for Access databases. Indicates the path to the MDW file.

sUserId: Indicates the login user name.

sPassword: Indicates the password.

sDBTable: Gives the name of the table into which the values are to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
bErrID : UDINT;
hDBID : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

hDBID: Returns the ID of the database.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.4 FB_DBOdbcConnectionAdd

The function block FB_DBOdbcConnectionAdd can be used to add further ODBC database connections to
the XML configuration file.

VAR_INPUT
VAR_INPUT
sNetID :T_AmsNetId;
eDBType :E_DBTypes;
eDBValueType :E_DBValueType;
sDBDriver :T_MaxString;
sDBServer :T_MaxString;

296 Version: 1.13.4 TF6420


PLC API

sDBDatabase :T_MaxString;
nDBPort :UDINT;
sDBProtocol :T_MaxString;
sDBUserId :T_MaxString;
sDBPassword :T_MaxString;
sDBScheme :T_MaxString;
sDBSequence :T_MaxString;
sDBClientDll :T_MaxString;
sDBTable :T_MaxString;
bExecute :BOOL;
tTimeout :TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

eDBType: Indicates the type of the database, e.g. 'Mobile server'.

eDBValueType: Indicates the form in which the values are or will be stored.

sDBDriver: Indicates the name of the ODBC driver to be used.

sDBServer: Indicates the name of the server.

sDBDatabase: Indicates the name of the database.

nDBPort: Indicates the port for the ODBC connection.

sDBProtocol: Indicates the protocol to be used (TCPIP).

sDBUserId: Indicates the user name.

sDBPassword: Indicates the password to be used.

sDBScheme: Indicates the database schema to be used.

sDBSequence: Indicates the sequence name for Oracle databases.

sDBClientDll: Contains the path to fbclient.dll. (Only for Firebird/Interbase databases)

sDBTable: Gives the name of the table into which the values are to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
bErrID : UDINT;
hDBID : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

hDBID: Returns the ID of the database.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

TF6420 Version: 1.13.4 297


PLC API

6.2.1.5 FB_AdsDeviceConnectionAdd

The function block FB_AdsDeviceConnectionAdd permits additional Ads-Device connections to be added to


the XML configuration file.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
sADSDevNetID : T_AmsNetID;
nADSDevPort : UINT;
tADSDevTimeout : TIME;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

sADSDevNetID: String containing the AMS network ID of the ADS device.

nADSDevPort: Indicates the port of the ADS device.

tAdsDevTimeout: Indicates the timeout time of the ADS device.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the duration of the timeout.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
hAdsId : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

hAdsId: Returns the ID of the ADS device.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

298 Version: 1.13.4 TF6420


PLC API

6.2.1.6 FB_GetDBXMLConfig

With this function block FB_GetDBXMLConfig all declared databases can be read out of the XML-
configuration file.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
cbDBCfg : UDINT;
pDBCfg : POINTER TO ARRAY [0.. MAX_XML_DECLARATIONS] OF ST_DBXMLCfg
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

cbDBCfg: Indicates the length of the array, into which the configurations are to be written.

pDBCfg: Indicates the pointer address of the array, into which the configurations are to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.7 FB_GetAdsDevXMLConfig

With this function block FB_GetAdsDevXMLConfig all declared ADS-devices can be read out of the XML-
configuration file.

TF6420 Version: 1.13.4 299


PLC API

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
cbAdsDevCfg : UDINT;
pAdsDevCfg : POINTER TO ARRAY [0.. MAX_XML_DECLARATIONS] OF ST_ADSDevXMLCfg
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

cbAdsDevCfg: Indicates the length of the array, into which the configurations are to be written.

pAdsDevCfg: Indicates the pointer address of the array, into which the configurations are to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.8 FB_DBConnectionOpen

You can open connections to databases with this function block FB_DBConnectionOpen. This can improve
the read and write access speed with the fuction blocks FB_DBWrite, FB_DBRead, FB_DBRecordInsert and
FB_FBRecordSelect.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : DINT;
bExecute: BOOL;
tTimeout: TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

300 Version: 1.13.4 TF6420


PLC API

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState : Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.9 FB_DBConnectionClose

The function block FB_DBConnectionClose can be used to make connections with databases. If a
connection with a database was opened previously, it must be closed again.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : DINT;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError: BOOL;
nErrID: UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

TF6420 Version: 1.13.4 301


PLC API

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.10 FB_DBCreate

The FB_DBCreate function block allows databases to be created.

The following database types can be created with this function block: MS SQL databases, MS SQL Compact
databases, MS Access databases and XML databases

ASCII files can (but do not have to) be created with the function block FB_DBCreate. If they do not exist,
they are created automatically during the first write access. They only have to be declared in the XML
configuration file.

It is not possible to create DB2, Oracle, MySQL, PostgreSQL, InterBase and Firebird databases. In addition,
it is not possible to overwrite existing databases. In this case the function block FB_DBCreate would return
an error.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
sPathName : T_MaxString;
sDBName : T_MaxString;
eDBType : E_DBTypes;
sSystemDB : T_MaxString;
sUserID : T_MaxString;
sPassword : T_MaxString;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

sPathName: Gives the path to the database.

sDBName: Gives the name of the database that is to be created.

eDBType: Gives the type of the database that is to be created.

sSystemDB: Only for Access databases. Contains the path to the MDW file.

sUserID: User name for the corresponding registration

sPassword: Corresponding password

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the duration of the timeout.

302 Version: 1.13.4 TF6420


PLC API

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

TwinCAT Database Server


If the newly created databases are to be used by the TwinCAT Database Server, the connection
data have to be written to the XML configuration file with the aid of the function block
FB_DBConnectionADD.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.11 FB_DBTableCreate

The FB_DBTableCreate function block permits tables with any desired table structure to be created in
databases.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
hDBID : UDINT;
sTableName : T_MaxString;
cbTableCfg : UDINT;
pTableCfg : POINTER TO ARRAY[0..MAX_DB_TABLE_COLUMNS] OF ST_DBColumnCfg;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: ID of the database to be used.

sTableName: Provides the name of the table.

cbTableCfg: Returns the length of the array in which the columns are configured.

pTableCfg: Provides the pointer address of the table structure array. The individual columns are written in
this array.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the duration of the timeout.

TF6420 Version: 1.13.4 303


PLC API

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.12 FB_DBCyclicRdWrt

The FB_DBCyclicRdWrt function block can be used to start or stop the cyclic logging \ writing of variables.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
bExecute: BOOL;
tTimeout: TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

bExecute: The read/write cycle is started with a rising edge and stopped with a falling edge.

tTimeout: States the length of the timeout that may not be exceeded by execution of the ADS command.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

304 Version: 1.13.4 TF6420


PLC API

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.13 FB_DBRead

The FB_DBRead allows values to be read from a database.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : DINT;
sDBVarName: STRING(80);
cbReadLen : UDINT;
pDestAddr : POINTER TO BYTE;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

sDBVarName: Gives the name of the variable that is to be read.

cbReadLen: Indicates the length of the buffer that is to be read.

pDestAddr: Contains the address of the buffer which is to receive the data that has been read.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

TF6420 Version: 1.13.4 305


PLC API

6.2.1.14 FB_DBWrite

The FB_DBWrite function block can be used to write the values of individual variables into databases.
The table structure must contain the columns "Timestamp", "Name", and "Value" (see "SQL Compact
database" [} 128]). In order to be able to use the function block, the database that is to be used for write
access and the ADS device, from which the variables are to be read, must be declared in the XML
configuration file.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
hDBID : UDINT;
hAdsID : UDINT;
sVarName : T_MaxString;
nIGroup : UDINT;
nIOffset : UDINT;
nVarSize : UDINT;
sVarType : T_MaxString;
sDBVarName : T_MaxString;
eDBWriteMode : E_DBWriteModes;
tRingBufferTime : TIME;
nRingBufferCount: UDINT;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: ID of the database to be used.

hAdsID: ID of the ADS device to be used.

sVarName: Provides the name of the variable.

nIGroup: Index group of the variable (optional, only on the BC9000).

nIOffset: Index offset of the variable (optional, only on the BC9000).

nVarSize: Size of the variable in bytes (optional, only on the BC9000).

sVarType: Data type of the variable (optional, only on the BC9000).

Possible variable data types: "BOOL" / "LREAL" / "REAL" / "INT16" / "DINT" / "USINT" / "BYTE" / "UDINT" /
"DWORD" / "UINT16" / "WORD" / "SINT"
sDBVarName: Variable name to be used in the database.

eDBWriteMode: Indicates whether the values are to be appended in new records or whether the existing
records are to be updated.

tRingBufferTime: Indicates the maximum age of records in a table (only for Ringbuffer_WriteMode).

306 Version: 1.13.4 TF6420


PLC API

nRingBufferCount: Indicates the maximum number of records in a table (only for Ringbuffer_WriteMode).

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Log values of ADS devices (except BC9000) Log values of BC9000


FB_DBWrite1( FB_DBWrite1( sNetID:= , hDBID:= 1, hAdsID:= 1,
sNetID:= , sVarName:= 'MAIN.TestVar', nIGroup:= 16448,
hDBID:= 1, nIOffset:= 0, nVarSize:= 16, sVarType:= 'REAL',
hAdsID:= 1, sDBVarName:= 'DBTestVar', eDBWriteMode:=
sVarName:= 'MAIN.TestVar', eDBWriteMode_Append, bExecute:= TRUE,
sDBVarName:= 'DBTestVar', tTimeout:= T#15s, bBusy=> busy, bError=> err,
eDBWriteMode:= eDBWriteMode_Append, nErrID=> errid, sSQLState=> sqlstate);
bExecute:= TRUE,
tTimeout:= T#15s,
bBusy=> busy,
bError=> err,
nErrID=> errid,
sSQLState=> sqlstate
);

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.15 FB_DBRecordDelete

The function block FB_DBRecordDelete can be used to delete individual records from a database. This
function block can be used to execute SQL DELETE commands with up to 10,000 characters.
To use the function block it is necessary to declare the database from which the records are to be deleted in
the XML configuration file.

TF6420 Version: 1.13.4 307


PLC API

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : UDINT;
cbCmdSize: UDINT;
pCmdAddr : POINTER TO BYTE;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

cbCmdSize: Indicates the length of the INSERT command.

pCmdAddr: Pointer to the executing INSERT command.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.16 FB_DBRecordInsert_EX

The function block FB_DBRecordInsert_EX can be used to write individual records with any structure into a
database. This function block can be used to execute SQL INSERT commands with up to 10,000 characters.
To use the function block it is necessary to declare the database to which the records are to be written in the
XML configuration file.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : UDINT;
cbCmdSize: UDINT;
pCmdAddr : POINTER TO BYTE;

308 Version: 1.13.4 TF6420


PLC API

bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

cbCmdSize: Indicates the length of the INSERT command.

pCmdAddr: Pointer to the executing INSERT command

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.17 FB_DBRecordArraySelect

The function block FB_DBRecordArraySelect can be used to read several records with any structure from
the database. This function block can be used to execute an SQL SELECT command with up to 10,000
characters.
This function block is not compatible with ASCII files.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
hDBID : UDINT;
cbCmdSize : UDINT;
pCmdAddr : UDINT;

TF6420 Version: 1.13.4 309


PLC API

nStartIndex : UDINT;
nRecordCount : UDINT;
cbRecordArraySize: UDINT;
pDestAddr : POINTER TO BYTE;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

cbCmdSize: Indicates the length of a SELECT command to be executed.

pCmdSize: Indicates the pointer address of a string variable with the SQL command to be executed.

nStartIndex: Indicates the index of the first record to be read.

nRecordCount: Indicates the number of records to be read.

cbRecordArraySize: Indicates the size of the structure array in bytes.

pDestAddr: Indicates the address of the structure array into which the records are to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
nRecords : UDINT;
END_VAR

ST_DBSQLError [} 321]

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code of the corresponding database type

nRecords: Returns the number of data records.

Sample in ST

Since the table, from which the records are to be read, has the structure below, a PLC structure with a
similar structure must be created.

Table:

Column name Data type


ID Bigint
Timestamp datetime
Name nvarchar(80)
Value float

Structure:
TYPE ST_Record:
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Name : STRING(80);

310 Version: 1.13.4 TF6420


PLC API

VALUE : LREAL;
END_STRUCT
END_TYPE

The library TcUtilities.lib must be integrated in order to be able to use the data type T_ULARGE_INTEGER.

For ARM processors the data types have to be arranged differently due to the byte alignment, and a "dummy
byte" has to be added.
TYPE ST_Record :
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Value : LREAL;
Name : STRING(80);
Dummy : BYTE;
END_STRUCT
END_TYPE
PROGRAM MAIN
VAR
FB_DBRecordArraySelect1 : FB_DBRecordArraySelect;
cmd : T_Maxstring := 'SELECT * FROM myTable';
(* Unter ARM*)
(*cmd : T_Maxstring := 'SELECT ID,Timestamp,Value,Name FROM myTable'*)
(*----------*)
recordArray : ARRAY [1..5] OF ST_Record;
busy : BOOL;
err : BOOL;
errid : UDINT;
sqlstate : ST_DBSQLError;
recAnz : UDINT;
END_VAR

PLC program
FB_DBRecordArraySelect1(
sNetID:= ,
hDBID:= 1,
cbCmdSize:= SIZEOF(cmd),
pCmdAddr:= ADR(cmd),
nStartIndex:= 0,
nRecordCount:= 5,
cbRecordArraySize:= SIZEOF(recordArray),
pDestAddr:= ADR(recordArray),
bExecute:= TRUE,
tTimeout:= T#15s,
bBusy=> busy,
bError=> err,
nErrID=> errid,
sSQLState=> sqlstate,
nRecords=> recAnz);

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.18 FB_DBStoredProcedures

The function block FB_DBStoredProcedures can be used to call up stored procedures. They can include
parameters in the process, which are used in the stored procedures.

TF6420 Version: 1.13.4 311


PLC API

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID :='';
hDBID : UDINT :=1;
sProcedureName : T_MaxString :='';
cbParameterList: UDINT;
pParameterList : POINTER TO ARRAY[0..MAX_STORED_PROCEDURES_PARAMETERS] OF ST_DBParameter;
bExecute : BOOL;
tTimeout : TIME := T#15s;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

sProcedureName: Indicates the name of the procedure to be executed

cbParameterList: Indicates the length of the parameter list.

pParameterList: Contains the address of the parameter list

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.19 FB_DBStoredProceduresRecordArray

The function block FB_DBStoredProceduresRecordArray can be used to call stored procedures that return
records. In contrast to the FB_DBStoredProceduresRecordReturn function block, this function block can be
used to return several records with a single call. They can include parameters in the process, which are used
in the stored procedures.

312 Version: 1.13.4 TF6420


PLC API

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID :='';
hDBID : UDINT :=1;
sProcedureName : T_MaxString :='';
cbParameterList : UDINT;
pParameterList : POINTER TO ARRAY[0..MAX_STORED_PROCEDURES_PARAMETERS] OF ST_DBParameter;
nStartIndex : UDINT;
nRecordCount : UDINT
cbRecordArraySize: UDINT;
pDesAddr : POINTER TO BYTE;
bExecute : BOOL;
tTimeout : TIME := T#15s;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

sProcedureName: Indicates the name of the procedure to be executed.

cbParameterList: Indicates the length of the parameter list.

pParameterList: Contains the address of the parameter list

nStartIndex: Indicates the index of the first record to be read.

nRecordCount: Indicates the number of records to be read.

cbRecordArraySize: Indicates the size of the structure array in bytes.

pDestAddr: Indicates the address of the structure array into which the records are to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
nRecords : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as "bBusy" remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

nRecords: Returns the number of data records.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

TF6420 Version: 1.13.4 313


PLC API

6.2.1.20 Obsolete

6.2.1.20.1 FB_DBAuthentificationAdd

The function block FB_DBAuthentificationAdd permits authentication information of declared database


connection to be added to the XML configuration file or to be changed.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
hDBID : DINT;
sDBSystemDB: T_MaxString;
sDBUserId : T_MaxString;
sDBPassword: T_MaxString;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Is the ID of the database to be used.

sSystemDB: Only for Access databases. Indicates the path to the MDW file.

sUserId: Indicates the login user name.

sPassword: Indicates the password.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the duration of the timeout.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError: BOOL;
nErrID: UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as "bBusy" remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code if the bError output is set.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

314 Version: 1.13.4 TF6420


PLC API

6.2.1.20.2 FB_DBRecordInsert

The function block FB_DBRecordInsert can be used to write individual records with any structure into a
database. To use the function block it is necessary to declare the database to which the records are to be
written in the XML configuration file.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : UDINT;
sInsertCmd: T_MaxString;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

sInsertCmd: Indicates which INSERT command is to be executed.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

TF6420 Version: 1.13.4 315


PLC API

6.2.1.20.3 FB_DBRecordSelect

The FB_DBRecordSelect allows individual data records to be read from a database.


This function block is not compatible with ASCII files.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
hDBID : UDINT;
sSelectCmd : T_MaxString;
nRecordIndex: UDINT;
cbRecordSize: UDINT;
pDestAddr : DWORD;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

sSelectCmd: Indicates which SELECT command is to be executed.

nRecordIndex: Gives the index of the data record that is to be read.

cbRecordSize: Provides the size of a data record in bytes.

pDestAddr: Indicates the address of the structure to which the record is to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
nRecords : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

nRecords: Returns the number of data records.

316 Version: 1.13.4 TF6420


PLC API

Example in ST:

Since the table, from which the records are to be read, has the structure below, a PLC structure with a
similar structure must be created.

Table:

Column name Data type


ID Bigint
Timestamp datetime
Name Ntext
Value Float

Structure:
TYPE ST_Record :
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Name : STRING;
VALUE : LREAL;
END_STRUCT
END_TYPE

The library TcUtilities.lib must be integrated in order to be able to use the data type T_ULARGE_INTEGER.

For ARM processors the data types have to be arranged differently due to the byte alignment, and a "dummy
BYTE" has to be added.
TYPE ST_Record :
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Value : LREAL;
Name : STRING;
Dummy : BYTE;
END_STRUCT
END_TYPE
PROGRAM MAIN
VAR
FB_DBRecordSelect1: FB_DBRecordSelect;
cmd : T_Maxstring := 'SELECT * FROM myTable';
(* Unter ARM*)
(*cmd : T_Maxstring := 'SELECT ID,Timestamp,Value,Name FROM myTable'*)
(*----------*)
record : ST_Record;
busy : BOOL;
err : BOOL;
errid : UDINT;
recAnz : DINT;
END_VAR

PLC program
FB_DBRecordSelect1(
sNetID := ,
hDBID := 2,
sSelectCmd := cmd,
nRecordIndex:= 0,
cbRecordSize:= SIZEOF(record),
pDestAddr := ADR(record),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => busy,
bError => err,
nErrID => errid,
nRecords => recAnz);

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

TF6420 Version: 1.13.4 317


PLC API

6.2.1.20.4 FB_DBRecordSelect_EX

The function block FB_DBRecordSelect_EX can be used to read individual records with any structure from
the database. This function block can be used to execute an SQL SELECT command with up to 10,000
characters.
This function block is not compatible with ASCII files.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
Hdbid : UDINT;
cbCmdSize : UDINT;
pCmdAddr : UDINT;
nRecordIndex: UDINT;
cbRecordSize: UDINT;
pDestAddr : POINTER TO BYTE;
bExecute : BOOL;
tTimeout : TIME;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

cbCmdSize: Indicates the length of a SELECT command to be executed.

pCmdSize: Indicates the pointer address of a string variable with the SQL command to be executed.

nRecordIndex: Gives the index of the data record that is to be read.

cbRecordSize: Provides the size of a data record in bytes.

pDestAddr: Indicates the address of the structure to which the record is to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
nRecords : UDINT;
END_VAR

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

318 Version: 1.13.4 TF6420


PLC API

nRecords: Returns the number of data records.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.1.20.5 FB_DBStoredProceduresRecordReturn

The function block FB_DBStoredProceduresRecordReturn can be used to call up stored procedures that
return a record. They can include parameters in the process, which are used in the stored procedures.

VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID :='';
hDBID : UDINT :=1;
sProcedureName : T_MaxString :='';
cbParameterList: UDINT;
pParameterList : POINTER TO ARRAY[0..MAX_STORED_PROCEDURES_PARAMETERS] OF ST_DBParameter;
nRecordIndex : UDINT;
cbRecordSize : UDINT;
pRecordAddr : POINTER TO BYTE;
bExecute : BOOL;
tTimeout : TIME := T#15s;
END_VAR

sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.

hDBID: Indicates the ID of the database to be used.

sProcedureName: Indicates the name of the procedure to be executed.

cbParameterList: Indicates the length of the parameter list.

pParameterList: Contains the address of the parameter list

nRecordIndex: Gives the index of the data record that is to be read.

cbRecordSize: Provides the size of a data record in bytes.

pRecordAddr: Indicates the address of the structure to which the record is to be written.

bExecute: The command is executed with a rising edge.

tTimeout: Indicates the time before the function is cancelled.

VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
nRecords : UDINT;
END_VAR

TF6420 Version: 1.13.4 319


PLC API

bBusy: The command is in the process of being transmitted by ADS. No new command will be accepted as
long as bBusy remains TRUE.

bError: Becomes TRUE, as soon as an error occurs.

nErrID: Returns the ADS error code or TcDatabaseSrv_Error_Codes [} 398] if the bError output is set.

sSQLState: Returns the SQL error code [} 321] of the corresponding database type

nRecords: Returns the number of data records.

Requirements

Development environment Target system type PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2 Data types

6.2.2.1 ST_DBColumnCfg

VAR_INPUT
TYPE ST_DBColumnCfg :
STRUCT
sColumnName : STRING(59);
sColumnProperty: STRING(59);
eColumnType : E_DbColumnTypes;
END_STRUCT
END_TYPE

sColumnName: Contains the name of the column to be created.

sColumnProperty: Contains certain column properties.

eColumnType: Gives the type of column.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.2 ST_DBXMLCfg

VAR_INPUT
TYPE ST_DBXMLCfg :
STRUCT
sDBName : STRING;
sDBTable: STRING;
nDBID : DINT;
eDBType : E_DBTypes;
END_STRUCT
END_TYPE

sDBName: Contains the name of the database.

sDBTable: Contains the name of the table.

nDBID: Returns the ID of the database.

eDBType: Gives the type of database.

320 Version: 1.13.4 TF6420


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.3 ST_ADSDevXMLCfg

VAR_INPUT
TYPE ST_ADSDevXMLCfg :
STRUCT
sAdsDevNetID : T_AmsNetID;
tAdsDevTimeout: TIME;
nAdsDevID : DINT;
nAdsDevPort : UINT;
END_STRUCT
END_TYPE

sAdsDevNetID: String containing the AMS network ID of the ADS device.

tAdsDevTimeout: Indicates the timeout time of the ADS device.

nAdsDevID: Returns the ID of the ADS device.

nAdsDevPort: Indicates the port of the ADS device.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.4 ST_DBSQLError

VAR_INPUT
TYPE ST_DBSQLError :
STRUCT
sSQLState : STRING(5);
nSQLErrorCode: DINT;
END_STRUCT
END_TYPE

sSQLState: Contains the 5-character error code, which is based on the SQL ANSI standard.

nSQLErrorCode: Returns a database-specific error code.

If no error has occurred, the structure contains the following values:


sSQLState := '00000';
nSQLErrorCode := 0;

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.5 ST_DBParameter

VAR_INPUT
TYPE ST_DBParameter :
STRUCT
sParameterName : STRING(59);
cbParameterValue : UDINT;
pParameterValue : UDINT;
eParameterDataType: E_DBColumnTypes;

TF6420 Version: 1.13.4 321


PLC API

eParameterType : E_DBParameterTypes;
END_STRUCT
END_TYPE

sParameterName: Indicates the name of the parameter.

cbParameterValue: Contains the size of the variable to be used in bytes.

pParameterValue: Contains the address of the variable to be used.

eParameterDataType: Indicates the data type of the parameter (E_DBColumnTypes [} 322]).

eParameterType: Indicates the parameter type (E_DBParameterTypes [} 323]).

Declaration sample

Variable Declaration
PROGRAM MAIN
VAR
paraList: ARRAY [0..2] OF ST_DBParameter;
p1: DINT := 3;
p2: LREAL;
p3: STRING;
END_VAR

PLC program
paraList[0].sParameterName := 'p1';
paraList[0].eParameterDataType:= eDBColumn_Integer;
paraList[0].eParameterType := eDBParameter_Input;
paraList[0].cbParameterValue := SIZEOF(p1);
paraList[0].pParameterValue := ADR(p1);

paraList[1].sParameterName := 'p2';
paraList[1].eParameterDataType:= eDBColumn_Float;
paraList[1].eParameterType := eDBParameter_Output;
paraList[1].cbParameterValue := SIZEOF(p2);
paraList[1].pParameterValue := ADR(p1);

paraList[2].sParameterName := 'p3';
paraList[2].eParameterDataType:= eDBColumn_NText;
paraList[2].eParameterType := eDBParameter_Output;
paraList[2].cbParameterValue := SIZEOF(p3);
paraList[2].pParameterValue := ADR(p3);

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.6 E_DbColumnTypes
TYPE E_DbColumnTypes :
(
eDBColumn_BigInt :=0,
eDBColumn_Integer :=1,
eDBColumn_SmallInt :=2,
eDBColumn_TinyInt :=3,
eDBColumn_Bit :=4,
eDBColumn_Money :=5,
eDBColumn_Float :=6,
eDBColumn_Real :=7,
eDBColumn_DateTime :=8,
eDBColumn_NText :=9,
eDBColumn_NChar :=10,
eDBColumn_Image :=11,
eDBColumn_NVarChar :=12,
eDBColumn_Binary :=13,
eDBColumn_VarBinary :=14
);
END_TYPE

322 Version: 1.13.4 TF6420


PLC API

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.7 E_DBTypes
TYPE E_DBTypes :
(
eDBType_Mobile_Server := 0,
eDBType_Access := 1,
eDBType_Sequal_Server := 2,
eDBType_ASCII := 3,
eDBType_ODBC_MySQL := 4,
eDBType_ODBC_PostgreSQL:= 5,
eDBType_ODBC_Oracle := 6,
eDBType_ODBC_DB2 := 7,
eDBType_ODBC_InterBase := 8,
eDBType_ODBC_Firebird := 9,
eDBType_XML := 10,
eDBType_OCI_Oracle := 11
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.8 E_DBValueType
TYPE E_DBValueType :
(
eDBValue_Double:= 0,
eDBValue_Bytes := 1
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.9 E_DBWriteModes
TYPE E_DBWriteModes :
(
eDBWriteMode_Update := 0,
eDBWriteMode_Append := 1,
eDBWriteMode_RingBuffer_Time := 2,
eDBWriteMode_RingBuffer_Count:= 3
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.2.10 E_DBParameterTypes
TYPE E_DBParameterTypes :
(
eDBParameter_Input := 0,
eDBParameter_Output := 1,
eDBParameter_InputOutput := 2,
eDBParameter_ReturnValue := 3,

TF6420 Version: 1.13.4 323


PLC API

eDBParameter_OracleCursor:= 4
);
END_TYPE

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.3 Global Constants

6.2.3.1 Constants
VAR_GLOBAL_CONSTANT

AMSPORT_DATABASESRV : UINT := 21372;

DBADS_IGR_RELOADXML : UDINT :=16#100;

DBADS_IGR_GETSTATE : UDINT :=16#200;

DBADS_IGR_DBCONNOPEN : UDINT :=16#300;


DBADS_IGR_DBCONNCLOSE : UDINT :=16#301;
DBADS_IGR_ADSDEVCONNOPEN : UDINT :=16#302;
DBADS_IGR_ADSDEVCONNCLOSE : UDINT :=16#303;

DBADS_IGR_DBSTOREDPROCEDURES : UDINT :=16#400;


DBADS_IGR_DBSTOREDPROCEDURES_RETURNRECORD : UDINT :=16#401;
DBADS_IGR_DBSTOREDPROCEDURES_RETURNRECORDARRAY: UDINT :=16#402;

DBADS_IGR_START : UDINT :=16#10000;


DBADS_IGR_STOP : UDINT :=16#20000;

DBADS_IGR_DBCONNADD : UDINT :=16#30000;


DBADS_IGR_ADSDEVCONNADD : UDINT :=16#30001;
DBADS_IGR_ODBC_DBCONNADD : UDINT :=16#30010;

DBADS_IGR_GETDBXMLCONFIG : UDINT :=16#30101;


DBADS_IGR_GETADSDEVXMLCONFIG : UDINT :=16#30102;

DBADS_IGR_DBWRITE : UDINT :=16#40000;


DBADS_IGR_DBREAD : UDINT :=16#50000;

DBADS_IGR_DBTABLECREATE : UDINT :=16#60000;


DBADS_IGR_DBCREATE : UDINT :=16#70000;

DBADS_IGR_DBRECORDSELECT : UDINT :=16#80001;


DBADS_IGR_DBRECORDINSERT : UDINT :=16#80002;
DBADS_IGR_DBRECORDDELETE : UDINT :=16#80003;

DBADS_IGR_DBAUTHENTIFICATIONADD : UDINT :=16#90000;

MAX_DB_TABLE_COLUMNS : UDINT := 255;


MAX_XML_DECLARATIONS : UDINT := 255;
MAX_STORED_PROCEDURES_PARAMETERS : UDINT := 255;

END_VAR

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

6.2.3.2 Library version


All libraries have a certain version. The version is indicated in the PLC library repository, for example. A
global constant contains the information about the library version:

Global_Version

324 Version: 1.13.4 TF6420


PLC API

VAR_GLOBAL CONSTANT
stLibVersion_TC3_Database_Server : ST_LibVersion;
END_VAR

Use the function F_CmpLibVersion (defined in the Tc2_System library) to check whether you are using the
correct version.

All other options for comparing library versions, which you may know from TwinCAT 2, are
outdated!

TF6420 Version: 1.13.4 325


Examples

7 Examples

7.1 Tc3_Database
The following pages introduce samples and tips for using the TwinCAT Database Server with the library for
TwinCAT 3.

7.1.1 Scenario examples


Each sample is assigned to a scenario, which can be adapted to specific use cases. Information on which
databases the samples are compatible with is also provided.

7.1.1.1 Home automation


This scenario example illustrates the configuration mode for building automation. Symbols are written to an
MySQL database in three different AutoLog groups without additional programming, i.e. purely based on the
configuration. Room temperatures are logged in the database at 5-minute intervals. Energy data are saved
at 1-minute intervals. Events such as "lamp on", "lamp off" are stored.

Category Configure Mode


Database used MySQL
Compatible databases Can be used for all supported database types
PLC function blocks used None
PLC libraries used Tc3_Database, Tc2_BABasic
Download https://infosys.beckhoff.com/content/1033/
TF6420_Tc3_Database_Server/Resources/
3495185419/.zip

ü TwinCAT Database Server project was created.

326 Version: 1.13.4 TF6420


Examples

1. Add and configure the database connection.

2. Since logging is to take place in three different tables, three AutoLog groups are appended to the
database connection. First the temperature AutoLog group is configured. TheCycleTime is set to
300000 ms to match the 5-minute database logging interval.

TF6420 Version: 1.13.4 327


Examples

3. Then the ADS device from which the ADS symbols are to be read is set up.

4. The symbols are created with the target browser.

328 Version: 1.13.4 TF6420


Examples

5. Now you can select the table into which the temperature values are to be written. The AutoLog groups
support two TableModes [} 39]. The standard table structure is used for the temperature values. A tick
indicates that the selected table has the correct structure.

6. Then the AutoLog group for the events is configured. The LogMode for the group is set to "onChange",
the cycle time to 1000 ms. This means that the symbols are checked at 1-second intervals but a table
entry is only created if a value changes.

TF6420 Version: 1.13.4 329


Examples

7. Then the ADS device and the symbols are selected, as described in steps 3 and 4.

8. The events are also store in a standard table structure.

330 Version: 1.13.4 TF6420


Examples

9. Finally the energy data are saved at 1-minute intervals.

10. For the energy data the ADS device and the symbols are also selected.

TF6420 Version: 1.13.4 331


Examples

11. The energy data should be stored in a custom table structure, with the various symbols assigned to the
columns.

ð Logging can now be started and monitored with the AutoLog Viewer [} 47].

7.1.1.2 Message logger


This scenario example illustrates the PLC Expert Mode for a Message Logger in the PLC. In the sample
program the function blocks of the TwinCAT Database Server are used to create a function block, which
provides various methods for generating and reading messages. The database in which the messages are
stored is created from the PLC. A sample application of the created function block is implemented in the
MAIN program. A new database file is created every 7 days. Three different messages can be sent. In
addition it is possible to call up the last message or all messages from a particular interval.

332 Version: 1.13.4 TF6420


Examples

Category PLC Expert Mode


Database used MS Compact [} 128]
Compatible databases Can be used with minor amendments for all
supported database types
PLC function blocks used FB_PLCDBCreateEvt [} 171], FB_PLCDBCmdEvt
[} 183], FB_PLCDBWriteEvt [} 178], FB_PLCDBReadEvt
[} 175]
PLC libraries used Tc3_Database, Tc3_Eventlogger
Download https://infosys.beckhoff.com/content/1033/
TF6420_Tc3_Database_Server/Resources/
3495187979/.zip

FB_ErrorLogger

CreateErrorLogDB (method)

The CreateErrorLogDB method creates an MS Compact database file and the table in which the messages
are stored.
METHOD CreateErrorLogDB : BOOL
VAR_INPUT
sDBName : T_MaxString;
END_VAR
CASE nState_CreateDB OF
0:
stDBConfig.sServer := CONCAT(CONCAT(sDBPath, sDBName), '.sdf');
stDBConfig.bAuthentification := FALSE;

nState_CreateDB := 1;
1:
IF fbPLCDBCreate.Database(pDatabaseConfig:= ADR(stDBConfig),
cbDatabaseConfig:= SIZEOF(stDBConfig),
bCreateXMLConfig:= FALSE, pDBID:= 0) THEN
ipResultEvt := fbPLCDBCreate.ipTcResult;
IF fbPLCDBCreate.bError THEN
nState_CreateDB := 100;
ELSE

TF6420 Version: 1.13.4 333


Examples

nState_CreateDB := 2;
END_IF
END_IF
2:
IF fbConfigTcDBSrv.Create(pTcDBSrvConfig:= ADR(stDBConfig),
cbTcDBSrvConfig:= SIZEOF(stDBConfig), bTemporary:= TRUE,
pConfigID:= ADR(nDBID) ) THEN
ipResultEvt := fbConfigTcDBSrv.ipTcResult;
IF fbConfigTcDBSrv.bError THEN
nState_CreateDB := 100;
ELSE
nState_CreateDB := 3;
END_IF
END_IF
3:
arrTableColumns[0].sName := 'ID';
arrTableColumns[0].eType := E_ColumnType.BigInt;
arrTableColumns[0].nLength := 8;
arrTableColumns[0].sProperty := 'IDENTITY(1,1)';

arrTableColumns[1].sName := 'Timestamp';
arrTableColumns[1].eType := E_ColumnType.DateTime;
arrTableColumns[1].nLength := 4;

arrTableColumns[2].sName := 'Severity';
arrTableColumns[2].eType := E_ColumnType.NVarChar;
arrTableColumns[2].nLength := 10;

arrTableColumns[3].sName := 'ErrorCode';
arrTableColumns[3].eType := E_ColumnType.Integer;
arrTableColumns[3].nLength := 4;

arrTableColumns[4].sName := 'Message';
arrTableColumns[4].eType := E_ColumnType.NVarChar;
arrTableColumns[4].nLength := 255;

IF fbPLCDBCreate.Table(hDBID:= nDBID, sTableName:= sTableName,


pTableCfg:= ADR(arrTableColumns),
cbTableCfg:= SIZEOF(arrTableColumns)) THEN
ipResultEvt := fbPLCDBCreate.ipTcResultEvent;
nState_CreateDB := 100;
END_IF
100:
IF _SetResultInfo(1033) THEN
IF NOT bError THEN
_bHasCreated := TRUE;
END_IF

nState_CreateDB := 0;
END_IF
END_CASE

CreateErrorLogDB := nState_CreateDB = 0;

AddErrorEntry (method)

The AddErrorEntry method can be used to write different messages into the database.
METHOD AddErrorEntry : BOOL
VAR_INPUT
tTimestamp : DT;
eSeverity : E_Severity;
nErrCode : UDINT;
sMessage : T_MaxString;
END_VAR
CASE nState_AddEntry OF
0:
ipResultEvt := fbPLCDBWrite.ipTcResult;

stError.tTimestamp := tTimestamp;
CASE eSeverity OF
TcEventSeverity.Info:
stError.sSeverity := 'Info';
TcEventSeverity.Warning:
stError.sSeverity := 'Warning';
TcEventSeverity.Verbose:
stError.sSeverity := 'Verbose';
TcEventSeverity.Critical:
stError.sSeverity := 'Critical';

334 Version: 1.13.4 TF6420


Examples

TcEventSeverity.Error:
stError.sSeverity := 'Error';
END_CASE
stError.nErrCode := nErrCode;
stError.sMsg := sMessage;

arrColumns[0] := 'Timestamp';
arrColumns[1] := 'ErrorCode';
arrColumns[2] := 'Severity';
arrColumns[3] := 'Message';

nState_AddEntry := 1;
1:
IF fbPLCDBWrite.WriteStruct(
hDBID:= nDBID,
sTableName:= sTableName,
pRecord:= ADR(stError),
cbRecord:= SIZEOF(stError),
pColumnNames:= ADR(arrColumns),
cbColumnNames:= SIZEOF(arrColumns)) THEN

nState_AddEntry := 100;
END_IF
100:
IF _SetResultInfo(1033) THEN
nState_AddEntry := 0;
END_IF
END_CASE

AddErrorEntry := nState_AddEntry = 0;

ReadLastError (method)

The method ReadLastError can be used to read the latest (last) entry from the database.
METHOD ReadLastError : BOOL
VAR_OUTPUT
tTimestamp : DT;
sSeverity : STRING(10);
nErrCode : UDINT;
sMessage : T_MaxString;
END_VAR
CASE nState_ReadLastEntry OF
0:
ipResultEvt := fbPLCDBRead.ipTcResult;

arrColumns[0] := 'Timestamp';
arrColumns[1] := 'ErrorCode';
arrColumns[2] := 'Severity';
arrColumns[3] := 'Message';

nState_ReadLastEntry := 1;
1:
IF fbPLCDBRead.ReadStruct(
hDBID:= nDBID,
sTableName:= sTableName,
pColumnNames:= ADR(arrColumns),
cbColumnNames:= SIZEOF(arrColumns),
sOrderByColumn:= 'ID',
eOrderType:= E_OrderType.DESC,
nStartIndex:= 0,
nRecordCount:= 1,
pData:= ADR(stReadData),
cbData:= SIZEOF(stReadData)) THEN

nState_ReadLastEntry := 100;
END_IF
100:
IF _SetResultInfo(1033) THEN
IF NOT fbPLCDBRead.bError THEN
tTimestamp := stReadData.tTimestamp;
sSeverity := stReadData.sSeverity;
nErrCode := stReadData.nErrCode;
sMessage := stReadData.sMsg;
END_IF

nState_ReadLastEntry := 0;
END_IF

TF6420 Version: 1.13.4 335


Examples

END_CASE

ReadLastError := nState_ReadLastEntry = 0;

GetErrorTimerange (method)

The method GetErrorTimerange can be used to read all messages from a particular interval.
METHOD GetErrorTimerange : BOOL
VAR_INPUT
tStartTimestamp : DT;
tEndTimestamp : DT;
nStartIndex : UDINT;
END_VAR
VAR_OUTPUT
nErrorCount: UDINT;
arrErrors : ARRAY [0..10] OF ST_ErrorEntry;
END_VAR
CASE nState_ErrorTimerange OF
0:
ipResultEvt := fbPLCDBRead.ipTcResult;

stSearchData.dtStartTimestamp := tStartTimestamp;
stSearchData.dtEndTimestamp := tEndTimestamp;

sCmd := 'SELECT Timestamp, ErrorCode, Severity, Message FROM


tbl_Errors WHERE Timestamp >= {start} AND Timestamp <= {end}';

arrParameter[0].sParaName := 'start';
arrParameter[0].eParaType := E_ExpParameterType.DateTime;
arrParameter[0].nParaSize := 4;

arrParameter[1].sParaName := 'end';
arrParameter[1].eParaType := E_ExpParameterType.DateTime;
arrParameter[1].nParaSize := 4;

nState_ErrorTimerange := 1;
1:
IF fbPLCDBCmd.ExecuteDataReturn(
hDBID:= nDBID,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(stSearchData),
cbData:= SIZEOF(stSearchData),
pParameter:= ADR(arrParameter),
cbParameter:= SIZEOF(arrParameter),
nStartIndex:= nStartIndex,
nRecordCount:= 10,
pReturnData:= ADR(arrErrs),
cbReturnData:= SIZEOF(arrErrs),
pRecords:= ADR(nErrCount)) THEN

nState_ErrorTimerange := 100;
END_IF
100:
IF _SetResultInfo(1033) THEN
nErrorCount := nErrCount;
arrErrors := arrErrs;

nState_ErrorTimerange := 0;
END_IF
END_CASE

GetErrorTimerange := nState_ErrorTimerange = 0;

_SetResultInfo (private method)

The I_Message message interface is evaluated by the TwinCAT EventLogger in the private _SetResultInfo
method.
METHOD _SetResultInfo : BOOL
VAR_INPUT
nLangId : INT := 1033;
END_VAR
_SetResultInfo := FALSE;

CASE nState_SetResInfo OF

336 Version: 1.13.4 TF6420


Examples

0:
IF ipResultEvt.RequestEventText(nLangId, EventText, SIZEOF(EventText)) THEN
nState_SetResInfo := 1;
END_IF
1:
IF ipResultEvt.RequestEventClassName(nLangId, EventClassName, SIZEOF(EventClassName)) THEN
EventSourcePath := ipResultEvt.ipSourceInfo.sName;
EventId := ipResultEvt.nEventId;

bError := (ipResultEvt.eSeverity = TcEventSeverity.Error) OR


(ipResultEvt.eSeverity = TcEventSeverity.Critical);

nState_SetResInfo:=0;
_SetResultInfo := TRUE;
END_IF
END_CASE

7.1.1.3 Production register


This scenario example illustrates the use of the SQL Expert Mode for handling stored procedures. A
connection to the database established from the PLC. A stored procedure is used to read product positions
from several tables. A visualization is used for the operation.

Category SQL Expert mode


Database used MS SQL [} 126]
Compatible databases MS SQL, MySQL, Oracle
PLC function blocks used FB_SQLDatabaseEvt [} 192],
FB_SQLStoredProcedureEvt [} 201], FB_SQLResultEvt
[} 199]
PLC libraries used Tc3_Database, Tc3_Eventlogger
Download https://infosys.beckhoff.com/content/1033/
TF6420_Tc3_Database_Server/Resources/
3495190539/.zip

In the MAIN program a so-called state machine is implemented for processing, through which the different
SQL function blocks are controlled. Since the methods of the function blocks no longer have an Execute flag,
the user must ensure that the method is not called again in the next cycle, in order to avoid repetition of the
procedure. This can easily be ensured through the state machine.
PROGRAM MAIN
VAR
bCONNECT: BOOL;

TF6420 Version: 1.13.4 337


Examples

bEXECUTE: BOOL;
bREAD : BOOL;
bDISCONNECT: BOOL;

R_TRIG1: R_TRIG;
R_TRIG2: R_TRIG;
R_TRIG3: R_TRIG;
R_TRIG4: R_TRIG;

nState: INT;
nState_Connect: INT;
nState_Disconnect: INT;

bConn: BOOL;
bSP: BOOL;
bResult: BOOL;
bData: BOOL;

nDBID: UDINT := 1;

fbSQLDatabase: FB_SQLDatabaseEvt(sNetID:='', tTimeout:=T#10S);


fbSQLStoredProcedure: FB_SQLStoredProcedureEvt(
sNetID:='', tTimeout:=T#10S);
fbSQLResult: FB_SQLResultEvt(sNetID:='', tTimeout:=T#10S);

arrParameter: ARRAY [0..0] OF ST_SQLSPParameter;

nCustomerID: DINT := 12345;

nRecordStartIndex: UDINT;
stRecordArr: ARRAY [1..20] OF ST_Record;
nRecs: UDINT;

ipResultEvt : Tc3_Eventlogger.I_TcMessage;
bError : BOOL;
nEventID: UDINT;
sEventClass : STRING(255);
sEventMsg : STRING(255);
END_VAR

R_TRIG1(CLK:=bCONNECT);
IF R_TRIG1.Q AND nState = 0 THEN
nState := 1;
END_IF

R_TRIG2(CLK:=bEXECUTE);
IF R_TRIG2.Q AND nState = 0 THEN
nState := 2;
END_IF

R_TRIG3(CLK:=bREAD);
IF R_TRIG3.Q AND nState = 0 THEN
nState := 3;
END_IF

R_TRIG4(CLK:=bDISCONNECT);
IF R_TRIG4.Q THEN
nState := 4;
END_IF
CASE nState OF
0:(*Idle*)
;
1: // Connect to database and create stored procedure instance
CASE nState_Connect OF
0:
IF fbSQLDatabase.Connect(hDBID:= nDBID) THEN
ipResultEvt := fbSQLDatabase.ipTcResult;
bConn := NOT fbSQLDatabase.bError;
IF bConn THEN
nState_Connect := 1;
ELSE
nState:=200;
END_IF
END_IF
1:
arrParameter[0].sParameterName := '@Customer_ID';
arrParameter[0].eParameterDataType :=
Tc3_Database.E_ColumnType.Integer;
arrParameter[0].eParameterType := E_SPParameterType.Input;

338 Version: 1.13.4 TF6420


Examples

arrParameter[0].nParameterSize := SIZEOF(nCustomerID);

IF fbSQLDatabase.CreateSP('SP_GetAddressByCustomerID',
ADR(arrParameter), SIZEOF(arrParameter),
ADR(fbSQLStoredProcedure)) THEN
ipResultEvt:= fbSQLDatabase.ipTcResult;
bSP := NOT fbSQLDatabase.bError;
nState_Connect:=0;
nState := 200;
END_IF
END_CASE
2: // Execute stored procedure
IF fbSQLStoredProcedure.ExecuteDataReturn(
pParameterStrc:= ADR(nCustomerID),
cbParameterStrc:= SIZEOF(nCustomerID),
pSQLDBResult:= ADR(fbSQLResult)) THEN
ipResultEvt:= fbSQLStoredProcedure.ipTcResult;
MEMSET(ADR(stRecordArr),0,SIZEOF(stRecordArr));
bResult := NOT fbSQLStoredProcedure.bError;
nState := 200;
END_IF
3: // Read customer positions
IF fbSQLResult.Read(nRecordStartIndex, 20, ADR(stRecordArr),
SIZEOF(stRecordArr), TRUE, FALSE) THEN
ipResultEvt:= fbSQLResult.ipTcResult;
bData := NOT fbSQLStoredProcedure.bError;
nRecs := fbSQLResult.nDataCount;
nState := 200;
END_IF
4:// Disconnect all
CASE nState_Disconnect OF
0:
IF bData THEN
IF fbSQLResult.Release() THEN
nState_Disconnect := 1;
END_IF
ELSE
nState_Disconnect := 1;
END_IF
1:
IF bSP THEN
IF fbSQLStoredProcedure.Release() THEN
nState_Disconnect := 2;
END_IF
ELSE
nState_Disconnect := 2;
END_IF
2:
IF bConn THEN
IF fbSQLDatabase.Disconnect() THEN
nState_Disconnect := 3;
END_IF
ELSE
nState_Disconnect := 3;
END_IF
3:
bData := FALSE;
bSP := FALSE;
bConn := FALSE;
bResult := FALSE;
sEventClass := "";
sEventMsg := "";
nEventID := 0;
bError := FALSE;
nState_Disconnect := 0;
nState := 0;
END_CASE
200:
IF ipResultEvt.RequestEventText(1033, sEventMsg, SIZEOF(sEventMsg)) THEN
nState := 201;
END_IF
201:
IF ipResultEvt.RequestEventClassName(1033, sEventClass, SIZEOF(sEventClass)) THEN

nEventID := ipResultEvt.nEventId;

bError := (ipResultEvt.eSeverity = TcEventSeverity.Error) OR


(ipResultEvt.eSeverity = TcEventSeverity.Critical);

TF6420 Version: 1.13.4 339


Examples

nState:=0;
END_IF
END_CASE

The individual process steps can be reproduced in the individual PLC states. Boolean flags are available to
facilitate handling.

1. bConnect: Connection with the database is established


2. bExecute: The stored procedure is executed, and results are loaded into the cache
3. bRead: The results are transferred to the PLC
4. bDisconnect: The connection is closed

If these steps are executed consecutively, the array stRecordArr is filled with values from the database:

7.1.1.4 Production recipe


This scenario example illustrates how the TwinCAT Database Server handles XML files with any structure.
The production recipe for building the product is read from an XML file. The corresponding test parameters
are read from a different file. In addition, the test results are written into an existing XML file.

340 Version: 1.13.4 TF6420


Examples

Category SQL Expert mode


Database used XML [} 135] (as free XML documents)
Compatible databases XML
PLC function blocks used FB_PLCDBCmdEvt [} 183]
PLC libraries used Tc3_Database, Tc3_Eventlogger
Download https://infosys.beckhoff.com/content/1033/
TF6420_Tc3_Database_Server/Resources/
3495193099/.zip

Recipe XML:

TF6420 Version: 1.13.4 341


Examples

Test XML:

FB_ProductionConfigData

GetConfig (method)

This method reads the production recipe for a product from an XML file. XPath queries can be used to find
the required recipe.
METHOD GetConfig : BOOL
VAR_INPUT
nTypeNum : DINT;
END_VAR
VAR_OUTPUT
stConfig : ST_Config;
END_VAR
GetConfig:= FALSE;

arrPara[0].sParaName := 'rLength';
arrPara[0].eParaType := Tc3_Database.E_ExpParameterType.Float32;
arrPara[0].nParaSize := 4;

arrPara[1].sParaName := 'rWidth';
arrPara[1].eParaType := Tc3_Database.E_ExpParameterType.Float32;

342 Version: 1.13.4 TF6420


Examples

arrPara[1].nParaSize := 4;

arrPara[2].sParaName := 'rHeight';
arrPara[2].eParaType := Tc3_Database.E_ExpParameterType.Float32;
arrPara[2].nParaSize := 4;

arrPara[3].sParaName := 'iQuantity';
arrPara[3].eParaType := Tc3_Database.E_ExpParameterType.Int32;
arrPara[3].nParaSize := 4;

arrPara[4].sParaName := 'iCounter';
arrPara[4].eParaType := Tc3_Database.E_ExpParameterType.Int32;
arrPara[4].nParaSize := 4;

sCmd := CONCAT(CONCAT('XPATH_SEL<SUBTAG>#ProductionConfig/Config[@TypeNum
= ', DINT_TO_STRING(nTypeNum)), ']');

CASE nState_GetConfig OF
0:
IF fbPLCDBCmd.ExecuteDataReturn(
hDBID:= 1,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= 0,
cbData:= 0,
pParameter:= ADR(arrPara),
cbParameter:= SIZEOF(arrPara[0])*5,
nStartIndex:= 0,
nRecordCount:= 1,
pReturnData:= ADR(_stConfig),
cbReturnData:= SIZEOF(_stConfig),
pRecords:= 0) THEN

ipResultEvt := fbPLCDBCmd.ipTcResult;
nState_GetConfig := 100;
END_IF
100:
IF _SetResultInfo(1033) THEN
GetConfig := TRUE;

stConfig := _stConfig;

nState_GetConfig := 0;
END_IF
END_CASE

GetTestParameter (method)

This method reads the product-specific test parameters.


METHOD GetTestParameter : BOOL
VAR_INPUT
nTypeNum : DINT;
END_VAR
VAR_OUTPUT
sTestNum : STRING(8);
stTestPara: ST_TestParameter;
END_VAR
GetTestParameter := FALSE;

CASE nState_GetTestPara OF
0:
arrPara[0].sParaName := 'Test';
arrPara[0].eParaType := Tc3_Database.E_ExpParameterType.STRING_;
arrPara[0].nParaSize := 8;

sCmd := CONCAT(CONCAT('XPATH_SEL<ATTR>#ProductionConfig/Config
[@TypeNum = ', DINT_TO_STRING(nTypeNum)), ']');

IF fbPLCDBCmd.ExecuteDataReturn(
hDBID:= 1,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= 0,
cbData:= 0,
pParameter:= ADR(arrPara),
cbParameter:= SIZEOF(arrPara[0]),
nStartIndex:= 0,
nRecordCount:= 1,

TF6420 Version: 1.13.4 343


Examples

pReturnData:= ADR(_sTestNum),
cbReturnData:= SIZEOF(_sTestNum),
pRecords:= 0) THEN

bError := fbPLCDBCmd.bError;
sErrClass := fbPLCDBCmd.ipTcResultEvent.EventClassDisplayName;
nErrID := fbPLCDBCmd.ipTcResultEvent.EventId;
sErrText := fbPLCDBCmd.ipTcResultEvent.Text;

IF fbPLCDBCmd .bError THEN


ipResultEvt := fbPLCDBCmd.ipTcResult;
nState_GetTestPara:= 100;
ELSE
nState_GetTestPara:= 1;
END_IF
END_IF
1:
arrPara[0].sParaName := 'MaxTemp';
arrPara[0].eParaType := Tc3_Database.E_ExpParameterType.Float32;
arrPara[0].nParaSize := 4;

arrPara[1].sParaName := 'MinTemp';
arrPara[1].eParaType := Tc3_Database.E_ExpParameterType.Float32;
arrPara[1].nParaSize := 4;

arrPara[2].sParaName := 'MaxPSI';
arrPara[2].eParaType := Tc3_Database.E_ExpParameterType.Int32;
arrPara[2].nParaSize := 4;

sCmd := CONCAT(CONCAT('XPATH_SEL<SUBTAG>#ProductionConfig/
TestParameter/Test[@Num = $'', _sTestNum), '$']');

IF fbPLCDBCmd.ExecuteDataReturn(
hDBID:= 2,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= 0,
cbData:= 0,
pParameter:= ADR(arrPara),
cbParameter:= SIZEOF(arrPara[0])*3,
nStartIndex:= 0,
nRecordCount:= 1,
pReturnData:= ADR(_stTest),
cbReturnData:= SIZEOF(_stTest),
pRecords:= 0) THEN

ipResultEvt := fbPLCDBCmd.ipTcResult;
nState_GetTestPara:= 100;
100:
IF _SetResultInfo(1033) THEN
nState_GetTestPara := 0;

stTestPara := _stTest;
sTestNum := _sTestNum;

GetTestParameter := TRUE;
END_IF
END_CASE

AddTestEntry (method)

This method adds the test result to the test XML file.
METHOD AddTestEntry : BOOL
VAR_INPUT
sTestNum : STRING(8);
nTypeNum : DINT;
sTimestamp : STRING;
sTester : STRING;
sResult : STRING;
END_VAR
AddTestEntry := FALSE;

arrPara[0].sParaName := 'TestNum';
arrPara[0].eParaType := Tc3_Database.E_ExpParameterType.STRING_;
arrPara[0].nParaSize := 8;

arrPara[1].sParaName := 'TypeNum';
arrPara[1].eParaType := Tc3_Database.E_ExpParameterType.Int32;

344 Version: 1.13.4 TF6420


Examples

arrPara[1].nParaSize := 4;

arrPara[2].sParaName := 'Timestamp';
arrPara[2].eParaType := Tc3_Database.E_ExpParameterType.STRING_;
arrPara[2].nParaSize := 81;

arrPara[3].sParaName := 'Tester';
arrPara[3].eParaType := Tc3_Database.E_ExpParameterType.STRING_;
arrPara[3].nParaSize := 81;

arrPara[4].sParaName := 'Result';
arrPara[4].eParaType := Tc3_Database.E_ExpParameterType.STRING_;
arrPara[4].nParaSize := 81;

arrPara[5].sParaName := 'Test';
arrPara[5].eParaType := Tc3_Database.E_ExpParameterType.XMLTAGName;
arrPara[5].nParaSize := 0;

sCmd := 'XPATH_ADD<ATTR>#ProductionConfig/Tests';

stTest.sTestNum := sTestNum;
stTest.nTypeNum := nTypeNum;
stTest.sTimestamp := sTimestamp;
stTest.sTester := sTester;
stTest.sResult := sResult;

CASE nState_AddEntry OF
0:
IF fbPLCDBCmd.Execute(
hDBID:= 2,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(stTest),
cbData:= SIZEOF(stTest),
pParameter:= ADR(arrPara),
cbParameter:= SIZEOF(arrPara)) THEN

ipResultEvt := fbPLCDBCmd.ipTcResult;
nState_AddEntry:= 100;
END_IF
100:
IF _SetResultInfo(1033) THEN
nState_AddEntry:= 0;
AddTestEntry:= TRUE;
END_IF
END_CASE

_SetResultInfo (private method)

The I_Message message interface is evaluated by the TwinCAT EventLogger in the private _SetResultInfo
method.
METHOD _SetResultInfo : BOOL
VAR_INPUT
nLangId : INT := 1033;
END_VAR
_SetResultInfo := FALSE;

CASE nState_SetResInfo OF
0:
IF ipResultEvt.RequestEventText(nLangId, EventText, SIZEOF(EventText)) THEN
nState_SetResInfo := 1;
END_IF
1:
IF ipResultEvt.RequestEventClassName(nLangId, EventClassName, SIZEOF(EventClassName)) THEN
EventId := ipResultEvt.nEventId;

bError := (ipResultEvt.eSeverity = TcEventSeverity.Error) OR


(ipResultEvt.eSeverity = TcEventSeverity.Critical);

nState_SetResInfo:=0;
_SetResultInfo := TRUE;
END_IF
END_CASE

TF6420 Version: 1.13.4 345


Examples

7.1.2 Best practices


The tips for using the TwinCAT Database Server illustrate the benefits of the individual function blocks and
applications in terms of performance, flexibility and complexity.

7.1.2.1 Writing CSV files


The TwinCAT 3 Database Server supports the CSV file format. There are different approaches, each with
advantages and disadvantages, to write content to the file or read from it. Two of these approaches are
explained in more detail here.

Select the ASCII database. The .csv file format can be specified under the file path. The ASCII-DB 3.0
format flag indicates the format of the ASCII/CSV file. If the format is checked, the SAX procedure is used.
With this setting, write access to the file, especially with the FB_PLCDBCmdEvt function block, is also very
efficient for large files. If the format is unchecked, the DOM procedure is used, which is particularly suitable
for reading a file. The data is stored in a structured form in the RAM. Therefore this method is recommended
for smaller files (less than 1 MB). However, this method offers some advantages due to the structured
storage. The CSV file can be used as an SQL database using a stored table structure. Use the SQL Query
Editor to do this. This file can be created directly via the 'Create' button.

Load your configuration onto your TwinCAT Database Server target system.

Table 2: ASCII format compatibility

Function block Table structure ASCII 3.0 format Standard ASCII


FB_PLCDBWriteEvt.Write standard

FB_PLCDBWriteEvt.WriteStr variable
uct*
FB_PLCDBReadEvt.Read standard

FB_:PLCDBReadEvt.ReadSt variable
ruct*
FB_PLCDBCmdEvt.Execute* variable

FB_SQLCommandEvt variable

Items marked with * are used in the following sample

High-performance writing to the CSV file

346 Version: 1.13.4 TF6420


Examples

The most efficient way to write to a CSV file is based on the function block FB_PLCDBCmdEvt. To this end,
the link to the CSV file must be set in ASCII-DB 3.0 format. The DBValueType is irrelevant here. A table
structure does not have to be defined in advance.

Sample:

The following structure is used as an example:


TYPE ST_CSVDataStruct :
STRUCT
ID: LINT;
Timestamp: DT;
Name: STRING(80);
Velocity: LREAL;
Temperature: LREAL;
END_STRUCT
END_TYPE

The function block is initialized as follows:


VAR
InputData: ST_CSVDataStruct;
fbPLCDBCmd: FB_PLCDBCmd (sNetID:= '', tTimeout := T#30S);

sCmd : T_MaxString := '{ID};{Timestamp};{Name};{Velocity};{Temperature}';

para : ARRAY [0..4] OF ST_ExpParameter :=[


(eParaType:= E_ExpParameterType.Int64, nParaSize := 8, sParaName := 'ID'),
(eParaType:= E_ExpParameterType.DateTime, nParaSize := 4, sParaName := 'Timestamp'),
(eParaType:= E_ExpParameterType.STRING_, nParaSize := 81, sParaName := 'Name'),
(eParaType:= E_ExpParameterType.Double64, nParaSize := 8, sParaName := 'Velocity'),
(eParaType:= E_ExpParameterType.Double64, nParaSize := 8, sParaName := 'Temperature')];
END_VAR

The individual parameters are specified in curly brackets within the command. Information about the type,
byte length and name is assigned via the initialization. The name is used to recognize the parameter in the
command and to replace it with the value from the PLC when it is written to the file.

The call in the PLC source code of the function block consists of a call:
IF fbPLCDBCmd.Execute(
hDBID:= 3,
pExpression:= ADR(sCmd),
cbExpression:= SIZEOF(sCmd),
pData:= ADR(InputData),
cbData:= SIZEOF(InputData) ,
pParameter:= ADR(para),
cbParameter:=SIZEOF(para))
THEN
;//Place for errorhandling or reactions;
END_IF
// Result: 16160;19-10-2018 12:27:38;Water Turbine;35.2238040741592;62.6461585412374

The hDBID depends on its configuration and can be taken from the database link. pData (or cbData) can be
the address for the individual structure or for an array of its structure. This can lead to further performance
improvements.

Structured writing and reading of a CSV file

Not all function blocks are possible with the ASCII format 3.0. Some functions of the TwinCAT Database
Server require a preconfigured table structure. However, this cannot be stored in ASCII format 3.0. In this
sample, a fixed structure is used to write and read the data with the PLCDBWriteEvt and PLCDBReadEvt
function blocks in any structure.

The following structure is used as an example:

TF6420 Version: 1.13.4 347


Examples

Export for the PLC under the 'Select' tab is also possible:
TYPE ST_CSVDataStruct :
STRUCT
ID: LINT;
Timestamp: DT;
Name: STRING(80);
Velocity: LREAL;
Temperature: LREAL;
END_STRUCT
END_TYPE

The Write/ReadStruct methods of the respective PLC function blocks are used for any table structures:
VAR
fbPLCDBWrite: FB_PLCDBWrite(sNetID:= '', tTimeout := T#30S);
fbPLCDBRead : FB_PLCDBRead(sNetID:= '', tTimeout := T#30S);
ColumnNames : ARRAY [0..4] OF STRING(50) := ['ID','Timestamp','Name','Velocity','Temperature'];
Data: ST_CSVDataStruct;
ReadData: ARRAY[0..4] OF ST_CSVDataStruct;
END_VAR
IF fbPLCDBWrite.WriteStruct(
hDBID:= hDBID,
sTableName:= 'CSV_Sample',
pRecord:= ADR(Data),
cbRecord:= SIZEOF(Data),
pColumnNames:= ADR(ColumnNames),
cbColumnNames:= SIZEOF(ColumnNames) )
THEN
;//Place for errorhandling or reactions
END_IF

IF fbPLCDBRead.ReadStruct(
hDBID:= hDBID,
sTableName:= 'CSV_Sample',
pColumnNames:= ADR(ColumnNames),
cbColumnNames:= SIZEOF(ColumnNames) ,
sOrderByColumn:= 'ID',
eOrderType := E_OrderType.ASC,
nStartIndex:= 0,
nRecordCount:= 5,
pData:= ADR(ReadData),
cbData:=SIZEOF(ReadData))
THEN
;//Place for errorhandling or reactions
END_IF

The WriteStruct(...) method writes the Data structure to the database. The structures of the PLC and the
CSV file are compared based on the ColumnNames.

The ReadStruct(...) method reads a certain number (nRecordCount) of records from the CSV file. These may
be sorted based on a selected column. The size of the ReadData target array should be sufficient to receive
all the retrieved data.

Appendix

348 Version: 1.13.4 TF6420


Examples

Sample configurations for both samples, as well as the complete code of a simple sample program, can be
downloaded here: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
5778536715/.zip. To illustrate the process, the program generates values and repeatedly sends them to the
CSV. The settings used above were stored in a separate function block, which communicates in different
ways with the two CSV formats.

7.1.2.2 Fast logging with data buffer


In order to log data in a database at millisecond intervals, the data must first be consolidated before it is
transferred to the database via the TwinCAT Database Server. These data buffers can vary in size according
to requirements. In the sample, 100 data samples are combined in a buffer before they are transferred with
the TwinCAT Database Server. To avoid gaps during the write process, several buffers must be created in
which the data samples are combined. In the sample, a total of 20 buffers are created using a 2-dimensional
array.

Data sample

Definition:
TYPE ST_Data :
STRUCT
Timestamp : LINT;
fAM : LREAL;
fPeak : LREAL;
fPulse : LREAL;
fSawtooth : LREAL;
fSine : LREAL;
fSquare : LREAL;
fStairs : LREAL;
fTriangular : LREAL;
END_STRUCT
END_TYPE

Each cycle fills one element of the data buffer. In the sample this happens at 10 ms intervals. Thus a buffer
contains data of a period of 1 s. If a buffer is filled with 100 elements, a further array indicates that the 100
elements can now be transferred with the function block FB_PLCDBCmdEvt. To this end, the entire buffer
can be transferred to the function block. Each individual element is then transferred from the TwinCAT
Database Server to the database. This sample can also be implemented with other function blocks. Note that
not all function blocks support arrays.

Extract from the function block FB_Record_tbl_Signals

( "State Machine" => State: Recording)



2://Recording
bRecording := TRUE;

//Fill buffer
stData[nWriteBufferIndex, nWriteIndex].Timestamp := nTimestamp;
stData[nWriteBufferIndex, nWriteIndex].fAM := fAM;
stData[nWriteBufferIndex, nWriteIndex].fPeak := fPeak;
stData[nWriteBufferIndex, nWriteIndex].fPulse := fPulse;
stData[nWriteBufferIndex, nWriteIndex].fSawtooth := fSawtooth;
stData[nWriteBufferIndex, nWriteIndex].fSine := fSine;
stData[nWriteBufferIndex, nWriteIndex].fSquare := fSquare;
stData[nWriteBufferIndex, nWriteIndex].fStairs := fStairs;
stData[nWriteBufferIndex, nWriteIndex].fTriangular := fTriangular;

//Set buffer index


nWriteIndex := nWriteIndex + 1;
IF nWriteIndex = 100 THEN
nWriteIndex := 0;
aWriteSQL[nWriteBufferIndex]:= TRUE;
nWriteBufferIndex := nWriteBufferIndex + 1;

IF nWriteBufferIndex = 20 THEN
nWriteBufferIndex := 0;
END_IF

IF aWriteSQL[nWriteBufferIndex] THEN
nState := 255;
RETURN;

TF6420 Version: 1.13.4 349


Examples

END_IF
END_IF

//Write buffer element (100 samples) to database


IF aWriteSQL[nSQLIndex] THEN
IF fbPLCDBCmd.Execute(nDBID, ADR(sCmd), SIZEOF(sCmd),
ADR(stData[nSQLIndex,0]), SIZEOF(stData[nSQLIndex,0]) * 100,
ADR(aPara), SIZEOF(aPara)) THEN
IF fbPLCDBCmd.bError THEN
nState := 255;
ELSE
nRecords := nRecords + 100;

aWriteSQL[nSQLIndex] := FALSE;

nSQLIndex := nSQLIndex + 1;
IF nSQLIndex = 20 THEN
nSQLIndex := 0;
END_IF

IF NOT bRecord THEN


bRecording := FALSE;
nState := 0;
END_IF
END_IF
END_IF
END_IF
….

Appendix:

In this best practice example, a function generator block is used to generate various signals that can be
logged in a database. The syntax of the INSERT command is generally valid, but has been specifically
tested with an MS SQL database. The ZIP file attached below contains the complete program code in Tnzip
format.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
6263666699/.zip

7.1.2.3 NoSQL
This document describes the handling of NoSQL databases.

Database used: MongoDB


Database type used: DocumentDB

Data writing

Database types of type DocumentDB can store JSON documents with any structure. Therefore it is possible
to map any structure of the PLC in DocumentDBs. This document can be created automatically using the
FB_JSONDataType or assembled using the string blocks. Make sure that the document variable is large
enough. If you want to write several documents at the same time, you can transfer them in a JSON array.

The QueryOptions [} 234] are defined in preparation. The collection concerned and the query type are
specified for this purpose. Each query type has its own structure. The structure
T_QueryOptionDocumentDB_Insert [} 235] is used for writing documents.
VAR
fbNoSQLQueryBuilder_DocumentDB: FB_NoSQLQueryBuilder_DocumentDB;
InsertQueryOptions: T_QueryOptionDocumentDB_Insert;
sDocument : STRING(2000);
END_VAR
InsertQueryOptions.pDocuments:= ADR(sDocument);
InsertQueryOptions.cbDocuments:= SIZEOF(sDocument);
fbNoSQLQueryBuilder_DocumentDB.eQueryType := E_DocumentDbQueryType.InsertOne;
fbNoSQLQueryBuilder_DocumentDB.sCollectionName := 'myCollection';
fbNoSQLQueryBuilder_DocumentDB.pQueryOptions := ADR(InsertQueryOptions);
fbNoSQLQueryBuilder_DocumentDB.cbQueryOptions := SIZEOF(InsertQueryOptions);

350 Version: 1.13.4 TF6420


Examples

The function block FB_NoSQLQueryEvt [} 208] is used for writing the document into the database. The
Execute() [} 209] method writes the transferred documents to the database. This execution is asynchronous
to the PLC and can take several cycles. The Boolean return value indicates when the function block has
completed its process:
VAR
fbNoSQLQuery: FB_NoSQLQueryEvt(sNetID := '', tTimeout := TIME#15S0MS);
fbJsonDataType: FB_JsonReadWriteDatatype;
END_VAR
CASE eState OF

eMyDbState.Write:
// set the document yourself as json format (Example)
sDocument := '{"myBool" : true,
"Name" : "Some Name Value",
"Value": 2.3,
"Value2":3,
"Child":{"Name":"Single Child",
"Value":1,
"myBool":true,
"arr":[12.0,13.0,14.0,15.0],
"myBool2" : true},
"Children":[
{"Name":"Child1"
,"Value": 1,
"myBool" : true,
"arr":[12.1,13.1,14.1,15.1],
"myBool2" : true},
{"Name":"Child2",
"Value":2,
"myBool" : true,
"arr":[12.2,13.2,14.2,15.2],
"myBool2" : true},
{"Name":"Child3",
"Value":1,
"myBool" : true,
"arr":[12.3,13.3,14.3,15.3],
"myBool2" : true}]
}';

IF fbNoSQLQuery.Execute(1, myQueryBuilder) THEN


IF fbNoSQLQuery.bError THEN
InfoResult := fbNoSQLQuery.ipTcResult;
eState:= eMyDbState.Error;
ELSE
eState:= eMyDbState.Idle;
END_IF
END_IF

END_CASE

The databases recognize the data type with which the individual variables are stored. However, as with
MongoDB, the data type can be specified explicitly. If a timestamp is to be saved explicitly as a data type, it
must be defined in the JSON document:
sDocument := '{…"myTimestamp": ISODate("2019-02-01T14:46:06.0000000"), …}’;

The string can not only be formatted via the string formatting function blocks of the TwinCAT 3 libraries, but
also via auxiliary function blocks for JSON documents, such as FB_JsonReadWriteDatatype from
Tc3_JsonXml.
// set the document by JsonDataType
sTypeName := fbJsonDataType.GetDatatypeNameByAddress(SIZEOF(anyValue[1]), ADR(anyValue[1]));
sDocument := fbJsonDataType.GetJsonStringFromSymbol(sTypeName, SIZEOF(anyValue [1]), ADR(anyValue
[1]));

Reading data

The data schema in the document-based database can be different for each document. In contrast, the PLC
follows a fixed process image. The data may not correspond to the process image.

There are two different ways of reading data in the database: the find query and the aggregation method.
Both return results from the database, although aggregation offers extended options for transforming the
data into an appropriate form or for performing operations, such as calculating average values directly.

TF6420 Version: 1.13.4 351


Examples

The QueryOptions [} 234] are defined in preparation. The collection concerned and the query type are
specified for this purpose. Each query type has its own structure. The structure
T_QueryOptionDocumentDB_Aggregation [} 234] is used for aggregating documents.
VAR
fbNoSQLQueryBuilder_DocumentDB: FB_NoSQLQueryBuilder_DocumentDB;
AggregationQueryOptions: T_QueryOptionDocumentDB_Aggregate;
sPipeStages: STRING(1000);
END_VAR
AggregationQueryOptions.pPipeStages := ADR(sPipeStages);
AggregationQueryOptions.cbPipeStages := SIZEOF(sPipeStages);
fbNoSQLQueryBuilder_DocumentDB.eQueryType := E_DocumentDbQueryType.Aggregation;
fbNoSQLQueryBuilder_DocumentDB.sCollectionName := 'myCollection';
fbNoSQLQueryBuilder_DocumentDB.pQueryOptions := ADR(AggregationQueryOptions);
fbNoSQLQueryBuilder_DocumentDB.cbQueryOptions := SIZEOF(AggregationQueryOptions);

The FB_NoSQLQueryEvt [} 208] is used for sending the aggregation query. The ExecuteDataReturn() [} 210]
method can be used to transfer the parameters and to place the returned data in the transferred memory
reference. This execution is asynchronous to the PLC and takes several cycles. The Boolean return value
indicates when the function block has completed its process:
VAR
fbNoSQLQuery: FB_NoSQLQueryEvt(sNetID := '', tTimeout := TIME#15S0MS);
fbNoSQLResult: FB_NoSQLResultEvt(sNetID := '', tTimeout := TIME#15S0MS);
END_VAR
CASE eState OF

eMyDbState.Aggregation:
sPipeStages :='{$$match :{}}';
IF fbNoSQLQuery.ExecuteDataReturn(1, myQueryBuilder, pNoSqlResult:= ADR(fbNoSQLResult),
nDocumentLength=> nDocumentLength)) THEN
IF fbNoSQLQuery.bError THEN
InfoResult := fbNoSQLQuery.ipTcResult;
eState:= eMyDbState.Error;
ELSE
eState:= eMyDbState.Idle;
END_IF
END_IF

END_CASE

The syntax of sPipeStages depends on the database type. It will return all records. Further options (with
fictitious records) include:

Operator Description
{$$match : {Place : “NorthEast”}} All records which have "NorthEast" as value of the
element "Place".
{$$project : { myValue : { $arrayElemAt : Returns all RotorSensor data from array element
["$WindPlantData.RotorSensor", 2]} } } location 2 as "myValue".
{$$project : {RotorAvg : {$avg: Returns the average value of the data array
"$WindPlantData.RotorSensor"} } } "RotorSensor" as "RotorAvg".

The complete documentation of the operators is available from the respective database provider.

A reference to the returned data can now be found in the function block FB_NoSQLResultEvt [} 211]. These
can now be read as JSON documents in a string or as a structure. The data is now read directly into an array
with a suitable structure. You can use the SQL Query Editor of the Database Server to directly generate a
structure that matches the record. Instead of an array, it is also possible to store an address for a single
structure when retrieving only one record.
VAR
fbNoSQLResult: FB_NoSQLResultEvt(sNetID := '', tTimeout := TIME#15S0MS);
aRdStruct : ARRAY [0..9] OF ST_MyCustomStruct;
fbNoSqlValidation : FB_NoSQLValidationEvt(sNetID := '', tTimeout := TIME#15S0MS);
END_VAR
CASE eState OF

eMyDbState.ReadStruct:
IF fbnoSQLDBResult.ReadAsStruct(0, 4, ADR(aRdStruct), SIZEOF(aRdStruct), bValidate := TRUE,
ADR(fbNoSqlValidation), bDataRelease:= TRUE) THEN
IF fbnoSQLDBResult.bError THEN
InfoResult := fbnoSQLDBResult.ipTcResult;

352 Version: 1.13.4 TF6420


Examples

eState:= eMyDbState.Error;
ELSE
eState:= eMyDbState.Idle;
END_IF
END_IF

END_CASE

The TwinCAT Database Server takes into account the names of the elements in the record and the names of
the variables when assigning record or structure. If these are to differ, the attribute "ElementName" can be
used in the PLC:
TYPE ST_WindFarmData :
STRUCT
{attribute 'ElementName' := '_id'}
ID: T_ObjectId_MongoDB;
{attribute 'ElementName' := 'Timestamp'}
LastTime: DT;
{attribute 'ElementName' := 'WindPlantData'}
Data: ST_WindFarmData_WindPlantData;
END_STRUCT
END_TYPE

In this sample, "ElementName" specifies the name of the data in the database document. The start index
and the number of records can be used to determine which records are to be returned with this call. In order
to avoid possible duplications, please note that these options can already be carried out with operators at the
"PipeplineStages".

Data validation

If there were conflicts between the record and the structure in the PLC at FB_NoSQLResult [} 211], they can
be read out with FB_NoSQLValidationEvt [} 215]. Examples of conflicts are missing or surplus records, or
data type problems. The method GetIssues() [} 216] can be used to read all conflicts as an array of strings.
Surplus data that were not found in the PLC structure can be read as an array of strings in JSON format via
GetRemainingData() [} 217]. If necessary, these can then be read out separately into the correct structure or
interpreted via the TwinCAT JSON library.
VAR
fbNoSqlValidation : FB_NoSQLValidationEvt(sNetID := '', tTimeout := TIME#15S0MS);
aIssues : ARRAY[0..99] OF STRING(512);
aRemaining : ARRAY [0..9] OF STRING(1000);
END_VAR
CASE eState OF

eMyDbState.ValidationIssues:
IF fbValidation.GetIssues(ADR(aIssues), SIZEOF(aIssues), FALSE) THEN
IF fbValidation.bError THEN
InfoResult := fbValidation.ipTcResult;
eState:= eMyDbState.Error;
ELSE
eState:= eMyDbState.Idle;
END_IF

eMyDbState.ValidationRemaining:
IF fbValidation.GetRemainingData(ADR(aRemaining), SIZEOF(aRemaining), SIZEOF(aRemaining[1]),
bDataRelease:= FALSE)THEN
IF fbValidation.bError THEN
InfoResult := fbValidation.ipTcResult;
eState:= eMyDbState.Error;
ELSE
eState:= eMyDbState.Idle;
END_IF

END_CASE

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
13743807627/.zip

TF6420 Version: 1.13.4 353


Examples

7.1.2.4 PostgreSql routines


In addition to the functions (PostgreSQL routine), from PostgreSQL 11 the database also supports stored
procedures to enable server-side programming. These two routine types have different properties and
functions:

Table 3: Comparison of stored procedures and functions


Stored Procedures Functions
OUT parameters + -
Return value - +
Can be used in queries - +
Supports transactions + -

These properties require different interfaces with the TwinCAT Database Server. As with other supported
databases, Stored Procedures are executed using the FB_SQLStoredProcedureEvt [} 201] function block.
Functions can be integrated in SQL commands, which are called via FB_PLCDBCmdEvt [} 183] or
FB_SQLCommandEvt [} 196].

PostgreSQL uses "RefCursor" for returning data sets of the routines. The TwinCAT Database Server
automatically evaluates these "RefCursor" and returns the data set referenced in them. It is not possible to
resolve multiple "RefCursor".

Calling a Stored Procedure

Procedures can be called via the FB_SQLStoredProcedureEvt.

Example (SQL)

SQL script for creating a procedure:


CREATE OR REPLACE PROCEDURE "public"."SP_getLastData"(
INOUT result_data refcursor)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
open result_data for SELECT * FROM "myTable_Double" LIMIT 10;
END
$BODY$;

If the procedure defines one (or more) "RefCursor" as output parameter(s), this (or the first) is automatically
interpreted and the resulting data sets are stored in the buffer for the FB_SQLResultEvt [} 199]. The data type
"RefCursor" is treated like a string by the TwinCAT Database Server.

Example (TwinCAT 3 in ST)


VAR
fbSqlDatabase : FB_SQLDatabaseEvt(sNetID := '', tTimeout := T#5S);
ParaInfo : ST_SQLSPParameter;
END_VAR
ParaInfo.sParameterName := '@result_data';
ParaInfo.eParameterType := E_SPParameterType.InputOutput;
ParaInfo.eParameterDataType := E_ColumnType.RefCursor; // 19
ParaInfo.nParameterSize := 81;

IF fbSQLDatabase.CreateSP('"public"."SP_getLastData"', ADR(ParaInfo), SIZEOF(ParaInfo), ADR(fbSQLSto


redProcedure)) THEN
IF fbSQLDatabase.bError THEN
nState:=255;
ELSE
nState:= nState+1;
END_IF
END_IF

The FB_SQLStoredProcedureEvt [} 201] uses the Stored Procedure previously linked with
FB_SQLDatabaseEvt.CreateSP() [} 192]

354 Version: 1.13.4 TF6420


Examples

VAR
fbSQLStoredProcedure : FB_SQLStoredProcedureEvt(sNetID:='', tTimeout := T#5S);
sRefCursor : STRING;
tcMessage : I_TcMessage;
END_VAR
IF fbSQLStoredProcedure.ExecuteDataReturn(pParameterStrc := ADR(sRefCursor),
cbParameterStrc:= SIZEOF(sRefCursor), pSQLDBResult := ADR(fbSqlResult)) THEN
IF fbSQLStoredProcedure.bError THEN
tcMessage := fbSQLStoredProcedure.ipTcResult;
nState := 255;
ELSE
nState := nState+1;
END_IF
END_IF

FB_SQLResultEvt [} 199] can then be used to read the data.

Calling a function

Functions can be called within SQL commands.

Example (SQL)

SQL script for creating a function:


CREATE OR REPLACE FUNCTION "public"."F_getLastData"()
RETURNS refcursor
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE result_data refcursor;
BEGIN
open result_data for SELECT * FROM "myTable_Double" ORDER BY "ID" DESC LIMIT 10;
return result_data;
END;$BODY$;

The following SQL command is used to call the function:


SELECT "public"."F_getLastData"();

The call itself returns a "RefCursor". This is automatically interpreted by the TwinCAT Database Server.

Example (TwinCAT 3 in ST)

The FB_SQLCommandEvt [} 196] uses the command created by FB_SQLDatabaseEvt.CreateCmd() [} 192].


VAR
fbSqlCommand : FB_SQLCommandEvt(sNetID := '', tTimeout := T#5S);
tcMessage : I_TcMessage;
END_VAR
sCmd := 'SELECT "public"."getLastData"();';

// call sql command


IF fbSQLCommand.ExecuteDataReturn(ADR(sCmd), SIZEOF(sCmd), ADR(fbSqlResult)) THEN
IF fbSQLCommand.bError THEN
tcMessage := fbSQLCommand.ipTcResult;
nState := 255; // error state
ELSE
nState := nState+1;
END_IF
END_IF

FB_SQLResultEvt [} 199] can then be used to read the data sets.

It is advisable to use this program code in a State Machine.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
13743810955/.zip

TF6420 Version: 1.13.4 355


Examples

7.1.2.5 Cyclical data and time series databases


This document describes the handling of time series and how cyclic data is stored in time series databases.

Database used: InfluxDB


Database type used: TimeSeriesDB

Introduction

Writing of data at regular or cyclic intervals is a common application in control technology. The data should
be recorded with high time precision. Since database communication is not real-time capable, it is useful to
store data that is measured regularly in a buffer. An array of the data structure can be used for this purpose.
The collected data is then sent to the TwinCAT Database Server, where it can be processed without time
constraints and subsequently stored in the database.

Time

Each data set that is stored in the database is assigned a timestamp. Together with the tag columns these
form a unique ID. If two data sets have the same ID (same timestamp and tag values), the newer data set
overwrites the old one.

Example:

time locationname (tag) temperature (field) windspeed (field)


1 1581675200630326200 Verl 11.5 6.3
2 1581675200630327200 Verl 10.3 5.2
3 1581675200630328200 Verl 9.8 2.8
4 1581675200630328200 Hamburg 14.2 14.9
4 1581675200630328200 Hamburg 15.6 8.9
… … … … …

Data set no. 4 is overwritten by a new data set, since the ID is identical.

The timestamp in the database is saved by default as UNIX epoch time. With the exception of the user-
created insert commands, the timestamps are received and converted as TwinCAT time (number of 100 ns
steps since January 1, 1601) in the function blocks of the TwinCAT 3 Database Server. The times are not
converted for insert commands.

Database configuration

InfluxDB should be selected in the database configuration. Insert the connection parameters for the required
database. If no database is available yet, you can create the database by clicking the "Create" button. Pay
attention to your firewall settings or port approvals. A table does not have to be created, since it is
automatically created during the first InfluxDB access. InfluxDB does not have a fixed table schema.
Columns can also be extended or added later.

Writing cyclic data

This example shows how symbols can be written from the PLC into a time series database with minimal
effort.

Declaration:
State: E_DbLogState;
bWriting: BOOL; // Set this bool fla to write the data once into the InfluxDB

dbid: UDINT := 1; // Handle to the configured database

QueryOption_TSDB_Insert : T_QueryOptionTimeSeriesDB_Insert; // defines detailed Queryparameter


fbNoSQLQueryBuilder_TimeSeriesDB : FB_NoSQLQueryBuilder_TimeSeriesDB; // defines database type
specific api
fbNoSqlQueryEvt : FB_NoSQLQueryEvt(sNetID := '', tTimeout := T#15S); // functionblock to execute

356 Version: 1.13.4 TF6420


Examples

queries

// databuffer for 1 second with 10 ms time delta


windTurbineData: ARRAY[1..100] OF WindTurbineData;

// error handling helper values


TcResult: Tc3_Database.I_TcMessage;
bError: BOOL;
sErrorMessage: STRING(255);

i: INT;
rand : DRAND;
nrand: LREAL;

Declaring the data source structure:

In this structure the attributes "TagName" and "FieldName" are used to declare the data fields as tags or
fields. By default they are declared as fields. These attributes can also be used if you want the column name
in the table to differ from the symbol name in the PLC.

To capture unset data during data analysis, default values outside the value range can be used to
detect such data during the analysis.

TYPE WindTurbineData :
STRUCT

{attribute 'TagName' := 'ID'}


WindTurbineID : STRING(255);

{attribute 'FieldName' := 'Power'}


Power : LREAL := -1; // [0) [kW]

{attribute 'FieldName' := 'Wind Speed'}


WindSpeed : LREAL := -1; // [0) [m/s]

{attribute 'FieldName' := 'Wind Direction'}


WindDirection : LREAL := -1; // [0,360][°]

END_STRUCT
END_TYPE

(WindTurbineData.tcDUT)

Declaration of the ENUM for the State-Machine:


TYPE E_DbLogState :
(
idle := 0,
init,
writing,
error
);
END_TYPE

Generating sample data:


FOR i := 1 TO 100 BY 1 DO
rand();
nrand := rand.Num;
windTurbineData[i].WindDirection := 240.328 + nrand;
windTurbineData[i].WindSpeed := 7.3292 + nrand;
windTurbineData[i].Power := 1133.1975 + nrand;
windTurbineData[i].WindTurbineID := 'Wind Turbine Verl 13';
END_FOR

CASE State OF

E_DbLogState.idle:
IF bWriting THEN
bWriting := FALSE;
State := E_DbLogState.init;
END_IF

Preparing the call:

TF6420 Version: 1.13.4 357


Examples

In this case, the array 'windTurbineData' is written into the 'WindMeasurement' table of the database.
Therefore the data is read directly from the process image. The data type is specified to read the addresses
in the memory. The time of the data sets is automatically generated by specifying the start time and the time
interval. The data must be stored correctly in the array. For example, one data set in the array can be used
per PLC cycle. It is useful to create a PLC task for this process. In this example the cycle time is 10 ms.
E_DbLogState.init:

fbNoSQLQueryBuilder_TimeSeriesDB.pQueryOptions := ADR(QueryOption_TSDB_Insert);
fbNoSQLQueryBuilder_TimeSeriesDB.cbQueryOptions := SIZEOF(QueryOption_TSDB_Insert);

QueryOption_TSDB_Insert.sTableName := 'WindMeasurement';
QueryOption_TSDB_Insert.sDataType := 'WindTurbineData';
QueryOption_TSDB_Insert.pSymbol := ADR(windTurbineData);
QueryOption_TSDB_Insert.cbSymbol := SIZEOF(windTurbineData);
QueryOption_TSDB_Insert.nDataCount := 100;
QueryOption_TSDB_Insert.nStartTimestamp := F_GetSystemTime();
QueryOption_TSDB_Insert.nCycleTime := 10000; // (in 100 ns)
State := E_DbLogState.writing;

Writing the data:

This call writes the data to the configured database with the corresponding database ID. This can take
several cycles, since it is an asynchronous process. If necessary, several storage arrays must be used to
ensure that the data is recorded seamlessly without gaps.
E_DbLogState.writing:

IF fbNoSqlQueryEvt.Execute(dbid, fbNoSQLQueryBuilder_TimeSeriesDB) THEN


IF fbNoSqlQueryEvt.bError THEN
TcResult := fbNoSqlQueryEvt.ipTcResult;
State := E_DbLogState.error;
ELSE
State := E_DbLogState.idle;
END_IF
END_IF

Error handling:

Use the Tc3 Eventlogger for error handling


E_DbLogState.error:

IF TcResult.RequestEventText(1033, sErrorMessage, SIZEOF(sErrorMessage)) THEN


TcResult.Send(F_GetSystemTime());
State := E_DbLogState.idle;
bError := TRUE;
END_IF

END_CASE

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
13743809291/.zip

7.2 Tc2_Database
All sample applications for the TwinCAT Database Server were consolidated in a solution. The solution can
be downloaded here from a central location: https://infosys.beckhoff.com/content/1033/
TF6420_Tc3_Database_Server/Resources/3494041099/.zip

In addition to the tszip file for the TwinCAT 3 solution, the zip file contains all the required file-based
databases. If the folder "Samples" from the zip file is located in the default installation folder: C:
\TwinCAT\Functions\TF6420-Database-Server\Win32, the paths in the Database Server configuration do not
have to be edited further. The samples with non-file-based databases, such as MS SQL, have to be
individual adapted with the configurator.

The individual samples are documented in detail on separate pages:

358 Version: 1.13.4 TF6420


Examples

SP project name Description


Create_DB_Sample [} 359] Creating a database connection and a table from the PLC
Cyclic_RdWrt_Sample [} 362] Cyclic logging/writing to/from a database
Write_DB_Sample [} 363] Writing of variables into a database with a simple PLC function block
without SQL command
SQL_InsertSelect_Sample [} 367] Sample with function block FB_DBRecordInsert/
FB_DBRecordArraySelect
StoredProcedures_Sample [} 369] Stored procedures with FB_DBStoredProceduresRecordArray
XML_DB_Sample [} 372] Using XML files as database
XML_XPath_Sample [} 377] XML XPath sample without schema
XML_XPath_Schema_Sample [} 380] XML XPath sample with XML Schema, comparable with TwinCAT XML
Server "Read"

7.2.1 Creating an MS Access database


This example illustrates the creation of a database from the PLC. In addition, a table is added, and the
database that has been generated is declared in the XML configuration file.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

TF6420 Version: 1.13.4 359


Examples

Database type used MS Access


Compatible database types MS SQL, MS Compact SQL, MS Access, XML
Function blocks used FB_DBCreate, FB_DBConnectionAdd,
FB_DBTableCreate
Libraries to be integrated Tc2_Database, Tc2_System, Tc2_Standard
Download file list TcDBSrv_InfoSysSamples.tszip

A table with the name "myTable", which has the following structure, is added to the generated database:

Column name Data type Property


ID Bigint IDENTITY(1,1)
Timestamp datetime
Name Ntext
Value Float

This table structure is generated with the following array:


tablestrc: ARRAY [0..3] OF ST_DBColumnCfg :=
[(sColumnName:='ID',sColumnProperty:='IDENTITY(1,1)',eColumnType:=EDBCOLUMN_BIGINT),
(sColumnName:='Timestamp',eColumnType:=EDBCOLUMN_DATETIME),
(sColumnName:='Name',eColumnType:=EDBCOLUMN_NTEXT),
(sColumnName:='Value',eColumnType:=EDBCOLUMN_FLOAT)];

Variable Declaration
PROGRAM MAIN
VAR
R_TRIG1 : R_TRIG;
bSTART : BOOL;

FB_FileDelete1 : FB_FileDelete;
FB_DBCreate1 : FB_DBCreate;
FB_DBConnectionAdd1: FB_DBConnectionAdd;
FB_DBTableCreate1 : FB_DBTableCreate;

bBusy_Delete : BOOL;
bBusy_CreateDB : BOOL;
bBusy_ConnAdd : BOOL;
bBusy_CreateTable : BOOL;

bErr : BOOL;
nErrid : UDINT;

nDBid : UDINT;

arrTablestrc : ARRAY [0..3] OF ST_DBColumnCfg :=


[(sColumnName:='ID',sColumnProperty:='IDENTITY(1,1)',eColumnType:=EDBCOLUMN_BIGINT),
(sColumnName:='Timestamp',eColumnType:=EDBCOLUMN_DATETIME),
(sColumnName:='Name',eColumnType:=EDBCOLUMN_NTEXT),
(sColumnName:='Value',eColumnType:=EDBCOLUMN_FLOAT)];

nState:BYTE := 0;

END_VAR

PLC program
CASE nState OF
0:
(*To start this sample you have to set a rising edge to the variable bSTART*)
R_TRIG1(CLK:=bSTART);
IF R_TRIG1.Q THEN
nState := 1;
FB_FileDelete1(bExecute:=FALSE);
FB_DBCreate1(bExecute:=FALSE);
FB_DBConnectionAdd1(bExecute:=FALSE);
FB_DBTableCreate1(bExecute:=FALSE);
bSTART := FALSE;
END_IF
1:
(*It isn't possible to overwrite an existing database file.
If the database file exist the FB_FileDelete block will delete the file*)
FB_FileDelete1(

360 Version: 1.13.4 TF6420


Examples

sNetId := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples\TestDB1000SPS.mdb',
ePath := PATH_GENERIC,
bExecute := TRUE,
tTimeout := T#5s,
bBusy => bBusy_Delete,
bError => ,
nErrId => );

IF NOT bBusy_Delete THEN


nState := 2;
END_IF

2:
(*The FB_DBCreate block will create the database file
"C:\TwinCAT\TcDatabaseSrv\Samples\TestDB1000SPS.mdb"*)
FB_DBCreate1(
sNetID := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples',
sDBName := 'TestDB1000SPS',
eDBType := eDBType_Access,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_CreateDB,
bError => bErr,
nErrID => nErrid);

IF NOT bBusy_CreateDB AND NOT bErr THEN


nState := 3;
END_IF
3:
(*The FB_DBConnectionAdd adds the connection information to the
XML configuration file*)
FB_DBConnectionAdd1(
sNetID := ,
eDBType := eDBType_Access,
eDBValueType:= eDBValue_Double,
sDBServer := ,
sDBProvider := 'Microsoft.Jet.OLEDB.4.0',
sDBUrl := 'C:\TwinCAT\TcDatabaseSrv\Samples\TestDB1000SPS.mdb',
sDBTable := 'myTable',
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_ConnAdd,
bError => bErr,
nErrID => nErrid,
hDBID => nDBid);

IF NOT bBusy_ConnAdd AND NOT bErr THEN


nState := 4;
END_IF
4:
(*The FB_DBTableCreate create the table "myTable"*)
FB_DBTableCreate1(
sNetID := ,
hDBID := nDBid,
sTableName := 'myTable',
cbTableCfg := SIZEOF(arrTablestrc),
pTableCfg := ADR(arrTablestrc),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_CreateTable,
bError => bErr,
nErrID => nErrid);

IF NOT bBusy_CreateTable AND NOT bErr THEN


nState := 0;
END_IF
END_CASE

In order to use this sample, you only need to transfer the NetID of the ADS device (on which the
TwinCAT Database Server is installed) to the sNetID input.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

TF6420 Version: 1.13.4 361


Examples

7.2.2 Starting / stopping, cyclic logging


This sample illustrates the starting and stopping of cyclic logging from the PLC.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

Database type used MS Compact SQL


Compatible database types ASCII, MS SQL, MS Compact SQL, MS Access,
MySQL, PostgreSQL, DB2, Oracle, InterBase/
Firebird, XML
Function blocks used FB_DBCyclicRdWrt
Libraries to be integrated Tc2_Database, Tc2_System, Tc2_Standard
Download file list TcDBSrv_InfoSysSamples.tszip,
CurrentConfigDataBase.xml, TestDB_Cyclic.sdf

In this sample the cyclic log function is started or stopped by toggling the bStartStop variable.
The cyclic log process begins in response to a positive edge at the bExecute input.
A negative edge will end the process again.

Variable declaration (PRG data types)


PROGRAM DataTypes
VAR
DBSrv_DT_INT : INT;
DBSrv_DT_UINT : UINT;
DBSrv_DT_DINT : DINT;
DBSrv_DT_UDINT : UDINT;
DBSrv_DT_REAL : REAL;
DBSrv_DT_LREAL : LREAL;
DBSrv_DT_BYTE : BYTE := 16#A1;
DBSrv_DT_BOOL : BOOL;
DBSrv_DT_MYSTRUCT: ST_MyStruct;
DBSrv_DT_ARRAY : ARRAY [0..19] OF UDINT;

362 Version: 1.13.4 TF6420


Examples

DBSrv_DT_WORD : WORD;
DBSrv_DT_DWORD : DWORD;
END_VAR

ST_MyStruct structure
TYPE ST_MyStruct :
STRUCT
iValue1 : INT;
iValue2 : UINT;
iValue3 : BOOL;
iValue4 : REAL;
END_STRUCT
END_TYPE

Variable Declaration
PROGRAM MAIN
VAR
fbDBCyclicRdWrt1: FB_DBCyclicRdWrt;

bCyclic : BOOL :=TRUE;

bBusy_Cyclic : BOOL;
bErr : BOOL;
nErrID : UDINT;
sSQLState : ST_DBSQLError;
END_VAR

PLC program
DataTypes;

fbDBCyclicRdWrt(
sNetID := ,
bExecute := bCyclic,
tTimeout := t#15s,
bBusy => bBusy_Cyclic,
bError => bErr,
nErrID => nErrID,
sSQLState => sSQLState);

In order to use this sample, you only need to transfer the NetID of the ADS device (on which the
TwinCAT Database Server is installed) to the sNetID input.
When you run the program and set the bCyclic variable to TRUE, all the variables that are declared in the
symbol group of the XML configuration file are logged.

TwinCAT Database Server


All Microsoft SQL Compact databases, which are declared in the XML configuration file, must exist.
They are not generated automatically.
The declared ASCII files, on the other hand, are generated automatically if they do not exist.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

7.2.3 Logging of a PLC variable with FB_DBWrite


This sample illustrates logging of a PLC variables from the PLC in a database and the operating principle of
the individual write modes.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

TF6420 Version: 1.13.4 363


Examples

Database type used MS SQL


Compatible database types ASCII, MS SQL, MS Compact SQL, MS Access,
MySQL, PostgreSQL, DB2, Oracle, InterBase/
Firebird, XML
Function blocks used FB_DBWrite
Libraries to be integrated Tc2_Database, Tc2_System, Tc2_Standard
Download file list TcDBSrv_InfoSysSamples.tszip,
CurrentConfigDataBase.xml, SQLQuery.sql

In order to be able to use this sample, you have to adapt the server name and the authentication in the XML
configuration file (CurrentConfigDataBase.xml). Ensure that no "TestDB" database is present before
executing the SQLQuery.sql script.

Sample configuration:

The variable "eWriteMode" can be used to set the write mode for logging.
The write operation can then be started with a positive edge at the variable "bSTART".

Table assignment:
• ADS_TO_DB_APPEND => eWriteAppend -> "tbl_Append"
• ADS_TO_DB_UPDATE => eWriteUpdate -> "tbl_Update"
• ADS_TO_DB_RINGBUFFER => eWriteRingBuffer -> "tbl_RingBuffer"

364 Version: 1.13.4 TF6420


Examples

Table structure used

Column name Data type Null permitted Feature


ID Bigint no IDENTITY(1,1)
Timestamp datetime no
Name Ntext no
Value Float no

Variable Declaration
PROGRAM MAIN
VAR
(*Test symbol which will be logged into the different database tables*)
lrTestValueVar : LREAL := 123.456;

eState : E_SampleState := eIdle;


R_TRIG1 : R_TRIG;

(*With a rising edge at bStart the FB_DBWrite block will be start once*)
bSTART : BOOL;

(*With eWriteMode you can select which FB_DBWrite block will be used*)
eWriteMode : E_SampleState := eWriteAppend;

FB_DBWrite_Append : FB_DBWrite;
FB_DBWrite_Update : FB_DBWrite;
FB_DBWrite_RingBuffer: FB_DBWrite;

(*Status outputs from the three FB_DBWrite blocks*)


bBusy : BOOL;
bErr : BOOL;
bErrid : UDINT;
stSqlstate : ST_DBSQLError;
END_VAR

Enum E_SampleState
TYPE E_SampleState :(
eIdle := 0,
eWriteAppend := 1,
eWriteUpdate := 2,
eWriteRingBuffer:= 3
);
END_TYPE

PLC program
CASE eState OF
eIdle :
R_TRIG1(CLK:=bSTART);
IF R_TRIG1.Q THEN
lrTestValueVar := lrTestValueVar + 1;
eState := eWriteMode;
bSTART := FALSE;
END_IF
(*Add a new record to the table tbl_Append*)
eWriteAppend :
FB_DBWrite_Append(
sNetID := ,
hDBID := 1,
hAdsID := 1,
sVarName := 'MAIN.lrTestValueVar',
nIGroup := ,
nIOffset := ,
nVarSize := ,
sVarType := ,
sDBVarName := 'lrTestValueVar',
eDBWriteMode := eDBWriteMode_Append,
tRingBufferTime := ,
nRingBufferCount:= ,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bErr,
nErrID => bErrid,
sSQLState => stSqlstate);

TF6420 Version: 1.13.4 365


Examples

IF NOT bBusy THEN


FB_DBWrite_Append(bExecute := FALSE);
eState := eIdle;
END_IF
(*Add a new record to the table tbl_Update if it not exist
else the existing record will be updated*)
eWriteUpdate :
FB_DBWrite_Update(
sNetID := ,
hDBID := 2,
hAdsID := 1,
sVarName := 'MAIN.lrTestValueVar',
nIGroup := ,
nIOffset := ,
nVarSize := ,
sVarType := ,
sDBVarName := 'lrTestValueVar',
eDBWriteMode := eDBWriteMode_Update,
tRingBufferTime := ,
nRingBufferCount := ,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bErr,
nErrID => bErrid,
sSQLState => stSqlstate);

IF NOT bBusy THEN


FB_DBWrite_Update(bExecute := FALSE);
eState := eIdle;
END_IF
(*Add a new record to the table tbl_RingBuffer.
If the maximum count is reached the records will be deleted in a FIFO process*)
eWriteRingBuffer :
FB_DBWrite_RingBuffer(
sNetID := ,
hDBID := 3,
hAdsID := 1,
sVarName := 'MAIN.lrTestValueVar',
nIGroup := ,
nIOffset := ,
nVarSize := ,
sVarType := ,
sDBVarName := 'lrTestValueVar',
eDBWriteMode := eDBWriteMode_RingBuffer_Count,
tRingBufferTime := ,
nRingBufferCount := 10,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bErr,
nErrID => bErrid,
sSQLState => stSqlstate);

IF NOT bBusy THEN


FB_DBWrite_RingBuffer(bExecute := FALSE);
eState := eIdle;
END_IF
END_CASE

TwinCAT Database Server


All Microsoft SQL Compact databases, which are declared in the XML configuration file, must exist.
They are not generated automatically.
The declared ASCII files, on the other hand, are generated automatically if they do not exist.

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

366 Version: 1.13.4 TF6420


Examples

7.2.4 Example with the FB_DBRecordInsert and


FB_DBRecordSelect function blocks
This example illustrates logging of several values in a database from the PLC with the function block
FB_DBRecordInsert. In this example, several PLC variables are logged in a single record. In addition, the
function block FB_DBRecordSelect can be used to read a record from this database.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

Database type used MS Access


Compatible database types MS SQL, MS Compact SQL, MS Access, MySQL,
PostgreSQL, DB2, Oracle, InterBase/Firebird, XML
Function blocks used FB_DBRecordInsert, FB_DBRecordSelect
Libraries to be integrated "Tc2_Database", "Tc2_System", "Tc2_Standard",
"Tc2_Utilities"
Download file list TcDBSrv_InfoSysSamples.tszip,
CurrentConfigDataBase.xml, TestDB_Access.mdb

The following table structure is used for writing:

Column name Data type


Timestamp datetime
PLC_TestValue1 float
PLC_TestValue2 float
PLC_TestValue3 float
PLC_TestValue4 String

Variable Declaration
(* Declaration *)PROGRAM MAIN
VAR
eState : E_SQLStatement;

NT_GetTime1 : NT_GetTime;
bTimestart : BOOL;
tTime : TIMESTRUCT;

TF6420 Version: 1.13.4 367


Examples

FB_FormatStringDateTime: FB_FormatString;
sDateTimeString : T_MaxString;

TestValue1 : REAL := 123.456;


TestValue2 : REAL := 234.567;
TestValue3 : REAL := 345.678;
TestValue4 : STRING(255) := 'No error occurred';

FB_FormatString1 : FB_FormatString;
sInsertString : T_MaxString;
bError : BOOL;
nErrid : UDINT;

FB_DBRecordInsert1: FB_DBRecordInsert;
bStartstopInsert : BOOL;
bBusyInsert : BOOL;
bErrInsert : BOOL;
nErridInsert : UDINT;
stSQLStateInsert : ST_DBSQLError;

stRecord : ST_Record;

FB_DBRecordSelect1: FB_DBRecordSelect;
nRecIndex : UDINT := 0;
bStartstopSelect : BOOL;
bBusySelect : BOOL;
bErrorSelect : BOOL;
nErrIDSelect : UDINT;
stSQLStateSelect : ST_DBSQLError;
nRecordCount : UDINT;
END_VAR

Enum E_SQLStatement
TYPEE_SQLStatement:(
eSQL_INSERT := 0,
eSQL_SELECT := 1
);
END_TYPE

Struct ST_Record
TYPEST_Record :
STRUCT
Timestamp : DT;
PLC_Value1: REAL;
PLC_Value2: REAL;
PLC_Value3: REAL;
PLC_Value4: STRING;
END_STRUCT
END_TYPE

PLC program
CASEeState OF
eSQL_INSERT:
(*Create the timestamp*)
NT_GetTime1( START:= bTimestart, TIMESTR=> tTime);
IF NOT NT_GetTime1.BUSY THEN
bTimestart:= NOT bTimestart;
END_IF

FB_FormatStringDateTime(
sFormat := '%D.%D.%D %D:%D:%D',
arg1 := F_WORD(tTime.wYear),
arg2 := F_WORD(tTime.wMonth),
arg3 := F_WORD(tTime.wDay),
arg4 := F_WORD(tTime.wHour),
arg5 := F_WORD(tTime.wMinute),
arg6 := F_WORD(tTime.wSecond),
sOut => sDateTimeString);

(*Create the SQL-INSERT command*)


FB_FormatString1(
sFormat := 'INSERT INTO tbl_Test VALUES($'%S$',%F,%F,%F,$'%S$')',
arg1 := F_STRING(sDateTimeString),
arg2 := F_REAL(TestValue1),
arg3 := F_REAL(TestValue2),

368 Version: 1.13.4 TF6420


Examples

arg4 := F_REAL(TestValue3),
arg5 := F_STRING(TestValue4),
sOut => sInsertString,
bError => bError,
nErrId => nErrid);

(*Write the record to the database*)


FB_DBRecordInsert1(
sNetID := ,
hDBID := 1,
sInsertCmd:= sInsertString,
bExecute := bStartstopInsert,
tTimeout := T#15s,
bBusy => bBusyInsert,
bError => bErrInsert,
nErrID => nErridInsert,
sSQLState => stSQLStateInsert);

eSQL_SELECT:
(*Read one record from the database*)
FB_DBRecordSelect1(
sNetID := ,
hDBID := 1,
sSelectCmd:= 'SELECT * FROM tbl_Test',
nRecordIndex:= nRecIndex,
cbRecordSize:= SIZEOF(stRecord),
pDestAddr := ADR(stRecord),
bExecute := bStartstopSelect,
tTimeout := T#15s,
bBusy => bBusySelect,
bError => bErrorSelect,
nErrID => nErrIDSelect,
sSQLState => stSQLStateSelect,
nRecords => nRecordCount);
END_CASE

To use this sample, you have to declare the Access database "Sample7.mdb" in the XML configuration file.
A record with the four PLC values and the timestamp is created in the database by generating a positive
edge at the variable "bStartstopInsert".

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

7.2.5 Stored procedures with


FB_DBStoredProceduresRecordArray
The function block FB_DBStoredProceduresRecordArray can be used to declare parameters as INPUT,
OUTPUT or INOUT and transfer them to the stored procedures. In this way complex SQL commands can be
preprogrammed in the database server and then triggered by the TwinCAT Database Server. In contrast to
the function block FB_DBStoredProceduresRecordReturn, this function block can be used to return several
records with a single call.

TF6420 Version: 1.13.4 369


Examples

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

Database type used MS SQL (MS SQL Server 2008)


Compatible database types MS SQL, MySQL, Oracle
Function blocks used FB_DBStoredProceduresRecordArray
Libraries to be integrated Tc2_Database, Tc2_System, Tc2_Base, Tc2_Utilities
Download file list TcDBSrv_InfoSysSamples.tszip,
CurrentConfigDataBase.xml

The following sample illustrates the call in a simple stored procedure with an input parameter and return
record. The procedure was created on a Microsoft SQL Server 2008.

Code der Stored Procedure SP_GetAddressByCustomerID


CREATE PROCEDURE [SP_GetAddressByCustomerID]
@Customer_ID bigint
AS
BEGIN
SELECT tbl_Customer.ID, tbl_Customer.Name, tbl_Customer.Customer, tbl_Products.SerNum,
tbl_Products.Product, tbl_Products.Info, tbl_Pos.Timestamp
FROM
tbl_Pos JOIN tbl_Customer ON tbl_Pos.CustomerNum = tbl_Customer.ID
JOIN tbl_Products ON tbl_Pos.ProductNum = tbl_Products.SerNum
WHERE
tbl_Pos.CustomerNum = @Customer_ID;
END

Variable declaration in the PLC


PROGRAM MAIN
VAR
R_TRIG1 : R_TRIG;
bREAD : BOOL := FALSE;

nState : BYTE;

370 Version: 1.13.4 TF6420


Examples

arrParaList : ARRAY [0..0] OF ST_DBParameter;

nCustomerID : DINT := 12345;

FB_DBStoredProceduresRecordArray1: FB_DBStoredProceduresRecordArray;

nCustomerID: DINT:= 12345;


nRecordStartIndex: UDINT;
stRecordArr : ARRAY [1..25] OF ST_Record;
nRecs : UDINT;

bBusy : BOOL;
bErr : BOOL;
nErrid : UDINT;
stSqlstate : ST_DBSQLError;
END_VAR

Record structure in the PLC (ST_Record)


TYPE ST_Record :
STRUCT
nID : T_ULARGE_INTEGER;
sCustomer : STRING(50);
sName : STRING(50);
nProductNum : DINT;
sProductName: STRING(50);
sProductInfo: T_MaxString;
tTimestamp : DT;
END_STRUCT
END_TYPE

PLC program
R_TRIG1(CLK:=bREAD);
IF R_TRIG1.Q AND NOT bBusy THEN
nState := 1;
END_IF

CASE nState OF
0:
;
1:(*Init of the parameters*)
arrParaList[0].sParameterName := '@Customer_ID';
arrParaList[0].eParameterDataType:= eDBColumn_Integer;
arrParaList[0].eParameterType := eDBParameter_Input;
arrParaList[0].cbParameterValue := SIZEOF(nCustomerID);
arrParaList[0].pParameterValue := ADR(nCustomerID);

nState := 2;
2:(*Start the stored procedure "SP_GetCustomerPosition"*)
FB_DBStoredProceduresRecordArray1(
sNetID:= ,
hDBID:= 1,
sProcedureName := 'SP_GetCustomerPositions',
cbParameterList := SIZEOF(arrParaList),
pParameterList := ADR(arrParaList),
nStartIndex := nRecordStartIndex,
nRecordCount := 25,
cbRecordArraySize:= SIZEOF(stRecordArr),
pDestAddr := ADR(stRecordArr),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bErr,
nErrID => nErrid,
sSQLState => stSqlstate,
nRecords => nRecs);

IF NOT bBusy THEN


FB_DBStoredProceduresRecordReturn1(bExecute:= FALSE);
nState := 0;
END_IF
END_CASE

TF6420 Version: 1.13.4 371


Examples

Visualization

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

7.2.6 Using XML as database


The TwinCAT Database Server provides the ability to use an XML file as a database. Apart from the "Stored
Procedure" functions, the XML database type supports all known function blocks for reading and writing in a
database. Even SQL commands that can be issued with the function blocks FB_DBRecordInsert or
FB_DBRecordSelect are interpreted by the TwinCAT Database Server and applied to the XML file.

This sample demonstrates how an XML database is created, filled with the function block FB_DBWrite and
subsequently read with an SQL SELECT command and the function block FB_DBRecordSelect.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

372 Version: 1.13.4 TF6420


Examples

Database type used XML


Compatible database types MS SQL, MS Compact SQL, MS Access, XML
Function blocks used FB_DBCreate, FB_DBConnectionAdd,
FB_DBTableCreate, FB_DBWrite,
FB_DBRecordSelect
Libraries to be integrated "Tc2_Database", "Tc2_System", "Tc2_Standard",
"Tc2_Utilities"
Download file list TcDBSrv_InfoSysSamples.tszip

MAIN program
PROGRAM MAIN
VAR
nState :BYTE := 0;

R_TRIG1 : R_TRIG;
bSTART : BOOL;

nCounter : INT;

FB_FileDelete1 : FB_FileDelete;
FB_DBCreate1 : FB_DBCreate;
FB_DBConnectionAdd1: FB_DBConnectionAdd;
FB_DBTableCreate1 : FB_DBTableCreate;

TF6420 Version: 1.13.4 373


Examples

FB_DBWrite1 : FB_DBWrite;
FB_DBRecordSelect1 : FB_DBRecordSelect;

bBusy_Delete : BOOL;
bBusy_CreateDB : BOOL;
bBusy_ConnAdd : BOOL;
bBusy_CreateTable : BOOL;
bBusy_WriteDB : BOOL;
bBusy_SelectRecord : BOOL;

bErr : BOOL;
nErrid : UDINT;
stSQLState : ST_DBSQLError;
nRecs : UDINT;

nDBid : UDINT;

arrTablestrc : ARRAY [0..3] OF ST_DBColumnCfg :=


[(sColumnName:='ID',sColumnProperty:='IDENTITY(1,1)',eColumnType:=EDBCOLUMN_BIGINT),
(sColumnName:='Timestamp',eColumnType:=EDBCOLUMN_DATETIME),
(sColumnName:='Name',sColumnProperty:='80',eColumnType:=EDBCOLUMN_NTEXT),
(sColumnName:='Value',eColumnType:=EDBCOLUMN_FLOAT)];

rTestValue : LREAL := 1234.56789;


stRecord : ST_Record;
END_VAR
CASE nState OF
0:
(*To start this sample you have to set a rising edge to the variable bSTART*)
R_TRIG1(CLK:=bSTART);
IF R_TRIG1.Q THEN
nState := 1;
FB_FileDelete1(bExecute:=FALSE);
FB_DBCreate1(bExecute:=FALSE);
FB_DBConnectionAdd1(bExecute:=FALSE);
FB_DBTableCreate1(bExecute:=FALSE);
FB_DBWrite1(bExecute:=FALSE);
FB_DBRecordSelect1(bExecute:=FALSE);
bSTART := FALSE;
nCounter:= 0;
END_IF
1:
(*It isn't possible to overwrite an existing database file.
If the database file exist the FB_FileDelete block will delete the file*)
FB_FileDelete1(
sNetId := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples\XMLTestDB.xml',
ePath := PATH_GENERIC,
bExecute := TRUE,
tTimeout := T#5s,
bBusy => bBusy_Delete,
bError => ,
nErrId => );

IF NOT bBusy_Delete THEN


nState := 10;
END_IF
10:
(*It isn't possible to overwrite an existing database file.
If the database file exist the FB_FileDelete block will delete the file*)
FB_FileDelete1(
sNetId := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples\XMLTestDB.xsd',
ePath := PATH_GENERIC,
bExecute := TRUE,
tTimeout := T#5s,
bBusy => bBusy_Delete,
bError => ,
nErrId => );

IF NOT bBusy_Delete THEN


FB_FileDelete1(bExecute:=FALSE);
nState := 2;
END_IF
2:
(*The FB_DBCreate block will create the database file
"C:\TwinCAT\TcDatabaseSrv\Samples\XMLTestDB.xml" and
C:\TwinCAT\TcDatabaseSrv\Samples\XMLTestDB.xsd "*)
FB_DBCreate1(

374 Version: 1.13.4 TF6420


Examples

sNetID := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples',
sDBName := 'XMLTestDB',
eDBType := eDBType_XML,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_CreateDB,
bError => bErr,
nErrID => nErrid);

IF NOT bBusy_CreateDB AND NOT bErr THEN


nState := 3;
END_IF
3:
(*The FB_DBConnectionAdd adds the connection information to the
XML configuration file*)
(*ATTENTION: Each database type has his own connection information*)
FB_DBConnectionAdd1(
sNetID := ,
eDBType := eDBType_XML,
eDBValueType:= eDBValue_Double,
sDBServer := 'XMLTestDB',
sDBProvider := ,
sDBUrl := 'C:\TwinCAT\TcDatabaseSrv\Samples\XMLTestDB.xml',
sDBTable := 'myTable',
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_ConnAdd,
bError => bErr,
nErrID => nErrid,
hDBID => nDBid);

IF NOT bBusy_ConnAdd AND NOT bErr THEN


nState := 4;
END_IF
4:
(*The FB_DBTableCreate create the table "myTable"*)
FB_DBTableCreate1(
sNetID := ,
hDBID := nDBid,
sTableName := 'myTable',
cbTableCfg := SIZEOF(arrTablestrc),
pTableCfg := ADR(arrTablestrc),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_CreateTable,
bError => bErr,
nErrID => nErrid);

IF NOTbBusy_CreateTable AND NOT bErr THEN


nState := 5;
END_IF
5:
(*The FB_DBWrite write five times the value of the plc variable "rTestValue" to
the database table "myTable"*)
FB_DBWrite1(
sNetID := ,
hDBID := nDBid,
hAdsID := 1,
sVarName := 'MAIN.rTestValue',
nIGroup := ,
nIOffset := ,
nVarSize := ,
sVarType := ,
sDBVarName := 'rTestValue',
eDBWriteMode := eDBWriteMode_Append,
tRingBufferTime := ,
nRingBufferCount:= ,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_WriteDB,
bError => bErr,
nErrID => nErrid,
sSQLState => stSQLState);

IF NOT bBusy_WriteDB AND NOT bErr THEN


FB_DBWrite1(bExecute := FALSE);
nCounter := nCounter + 1;
IFnCounter = 5 THEN
nState := 6;

TF6420 Version: 1.13.4 375


Examples

END_IF
END_IF
6:
(*The FB_DBRecordSelect select one record of the database table "myTable""*)
FB_DBRecordSelect1(
sNetID := ,
hDBID := nDBid,
sSelectCmd := 'SELECT * FROM myTable WHERE Name = $'rTestValue$'',
nRecordIndex := 0,
cbRecordSize := SIZEOF(stRecord),
pDestAddr := ADR(stRecord),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_SelectRecord,
bError => bErr,
nErrID => nErrid,
sSQLState => stSQLState,
nRecords => nRecs);

IF NOT bBusy_SelectRecord AND NOT bErr THEN


nState := 0;
END_IF
END_CASE

The process is started with a positive edge at the toggle variable bSTART.

The following files are created:

XMLTestDB.xml (XML database file)


<?xmlversion="1.0"encoding="UTF-8"?>
<XMLTestDBxmlns:xs="http://www.w3.org/2001/XMLSchema-
instance"xs:noNamespaceSchemaLocation="XMLTestDB.xsd">
<myTable>
<rowID="1"Timestamp="2012-05-10T13:48:47"Name="rTestValue"Value="1234.56789" />
<rowID="2"Timestamp="2012-05-10T13:48:47"Name="rTestValue"Value="1234.56789" />
<rowID="3"Timestamp="2012-05-10T13:48:47"Name="rTestValue"Value="1234.56789" />
<rowID="4"Timestamp="2012-05-10T13:48:47"Name="rTestValue"Value="1234.56789" />
<rowID="5"Timestamp="2012-05-10T13:48:47"Name="rTestValue"Value="1234.56789" />
</myTable>
</XMLTestDB>

XMLTestDB.xsd (XML Schema)


<?xmlversion="1.0"?>
<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:simpleTypename="bigint">
<xsd:restrictionbase="xsd:long" />
</xsd:simpleType>
<xsd:simpleTypename="datetime">
<xsd:restrictionbase="xsd:dateTime" />
</xsd:simpleType>
<xsd:simpleTypename="ntext_80">
<xsd:restrictionbase="xsd:string">
<xsd:maxLengthvalue="80" />
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleTypename="float">
<xsd:restrictionbase="xsd:double" />
</xsd:simpleType>
<xsd:complexTypename="myTable_Type">
<xsd:sequence>
<xsd:elementminOccurs="0"maxOccurs="unbounded"name="row">
<xsd:complexType>
<xsd:attributename="ID"type="bigint" />
<xsd:attributename="Timestamp"type="datetime" />
<xsd:attributename="Name"type="ntext_80" />
<xsd:attributename="Value" type="float" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:elementname="XMLTestDB">
<xsd:complexType>
<xsd:sequenceminOccurs="1"maxOccurs="1">
<xsd:elementname="myTable"type="myTable_Type" />
</xsd:sequence>

376 Version: 1.13.4 TF6420


Examples

</xsd:complexType>
</xsd:element>
</xsd:schema>

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

7.2.7 XPath sample to illustrate the different SELECT types


The function block FB_DBRecordArraySelect/FB_DBRecordSelect can be used to issue XPath commands
and read XML tags from any XML file. This sample illustrates reading of different entries from XML files via
the TwinCAT Database Server. Individual tags, subtags and reading of attributes is supported, and these are
displayed.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

Database type used XML


Compatible database types XML
Function blocks used FB_DBRecordArraySelect
Libraries to be integrated Tc2_Database, Tc2_System, Tc2_Standard,
Tc2_Utilities
Download file list TcDBSrv_InfoSysSamples.tszip

Sample XML file (XMLFactoryXY.xml)


<?xmlversion="1.0" encoding="utf-8" ?>
<Factory_XY>
<Name>Sample Factory XY</Name>
<Factory_Info>
<Street>Samplestreet 25</Street>
<City>33415 Verl</City>
<Country>Germany</Country>
<Office_Count>1</Office_Count>
<Employe_Count>6</Employe_Count>
<Manager>Max Mustermann</Manager>
</Factory_Info>
<Employees>

TF6420 Version: 1.13.4 377


Examples

<Employeeid="10001" name="Julia Kingston" department="Development" position="Worker"


hired="2001-08-01" />
<Employeeid="10002" name="Jens Marx" department="Import" position="Worker" hired="2003-08-01" />
<Employeeid="10003" name="Justus Kaiser" department="Export" position="Worker" hired="2003-08-01" />
<Employeeid="10004" name="Marc Klein" department="Production" position="Worker" hired="2005-08-01" /
>
<Employeeid="10005" name="Matt Bloomberg" department="Production" position="Worker"
hired="2005-08-01" />
<Employeeid="10006" name="Frida Hundt" department="Production" position="Worker"
hired="2010-08-01" />
</Employees>
</Factory_XY>

ST_FactoryInfo structure
TYPEST_FactoryInfo :
STRUCT
sStreet : T_MaxString;
sCity : T_MaxString;
sCountry : T_MaxString;
sOffice_Count : T_MaxString;
sEmploye_Count: T_MaxString;
sManager : T_MaxString;
END_STRUCT
END_TYPE

ST_Employee structure
TYPEST_Employee :
STRUCT
sID : T_MaxString;
sName : T_MaxString;
sDepartment : T_MaxString;
sPosition : T_MaxString;
sHired : T_MaxString;
END_STRUCT
END_TYPE

MAIN program
PROGRAM MAIN
VAR
bSTART : BOOL;
R_TRIG1 : R_TRIG;

nState : INT;

sXPath : T_MaxString;

fbDBRecordArraySelect : FB_DBRecordArraySelect;

bBusy_ReadFactoryName : BOOL;
bError_ReadFactoryName: BOOL;
nErrID_ReadFactoryName: UDINT;

bBusy_ReadFactoryInfo : BOOL;
bError_ReadFactoryInfo: BOOL;
nErrID_ReadFactoryInfo: UDINT;

bBusy_ReadEmployee : BOOL;
bError_ReadEmployee : BOOL;
nErrID_ReadEmployee : UDINT;

stSQLState : ST_DBSQLError;

sFactoryName : T_MaxString;
stFactoryInfo : ST_FactoryInfo;
aEmployees : ARRAY [1..10] OF ST_Employee;
END_VAR
R_TRIG1(CLK:=bSTART);
IF R_TRIG1.Q THEN
bSTART:=FALSE;
fbDBRecordArraySelect(bExecute:=FALSE);
nState:=1;
END_IF
CASE nState OF
0://IDLE
;

378 Version: 1.13.4 TF6420


Examples

1://Read Factory Name


sXPath:= 'XPATH#Factory_XY/Name';
fbDBRecordArraySelect(
sNetID := ,
hDBID := 7,
pCmdAddr := ADR(sXPath),
cbCmdSize := SIZEOF(sXPath),
nStartIndex := 0,
nRecordCount := 1,
pDestAddr := ADR(sFactoryName),
cbRecordArraySize:= SIZEOF(sFactoryName),
bExecute := TRUE,
tTimeout := T#15S,
bBusy => bBusy_ReadFactoryName,
bError => bError_ReadFactoryName,
nErrID => nErrID_ReadFactoryName,
sSQLState => stSQLState,
nRecords => );

IF NOT bBusy_ReadFactoryName THEN


fbDBRecordArraySelect(bExecute:=FALSE);
IF NOT bError_ReadFactoryName THEN
nState :=2;
ELSE
nState :=255;
END_IFEND_IF
2://Read Factory Info
sXPath := 'XPATH#Factory_XY/Factory_Info';
fbDBRecordArraySelect(
sNetID := ,
hDBID := 7,
pCmdAddr := ADR(sXPath),
cbCmdSize := SIZEOF(sXPath),
nStartIndex := 0,
nRecordCount := 1,
pDestAddr := ADR(stFactoryInfo),
cbRecordArraySize := SIZEOF(stFactoryInfo),
bExecute := TRUE,
tTimeout := T#15S,
bBusy => bBusy_ReadFactoryInfo,
bError => bError_ReadFactoryInfo,
nErrID => nErrID_ReadFactoryInfo,
sSQLState => stSQLState,
nRecords => );

IF NOT bBusy_ReadFactoryInfo THEN


fbDBRecordArraySelect(bExecute:=FALSE);
IF NOT bError_ReadFactoryInfo THEN
nState :=3;
ELSE
nState :=255;
END_IF
END_IF
3://Read Employees
sXPath := 'XPATH#Factory_XY/Employees/Employee';
fbDBRecordArraySelect(
sNetID := ,
hDBID := 7,
pCmdAddr := ADR(sXPath),
cbCmdSize := SIZEOF(sXPath),
nStartIndex := 0,
nRecordCount := 10,
pDestAddr := ADR(aEmployees),
cbRecordArraySize := SIZEOF(aEmployees),
bExecute := TRUE,
tTimeout := T#15S,
bBusy => bBusy_ReadEmployee,
bError => bError_ReadEmployee,
nErrID => nErrID_ReadEmployee,
sSQLState => stSQLState,
nRecords => );

IF NOT bBusy_ReadEmployee THEN


fbDBRecordArraySelect(bExecute:=FALSE);
IF NOT bError_ReadEmployee THEN
nState :=0;
ELSE
nState :=255;
END_IFEND_IF

TF6420 Version: 1.13.4 379


Examples

255://Error State
;
END_CASE

A positive edge at the variable "bStart" triggers issuing of the XPath commands and reading of the individual
elements from the XML file. The results will then be in the variables "sFactoryName", "stFactoryInfo" and
"aEmployees".

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

7.2.8 XPath sample with XML schema


The function blocks FB_DBRecordSelect or FB_DBRecordArraySelect can be used to issue XPath
commands and to read XML tags, XML subtags or XML attributes from any XML file. If a suitable XML
schema exists for the XML file to be read, the content of the tags or attributes is converted to the
corresponding data types, as defined in the schema.

Further information about XML schemas can be found here: http://www.edition-w3.de/TR/2001/REC-


xmlschema-0-20010502/

In this sample, FB_DBRecordArraySelect is used to read two different subtags from an XML file with
corresponding XML schema.

Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip

Database type used XML


Compatible database types XML
Function blocks used FB_DBRecordSelect
Libraries to be integrated Tc2_Database, Tc2_System, Tc2_Standard,
Tc2_Utilities
Download file list TcDBSrv_InfoSysSamples.tszip,
CurrentConfigDatabase.xml, PLC_Structs.xml,
PLC_Structs.xsd

380 Version: 1.13.4 TF6420


Examples

Sample XML file (PLC_Structs.xml)


<?xml version = "1.0" encoding="utf-8" ?>
<Beckhoff_PLC>
<PLC_Structs>
<PLC_Struct Name="ST_TestStruct">
<Struct Instance="1">
<nINT64>123456789</nINT64>
<nUINT16>1234</nUINT16>
<rREAL64>1234.5678</rREAL64>
<sSTRING>This is instance one of ST_TestStruct</sSTRING>
<bBOOL>true</bBOOL>
<nINT32>-100</nINT32>
</Struct>
<Struct Instance="2">
<nINT64>234567890</nINT64>
<nUINT16>2345</nUINT16>
<rREAL64>234.56789</rREAL64>
<sSTRING>This is instance two of ST_TestStruct</sSTRING>
<bBOOL>false</bBOOL>
<nINT32>-50</nINT32>
</Struct>
<Struct Instance="3">
<nINT64>345678901</nINT64>
<nUINT16>3456</nUINT16>
<rREAL64>3456.78901</rREAL64>
<sSTRING>This is instance three of ST_TestStruct</sSTRING>
<bBOOL>true</bBOOL>
<nINT32>-150</nINT32>
</Struct>
</PLC_Struct>
<PLC_Struct Name="ST_TestStruct2">
<Struct2 Instance="1">
<sSTRING>This is instance one of ST_TestStruct2</sSTRING>
<bBOOL>false</bBOOL>
<nINT32>-88</nINT32>
</Struct2>
<Struct2 Instance="2">
<sSTRING>This is instance two of ST_TestStruct2</sSTRING>
<bBOOL>true</bBOOL>
<nINT32>-9</nINT32>
</Struct2>
</PLC_Struct>
</PLC_Structs>
</Beckhoff_PLC>

Corresponding XML schema (PLC_Structs.xsd)


<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://
www.w3.org/2001/XMLSchema">
<xs:element name="Beckhoff_PLC">
<xs:complexType >
<xs:sequence >
<xs:element name = "PLC_Structs">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs = "unbounded" name="PLC_Struct">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs = "0" maxOccurs="unbounded" name="Struct">
<xs:complexType>
<xs:sequence>
<xs:element name = "nINT64" type="xs:long" />
<xs:element name = "nUINT16" type="xs:unsignedShort" />
<xs:element name = "rREAL64" type="xs:double" />
<xs:element name = "sSTRING" type="xs:string" />
<xs:element name = "bBOOL" type="xs:boolean" />
<xs:element name = "nINT32" type="xs:int" />
</xs:sequence>
<xs:attribute name = "Instance" type="xs:unsignedByte" use="required" />
</xs:complexType>
</xs:element>
<xs:element minOccurs = "0" maxOccurs="unbounded" name="Struct2">
<xs:complexType>
<xs:sequence>
<xs:element name = "sSTRING" type="xs:string" />
<xs:element name = "bBOOL" type="xs:boolean" />
<xs:element name = "nINT32" type="xs:int" />
</xs:sequence>

TF6420 Version: 1.13.4 381


Examples

<xs:attribute name = "Instance" type="xs:unsignedByte" use="required" />


</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name = "Name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Structure1 ST_TestStruct
TYPE ST_TestStruct :
STRUCT
nINT64 : T_LARGE_INTEGER;
nUINT16: UINT;
rREAL64: LREAL;
sSTRING: T_MaxString;
bBOOL : BOOL;
nINT32 : DINT;
END_STRUCT
END_TYPE

Structure2 ST_TestStruct2
TYPE ST_TestStruct2 :
STRUCT
sSTRING: T_MaxString;
bBOOL : BOOL;
nINT32 : DINT;
END_STRUCT
END_TYPE

MAIN program
PROGRAM MAIN
VAR
nState : BYTE;

R_TRIG1 : R_TRIG;
bStartStop : BOOL;

sCmd : T_MaxString;

FB_DBRecordArraySelect1: FB_DBRecordArraySelect;
arrTestStruct : ARRAY [0..3] OF ST_TestStruct;
arrTestStruct2 : ARRAY [0..3] OF ST_TestStruct2;

bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
stSQLState : ST_DBSQLError;

nRecs1 : UDINT;
nRecs2 : UDINT;
END_VAR
R_TRIG1(CLK:=bStartStop);
IF R_TRIG1.Q THEN
FB_DBRecordArraySelect1(bExecute:=FALSE);
nState := 1;
END_IF
CASE nState OF
0:(*Idle*)
;
1:
sCmd:='XPATH<SUBTAG>#/Beckhoff_PLC/PLC_Structs/PLC_Struct[@Name=$'ST_TestStruct$']/Struct';

FB_DBRecordArraySelect1(
sNetID := ,
hDBID := 1,
cbCmdSize := SIZEOF(sCmd),
pCmdAddr := ADR(sCmd),
nStartIndex := 0,

382 Version: 1.13.4 TF6420


Examples

nRecordCount := 4,
cbRecordArraySize := SIZEOF(arrTestStruct),
pDestAddr := ADR(arrTestStruct),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bError,
nErrID => nErrID,
sSQLState => stSQLState,
nRecords => nRecs1);

IF NOT bBusy THEN


FB_DBRecordArraySelect1(bExecute:=FALSE);
IF NOT bError THEN
nState := 2;
ELSE
nState := 255;
END_IFEND_IF
2:
sCmd:='XPATH<SUBTAG>#Beckhoff_PLC/PLC_Structs/PLC_Struct[@Name=$'ST_TestStruct2$']/Struct2';

FB_DBRecordArraySelect1(
sNetID := ,
hDBID := 1,
cbCmdSize := SIZEOF(sCmd),
pCmdAddr := ADR(sCmd),
nStartIndex := 0,
nRecordCount := 4,
cbRecordArraySize := SIZEOF(arrTestStruct2),
pDestAddr := ADR(arrTestStruct2),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bError,
nErrID => nErrID,
sSQLState => stSQLState,
nRecords => nRecs2);

IF NOT bBusy THEN


FB_DBRecordArraySelect1(bExecute:=FALSE);
IF NOT bError THEN
nState := 0;
ELSE
nState := 255;
END_IFEND_IF
255: (* Error Step*)
;
END_CASE

Reading is started with a positive edge at the toggle variable "bStartStop".

TF6420 Version: 1.13.4 383


Examples

Requirements

Development environment Target platform PLC libraries to be linked


TwinCAT v3.0.0 PC or CX (x86) Tc2_Database

384 Version: 1.13.4 TF6420


Appendix

8 Appendix

8.1 Error codes

8.1.1 Tc3_Database

8.1.1.1 PLC return values


The error output of all PLC blocks of the Tc3_Database.compiled library takes place via the I_TcResultEvent
interfaces from the Tc3_Eventlogger.compiled library. This new interface structure enables a more detailed
description of events, as well as classification.
Interface I_TcMessage [} 224]
nEventId: UDINT;
EventClass: GUID;
eSeverity: TcEventSeverity [} 225];
ipSourceInfo: I_TcSourceInfo;

nEventID: specific event code

EventClass: GUID

EventClassName: The corresponding event class name can be read using the RequestEventClassName
method

eSeverity: events classification: from "info" to "critical error"

ipSourceInfo: path to the event location.

Text: description of the event in plain text can be read with the RequestEventText method

The following event classes can occur:


• TC3 ADS Error
ADS errors that may occur during the communication with the TwinCAT Database Server.
• TC3 Database Server Internal Error
Internal errors that may occur if the TwinCAT Database Server is configured incorrectly.
• TC3 Database Server Database Error
Database errors that may occur during communication with the corresponding databases. The different
database-specific error codes are mapped in a database error list. The database-specific codes are
written into the ErrorLog, as required.
• TC3 Database Server ADS Device Error
ADS error that may occur during internal communication with configured ADS devices.
• TC3 Database Server NoSQL Error
Database error of a NoSQL database that occurred during communication with the corresponding
databases.

TF6420 Version: 1.13.4 385


Appendix

8.1.1.2 ADS return codes

Global error codes


Hex Dec HRESULT Name Description
0x0 0 0x98110000 ERR_NOERROR No error.
0x1 1 0x98110001 ERR_INTERNAL Internal error.
0x2 2 0x98110002 ERR_NORTIME No real time.
0x3 3 0x98110003 ERR_ALLOCLOCKEDMEM Allocation locked – memory error.
0x4 4 0x98110004 ERR_INSERTMAILBOX Mailbox full – the ADS message could not be sent.
Reducing the number of ADS messages per cycle will
help.
0x5 5 0x98110005 ERR_WRONGRECEIVEHMSG Wrong HMSG.
0x6 6 0x98110006 ERR_TARGETPORTNOTFOUND Target port not found – ADS server is not started or is
not reachable.
0x7 7 0x98110007 ERR_TARGETMACHINENOTFOUND Target computer not found – AMS route was not found.
0x8 8 0x98110008 ERR_UNKNOWNCMDID Unknown command ID.
0x9 9 0x98110009 ERR_BADTASKID Invalid task ID.
0xA 10 0x9811000A ERR_NOIO No IO.
0xB 11 0x9811000B ERR_UNKNOWNAMSCMD Unknown AMS command.
0xC 12 0x9811000C ERR_WIN32ERROR Win32 error.
0xD 13 0x9811000D ERR_PORTNOTCONNECTED Port not connected.
0xE 14 0x9811000E ERR_INVALIDAMSLENGTH Invalid AMS length.
0xF 15 0x9811000F ERR_INVALIDAMSNETID Invalid AMS Net ID.
0x10 16 0x98110010 ERR_LOWINSTLEVEL Installation level is too low –TwinCAT 2 license error.
0x11 17 0x98110011 ERR_NODEBUGINTAVAILABLE No debugging available.
0x12 18 0x98110012 ERR_PORTDISABLED Port disabled – TwinCAT system service not started.
0x13 19 0x98110013 ERR_PORTALREADYCONNECTED Port already connected.
0x14 20 0x98110014 ERR_AMSSYNC_W32ERROR AMS Sync Win32 error.
0x15 21 0x98110015 ERR_AMSSYNC_TIMEOUT AMS Sync Timeout.
0x16 22 0x98110016 ERR_AMSSYNC_AMSERROR AMS Sync error.
0x17 23 0x98110017 ERR_AMSSYNC_NOINDEXINMAP No index map for AMS Sync available.
0x18 24 0x98110018 ERR_INVALIDAMSPORT Invalid AMS port.
0x19 25 0x98110019 ERR_NOMEMORY No memory.
0x1A 26 0x9811001A ERR_TCPSEND TCP send error.
0x1B 27 0x9811001B ERR_HOSTUNREACHABLE Host unreachable.
0x1C 28 0x9811001C ERR_INVALIDAMSFRAGMENT Invalid AMS fragment.
0x1D 29 0x9811001D ERR_TLSSEND TLS send error – secure ADS connection failed.
0x1E 30 0x9811001E ERR_ACCESSDENIED Access denied – secure ADS access denied.

RTime error codes

386 Version: 1.13.4 TF6420


Appendix

Hex Dec HRESULT Name Description


0x1000 4096 0x98111000 RTERR_INTERNAL Internal error in the real-time system.
0x1001 4097 0x98111001 RTERR_BADTIMERPERIODS Timer value is not valid.
0x1002 4098 0x98111002 RTERR_INVALIDTASKPTR Task pointer has the invalid value 0 (zero).
0x1003 4099 0x98111003 RTERR_INVALIDSTACKPTR Stack pointer has the invalid value 0 (zero).
0x1004 4100 0x98111004 RTERR_PRIOEXISTS The request task priority is already assigned.
0x1005 4101 0x98111005 RTERR_NOMORETCB No free TCB (Task Control Block) available. The
maximum number of TCBs is 64.
0x1006 4102 0x98111006 RTERR_NOMORESEMAS No free semaphores available. The maximum number of
semaphores is 64.
0x1007 4103 0x98111007 RTERR_NOMOREQUEUES No free space available in the queue. The maximum
number of positions in the queue is 64.

0x100D 4109 0x9811100D RTERR_EXTIRQALREADYDEF An external synchronization interrupt is already applied.


0x100E 4110 0x9811100E RTERR_EXTIRQNOTDEF No external sync interrupt applied.
0x100F 4111 0x9811100F RTERR_EXTIRQINSTALLFAILED Application of the external synchronization interrupt has
failed.
0x1010 4112 0x98111010 RTERR_IRQLNOTLESSOREQUAL Call of a service function in the wrong context
0x1017 4119 0x98111017 RTERR_VMXNOTSUPPORTED Intel VT-x extension is not supported.
0x1018 4120 0x98111018 RTERR_VMXDISABLED Intel VT-x extension is not enabled in the BIOS.
0x1019 4121 0x98111019 RTERR_VMXCONTROLSMISSING Missing function in Intel VT-x extension.
0x101A 4122 0x9811101A RTERR_VMXENABLEFAILS Activation of Intel VT-x fails.

Router error codes


Hex Dec HRESULT Name Description
0x500 1280 0x98110500 ROUTERERR_NOLOCKEDMEMORY Locked memory cannot be allocated.

0x501 1281 0x98110501 ROUTERERR_RESIZEMEMORY The router memory size could not be changed.

0x502 1282 0x98110502 ROUTERERR_MAILBOXFULL The mailbox has reached the maximum number of
possible messages.

0x503 1283 0x98110503 ROUTERERR_DEBUGBOXFULL The Debug mailbox has reached the maximum
number of possible messages.

0x504 1284 0x98110504 ROUTERERR_UNKNOWNPORTTYPE The port type is unknown.


0x505 1285 0x98110505 ROUTERERR_NOTINITIALIZED The router is not initialized.
0x506 1286 0x98110506 ROUTERERR_PORTALREADYINUSE The port number is already assigned.
0x507 1287 0x98110507 ROUTERERR_NOTREGISTERED The port is not registered.
0x508 1288 0x98110508 ROUTERERR_NOMOREQUEUES The maximum number of ports has been reached.
0x509 1289 0x98110509 ROUTERERR_INVALIDPORT The port is invalid.
0x50A 1290 0x9811050A ROUTERERR_NOTACTIVATED The router is not active.
0x50B 1291 0x9811050B ROUTERERR_FRAGMENTBOXFULL The mailbox has reached the maximum number for
fragmented messages.
0x50C 1292 0x9811050C ROUTERERR_FRAGMENTTIMEOUT A fragment timeout has occurred.
0x50D 1293 0x9811050D ROUTERERR_TOBEREMOVED The port is removed.

General ADS error codes

TF6420 Version: 1.13.4 387


Appendix

Hex Dec HRESULT Name Description


0x700 1792 0x98110700 ADSERR_DEVICE_ERROR General device error.
0x701 1793 0x98110701 ADSERR_DEVICE_SRVNOTSUPP Service is not supported by the server.
0x702 1794 0x98110702 ADSERR_DEVICE_INVALIDGRP Invalid index group.
0x703 1795 0x98110703 ADSERR_DEVICE_INVALIDOFFSET Invalid index offset.
0x704 1796 0x98110704 ADSERR_DEVICE_INVALIDACCESS Reading or writing not permitted.
0x705 1797 0x98110705 ADSERR_DEVICE_INVALIDSIZE Parameter size not correct.
0x706 1798 0x98110706 ADSERR_DEVICE_INVALIDDATA Invalid data values.
0x707 1799 0x98110707 ADSERR_DEVICE_NOTREADY Device is not ready to operate.
0x708 1800 0x98110708 ADSERR_DEVICE_BUSY Device is busy.
0x709 1801 0x98110709 ADSERR_DEVICE_INVALIDCONTEXT Invalid operating system context. This can result
from use of ADS blocks in different tasks. It may be
possible to resolve this through multitasking
synchronization in the PLC.
0x70A 1802 0x9811070A ADSERR_DEVICE_NOMEMORY Insufficient memory.
0x70B 1803 0x9811070B ADSERR_DEVICE_INVALIDPARM Invalid parameter values.
0x70C 1804 0x9811070C ADSERR_DEVICE_NOTFOUND Not found (files, ...).
0x70D 1805 0x9811070D ADSERR_DEVICE_SYNTAX Syntax error in file or command.
0x70E 1806 0x9811070E ADSERR_DEVICE_INCOMPATIBLE Objects do not match.
0x70F 1807 0x9811070F ADSERR_DEVICE_EXISTS Object already exists.
0x710 1808 0x98110710 ADSERR_DEVICE_SYMBOLNOTFOUND Symbol not found.
0x711 1809 0x98110711 ADSERR_DEVICE_SYMBOLVERSIONINVALID Invalid symbol version. This can occur due to an
online change. Create a new handle.
0x712 1810 0x98110712 ADSERR_DEVICE_INVALIDSTATE Device (server) is in invalid state.
0x713 1811 0x98110713 ADSERR_DEVICE_TRANSMODENOTSUPP AdsTransMode not supported.
0x714 1812 0x98110714 ADSERR_DEVICE_NOTIFYHNDINVALID Notification handle is invalid.
0x715 1813 0x98110715 ADSERR_DEVICE_CLIENTUNKNOWN Notification client not registered.
0x716 1814 0x98110716 ADSERR_DEVICE_NOMOREHDLS No further handle available.
0x717 1815 0x98110717 ADSERR_DEVICE_INVALIDWATCHSIZE Notification size too large.
0x718 1816 0x98110718 ADSERR_DEVICE_NOTINIT Device not initialized.
0x719 1817 0x98110719 ADSERR_DEVICE_TIMEOUT Device has a timeout.
0x71A 1818 0x9811071A ADSERR_DEVICE_NOINTERFACE Interface query failed.
0x71B 1819 0x9811071B ADSERR_DEVICE_INVALIDINTERFACE Wrong interface requested.
0x71C 1820 0x9811071C ADSERR_DEVICE_INVALIDCLSID Class ID is invalid.
0x71D 1821 0x9811071D ADSERR_DEVICE_INVALIDOBJID Object ID is invalid.
0x71E 1822 0x9811071E ADSERR_DEVICE_PENDING Request pending.
0x71F 1823 0x9811071F ADSERR_DEVICE_ABORTED Request is aborted.
0x720 1824 0x98110720 ADSERR_DEVICE_WARNING Signal warning.
0x721 1825 0x98110721 ADSERR_DEVICE_INVALIDARRAYIDX Invalid array index.
0x722 1826 0x98110722 ADSERR_DEVICE_SYMBOLNOTACTIVE Symbol not active.
0x723 1827 0x98110723 ADSERR_DEVICE_ACCESSDENIED Access denied.
0x724 1828 0x98110724 ADSERR_DEVICE_LICENSENOTFOUND Missing license.
0x725 1829 0x98110725 ADSERR_DEVICE_LICENSEEXPIRED License expired.
0x726 1830 0x98110726 ADSERR_DEVICE_LICENSEEXCEEDED License exceeded.
0x727 1831 0x98110727 ADSERR_DEVICE_LICENSEINVALID Invalid license.
0x728 1832 0x98110728 ADSERR_DEVICE_LICENSESYSTEMID License problem: System ID is invalid.
0x729 1833 0x98110729 ADSERR_DEVICE_LICENSENOTIMELIMIT License not limited in time.
0x72A 1834 0x9811072A ADSERR_DEVICE_LICENSEFUTUREISSUE Licensing problem: time in the future.
0x72B 1835 0x9811072B ADSERR_DEVICE_LICENSETIMETOLONG License period too long.
0x72C 1836 0x9811072C ADSERR_DEVICE_EXCEPTION Exception at system startup.
0x72D 1837 0x9811072D ADSERR_DEVICE_LICENSEDUPLICATED License file read twice.
0x72E 1838 0x9811072E ADSERR_DEVICE_SIGNATUREINVALID Invalid signature.
0x72F 1839 0x9811072F ADSERR_DEVICE_CERTIFICATEINVALID Invalid certificate.
0x730 1840 0x98110730 ADSERR_DEVICE_LICENSEOEMNOTFOUND Public key not known from OEM.
0x731 1841 0x98110731 ADSERR_DEVICE_LICENSERESTRICTED License not valid for this system ID.
0x732 1842 0x98110732 ADSERR_DEVICE_LICENSEDEMODENIED Demo license prohibited.
0x733 1843 0x98110733 ADSERR_DEVICE_INVALIDFNCID Invalid function ID.
0x734 1844 0x98110734 ADSERR_DEVICE_OUTOFRANGE Outside the valid range.
0x735 1845 0x98110735 ADSERR_DEVICE_INVALIDALIGNMENT Invalid alignment.
0x736 1846 0x98110736 ADSERR_DEVICE_LICENSEPLATFORM Invalid platform level.

388 Version: 1.13.4 TF6420


Appendix

Hex Dec HRESULT Name Description


0x737 1847 0x98110737 ADSERR_DEVICE_FORWARD_PL Context – forward to passive level.
0x738 1848 0x98110738 ADSERR_DEVICE_FORWARD_DL Context – forward to dispatch level.
0x739 1849 0x98110739 ADSERR_DEVICE_FORWARD_RT Context – forward to real time.
0x740 1856 0x98110740 ADSERR_CLIENT_ERROR Client error.
0x741 1857 0x98110741 ADSERR_CLIENT_INVALIDPARM Service contains an invalid parameter.
0x742 1858 0x98110742 ADSERR_CLIENT_LISTEMPTY Polling list is empty.
0x743 1859 0x98110743 ADSERR_CLIENT_VARUSED Var connection already in use.
0x744 1860 0x98110744 ADSERR_CLIENT_DUPLINVOKEID The called ID is already in use.
0x745 1861 0x98110745 ADSERR_CLIENT_SYNCTIMEOUT Timeout has occurred – the remote terminal is not
responding in the specified ADS timeout. The route
setting of the remote terminal may be configured
incorrectly.
0x746 1862 0x98110746 ADSERR_CLIENT_W32ERROR Error in Win32 subsystem.
0x747 1863 0x98110747 ADSERR_CLIENT_TIMEOUTINVALID Invalid client timeout value.
0x748 1864 0x98110748 ADSERR_CLIENT_PORTNOTOPEN Port not open.
0x749 1865 0x98110749 ADSERR_CLIENT_NOAMSADDR No AMS address.
0x750 1872 0x98110750 ADSERR_CLIENT_SYNCINTERNAL Internal error in Ads sync.
0x751 1873 0x98110751 ADSERR_CLIENT_ADDHASH Hash table overflow.
0x752 1874 0x98110752 ADSERR_CLIENT_REMOVEHASH Key not found in the table.
0x753 1875 0x98110753 ADSERR_CLIENT_NOMORESYM No symbols in the cache.
0x754 1876 0x98110754 ADSERR_CLIENT_SYNCRESINVALID Invalid response received.
0x755 1877 0x98110755 ADSERR_CLIENT_SYNCPORTLOCKED Sync Port is locked.
0x756 1878 0x98110756 ADSERR_CLIENT_REQUESTCANCELLED The request was cancelled.

8.1.1.3 Database return codes

TF6420 Version: 1.13.4 389


Appendix

ErrorCode ErrorName ErrorDescription


1 DB_SQLState_01000 General warning
2 DB_SQLState_01001 Cursor operation conflict
3 DB_SQLState_01002 Disconnect error
4 DB_SQLState_01003 NULL value eliminated in set function
5 DB_SQLState_01004 String data, right-truncated
6 DB_SQLState_01006 Privilege not revoked
7 DB_SQLState_01007 Privilege not granted
8 DB_SQLState_01S00 Invalid connection string attribute
9 DB_SQLState_01S01 Error in row
10 DB_SQLState_01S02 Option value changed
11 DB_SQLState_01S06 Attempt to fetch before the result set returned the first row set
12 DB_SQLState_01S07 Fractional truncation
13 DB_SQLState_01S08 Error saving File DSN
14 DB_SQLState_01S09 Invalid keyword

15 DB_SQLState_07000 Dynamic SQL error


16 DB_SQLState_07001 Wrong number of parameters
17 DB_SQLState_07002 COUNT field incorrect
18 DB_SQLState_07005 Prepared statement not a cursor-specification
19 DB_SQLState_07006 Restricted data type attribute violation
20 DB_SQLState_07009 Invalid descriptor index
21 DB_SQLState_07S01 Invalid use of default parameter

22 DB_SQLState_08000 Connection exception


23 DB_SQLState_08001 Client unable to establish connection
24 DB_SQLState_08002 Connection name in use
25 DB_SQLState_08003 Connection not open
26 DB_SQLState_08004 Server rejected the connection
27 DB_SQLState_08007 Connection failure during transaction
28 DB_SQLState_08S01 Communication link failure

29 DB_SQLState_21000 Cardinality violation


30 DB_SQLState_21S01 Insert value list does not match column list
31 DB_SQLState_21S02 Degree of derived table does not match column list

32 DB_SQLState_22000 Data exception


33 DB_SQLState_22001 String data, right-truncated
34 DB_SQLState_22002 Indicator variable required but not supplied
35 DB_SQLState_22003 Numeric value out of range
36 DB_SQLState_22007 Invalid datetime format
37 DB_SQLState_22008 Date/time field overflow
38 DB_SQLState_22012 Division by zero
39 DB_SQLState_22015 Interval field overflow
40 DB_SQLState_22018 Invalid character value for cast specification
41 DB_SQLState_22019 Invalid escape character
42 DB_SQLState_22025 Invalid escape sequence
43 DB_SQLState_22026 String data, length mismatch

390 Version: 1.13.4 TF6420


Appendix

44 DB_SQLState_23000 Integrity constraint violation

45 DB_SQLState_24000 Invalid cursor state

46 DB_SQLState_25000 Invalid transaction state


47 DB_SQLState_25S01 Transaction state
48 DB_SQLState_25S02 Transaction is still active
49 DB_SQLState_25S03 Transaction is rolled back

50 DB_SQLState_28000 Invalid authorization specification

51 DB_SQLState_34000 Invalid cursor name

52 DB_SQLState_3C000 Duplicate cursor name

53 DB_SQLState_3D000 Invalid catalog name

54 DB_SQLState_3F000 Invalid schema name

55 DB_SQLState_40000 Transaction rollback


56 DB_SQLState_40001 Serialization failure
57 DB_SQLState_40002 Integrity constraint violation
58 DB_SQLState_40003 Statement completion unknown

59 DB_SQLState_42000 Syntax error or access violation


60 DB_SQLState_42S01 Base table or view already exists
61 DB_SQLState_42S02 Base table or view not found
62 DB_SQLState_42S11 Index already exists
63 DB_SQLState_42S12 Index not found
64 DB_SQLState_42S21 Column already exists
65 DB_SQLState_42S22 Column not found

66 DB_SQLState_44000 WITH CHECK OPTION violation

67 DB_SQLState_HY000 General error


68 DB_SQLState_HY001 Memory allocation error
69 DB_SQLState_HY003 Invalid application buffer type
70 DB_SQLState_HY004 Invalid SQL data type
71 DB_SQLState_HY007 Associated statement is not prepared
72 DB_SQLState_HY008 Operation cancelled
73 DB_SQLState_HY009 Invalid use of null pointer
74 DB_SQLState_HY010 Function sequence error
75 DB_SQLState_HY011 Attribute cannot be set now
76 DB_SQLState_HY012 Invalid transaction operation code
77 DB_SQLState_HY013 Memory management error
78 DB_SQLState_HY014 Limit on the number of handles exceeded
79 DB_SQLState_HY015 No cursor name available
80 DB_SQLState_HY016 Cannot modify an implementation row descriptor
81 DB_SQLState_HY017 Invalid use of an automatically allocated descriptor handle

TF6420 Version: 1.13.4 391


Appendix

82 DB_SQLState_HY018 Server declined cancel request


83 DB_SQLState_HY019 Non-character and non-binary data sent in pieces
84 DB_SQLState_HY020 Attempt to concatenate a null value
85 DB_SQLState_HY021 Inconsistent descriptor information
86 DB_SQLState_HY024 Invalid attribute value
87 DB_SQLState_HY090 Invalid string or buffer length
88 DB_SQLState_HY091 Invalid descriptor field identifier
89 DB_SQLState_HY092 Invalid attribute/option identifier
90 DB_SQLState_HY095 Function type out of range
91 DB_SQLState_HY096 Invalid information type
92 DB_SQLState_HY097 Column type out of range
93 DB_SQLState_HY098 Scope type out of range
94 DB_SQLState_HY099 Nullable type out of range
95 DB_SQLState_HY100 Uniqueness option type out of range
96 DB_SQLState_HY101 Accuracy option type out of range
97 DB_SQLState_HY103 Invalid retrieval code
98 DB_SQLState_HY104 Invalid precision or scale value
99 DB_SQLState_HY105 Invalid parameter type
100 DB_SQLState_HY106 Fetch type out of range
101 DB_SQLState_HY107 Row value out of range
102 DB_SQLState_HY109 Invalid cursor position
103 DB_SQLState_HY110 Invalid driver completion
104 DB_SQLState_HY111 Invalid bookmark value
105 DB_SQLState_HYC00 Optional feature not implemented
106 DB_SQLState_HYT00 Timeout expired
107 DB_SQLState_HYT01 Connection timeout expired

108 DB_SQLState_IM001 Driver does not support this function


109 DB_SQLState_IM002 Data source name not found and no default driver specified
110 DB_SQLState_IM003 Specified driver could not be loaded
111 DB_SQLState_IM004 Driver's SQLAllocHandle on SQL_HANDLE_ENV failed
112 DB_SQLState_IM005 Driver's SQLAllocHandle on SQL_HANDLE_DBC failed
113 DB_SQLState_IM006 Driver's SQLSetConnectAttr failed
114 DB_SQLState_IM007 No data source or driver specified dialog prohibited
115 DB_SQLState_IM008 Dialog failed
116 DB_SQLState_IM009 Unable to load translation DLL
117 DB_SQLState_IM010 Data source name too long
118 DB_SQLState_IM011 Driver name too long
119 DB_SQLState_IM012 DRIVER keyword syntax error
120 DB_SQLState_IM013 Trace file error
121 DB_SQLState_IM014 Invalid name of File DSN
122 DB_SQLState_IM015 Corrupt file data source

200 DB_FunctionNotImpleme Function not implemented


nted
255 DB_SQLState_Unspecifie Unspecified Error
d

392 Version: 1.13.4 TF6420


Appendix

8.1.1.4 NoSQL database return codes


ErrorCode ErrorName ErrorDescription
0 NoSql_0 No Error
1 NoSql_Specific_1 Internal MongoDB exception. Please check the information
log for more details.
2 NoSql_Specific_2 Database side error. Please check the information log for
more details.
8 NoSql_Specific_8 Timeout error occurred on command execution
9 NoSql_Specific_9 Format error occurred on command execution. Please check
the command or document syntax.
11 NoSql_Specific_11 RunCommand execution failed. Please check the event log
for more information
12 NoSql_Specific_12 There is no metadata including the tableschema for this table
13 NoSql_Specific_13 Syntax error in command / filter
14 NoSql_Specific_14 Connection error occured
15 NoSql_Specific_15 Authentication failed
16 NoSql_Specific_16 Error occured during write operation
20 NoSql_Specific_20 Functionality is not supported by the TwinCAT Database
Server
48 NoSql_Specific_48 Namespace / CollectionName already exists
51 NoSql_Specific_51 The queried data is empty
141 NoSql_Specific_141 Internal TwinCAT 3 Database Server Error

8.1.1.5 TwinCAT database server codes

TF6420 Version: 1.13.4 393


Appendix

ErrorCode ErrorName ErrorDescription


0 InternalErrorCode_0 No Error
1 InternalErrorCode_1 NULL Values not allowed
2 InternalErrorCode_2 FB_DBRead selected value is NULL
3 InternalErrorCode_3 DBID is unknown
4 InternalErrorCode_4 ADSDevID is unknown
5 InternalErrorCode_5 No open database connection found for DBID: xy
6 InternalErrorCode_6 No open ADS Device connection found for ADSDevID: xy
7 InternalErrorCode_7 Init of AutoLog Groups failed
8 InternalErrorCode_8 AutoLog could NOT be started. TwinCAT Database Server
has no valid device state
9 InternalErrorCode_9 Record select value return => Wrong Parametersize from
ADS-Device
10 InternalErrorCode_10 Invalid Parameter
11 InternalErrorCode_11 Couldn’t find PLCDBWrite Value in list
12 InternalErrorCode_12 No valid symbol TYPE
13 InternalErrorCode_13 Invalid parameter size
14 InternalErrorCode_14 Execution timeout
15 InternalErrorCode_15 Database connection already open
16 InternalErrorCode_16 Database connection not initialized
1000 InternalErrorCode_1000 Unknown internal Error

8.1.2 Tc2_Database

8.1.2.1 ADS Return Codes


Grouping of error codes:
Global error codes: ADS Return Codes [} 394]... (0x9811_0000 ...)
Router error codes: ADS Return Codes [} 395]... (0x9811_0500 ...)
General ADS errors: ADS Return Codes [} 395]... (0x9811_0700 ...)
RTime error codes: ADS Return Codes [} 397]... (0x9811_1000 ...)

Global error codes

394 Version: 1.13.4 TF6420


Appendix

Hex Dec HRESULT Name Description


0x0 0 0x98110000 ERR_NOERROR No error.
0x1 1 0x98110001 ERR_INTERNAL Internal error.
0x2 2 0x98110002 ERR_NORTIME No real time.
0x3 3 0x98110003 ERR_ALLOCLOCKEDMEM Allocation locked – memory error.
0x4 4 0x98110004 ERR_INSERTMAILBOX Mailbox full – the ADS message could not be sent.
Reducing the number of ADS messages per cycle will
help.
0x5 5 0x98110005 ERR_WRONGRECEIVEHMSG Wrong HMSG.
0x6 6 0x98110006 ERR_TARGETPORTNOTFOUND Target port not found – ADS server is not started or is
not reachable.
0x7 7 0x98110007 ERR_TARGETMACHINENOTFOUND Target computer not found – AMS route was not found.
0x8 8 0x98110008 ERR_UNKNOWNCMDID Unknown command ID.
0x9 9 0x98110009 ERR_BADTASKID Invalid task ID.
0xA 10 0x9811000A ERR_NOIO No IO.
0xB 11 0x9811000B ERR_UNKNOWNAMSCMD Unknown AMS command.
0xC 12 0x9811000C ERR_WIN32ERROR Win32 error.
0xD 13 0x9811000D ERR_PORTNOTCONNECTED Port not connected.
0xE 14 0x9811000E ERR_INVALIDAMSLENGTH Invalid AMS length.
0xF 15 0x9811000F ERR_INVALIDAMSNETID Invalid AMS Net ID.
0x10 16 0x98110010 ERR_LOWINSTLEVEL Installation level is too low –TwinCAT 2 license error.
0x11 17 0x98110011 ERR_NODEBUGINTAVAILABLE No debugging available.
0x12 18 0x98110012 ERR_PORTDISABLED Port disabled – TwinCAT system service not started.
0x13 19 0x98110013 ERR_PORTALREADYCONNECTED Port already connected.
0x14 20 0x98110014 ERR_AMSSYNC_W32ERROR AMS Sync Win32 error.
0x15 21 0x98110015 ERR_AMSSYNC_TIMEOUT AMS Sync Timeout.
0x16 22 0x98110016 ERR_AMSSYNC_AMSERROR AMS Sync error.
0x17 23 0x98110017 ERR_AMSSYNC_NOINDEXINMAP No index map for AMS Sync available.
0x18 24 0x98110018 ERR_INVALIDAMSPORT Invalid AMS port.
0x19 25 0x98110019 ERR_NOMEMORY No memory.
0x1A 26 0x9811001A ERR_TCPSEND TCP send error.
0x1B 27 0x9811001B ERR_HOSTUNREACHABLE Host unreachable.
0x1C 28 0x9811001C ERR_INVALIDAMSFRAGMENT Invalid AMS fragment.
0x1D 29 0x9811001D ERR_TLSSEND TLS send error – secure ADS connection failed.
0x1E 30 0x9811001E ERR_ACCESSDENIED Access denied – secure ADS access denied.

Router error codes


Hex Dec HRESULT Name Description
0x500 1280 0x98110500 ROUTERERR_NOLOCKEDMEMORY Locked memory cannot be allocated.

0x501 1281 0x98110501 ROUTERERR_RESIZEMEMORY The router memory size could not be changed.

0x502 1282 0x98110502 ROUTERERR_MAILBOXFULL The mailbox has reached the maximum number of
possible messages.

0x503 1283 0x98110503 ROUTERERR_DEBUGBOXFULL The Debug mailbox has reached the maximum
number of possible messages.

0x504 1284 0x98110504 ROUTERERR_UNKNOWNPORTTYPE The port type is unknown.


0x505 1285 0x98110505 ROUTERERR_NOTINITIALIZED The router is not initialized.
0x506 1286 0x98110506 ROUTERERR_PORTALREADYINUSE The port number is already assigned.
0x507 1287 0x98110507 ROUTERERR_NOTREGISTERED The port is not registered.
0x508 1288 0x98110508 ROUTERERR_NOMOREQUEUES The maximum number of ports has been reached.
0x509 1289 0x98110509 ROUTERERR_INVALIDPORT The port is invalid.
0x50A 1290 0x9811050A ROUTERERR_NOTACTIVATED The router is not active.
0x50B 1291 0x9811050B ROUTERERR_FRAGMENTBOXFULL The mailbox has reached the maximum number for
fragmented messages.
0x50C 1292 0x9811050C ROUTERERR_FRAGMENTTIMEOUT A fragment timeout has occurred.
0x50D 1293 0x9811050D ROUTERERR_TOBEREMOVED The port is removed.

General ADS error codes

TF6420 Version: 1.13.4 395


Appendix

Hex Dec HRESULT Name Description


0x700 1792 0x98110700 ADSERR_DEVICE_ERROR General device error.
0x701 1793 0x98110701 ADSERR_DEVICE_SRVNOTSUPP Service is not supported by the server.
0x702 1794 0x98110702 ADSERR_DEVICE_INVALIDGRP Invalid index group.
0x703 1795 0x98110703 ADSERR_DEVICE_INVALIDOFFSET Invalid index offset.
0x704 1796 0x98110704 ADSERR_DEVICE_INVALIDACCESS Reading or writing not permitted.
0x705 1797 0x98110705 ADSERR_DEVICE_INVALIDSIZE Parameter size not correct.
0x706 1798 0x98110706 ADSERR_DEVICE_INVALIDDATA Invalid data values.
0x707 1799 0x98110707 ADSERR_DEVICE_NOTREADY Device is not ready to operate.
0x708 1800 0x98110708 ADSERR_DEVICE_BUSY Device is busy.
0x709 1801 0x98110709 ADSERR_DEVICE_INVALIDCONTEXT Invalid operating system context. This can result
from use of ADS blocks in different tasks. It may be
possible to resolve this through multitasking
synchronization in the PLC.
0x70A 1802 0x9811070A ADSERR_DEVICE_NOMEMORY Insufficient memory.
0x70B 1803 0x9811070B ADSERR_DEVICE_INVALIDPARM Invalid parameter values.
0x70C 1804 0x9811070C ADSERR_DEVICE_NOTFOUND Not found (files, ...).
0x70D 1805 0x9811070D ADSERR_DEVICE_SYNTAX Syntax error in file or command.
0x70E 1806 0x9811070E ADSERR_DEVICE_INCOMPATIBLE Objects do not match.
0x70F 1807 0x9811070F ADSERR_DEVICE_EXISTS Object already exists.
0x710 1808 0x98110710 ADSERR_DEVICE_SYMBOLNOTFOUND Symbol not found.
0x711 1809 0x98110711 ADSERR_DEVICE_SYMBOLVERSIONINVALID Invalid symbol version. This can occur due to an
online change. Create a new handle.
0x712 1810 0x98110712 ADSERR_DEVICE_INVALIDSTATE Device (server) is in invalid state.
0x713 1811 0x98110713 ADSERR_DEVICE_TRANSMODENOTSUPP AdsTransMode not supported.
0x714 1812 0x98110714 ADSERR_DEVICE_NOTIFYHNDINVALID Notification handle is invalid.
0x715 1813 0x98110715 ADSERR_DEVICE_CLIENTUNKNOWN Notification client not registered.
0x716 1814 0x98110716 ADSERR_DEVICE_NOMOREHDLS No further handle available.
0x717 1815 0x98110717 ADSERR_DEVICE_INVALIDWATCHSIZE Notification size too large.
0x718 1816 0x98110718 ADSERR_DEVICE_NOTINIT Device not initialized.
0x719 1817 0x98110719 ADSERR_DEVICE_TIMEOUT Device has a timeout.
0x71A 1818 0x9811071A ADSERR_DEVICE_NOINTERFACE Interface query failed.
0x71B 1819 0x9811071B ADSERR_DEVICE_INVALIDINTERFACE Wrong interface requested.
0x71C 1820 0x9811071C ADSERR_DEVICE_INVALIDCLSID Class ID is invalid.
0x71D 1821 0x9811071D ADSERR_DEVICE_INVALIDOBJID Object ID is invalid.
0x71E 1822 0x9811071E ADSERR_DEVICE_PENDING Request pending.
0x71F 1823 0x9811071F ADSERR_DEVICE_ABORTED Request is aborted.
0x720 1824 0x98110720 ADSERR_DEVICE_WARNING Signal warning.
0x721 1825 0x98110721 ADSERR_DEVICE_INVALIDARRAYIDX Invalid array index.
0x722 1826 0x98110722 ADSERR_DEVICE_SYMBOLNOTACTIVE Symbol not active.
0x723 1827 0x98110723 ADSERR_DEVICE_ACCESSDENIED Access denied.
0x724 1828 0x98110724 ADSERR_DEVICE_LICENSENOTFOUND Missing license.
0x725 1829 0x98110725 ADSERR_DEVICE_LICENSEEXPIRED License expired.
0x726 1830 0x98110726 ADSERR_DEVICE_LICENSEEXCEEDED License exceeded.
0x727 1831 0x98110727 ADSERR_DEVICE_LICENSEINVALID Invalid license.
0x728 1832 0x98110728 ADSERR_DEVICE_LICENSESYSTEMID License problem: System ID is invalid.
0x729 1833 0x98110729 ADSERR_DEVICE_LICENSENOTIMELIMIT License not limited in time.
0x72A 1834 0x9811072A ADSERR_DEVICE_LICENSEFUTUREISSUE Licensing problem: time in the future.
0x72B 1835 0x9811072B ADSERR_DEVICE_LICENSETIMETOLONG License period too long.
0x72C 1836 0x9811072C ADSERR_DEVICE_EXCEPTION Exception at system startup.
0x72D 1837 0x9811072D ADSERR_DEVICE_LICENSEDUPLICATED License file read twice.
0x72E 1838 0x9811072E ADSERR_DEVICE_SIGNATUREINVALID Invalid signature.
0x72F 1839 0x9811072F ADSERR_DEVICE_CERTIFICATEINVALID Invalid certificate.
0x730 1840 0x98110730 ADSERR_DEVICE_LICENSEOEMNOTFOUND Public key not known from OEM.
0x731 1841 0x98110731 ADSERR_DEVICE_LICENSERESTRICTED License not valid for this system ID.
0x732 1842 0x98110732 ADSERR_DEVICE_LICENSEDEMODENIED Demo license prohibited.
0x733 1843 0x98110733 ADSERR_DEVICE_INVALIDFNCID Invalid function ID.
0x734 1844 0x98110734 ADSERR_DEVICE_OUTOFRANGE Outside the valid range.
0x735 1845 0x98110735 ADSERR_DEVICE_INVALIDALIGNMENT Invalid alignment.
0x736 1846 0x98110736 ADSERR_DEVICE_LICENSEPLATFORM Invalid platform level.

396 Version: 1.13.4 TF6420


Appendix

Hex Dec HRESULT Name Description


0x737 1847 0x98110737 ADSERR_DEVICE_FORWARD_PL Context – forward to passive level.
0x738 1848 0x98110738 ADSERR_DEVICE_FORWARD_DL Context – forward to dispatch level.
0x739 1849 0x98110739 ADSERR_DEVICE_FORWARD_RT Context – forward to real time.
0x740 1856 0x98110740 ADSERR_CLIENT_ERROR Client error.
0x741 1857 0x98110741 ADSERR_CLIENT_INVALIDPARM Service contains an invalid parameter.
0x742 1858 0x98110742 ADSERR_CLIENT_LISTEMPTY Polling list is empty.
0x743 1859 0x98110743 ADSERR_CLIENT_VARUSED Var connection already in use.
0x744 1860 0x98110744 ADSERR_CLIENT_DUPLINVOKEID The called ID is already in use.
0x745 1861 0x98110745 ADSERR_CLIENT_SYNCTIMEOUT Timeout has occurred – the remote terminal is not
responding in the specified ADS timeout. The route
setting of the remote terminal may be configured
incorrectly.
0x746 1862 0x98110746 ADSERR_CLIENT_W32ERROR Error in Win32 subsystem.
0x747 1863 0x98110747 ADSERR_CLIENT_TIMEOUTINVALID Invalid client timeout value.
0x748 1864 0x98110748 ADSERR_CLIENT_PORTNOTOPEN Port not open.
0x749 1865 0x98110749 ADSERR_CLIENT_NOAMSADDR No AMS address.
0x750 1872 0x98110750 ADSERR_CLIENT_SYNCINTERNAL Internal error in Ads sync.
0x751 1873 0x98110751 ADSERR_CLIENT_ADDHASH Hash table overflow.
0x752 1874 0x98110752 ADSERR_CLIENT_REMOVEHASH Key not found in the table.
0x753 1875 0x98110753 ADSERR_CLIENT_NOMORESYM No symbols in the cache.
0x754 1876 0x98110754 ADSERR_CLIENT_SYNCRESINVALID Invalid response received.
0x755 1877 0x98110755 ADSERR_CLIENT_SYNCPORTLOCKED Sync Port is locked.
0x756 1878 0x98110756 ADSERR_CLIENT_REQUESTCANCELLED The request was cancelled.

RTime error codes


Hex Dec HRESULT Name Description
0x1000 4096 0x98111000 RTERR_INTERNAL Internal error in the real-time system.
0x1001 4097 0x98111001 RTERR_BADTIMERPERIODS Timer value is not valid.
0x1002 4098 0x98111002 RTERR_INVALIDTASKPTR Task pointer has the invalid value 0 (zero).
0x1003 4099 0x98111003 RTERR_INVALIDSTACKPTR Stack pointer has the invalid value 0 (zero).
0x1004 4100 0x98111004 RTERR_PRIOEXISTS The request task priority is already assigned.
0x1005 4101 0x98111005 RTERR_NOMORETCB No free TCB (Task Control Block) available. The
maximum number of TCBs is 64.
0x1006 4102 0x98111006 RTERR_NOMORESEMAS No free semaphores available. The maximum number of
semaphores is 64.
0x1007 4103 0x98111007 RTERR_NOMOREQUEUES No free space available in the queue. The maximum
number of positions in the queue is 64.

0x100D 4109 0x9811100D RTERR_EXTIRQALREADYDEF An external synchronization interrupt is already applied.


0x100E 4110 0x9811100E RTERR_EXTIRQNOTDEF No external sync interrupt applied.
0x100F 4111 0x9811100F RTERR_EXTIRQINSTALLFAILED Application of the external synchronization interrupt has
failed.
0x1010 4112 0x98111010 RTERR_IRQLNOTLESSOREQUAL Call of a service function in the wrong context
0x1017 4119 0x98111017 RTERR_VMXNOTSUPPORTED Intel VT-x extension is not supported.
0x1018 4120 0x98111018 RTERR_VMXDISABLED Intel VT-x extension is not enabled in the BIOS.
0x1019 4121 0x98111019 RTERR_VMXCONTROLSMISSING Missing function in Intel VT-x extension.
0x101A 4122 0x9811101A RTERR_VMXENABLEFAILS Activation of Intel VT-x fails.

Specific positive HRESULT Return Codes:


HRESULT Name Description
0x0000_0000 S_OK No error.
0x0000_0001 S_FALSE No error.
Example: successful processing, but with a negative or
incomplete result.
0x0000_0203 S_PENDING No error.
Example: successful processing, but no result is available
yet.
0x0000_0256 S_WATCHDOG_TIMEOUT No error.
Example: successful processing, but a timeout occurred.

TCP Winsock error codes

TF6420 Version: 1.13.4 397


Appendix

Hex Dec Name Description


0x274C 10060 WSAETIMEDOUT A connection timeout has occurred - error while establishing the
connection, because the remote terminal did not respond properly after a
certain period of time, or the established connection could not be
maintained because the connected host did not respond.
0x274D 10061 WSAECONNREFUSED Connection refused - no connection could be established because the
target computer has explicitly rejected it. This error usually results from an
attempt to connect to a service that is inactive on the external host, that is,
a service for which no server application is running.
0x2751 10065 WSAEHOSTUNREACH No route to host - a socket operation referred to an unavailable host.
More Winsock error codes: Win32 error codes

8.1.2.2 TwinCAT Database Server error codes overview


Code (hex) Code (Dec) Description
0x0001 + ADS error code 65537 - 131071 ADS error code from declared ADS
device
0x00020001 131073 Microsoft SQL Compact database
(error code)
0x00040001 262145 Microsoft SQL database (error
code)
0x00080001 524289 Microsoft Access database (error
code)
0x00100001 1048577 MySQL database (error code)
0x00200001 2097153 Oracle database (error code)
0x00400001 4194305 DB2 database (error code)
0x00800001 8388609 PostgreSQL database (error code)
0x01000001 16777217 Interbase/Firebird database (error
code)
0x02000001 33554433 TwinCAT Database Server error
code [} 405]
0x04000001 67108865 XML database (error code)
0x08000001 134217729 ASCII database (error code)

If one of the error codes mentioned above is issued at the "nErrID" output of a function block, an error has
occurred during execution of an SQL statement. The SQL error code is then issued at the "sSQLState"
output of the function block. The "sSQLState" output has the data type ST_DBSQLError [} 321]. For each
database type individual error codes are output.

A list of SQLStates can be found under: http://msdn.microsoft.com/en-us/library/ms714687(VS.85).aspx


(SQLStates)

398 Version: 1.13.4 TF6420


Appendix

Database type Error code reference


Microsoft SQL Compact database http://technet.microsoft.com/en-us/library/
ms171788.aspx / OleDB_Errorcodes.htm [} 400]
Microsoft SQL database OleDB_Errorcodes.htm [} 400]
Microsoft Access database OleDB_Errorcodes.htm [} 400]
MySQL database https://dev.mysql.com/doc/mysql-errors/8.0/en/
client-error-reference.html
Oracle database https://docs.oracle.com/cd/E11882_01/server.112/
e17766/toc.htm
DB2 database https://www.ibm.com/docs/en/db2-for-zos/12?
topic=diagnostics-sqlstates-odbc-error-reporting
PostgreSQL database http://www.postgresql.org/docs/current/static/
errcodes-appendix.html
Interbase/Firebird database http://www.firebirdsql.org/file/documentation/
reference_manuals/reference_material/Firebird-2.1-
ErrorCodes.pdf
XML database TcDBServer_XML_Errorcodes.htm [} 405]
ASCII database TcDBServer_ASCII_Errorcodes.htm [} 405]

TF6420 Version: 1.13.4 399


Appendix

8.1.2.3 OleDB error codes

400 Version: 1.13.4 TF6420


Appendix

Value Description
0x80040E00 The accessor is invalid.
0x80040E01 It was not possible to insert a row into the row set, because the maximum number of
active rows for the provider would have been exceeded.
0x80040E02 The accessor is write-protected. The procedure has failed.
0x80040E03 Values violate the database schema.
0x80040E04 The row handle is invalid.
0x80040E05 The object was open.
0x80040E06 Invalid chapter
0x80040E07 A literal value in the command could not be converted to the correct type for a reason
other than data overflow.
0x80040E08 Invalid binding information
0x80040E09 Permission denied
0x80040E0A The specified column contains no bookmarks or chapters.
0x80040E0B Some cost limitations were rejected.
0x80040E0C No command was specified for the command object.
0x80040E0D No query plan was found within the specified cost limitation.
0x80040E0E Invalid bookmark
0x80040E0F Invalid lock mode
0x80040E10 No value was specified for at least one of the required parameters.
0x80040E11 Invalid column ID
0x80040E12 Invalid quota
0x80040E13 Invalid value
0x80040E14 The command contained at least one error.
0x80040E15 The currently executed command cannot be aborted.
0x80040E16 The provider offers no support for the specified dialect.
0x80040E17 A data source with the specified name already exists.
0x80040E18 The row set was created via a live datastream and cannot be restarted.
0x80040E19 In the current range no key matches the described characteristics.
0x80040E1B The provider is unable to determine the identity for the newly added rows.
0x80040E1A The ownership of this structure was transferred to the provider.
0x80040E1C Non-zero weighting values are not supported as target information. The target was
therefore rejected. The current target was not changed.
0x80040E1D The requested conversion is not supported.
0x80040E1E RowsOffset leads to position after the end of the row set, irrespective of the specified
cRows value. cRowsObtained is 0.
0x80040E20 The provider has called an IRowsetNotify method in the consumer and has not yet
received a return from the method.
0x80040E21 Error
0x80040E22 A non-zero controlling IUnknown object was specified, and the currently created
object does not support aggregation.
0x80040E23 The current row was deleted.
0x80040E24 The row set does not support backward calls.
0x80040E25 All HROW objects have to be released before new HROW objects can be received.
0x80040E26 A specified memory flag was not supported.
0x80040E27 The comparison operator was invalid.
0x80040E28 The specified status flag was neither DBCOLUMNSTATUS_OK nor
DBCOLUMNSTATUS_ISNULL.
0x80040E29 The row set cannot be processed backwards.
0x80040E2A Invalid range handle.

TF6420 Version: 1.13.4 401


Appendix

Value Description
0x80040E2B The specified row set was not adjacent to the rows of the specified monitoring range,
and there was no overlap.
0x80040E2C A transition from ALL* to MOVE* or EXTEND* was specified.
0x80040E2D The specified range is not a valid subrange of the range identified by the specified
monitoring range handle.
0x80040E2E The provider does not support commands with several statements.
0x80040E2F A specified value violated the integrity restrictions for a column or table.
0x80040E30 The specified type name was not recognized.
0x80040E31 Execution was aborted, since no further resources were available. No results were
returned.
0x80040E32 A command object with a command hierarchy containing at least one row set could
not be cloned.
0x80040E33 The current structure cannot be shown as text.
0x80040E34 The specified index already exists.
0x80040E35 The specified index does not exist.
0x80040E36 The specified index was used.
0x80040E37 The specified table does not exist.
0x80040E38 The row set has uses fully parallelism, and the value of a column was changed since
the last read operation.
0x80040E39 Errors were found during copying.
0x80040E3A A precision statement was invalid.
0x80040E3B A specified decimal value was invalid.
0x80040E3C Invalid table ID.
0x80040E3D A specified type was invalid.
0x80040E3E A column ID occurred several times in the specification.
0x80040E3F The specified table already exists.
0x80040E40 The specified table was used.
0x80040E41 The specified range schema ID was not supported.
0x80040E42 The specified record number is invalid.
0x80040E43 No matching row could be found, despite the fact that the bookmark formatting was
valid.
0x80040E44 The value of a property was invalid.
0x80040E45 The row set was not subdivided into chapters.
0x80040E46 Invalid accessor
0x80040E47 Invalid memory flags
0x80040E48 Accessors for transfer as reference are not supported by this provider.
0x80040E49 NULL accessors are not supported by this provider.
0x80040E4A The command was not prepared.
0x80040E4B The specified accessor was not a parameter accessor.
0x80040E4C The specified accessor was write-protected.
0x80040E4D Error during authentication.
0x80040E4E The change was aborted during the notification; no columns were modified.
0x80040E4F The row set consisted of a chapter, but the chapter was not enabled.
0x80040E50 Invalid source handle
0x80040E51 The provider is unable to derive parameter information, and SetParameterInfo was not
called.
0x80040E52 The data source object is already initialized.
0x80040E53 The provider does not support this method.
0x80040E54 The number of rows with pending modifications exceeds the specified limit.
0x80040E55 The specified column did not exist.

402 Version: 1.13.4 TF6420


Appendix

Value Description
0x80040E56 Changes are pending in a row with a reference counter of zero.
0x80040E57 A literal value in the command let to a range violation for the type of the assigned
column.
0x80040E58 The transferred HRESULT value was invalid.
0x80040E59 The transferred LookupID value was invalid.
0x80040E5A The transferred DynamicErrorID value was invalid.
0x80040E5B No visible data for a newly added row that has not yet been updated can be retrieved.
0x80040E5C Invalid conversion flag
0x80040E5D The specified parameter name was not recognized.
0x80040E5E Several memory objects cannot be open simultaneously.
0x80040E5F The requested filter could not be opened.
0x80040E60 The requested sequence could not be opened.
0x80040E65 The transferred columnID value was invalid.
0x80040E67 The transferred command has no DBID value.
0x80040E68 The transferred DBID value already exists.
0x80040E69 The maximum number of session objects supported by this provider has already been
reached. The consumer must release at least one current session object, before a
new session object can be retrieved.
0x80040E72 The index ID is invalid.
0x80040E73 The specified initialization character sequence does not match the specification.
0x80040E74 The OLE DB master enumerator has not returned any providers that match the
requested SOURCES_TYPE value.
0x80040E75 The initialization character sequence indicates a provider that does not match the
currently active provider.
0x80040E76 The specified DBID value is invalid.
0x80040E6A Invalid value for trust recipient.
0x80040E6B The trust recipient is not intended for the current data source.
0x80040E6C The trust recipient offers no support for memberships/list.
0x80040E6D The object is invalid, or the provider is unknown.
0x80040E6E The object has no owner.
0x80040E6F The transferred access entry list is invalid.
0x80040E70 The trust recipient transferred as owner is invalid, or the provider is unknown.
0x80040E71 The permission transferred in the access entry list is invalid.
0x80040E77 The ConstraintType value was invalid or was not supported by the provider.
0x80040E78 The ConstraintType value was not DBCONSTRAINTTYPE_FOREIGNKEY, and
cForeignKeyColumns was not zero.
0x80040E79 The Deferability value was invalid or was not supported by the provider.
0x80040E80 The MatchType value was invalid or was not supported by the provider.
0x80040E8A The UpdateRule or DeleteRule value was invalid or was not supported by the
provider.
0x80040E8B Invalid restriction ID.
0x80040E8C The dwFlags value was invalid.
0x80040E8D The rguidColumnType value pointed to a GUID that does not match the object type of
this column, or this column was not specified.
0x80040E91 No source row exists.
0x80040E92 The OLE DB object represented by this URL is locked by at least one other process.
0x80040E93 The client requested an object type that is only for lists.
0x80040E94 The calling process requested write access for a write-protected object.
0x80040E95 The provider was unable to establish a connection with the server for this object.
0x80040E96 The provider was unable to establish a connection with the server for this object.

TF6420 Version: 1.13.4 403


Appendix

Value Description
0x80040E97 Timeout during binding to the object
0x80040E98 The provider was unable to create an object with this URL, since an object named by
this URL already exists.
0x80040E8E The requested URL was outside the valid range.
0x80040E90 The column or restriction could not be deleted, since a dependent view or restriction
refers to it.
0x80040E99 The restriction already exists.
0x80040E9A The object cannot be created with this URL, since the server has insufficient physical
memory.
0x00040EC0 During retrieval of the requested number of rows the total number of active rows
supported by this row set was exceeded.
0x00040EC1 At least one column type is not compatible; conversion errors may occur during
copying.
0x00040EC2 Information on the parameter type were disabled by the calling process.
0x00040EC3 The bookmark for a deleted or irrelevant row was skipped.
0x00040EC5 No further row sets are available.
0x00040EC6 Start or end of the row set or chapter reached.
0x00040EC7 The command was executed again by the provider.
0x00040EC8 The data buffer for the variable is full.
0x00040EC9 No further results are available.
0x00040ECA The server is unable to cancel or downgrade a lockout until a transaction is complete.
0x00040ECB The specified weighting value was not supported or exceeded the supported limit. The
value was set to 0 or to the limit.
0x00040ECC For this reason the consumer rejects further notification calls.
0x00040ECD The input dialect was ignored, and the text was returned in another dialect.
0x00040ECE The consumer rejects further notification calls for this phase.
0x00040ECF For this reason the consumer rejects further notification calls.
0x00040ED0 The operation is processed asynchronously.
0x00040ED1 To reach the start of the row set, the provider has to execute the query again. Either
the order of the columns has changed, or columns were added to the row set, or
columns were removed from the row set.
0x00040ED2 The method had several errors. The errors were returned in the error array.
0x00040ED3 Invalid row handle
0x00040ED4 A specified HROW object referred to a permanently deleted row.
0x00040ED5 The provider was unable to trace all modifications. The client has to retrieve the data
assigned the monitoring range again via another method.
0x00040ED6 The execution was terminated because no more resources were available. The results
received up to this time were returned, but the execution cannot continue.
0x00040ED8 A lockout was upgraded relative to the specified value.
0x00040ED9 At least one property was changed according to the options permitted by the provider.
0x00040EDA Error
0x00040EDB A specified parameter was invalid.
0x00040EDC Due to the update of this row several rows in the data source had to be updated.
0x00040ED7 The binding failed, since the provider was not able to meet all binding flags or
properties.
0x00040EDD The row contains no row-specific columns.

404 Version: 1.13.4 TF6420


Appendix

8.1.2.4 ASCII error codes


Value Description
1 Function not available
2 Syntax error
3 File could not be opened.

8.1.2.5 XML error codes


Value Description
1 Function not available
2 XML file could not be loaded
3 XML schema could not be loaded
4 Syntax error
5 Table could not be created
6 The INSERT VALUE list does not match the columns list
7 PLC structure is not large enough
8 XML file could not be created
9 XML database not found.
10 XML table not found

8.1.2.6 Internal error codes


Error code Description
0x02000001 NULL values are not allowed
0x02000002 FB_DBRead selected value is NULL
0x02000003 DBID is unknown
0x02000004 ADSDevID is unknown
0x02000005 No open database connection found for DBID xy
0x02000006 No open ADS device connection found for ADSDevID xy

8.2 FAQ - frequently asked questions and answers


In this section frequently asked questions are answered, in order to facilitate your work with the TwinCAT
Database Server.
If you have any further questions, contact please our Support.

1. What performance can be achieved with the TwinCAT Database Server? [} 406]

2. Are so-called stored procedures supported? [} 406]

3. Which database types does the TwinCAT Database Server support? [} 406]

4. Can old database server configurations still be used in later versions? [} 406]

5. How can individual variables be written into an existing database structure or read from it? [} 406]

6. Can several records be written into a database simultaneously? [} 406]

7. How can the TwinCAT Database Server be operated in a network? [} 406]

8. Which functions of the TwinCAT Database Server are supported by the database type "XML"? [} 406]

9. Which Visual Studio versions are currently supported by the database server configurator? [} 406]

TF6420 Version: 1.13.4 405


Appendix

What performance can be achieved with the TwinCAT Database Server?


This question cannot be answered in general terms. The performance that can be achieved depends on the
hardware used, the actions to be execute (e.g. ring buffer logging) and the number of variables. Another key
factor is the database type that is used.

Are so-called Stored Procedures supported?


Yes, the TwinCAT Database Server supports Stored Procedures. The function block FB_SQLStoredProcedure
[} 201] is provided for this purpose in the PLC library. The SQL Query Editor can be used to test stored
procedures, and corresponding PLC code for the function block FB_SQLStoredProcedure can be generated.
Not all databases support this function.

Which database types does the TwinCAT Database Server support?


Information on the supported databases can be found in section "Databases [} 123]".

Can old database server configurations still be used in later versions?


It goes without saying that we aim to ensure compatibility. This was also taken into account during major
version upgrades or complete redesigns (e.g. old: 3.0.x, new: 3.1.x). Further details can be found in section
"Compatibility [} 20]".

How can individual variables be written into an existing database structure or read from it?
The function block FB_SQLCommand [} 196] can be used to write individual variables into an existing
database structure or read from it.

Can several records be written into a database simultaneously?


This depends on the database used. With a Microsoft SQL database this would be possible in conjunction
with the function block FB_SQLCommand [} 196], since several SQL insert commands (separated by
semicolon) can be transferred to the PLC function block.

How can the TwinCAT Database Server be operated in a network?


The TwinCAT Database Server can be used in a network in several ways. Further information on support
network topologies can be found in section "Areas of application and network topologies [} 18]".

Which functions of the TwinCAT Database Server are supported by the database type "XML"?
The "XML" database type supports the full functionality of the TwinCAT Database Server, except for "stored
procedures". The XML file can be used to communicate with any other database via SQL commands, and
PLC values can be logged in the XML file with the cyclic write mode. In addition, it is possible to execute
XPath commands and read the corresponding XML tags. Further information can be found in section "XML
database [} 134]".

Which Visual Studio versions are currently supported by the database server configurator?

Currently the Visual Studio® versions 2013, 2015 and 2017 are supported with our configurator integration
[} 23].

8.3 Support and Service


Beckhoff and their partners around the world offer comprehensive support and service, making available fast
and competent assistance with all questions related to Beckhoff products and system solutions.

Download finder

Our download finder contains all the files that we offer you for downloading. You will find application reports,
technical documentation, technical drawings, configuration files and much more.

The downloads are available in various formats.

Beckhoff's branch offices and representatives

Please contact your Beckhoff branch office or representative for local support and service on Beckhoff
products!

The addresses of Beckhoff's branch offices and representatives round the world can be found on our internet
page: www.beckhoff.com

406 Version: 1.13.4 TF6420


Appendix

You will also find further documentation for Beckhoff components there.

Beckhoff Support

Support offers you comprehensive technical assistance, helping you not only with the application of
individual Beckhoff products, but also with other, wide-ranging services:
• support
• design, programming and commissioning of complex automation systems
• and extensive training program for Beckhoff system components
Hotline: +49 5246 963-157
e-mail: [email protected]

Beckhoff Service

The Beckhoff Service Center supports you in all matters of after-sales service:
• on-site service
• repair service
• spare parts service
• hotline service
Hotline: +49 5246 963-460
e-mail: [email protected]

Beckhoff Headquarters

Beckhoff Automation GmbH & Co. KG

Huelshorstweg 20
33415 Verl
Germany
Phone: +49 5246 963-0
e-mail: [email protected]
web: www.beckhoff.com

TF6420 Version: 1.13.4 407


More Information:
www.beckhoff.com/tf6420

Beckhoff Automation GmbH & Co. KG


Hülshorstweg 20
33415 Verl
Germany
Phone: +49 5246 9630
[email protected]
www.beckhoff.com

You might also like