TF6420 TC3 Database Server en
TF6420 TC3 Database Server en
TF6420
TwinCAT 3 | Database Server
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
1 Foreword
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
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.
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.
NOTICE
The environment, equipment, or data may be damaged.
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.
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]".
3 Installation
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.
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.
ð A dialog box informs you that the TwinCAT system must be stopped to proceed with the installation.
6. Confirm the dialog with Yes.
ð 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).
A description of the procedure to license a full version can be found in the Beckhoff Information System in
the documentation "TwinCAT 3 Licensing".
ð A dialog box opens, prompting you to enter the security code displayed in the dialog.
If an older TFxxx version is already installed on the Windows CE device, it can be updated:
• Software upgrade [} 15]
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.
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.
Further information can be found in the Beckhoff Information System in the "Operating Systems"
documentation (Embedded PC > Operating Systems > CE).
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.
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.
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.
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.
4 Technical introduction
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.1 General
This chapter describes the various functions and components of the Visual Studio integration of the
TwinCAT Database Server.
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.
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]".
Event display
Database pool
AutoLog Viewer
InformationLog View
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
Individual database configurations can be disabled in the project. These are then marked in red and ignored
when the project is activated.
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.
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.
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:
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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:
Yellow: the byte length of the data set does not match, or underlying data sets are left over or missing.
Green: no conflicts
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.
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.
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.
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.
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 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.
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.
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.
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:
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.
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.
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])
Refresh The display in the Target Browser tree can be manually updated with this button.
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.
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.
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.
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.
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
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
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.
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
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.
This button can be used to customize various properties of the TcAnalyticsFile extension.
Properties
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.
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
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
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
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Delete command
This SQL command can also be customized, in order to delete only a particular section of the table, for
example.
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].
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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 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.
5.1.2.1 General
Event display
Database pool
AutoLog Viewer
InformationLog View
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:
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.
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 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:
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.
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.
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.
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.
RingBuffer-Arten
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.
RingBuffer_Time:
RingBuffer_Count:
RingBuffer_Time:
RingBuffer_Count:
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.
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).
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.
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.
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.
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.
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.
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:
Yellow: the byte length of the data set does not match, or underlying data sets are left over or missing.
Green: no conflicts
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.
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.
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.
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.
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 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.
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
*additional server or client drivers for the database must be installed on the device
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.
The configuration of the individual databases and mapping of the data sets in the PLC is explained on the
following sections.
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.
Performance impairment
Some databases cause performance problems, because additional SQL commands have to be sent
in order to read the character set.
Currently, BULK commands via the FB_PLCDBCmdEvt function block are supported by the TwinCAT
Database Server for Microsoft SQL databases.
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.
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.
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.
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.
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.
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)
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.
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.
The TwinCAT Database Server requires the 32-bit version of the .NET ODP components.
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.
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.
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.
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.
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.
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.
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.
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.
Further information on working with XML files as databases can be found in section "XML - information
[} 135]".
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.
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.
2. Apply XPath queries to an XML file with the TwinCAT 3 Database Server
1. XML as database
<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>
<xsd:simpleTypename="datetime">
<xsd:restrictionbase="xsd:dateTime" />
</xsd:simpleType>
<xsd:simpleTypename="float">
<xsd:restrictionbase="xsd:double" />
</xsd:simpleType>
<xsd:simpleTypename="bit">
<xsd:restrictionbase="xsd:boolean" />
</xsd:simpleType>
<xsd:simpleTypename="integer">
<xsd:restrictionbase="xsd:int" />
</xsd:simpleType>
<xsd:simpleTypename="money">
<xsd:restrictionbase="xsd:double" />
</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>
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.
XPath types
The syntax of the prefixes of the XPaths in the TwinCAT Database Server is as follows:
XPATH_[Type]<[Position]>#[Path]
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>
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.
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.
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.
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.
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.
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.
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.
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.6 Firebird
This section contains information on the configuration and the data type mapping of Firebird databases with
ODBC.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.14 InfluxDB
This section contains information about the configuration and the data type mapping of InfluxDB.
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.
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.
The standard table structure for InfluxDB looks like this in the PLC:
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.
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.
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.
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.
6 PLC API
6.1 Tc3_Database
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.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
Outputs
Properties
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
Inputs
Return value
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
Outputs
Methods
Requirements
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
Return value
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
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
Return value
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
Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLogEvt (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF
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
Inputs
Outputs
Properties
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
Inputs
Return value
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
Outputs
Methods
Requirements
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
Return value
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
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
Return value
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
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
Inputs
Outputs
Properties
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
6.1.1.2.4 FB_PLCDBReadEvt
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
Outputs
Properties
Methods
Requirements
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
Return value
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
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
Return value
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
6.1.1.2.5 FB_PLCDBWriteEvt
Syntax
Definition:
FUNCTION_BLOCK FB_PLCDBWriteEvt
VAR_INPUT
sNetID: T_AmsNetID := '';
Inputs
Outputs
Properties
Methods
Requirements
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;
Inputs
Return value
Sample
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.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
Return value
Sample
// 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
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
Return value
Sample
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
// 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
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
Inputs
Outputs
Properties
Methods
Requirements
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
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;
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
Return value
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';
// 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.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
Inputs
Outputs
Properties
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
Inputs
Return value
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
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
Outputs
Properties
Methods
Requirements
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
Return value
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
Return value
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
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
Return value
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;
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.
Syntax
METHOD Disconnect : BOOL
Return value
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
Outputs
Properties
Methods
Requirements
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
Return value
Sample
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
Return value
Sample
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';
6.1.1.3.4 FB_SQLResultEvt
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
Outputs
Properties
Methods
Requirements
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
Return value
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
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
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;
END_VAR
VAR_OUTPUT
bBusy: BOOL;
bError: BOOL;
ipTcResult: Tc3_EventLogger.I_TcMessage
END_VAR
Inputs
Outputs
Properties
Methods
Requirements
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.
Syntax
METHOD Execute : BOOL
VAR_INPUT
pParameterStrc: POINTER TO BYTE;
cbParameterStrc: UDINT;
END_VAR
Inputs
Return value
Sample
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
Return value
Sample
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
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:
Inputs
Methods
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
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.
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
Syntax
Definition:
FUNCTION BLOCK FB_NoSQLQueryBuilder_TimeSeriesDB
VAR_INPUT
pQueryOptions : POINTER TO BYTE;
cbQueryOptions : UDINT;
END_VAR
VAR_OUTPUT
END_VAR
Methods
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
Requirements
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
Properties
Outputs
Methods
Requirements
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
Return value
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);
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
Return value
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);
6.1.1.4.3 FB_NoSQLResultEvt
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
Outputs
Properties
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
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
Outputs
Properties
Methods
Requirements
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
Return value
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
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
Return value
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
Return value
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
Properties
Methods
Requirements
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
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.
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
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
Requirements
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
Return value
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
Return value
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
Return value
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
Return value
6.1.1.5.1.5 GetJsonAttribute
Syntax
METHOD GetJsonAttribute : HRESULT
VAR_INPUT
sJsonAttribute : REFERENCE TO STRING;
nJsonAttribute : UDINT;
END_VAR
Inputs
Return value
6.1.1.5.1.6 RequestEventClassName
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
Return value
Outputs
6.1.1.5.1.7 RequestEventText
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
Return value
Outputs
6.1.1.5.2 I_TcMessage
This interface provides methods and properties for the message handling.
Inheritance hierarchy
I_TcEventBase [} 220]
I_TcMessage
Methods
Name Description
Send [} 225] Sends a message
Requirements
6.1.1.5.2.1 Send
Syntax
METHOD Send : HRESULT
VAR_INPUT
nTimeStamp: ULINT;
END_VAR
Inputs
Return value
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
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
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
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
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
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
Parameter
Requirements
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
Requirements
6.1.2.1.7 ST_ConnStringParameter
Syntax
Definition:
TYPE ST_ConnStringParameter
STRUCT
sName: T_MaxString;
sValue: T_MaxString;
END_STRUCT
END_TYPE
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Requirements
6.1.2.1.8.5 T_DBConfig_MsSQL
Describes the database configuration structure for a Microsoft SQL database.
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
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
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:
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
Requirements
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
Requirements
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
Parameter
Requirements
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
Requirements
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
Requirements
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
Requirements
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
Parameter
Requirements
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
Requirements
6.1.2.2.5 E_TimeSeriesDbQueryType
Syntax
{attribute 'qualified_only'}
TYPE E_ TimeSeriesDbQueryType:
(
Insert := 1,
Query := 2
);
END_TYPE
Requirements
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
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
6.1.2.3.3 E_VerifyResult
Syntax
Definition:
{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
Requirements
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
6.1.2.4.2 E_ErrorType
Syntax
Definition:
{attribute 'qualified_only'}
TYPE E_ErrorType :
(
noError := 0,
InternalError,
DataBaseError,
ADSError
);
END_TYPE
Requirements
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
Requirements
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
6.1.2.4.5 E_OrderType
Syntax
Definition:
{attribute 'qualified_only'}
TYPE E_OrderType :
(
ASC := 0,
DESC := 1
);
END_TYPE
Requirements
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,
eType_BigType := 13
);
END_TYPE
Requirements
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
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
Requirements
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
Requirements
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
Requirements
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
Requirements
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
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
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
Requirements
6.1.3.1 Constants
Requirements
6.1.4 Obsolete
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
Outputs
Methods
Requirements
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
Return value
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.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
Return value
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.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
Return value
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
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
Outputs
Methods
Requirements
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.
Syntax
METHOD RunOnce : BOOL
VAR_INPUT
hAutoLogGrpID: UDINT;
bAll: BOOL;
END_VAR
Inputs
Return value
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
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;
Inputs
Return value
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
Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF
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
Outputs
Methods
Requirements
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
Return value
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.
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
Return value
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.
Syntax
METHOD Delete : BOOL
VAR_INPUT
eTcDBSrvConfigType: E_TcDBSrvConfigType;
hConfigID: UDINT;
END_VAR
Inputs
Return value
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
Inputs
Outputs
Methods
Requirements
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
Return value
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
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
Inputs
Return value
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
Sample
VAR
fbPLCDBAutoLog : FB_PLCDBAutoLog (sNetID:='', tTimeout := T#5S);
END_VAR
IF fbPLCDBAutoLog.Stop() THEN
; // ...
END_IF
6.1.4.2.3 FB_PLCDBCreate
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
Outputs
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
6.1.4.2.4 FB_PLCDBRead
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
Outputs
Methods
Requirements
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;
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
Return value
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
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
Return value
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
6.1.4.2.5 FB_PLCDBWrite
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
Inputs
Outputs
Methods
Requirements
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
Inputs
Return value
Sample
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.
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
Return value
Sample
// 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
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
Return value
Sample
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
// 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
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
Outputs
Methods
Requirements
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;
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;
Inputs
Return value
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';
// 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.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
Outputs
Methods
Requirements
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
Inputs
Return value
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
Inputs
Return value
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
Inputs
Return value
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
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
Outputs
Methods
Requirements
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
Return value
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.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
Return value
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
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.
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
Return value
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;
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
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
Outputs
Methods
Requirements
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
Return value
Sample
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
Return value
Sample
6.1.4.3.4 FB_SQLResult
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
Outputs
Methods
Requirements
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
Inputs
Return value
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
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
Return value
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
Outputs
Methods
Requirements
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
Return value
Sample
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
Return value
Sample
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
Return value
6.2 Tc2_Database
Overview
The Tc2_Database library contains function blocks for controlling and configuring the TwinCAT 3 database
server.
Function blocks
Name Description
FB_GetStateTcDatabase [} 293] Retrieves status information.
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
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.
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.
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
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.
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;
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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.
eDBValueType: Indicates the form in which the values are or will be stored.
sSystemDB: Only for Access databases. Indicates the path to the MDW file.
sDBTable: Gives the name of the table into which the values are to be written.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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;
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.
eDBValueType: Indicates the form in which the values are or will be stored.
sDBTable: Gives the name of the table into which the values are to be written.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
6.2.1.5 FB_AdsDeviceConnectionAdd
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.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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.
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.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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.
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.
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
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.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
6.2.1.10 FB_DBCreate
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.
sSystemDB: Only for Access databases. Contains the path to the MDW file.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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.
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.
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.
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
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.
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
6.2.1.13 FB_DBRead
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.
pDestAddr: Contains the address of the buffer which is to receive the data that has been read.
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.
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
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.
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).
nRingBufferCount: Indicates the maximum number of records in a table (only for Ringbuffer_WriteMode).
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.
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
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.
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.
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.
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
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;
bExecute : BOOL;
tTimeout : TIME;
END_VAR
sNetID: String containing the AMS network ID of the target device, at which the ADS command is directed.
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.
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
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;
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.
pCmdSize: Indicates the pointer address of a string variable with the SQL command to be executed.
pDestAddr: Indicates the address of the structure array into which the records are to be written.
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.
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
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:
Structure:
TYPE ST_Record:
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Name : STRING(80);
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
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.
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.
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.
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
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.
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.
pDestAddr: Indicates the address of the structure array into which the records are to be written.
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.
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
6.2.1.20 Obsolete
6.2.1.20.1 FB_DBAuthentificationAdd
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.
sSystemDB: Only for Access databases. Indicates the path to the MDW file.
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.
nErrID: Returns the ADS error code if the bError output is set.
Requirements
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.
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.
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
6.2.1.20.3 FB_DBRecordSelect
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.
pDestAddr: Indicates the address of the structure to which the record is to be written.
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.
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
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:
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
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.
pCmdSize: Indicates the pointer address of a string variable with the SQL command to be executed.
pDestAddr: Indicates the address of the structure to which the record is to be written.
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.
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
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.
pRecordAddr: Indicates the address of the structure to which the record is to be written.
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.
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
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
Requirements
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
Requirements
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
Requirements
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.
Requirements
6.2.2.5 ST_DBParameter
VAR_INPUT
TYPE ST_DBParameter :
STRUCT
sParameterName : STRING(59);
cbParameterValue : UDINT;
pParameterValue : UDINT;
eParameterDataType: E_DBColumnTypes;
eParameterType : E_DBParameterTypes;
END_STRUCT
END_TYPE
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
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
Requirements
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
6.2.2.8 E_DBValueType
TYPE E_DBValueType :
(
eDBValue_Double:= 0,
eDBValue_Bytes := 1
);
END_TYPE
Requirements
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
6.2.2.10 E_DBParameterTypes
TYPE E_DBParameterTypes :
(
eDBParameter_Input := 0,
eDBParameter_Output := 1,
eDBParameter_InputOutput := 2,
eDBParameter_ReturnValue := 3,
eDBParameter_OracleCursor:= 4
);
END_TYPE
Requirements
6.2.3.1 Constants
VAR_GLOBAL_CONSTANT
END_VAR
Requirements
Global_Version
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!
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.
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.
3. Then the ADS device from which the ADS symbols are to be read is set up.
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.
7. Then the ADS device and the symbols are selected, as described in steps 3 and 4.
10. For the energy data the ADS device and the symbols are also selected.
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].
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
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;
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';
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
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;
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;
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
EventSourcePath := ipResultEvt.ipSourceInfo.sName;
EventId := ipResultEvt.nEventId;
nState_SetResInfo:=0;
_SetResultInfo := TRUE;
END_IF
END_CASE
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;
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;
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;
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;
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.
If these steps are executed consecutively, the array stRecordArr is filled with values from the database:
Recipe XML:
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;
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)
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,
pReturnData:= ADR(_sTestNum),
cbReturnData:= SIZEOF(_sTestNum),
pRecords:= 0) THEN
bError := fbPLCDBCmd.bError;
sErrClass := fbPLCDBCmd.ipTcResultEvent.EventClassDisplayName;
nErrID := fbPLCDBCmd.ipTcResultEvent.EventId;
sErrText := fbPLCDBCmd.ipTcResultEvent.Text;
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;
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
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;
nState_SetResInfo:=0;
_SetResultInfo := TRUE;
END_IF
END_CASE
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.
FB_PLCDBWriteEvt.WriteStr variable
uct*
FB_PLCDBReadEvt.Read standard
FB_:PLCDBReadEvt.ReadSt variable
ruct*
FB_PLCDBCmdEvt.Execute* variable
FB_SQLCommandEvt variable
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 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.
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.
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
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.
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.
//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;
IF nWriteBufferIndex = 20 THEN
nWriteBufferIndex := 0;
END_IF
IF aWriteSQL[nWriteBufferIndex] THEN
nState := 255;
RETURN;
END_IF
END_IF
aWriteSQL[nSQLIndex] := FALSE;
nSQLIndex := nSQLIndex + 1;
IF nSQLIndex = 20 THEN
nSQLIndex := 0;
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.
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);
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}]
}';
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.
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;
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
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".
Example (SQL)
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.
The FB_SQLStoredProcedureEvt [} 201] uses the Stored Procedure previously linked with
FB_SQLDatabaseEvt.CreateSP() [} 192]
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
Calling a function
Example (SQL)
The call itself returns a "RefCursor". This is automatically interpreted by the TwinCAT Database Server.
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
13743810955/.zip
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:
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.
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
queries
i: INT;
rand : DRAND;
nrand: LREAL;
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
END_STRUCT
END_TYPE
(WindTurbineData.tcDUT)
CASE State OF
E_DbLogState.idle:
IF bWriting THEN
bWriting := FALSE;
State := E_DbLogState.init;
END_IF
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;
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:
Error handling:
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.
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip
A table with the name "myTable", which has the following structure, is added to the generated database:
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;
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(
sNetId := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples\TestDB1000SPS.mdb',
ePath := PATH_GENERIC,
bExecute := TRUE,
tTimeout := T#5s,
bBusy => bBusy_Delete,
bError => ,
nErrId => );
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);
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
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip
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.
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;
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.
Requirements
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip
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"
Variable Declaration
PROGRAM MAIN
VAR
(*Test symbol which will be logged into the different database tables*)
lrTestValueVar : LREAL := 123.456;
(*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;
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);
Requirements
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip
Variable Declaration
(* Declaration *)PROGRAM MAIN
VAR
eState : E_SQLStatement;
NT_GetTime1 : NT_GetTime;
bTimestart : BOOL;
tTime : TIMESTRUCT;
FB_FormatStringDateTime: FB_FormatString;
sDateTimeString : T_MaxString;
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);
arg4 := F_REAL(TestValue3),
arg5 := F_STRING(TestValue4),
sOut => sInsertString,
bError => bError,
nErrId => nErrid);
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
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip
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.
nState : BYTE;
FB_DBStoredProceduresRecordArray1: FB_DBStoredProceduresRecordArray;
bBusy : BOOL;
bErr : BOOL;
nErrid : UDINT;
stSqlstate : ST_DBSQLError;
END_VAR
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);
Visualization
Requirements
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
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;
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;
sNetID := ,
sPathName:= 'C:\TwinCAT\TcDatabaseSrv\Samples',
sDBName := 'XMLTestDB',
eDBType := eDBType_XML,
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_CreateDB,
bError => bErr,
nErrID => nErrid);
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);
The process is started with a positive edge at the toggle variable bSTART.
</xsd:complexType>
</xsd:element>
</xsd:schema>
Requirements
Download: https://infosys.beckhoff.com/content/1033/TF6420_Tc3_Database_Server/Resources/
3494041099/.zip
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
;
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
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
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,
nRecordCount := 4,
cbRecordArraySize := SIZEOF(arrTestStruct),
pDestAddr := ADR(arrTestStruct),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy,
bError => bError,
nErrID => nErrID,
sSQLState => stSQLState,
nRecords => nRecs1);
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);
Requirements
8 Appendix
8.1.1 Tc3_Database
EventClass: GUID
EventClassName: The corresponding event class name can be read using the RequestEventClassName
method
Text: description of the event in plain text can be read with the RequestEventText method
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.
8.1.2 Tc2_Database
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.
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.
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.
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.
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.
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.
1. What performance can be achieved with the TwinCAT Database Server? [} 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]
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]
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.
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].
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.
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
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
Huelshorstweg 20
33415 Verl
Germany
Phone: +49 5246 963-0
e-mail: [email protected]
web: www.beckhoff.com