TF6420 TC3 Database Server en
TF6420 TC3 Database Server en
TwinCAT
Version: 1.4
Date: 2016-07-26
Order No.: TF6420
Table of contents
Table of contents
1 Foreword .................................................................................................................................................... 5
1.1 Notes on the documentation............................................................................................................. 5
1.2 Safety instructions ............................................................................................................................ 6
2 Overview..................................................................................................................................................... 7
3 Installation.................................................................................................................................................. 8
3.1 System requirements........................................................................................................................ 8
3.2 Installation......................................................................................................................................... 8
3.3 Licensing......................................................................................................................................... 11
3.4 Installation Windows CE ................................................................................................................. 15
5 Configuration ........................................................................................................................................... 21
5.1 TF6420 Database Server Configuration Editor............................................................................... 21
5.2 TwinCAT Database Server : SQL Query Editor.............................................................................. 34
5.3 Write Direction Mode ...................................................................................................................... 40
5.4 Properties and use of the XML configuration file ............................................................................ 43
5.5 Databases....................................................................................................................................... 44
5.5.1 Declaration of the different database types ........................................................................ 44
5.5.2 MS SQL database............................................................................................................... 51
5.5.3 MS SQL Compact database ............................................................................................... 52
5.5.4 MS Azure SQL database .................................................................................................... 53
5.5.5 MS Access database .......................................................................................................... 54
5.5.6 MS Excel database ............................................................................................................. 55
5.5.7 NET / ODBC - MySQL Database........................................................................................ 56
5.5.8 OCI / ODBC - Oracle Database .......................................................................................... 57
5.5.9 SQLite ................................................................................................................................. 58
5.5.10 ASCII - File.......................................................................................................................... 60
5.5.11 XML - Database .................................................................................................................. 60
5.5.12 ODBC - PostgreSQL Database .......................................................................................... 61
5.5.13 ODBC - DB2 Database ....................................................................................................... 63
5.5.14 ODBC - InterBase Database............................................................................................... 63
5.5.15 ODBC - Firebird Database.................................................................................................. 64
5.5.16 Additional information ......................................................................................................... 65
5.6 Expert ............................................................................................................................................. 71
5.6.1 Impersonate option ............................................................................................................. 71
5.6.2 Additional Registry configuration ........................................................................................ 72
5.6.3 XML - configuration file ....................................................................................................... 73
6 API............................................................................................................................................................. 76
6.1 PLC reference................................................................................................................................. 76
6.1.1 Tc2_Database..................................................................................................................... 76
6.1.2 Function blocks ................................................................................................................... 78
6.1.3 Data types......................................................................................................................... 106
6.1.4 Global Constants .............................................................................................................. 110
7 Samples.................................................................................................................................................. 112
7.1 Workshop Handout ....................................................................................................................... 112
7.2 Generation of a MS Access database .......................................................................................... 123
7.3 Start / Stop of the cyclic log .......................................................................................................... 126
7.4 To log a PLC variable with FB_DBWrite....................................................................................... 128
8 Appendix ................................................................................................................................................ 150
8.1 Errorcodes .................................................................................................................................... 150
8.1.1 ADS Return Codes ........................................................................................................... 150
8.1.2 Internal Errorcodes of the TwinCAT Database Server...................................................... 155
8.1.3 OleDB Errorcodes............................................................................................................. 156
8.1.4 ASCII Errorcodes .............................................................................................................. 162
8.1.5 XML Errorcodes ................................................................................................................ 162
8.2 FAQ - Frequently asked questions and their answers.................................................................. 162
1 Foreword
The responsible staff must ensure that the application or use of the products described satisfy all the
requirements for safety, including all the relevant laws, regulations, guidelines and standards.
Disclaimer
The documentation has been prepared with care. The products described are, however, constantly under
development.
For that reason the documentation is not in every case checked for consistency with performance data,
standards or other characteristics.
In the event that it contains technical or editorial errors, we retain the right to make alterations at any time
and without warning.
No claims for the modification of products that have already been supplied may be made on the basis of the
data, diagrams and descriptions in this documentation.
Trademarks
Beckhoff®, TwinCAT®, EtherCAT®, Safety over EtherCAT®, TwinSAFE®, XFC®and XTS® are registered
trademarks of and licensed by Beckhoff Automation GmbH.
Other designations used in this publication may be trademarks whose use by third parties for their own
purposes could violate the rights of the owners.
Patent Pending
The EtherCAT Technology is covered, including but not limited to the following patent applications and
patents:
EP1590927, EP1789857, DE102004044764, DE102007017835
with corresponding applications or registrations in various other countries.
The TwinCAT Technology is covered, including but not limited to the following patent applications and
patents:
EP0851348, US6167425 with corresponding applications or registrations in various other countries.
EtherCAT® is registered trademark and patented technology, licensed by Beckhoff Automation GmbH,
Germany
Copyright
© Beckhoff Automation GmbH & Co. KG, Germany.
The reproduction, distribution and utilization of this document as well as the communication of its contents to
others without express authorization are prohibited.
Offenders will be held liable for the payment of damages. All rights reserved in the event of the grant of a
patent, utility model or design.
Exclusion of liability
All the components are supplied in particular hardware and software configurations appropriate for the
application. Modifications to hardware or software configurations other than those described in the
documentation are not permitted, and nullify the liability of Beckhoff Automation GmbH & Co. KG.
Personnel qualification
This description is only intended for trained specialists in control, automation and drive engineering who are
familiar with the applicable national standards.
Description of symbols
In this documentation the following symbols are used with an accompanying safety instruction or note. The
safety instructions must be read carefully and followed without fail!
Risk of injury!
Failure to follow the safety instructions associated with this symbol endangers the life and
health of persons.
WARNING
Personal injuries!
Failure to follow the safety instructions associated with this symbol can lead to injuries to
persons.
CAUTION
Tip or pointer
This symbol indicates information that contributes to better understanding.
Note
2 Overview
The TwinCAT Database Server enables data exchange between the TwinCAT System and different
database systems. For smaller applications you can use the server over a configurator without influencing
the existing program code. For complex tasks and a maximum of flexibility the Database Server offers a
detailed library of PLC function blocks. Directly out of the PLC you can use SQL-commands like Insert and
Select. If necessary you can relieve the PLC by calling up Stored Procedures in the database. The
transfered parameters from the PLC function block will be used from the database in connection with the
stored procedure and results will be returned to the controller.
At the moment the TwinCAT Database Server supports eleven different database systems [} 44]: MS SQL,
MS SQL Compact, MS Access, MySQL, PostgreSQL, DB2, Oracle, Interbase, Firebird, ASCII (e.g. .txt
or .csv) as well as XML files.
Components:
• TwinCAT Database Server [} 18]: a service which starts and stops along with TwinCAT. It is a
connector between the TwinCAT system and the database.
• Configurator [} 21]: the TwinCAT Database Server configurator enables an easy visual setting of
database parameters, which are necessary for the basic communication with the respective database.
• PLC library [} 76]: the PLC library offers several function blocks to generate a database connection or
a new chart. Furthermore you can write data into any chart structures with Insert-commands or read
them through Select-commands. It is also possible to update or delete database entries. Stored
procedures can be activated.
Functional principle:
The Database Server communicates over ADS within the TwinCAT system. Outwards the server connects
with the respective database. Possible network topologies can be found here [} 19].
3 Installation
3.2 Installation
Description of the installation procedure of a TwinCAT 3 Function for Windows-based operating Systems.
1. Double-click the downloaded setup file "TE1610 TC3 EAP-Configurator.exe".
Please note: Under Windows 32-bit/64-bit, please start the installation with "Run as Administrator" by
right-clicking the setup file and selecting the corresponding option in the context menu.
2. Click on "Next" and accept the license Agreement.
4. To install the full product, including all sub-components, please choose "Complete" as the Setup
Type.Alternatively you can also install each component seperately by choosing "Custom".
3.3 Licensing
The TwinCAT 3 functions are available both as a full and as a 7-Day trial version. Both license types can be
activated via TwinCAT XAE.For more information about TwinCAT 3 licensing, please consult the TwinCAT 3
Help System.The following document describes both licensing scenarios for a TwinCAT 3 function on
TwinCAT 3 and is divided into the following sections:
• Licensing a 7-Day trial version [} 11]
• Licensing a full version [} 12]
4. Open the tab "Manage Licenses" and add a "Runtime License" for your product (in this screenshot
“TE1300: TC3 Scope View Professional”)
5. Optional: If you would like to add a license for a remote device, you first need to connect to the remote
device via TwinCAT XAE toolbar
6. Switch to the tab "Order Information" and click the button "Activate 7 Days Trial License..."to
activate a test version
11. Open the tab "Manage Licenses" and add a "Runtime License" for your product (in this screenshot "
TE1300: TC3 Scope View Professional”).
12. Optional:If you would like to add a license for a remote device, you first need to connect to the remote
device via TwinCAT XAE toolbar
15. enter the "Beckhoff License ID" and click on "Generate License Request File...". If you are not aware
of your "Beckhoff License ID" please contact your local sales representative.
16. After the license request file has been saved, the system asks whether to send this file via E-Mail to the
Beckhoff Activation Server
17. After clicking "Yes", the standard E-Mail client opens and creates a new E-Mail message to
"tclicense@beckhoff.com" which contains the "License Request File"
18. Send this Activation Request to Beckhoff
NOTE! The “License Response File“ will be sent to the same E-Mail address used for sending
out the ”License Request File”
19. After receiving the activation file, please click on the button "Activate License Response File..."in the
TwinCAT XAE license Interface.
20. Select the received "Licnse response file" and click on "Open"
21. The "License Response File" will be imported and all included licenses will be activated. If there have
been any trial licenses, these will be removed accordingly.
22. Please restart TwinCAT to activate licenses..
The CE-ARM and CE-X86 folders contain the TFxxx ( here TF6310) CAB-File for Windows CE -
corresponding to the hardware platform of your Windows CE device. This file needs to be transfered to the
Windows CE device.
For more information, please consult the "Windows CE" section in our Infosys documentation system.
Software installation
After the CAB-File has been transfered via one of the above methods, you need to execute the file and
acknowledge the following dialog with "Ok". Restart your Windows CE device after the installation has
finished.
After the restart has been completed, the TFxxxx executable files will be automatically started in background
and is now available to use.
The software will be installed in the following directory on the CE device: \Hard Disk\TwinCAT\Functions
\TFxxxx
Upgrade instructions
If you have already a version of TF6310 installed on your Windows CE device, you need to perform the
following things on the Windows CE device to upgrade to a newer version:
1. Open the CE Explorer by clicking on Start --> Run and entering "explorer"
2. Navigate to \Hard Disk\TwinCAT\Functions\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 CE device
6. Execute the CAB-File and install the new version
7. Delete “Tc*.old.”
8. Restart the Windows CE device
ð After the restart is complete, the new version is active.
4 Technical Introduction
• Configuration of the "TwinCAT Database Server" is based on an XML file. This configuration file
describes the required "databases", ADS devices (e.g. PLC runtime systems), and variables.
Two storage methods:
- "Double" The compatible variable data types are: BOOL, LREAL, REAL, INT, DINT, USINT, BYTE,
UDINT, DWORD, UINT, WORD, SINT
- "Bytes" Compatible to all variable data types especially for strings and data structures
The central unit of the TwinCAT 3 Database Server is the XML-Configuration file editor from which all
needed options and configurations are made. The created Configuration could be used in two different
modes (AutoStart/Manual). The TwinCAT 3 Database Server is the connective link between the PLC and the
database.
The following synoptic shows various network topologies in which the TwinCAT Database Server can be
used.
Please refer to the associated information for more precise details regarding how your database server
needs to be configured.
5 Configuration
Description
New configuration file Creates an empty configuration file with default
settings.
Open Opens an existing XML configuration file.
Open from Targetsystem Opens an active XML configuration file from a target.
Save Saves all the changes that have been made, creating
a configuration file with the name:
"CurrentConfigDataBase.xml".
File Upload Uploading of the configuration file to the Database
Server, saves the configuration file at the specified
"Boot"-directory and activates the configuration.
New database Creates a new database configuration entry.
New ADS device Creates a new ADS device configuration entry.
New symbol group Creates a new symbol group configuration entry.
Copy Copies the selected configuration entry. This can be
a database, an ADS device or a symbol group.
Delete Deletes the selected configuration entry. This can be
a database, an ADS device or a symbol group.
Insert symbols TPY Imports symbols/variables from a TPY file into the
selected symbol group.
Insert symbols ROUTE Imports symbols/variables from a Runtime system of
a specified route.
SQL Query Editor Editor for generate SQL commands easily. Further
information here [} 34].
Live Status Shows the current state of the TF6420 Database
Server and start or stop the cyclic read/write function.
Error Log Shows the logged errors of the error logfile
"TcDBSrvErrorLog.txt"
Option dialog
This dialog can be used to set options for the TwinCAT Database Server:
• StartUp Option:
Two options are available.
"Manual" => TwinCAT Database Server is active and waiting for function calls from the PLC, with
the aid of function blocks from TcDatabase.lib.
"AutoStart" => TwinCAT Database Server is active and starts logging the set symbol groups as
soon as the TwinCAT system is in "RUN" mode.
ATTENTION: PLC programs from which variable values are to be logged must run as boot
projects!
• ErrorLog Option:
This option can be used to log errors in a text file. The logged errors can then be used for
troubleshooting. In addition, you can specify the path for the text file and the maximum file size. To
activate logging, the TcDBSrv configuration has to be reloaded onto the target system. For
performance reasons, this should be done explicitly. We also recommend that logging is deactivated
again after the error analysis, unless it is specifically still required.
• Impersonate Option:
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. For further
information see Impersonate [} 71]. This feature is currently not supported in Windows CE.
• Password:
The generated XML configuration file can be secured with a password. Before the file can be edited,
the user then has to enter the specified password.
The DBValueType indicates the data type of the "Value" column. PLC structures and strings cannot be
logged if the data type is "double". Structures and strings can be logged if the data type is "bytes".
You can choose if the database communication needs an authentication or not. If you want to add
authentication information, the fields DBSystemDB, DBUserId and DBPassword will be enable.
The field DBSystemDB is needed for Access databases only. In this field you have to write the path of the
MDW-file. In this file all information like usernames and passwords are saved.
DBUserId is the username and DBPassword is the necessary password.
If you choose ODBC-database types the input mask will be changed. Further information for the ODBC-
connection like Port, Protocol, Driver, Scheme and Sequence have to be insert.
This dialog also contains a symbol counter. It returns the number of symbols declared in the individual
groups. If more than 500 symbols are declared, the display turns red, as no more than 500 symbols/
variables may be declared for each symbol group.
If, due to the database settings, data types are not supported, these symbols are highlighted in red and a
warning message is displayed in the upper region.
Of course symbolrows could be copy and paste. You only have to select a row and click the right mouse
button. A context menu open and you can choose the desired function.
Import of symbols
It gives two possibilities to import symbols into the TwinCAT Database XML configurator. One way is to read
out the TPY file. The other way is directly from the target device with the Target Browser.
The Target Browse is used to add channels by a known Symbol to the configuration. The Target Browser is
separated in three parts. The left one shows a tree view with the root named ROUTES. Beneath all TwinCAT
System Manager known targets are listed. The color of the nodes explain the system state: Red= not
Connected (Stop-Mode), Blue= Config Mode, Green= Run Mode.
The second part contains a list view showing the details of the selected node in the tree view.
In the third part is a list view which show all choose symbols.
It is possible to add new ADS ports in the Target Browser. So it is realisable to log values directly from
EtherCAT terminals, if the ADS port is enabled in the TwinCAT System Manager under EtherCAT Device
Image.
Another possibility for this procedure is to activate the file with the help of the "Upload"-dialog. You only have
to choose the right ADS-device and start the upload procedure with the Upload button. The XML
configuration file will be uploaded to the TwinCAT Database Server, stored in the boot directory and reload
from the Database Server.
Attention: To use this service, the TwinCAT system has to be installed on the host PC where the XML-
configuration file editor runs. The host pc and the ADS-device has to be in RUN mode.
With the editor you are able to generate SQL commands and test them with standard PLC function blocks of
the TwinCAT Database Server. Additional it is possible to export the generated commands or structs to
TwinCAT. It is also possible to select, insert, delete datasets or create tables. The generated SQL
commands based of the database specific syntax. The different functionalities of the editor will be sent to the
configured database connections.
Menu Bar
Description
1 Target TwinCAT Database Server Choose the Target TwinCAT Database
Server for communication.
2 Database List of the configurated database connections
3 Table Tablenname for SQL command generating
4 Copy for PLC Copy the created SQL command with correct
PLC syntax into the clipboard
5 Export TC2 Create an export file for TwinCAT 2 for the
SELECT PLC struct
6 Export TC3 Create an export file for TwinCAT 3 for the
SELECT PLC struct
7 Get Tableschema Reads the table structure of the given table
8 Create Cmd Create SQL commands based of the different
database syntax
9 Execute Executes the SQL command
If all column values are insert, and the button "Create Cmd" would be clicked, the INSERT SQL command
will be created with the right database syntax. After that, you only have to press the "Execute" button to send
the command to the database. This operation will be execute internally with the function block
FB_DBRecordInsert_EX
DELETE Records
DELETE Tables
DB_TO_ADS:
With this write mode it is possible to read cyclic values out of a database and write them in variables in the
PLC.
ADS_TO_DB_APPEND:
With this write mode it is possible to write cyclic values from the PLC into a database. Each cycle a new
record is created and added to the end of the table / file.
ADS_TO_DB_UPDATE:
With this write mode values will be cyclically read out of the PLC. These values will be compared with the
records in the database. If the values differs the specified record will be updated with the new value.
ADS_TO_DB_RINGBUFFER:
With this write mode you can limit the count or the age of datasets on database tables.
This write mode is available for the cyclic logging with symbol groups and for logging with the function block
FB_DBWrite.
Every databasetype can be used with this write mode. Also logging in ASCII-files can be influenced with the
RingBufferMode.
"RingBuffer"-Versions:
The RingBuffer works in two different ways: - "RingBuffer_Time"
- "RingBuffer_Count"
RingBuffer "Time":
In this mode a timestamp can be set, this timestamp defines the maximum age of the datasets. If this age is
exceeded, the affected datasets will be deleted.
RingBuffer "Count":
In this mode a maximum count of datasets can be defined. If the maximum count is obtained, the old
datasets will be deleted to get space for new datasets.
RingBuffer_Count
RingBuffer_Count
On CE devices the configuration file is placed at the following folder "\Hard Disk\TwinCAT\Boot" (If you
change the XML-configuration file with the XML-configuration file editor, you have to copy this file back to the
folder "\Hard Disk\TwinCAT\Boot")
"FB_DBCyclicRdWrt"
All sections of the configuration file are needed for this function block.
Create the connection to the databases and the ADS-devices which are declared in the XML-configuration
file and the cyclic logging with all symbol groups will be started.
All other function blocks only needs the declared databases and ADS-devices of the configuration file. The
symbol groups will be ignored. You can see that at the following function block.
"FB_DBWrite"
A connection to the selected database (hDBID) and the selected ADS-device (hAdsID) will be created. After
this the variable which is indicated at the function block will be read out from the ADS-device and logged into
the database.
5.5 Databases
DBUrl DBUrl contains the path to the MDB file. e.g. ("C:
\TwinCAT\TcDatabaseSrv\Samples\TestDB.mdb")
DBTable: DBTable contains the name of the table.
WinCE Support: No
DBUrl DBUrl contains the path to the Excel file. e.g. ("C:
\TwinCAT\TcDatabaseSrv\Samples\TestDB.xls")
DBTable: DBTable contains the name of the table.
WinCE Support: No
ASCII - file
DBValueType: To limit logging to data types alphanumeric and
Boolean select "Double".
To also log structures and strings select "Bytes"
DBType: Select "ASCII". PLC: eDBType_ASCII.
DBServer: Not required.
DBProvider: Not required.
DBUrl DBUrl contains the path to the ASC, TXT or CSV file.
e.g. ("C:\TwinCAT\TcDatabaseSrv\Samples
\TestDB.asc")
DBTable: Not required. It is not possible to create tables in
ASCII files.
WinCE Support: Yes - local
NET-MySQL database
DBValueType: To limit logging to data types alphanumeric and
Boolean select "Double".
To also log structures and strings select "Bytes"
DBType: Select "NET_MySQL". PLC:
eDBType_NET_MySQL.
ODBC Driver: Not required.
Server name: Contains the name of the server or the IP address/
name of the host.
Database name: Contains the name of the database.
Port: Contains the port for the connection. (Standard 3306)
Protocol: Not required.
Scheme: Not required.
Sequence: Not required.
Table name: Contains the name of the table for writing or reading.
UserId: Contains the name of the user for logging into the
server.
Password: Contains the password to be used for authentication.
WinCE Support: Yes
ODBC-MySQL Database
DBValueType: To limit logging to data types alphanumeric and
Boolean select "Double".
To also log structures and strings select "Bytes"
DBType: Select "ODBC_MySQL". PLC:
eDBType_ODBC_MySQL.
ODBC Driver: Enter the name of the ODBC driver. ("MySQL ODBC
3.51 Driver")
Server name: Contains the name of the server or the IP address/
name of the host.
Database name: Contains the name of the database.
Port: Contains the port for connection of the ODBC driver.
Protocol: Not required.
Scheme: Not required.
Sequence: Not required.
Table name: Contains the name of the table for writing or reading.
UserId: Contains the name of the user for logging into the
server.
Password: Contains the password to be used for authentication.
WinCE Support: No
SQLite
DBValueType: To limit logging to data types alphanumeric and
Boolean select "Double".
To also log structures and strings select "Bytes"
DBType: Select "SQLite". PLC: eDBType_SQLite.
DBServer: Contains the name of the database.
DBProvider: Not required.
DBUrl DBUrl contains the path to the SQLite file. e.g. ("C:
\TwinCAT\TcDatabaseSrv\Samples\")
DBTable: DBTable contains the name of the table.
WinCE Support: Yes, but only for ARM-based devices!
XML database
DBValueType: To limit logging to data types alphanumeric and
Boolean select "Double".
To also log structures and strings select "Bytes"
DBType: Select "XML". PLC: eDBType_XML.
DBServer: Contains the name of the database.
DBProvider: Not required.
DBUrl DBUrl contains the path to the XML file. e.g. ("C:
\TwinCAT\TcDatabaseSrv\Samples\TestDB.xml")
The XSD file must be in same directory and have the
same file name. e.g. ("C:\TwinCAT\TcDatabaseSrv
\Samples\TestDB.xsd")
DBTable: DBTable contains the name of the table.
WinCE Support: Yes - local
Compatible versions: Microsoft SQL database 20xx. Declarations see "Declaration for different
databases" [} 44]
ValueType="Double"
Value float no
ValueType="Bytes"
Value varbinary no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the IDENTITY property possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
/*ValueType="Bytes"*/
CREATE TABLE myTable(
ID bigint IDENTITY(1,1) NOT NULL,
Timestamp datetime NOT NULL,
Name ntext NOT NULL,
Value varbinary NOT NULL
)
ValueType = "Double"
Value float no
ValueType = "Bytes"
Value image no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the IDENTITY property possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
/*ValueType = "Bytes"*/
CREATE TABLE myTable(
ID bigint IDENTITY(1,1) NOT NULL,
Timestamp datetime NOT NULL,
Name ntext NOT NULL,
Value image NOT NULL
)
ValueType="Double"
Value float no
ValueType="Bytes"
Value varbinary no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the IDENTITY property possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
/*ValueType="Bytes"*/
CREATE TABLE myTable(
ID bigint IDENTITY(1,1) NOT NULL,
Timestamp datetime NOT NULL,
Name ntext NOT NULL,
Value varbinary NOT NULL
)
Databasefiles of Access 2000 and Access 2003 (*.mdb) are as compatible as databasefiles of Access 2007
(*.accdb).
You only have to declare different provider in the XML - configuration file for these different filetypes. More
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column
The "Value" column stores the value of the variable.
For details re. MS Excel declaration see "Declaration for different databases" [} 44].
Attention
ValueType="Double"
Value DOUBLE no
ValueType="Bytes"
Value BLOB no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the IDENTITY property possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
ValueType="Double"
Value FLOAT no
ValueType="Bytes"
Value BLOB no
To get the functionality of an AutoID a sequence will be create at the scheme you use with the following
attributes:
typ: "ascending"
minimum: "1"
maximum: "1.0E27"
intervall: "1"
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the sequence possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
5.5.9 SQLite
SQLite
The values of the variables are saved in a SQLite database. SQLite is a compact database, which is ideal for
embedding in mobile applications. This file-based SQL database requires no installation, since it is already
integrated in the TwinCAT Database Server. The TwinCAT Database Server facilitates administration and
configuration. 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.
ValueType = "Double"
Value float no
ValueType = "Bytes"
Value image no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the IDENTITY property possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column
The "Value" column stores the value of the variable.
/*ValueType = "Bytes"*/
CREATE TABLE myTable(
ID bigint IDENTITY(1,1) NOT NULL,
Timestamp datetime NOT NULL,
Name ntext NOT NULL,
Value image NOT NULL
)
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
Important!
Do not save the database on the Compact Flash Card in case of an embedded system.
Either use the database in RAM, i.e. do not save to the "Hard disk" folder, or save on a network folder. To
many write cycles to the Compact Flash Card can shorten its service life.
<?xmlversion="1.0"encoding="UTF-8"?>
<TestDB_XMLxmlns:xs="http://www.w3.org/2001/XMLSchema-
instance"xs:noNamespaceSchemaLocation="TestDB_XML.xsd">
<myTable_Double>
<rowID="1"Timestamp="2012-03-08T12:45:08"Name="TestValue1"Value="222.222" />
<rowID="2"Timestamp="2012-03-08T12:45:14"Name="TestValue1"Value="222.222" />
<rowID="3"Timestamp="2012-03-08T12:45:18"Name="TestValue1"Value="222.222" />
<rowID="4"Timestamp="2012-03-08T12:45:22"Name="TestValue1"Value="222.222" />
<rowID="5"Timestamp="2012-03-08T12:45:23"Name="TestValue1"Value="222.222" />
</myTable_Double>
</TestDB_XML>
Table 1: The variable values are saved in the following table structure.
ValueType="Double"
ValueType="Bytes"
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
ValueType="Double"
ValueType="Bytes"
value BLOB no
To get the functionality of an AutoID a sequence will be create at the scheme you use with the following
attributes:
name: "mytable_ID_seq"
minimum: "1"
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the sequence possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
ValueType="Double"
Value DOUBLE no
ValueType="Bytes"
Value BLOB no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1. This functionality makes the IDENTITY property possible.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
ValueType="Double"
Value FLOAT no
ValueType="Bytes"
Value BLOB no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
ValueType="Double"
Value FLOAT no
ValueType="Bytes"
Value BLOB no
An AutoID is generated in the "ID" column. The value in this column is, in other words, always increased by
1.
The "Timestamp" column stores the time at which the data record was saved.
The name of the variable is stored in the "Name" column.
The "Value" column stores the value of the variable.
It is possible to suppress logging to the Windows Eventlog. Then no events will be logged at all. No
distinction can be made between the different types of event.
• Under SQL Server 2005 Services in the SQL Configuration Manager, select the SQL Server
(SQLEXPRESS) and right-click on Properties. On the Advanced tab there is a sub-item called "Startup
Parameters". The individual parameters are separated by semicolons. Add the parameter –n.
Thereafter restart the service.
From this point onwards no further events will be logged by the SQL Server.
2. Execute XPath queries at a XML file with the TF6420 Database Server
You can find further information about XML schema- here: http://www.w3.org/TR/xmlschema-0/
1. XML as Database
XSD-Schema for standard table structure
<?xmlversion="1.0"?>
<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:simpleTypename="bigint">
<xsd:restrictionbase="xsd:long" />
</xsd:simpleType>
<xsd:simpleTypename="datetime">
<xsd:restrictionbase="xsd:dateTime" />
</xsd:simpleType>
<xsd:simpleTypename="ntext_80">
<xsd:restrictionbase="xsd:string">
<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>
<rowID="1"Timestamp="2012-03-08T12:45:08"Name="TestValue1"Value="222.222" />
<rowID="2"Timestamp="2012-03-08T12:45:14"Name="TestValue1"Value="222.222" />
<rowID="3"Timestamp="2012-03-08T12:45:18"Name="TestValue1"Value="222.222" />
<rowID="4"Timestamp="2012-03-08T12:45:22"Name="TestValue1"Value="222.222" />
<rowID="5"Timestamp="2012-03-08T12:45:23"Name="TestValue1"Value="222.222" />
</myTable_Double>
</TestDB_XML>
<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>
<xsd:maxLengthvalue="1" />
</xsd:restriction>
</xsd:simpleType>
For creating data records it is possible to use standard SQL commands. The SQL INSERT commands will
be interpreted of the TwinCAT 3 Database Server and creates the specified XML-Nodes for the used XML
file. The SQL SELECT commands will be converted to XPath queries which will be executed at the used
XML file.
• FB_DBRecordSelect_EX
• FB_DBTableCreate
• FB_DBWrite
Samples
XML Datei:
<?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>
5.6 Expert
Since the TwinCAT Database Server runs as a system process, it has no access rights to the target device
for reading or writing. You can only get around this problem by granting the user "Guest" read and write
rights to the public folder. This method is very unsafe, however, because every user then has access rights
to this folder.
The safer way to do this is to use the "Impersonate" option, with which you can log onto this target device
with certain user data. The authentication data have to be saved in the registry, as shown in the picture
below.
->[HKEY_LOCAL_MACHINE\SOFTWARE\Beckhoff\TwinCAT3\System] "ImpersonatedPassword"
Contains the password for the authentication.
>[HKEY_LOCAL_MACHINE\SOFTWARE\Beckhoff\TwinCAT3\System] "ImpersonatedUserDomain"
Contains the name of the domain to which the user is logged on.
>[HKEY_LOCAL_MACHINE\SOFTWARE\Beckhoff\TwinCAT3\System] "ImpersonatedUserName"
Contains the name of the user.
• DataBases:
Configuration of all "databases" including SQL database, ASCII file, ...
• AdsDevices:
Configuration of all ADS devices (e.g. PLC runtime systems)
• SymbolGroups:
Grouping of different "symbols" (e.g. PLC variables) associated with an ADS device into a logical
group.
A logical group can be configured for transporting data:
- from a database to an ADS system,
- from an ADS device to a database.
<?xml version="1.0"?>
<Configuration>
<Log>1</Log>
<LogPath>C:\TwinCAT\TcDatabaseSrv</LogPath>
<StartUp>Manual</StartUp>
<PwdInfos>tZuYPxhe+G5NKHWLYSZE+NiFAINdlcBgtIUVD+j076ID3geO7FdGzvdfPl0Q09Zb2CKpwj=</PwdInfos>
<Databases>
<Database Type="Mobile-Server"ValueType="Double">
<DBId>1</DBId>
<DBServer />
<DBProvider />
<DBUrl>C:\TwinCAT\TcDatabaseSrv\Samples\TestDB_CompactSQL.sdf</DBUrl>
<DBSystemDB />
<DBUserId />
<DBTable>myTable</DBTable>
</Database>
</Databases>
<AdsDevices>
<AdsDevice>
<AdsId>1</AdsId>
<NetID>10.1.128.49.1.1</NetID>
<Port>801</Port>
<Timeout>2000</Timeout>
<ADSReadWriteSetting>1</ADSReadWriteSetting>
</AdsDevice>
</AdsDevices>
<SymbolGroups>
<SymbolGroup>
<Direction RingBuffMode="Count">ADS_to_DB_RINGBUFFER</Direction>
<RingBuffCount>20</RingBuffCount>
<CycleTime>30000</CycleTime>
<AdsId>1</AdsId>
<DBId>1</DBId>
<Symbols>
<Symbol>
<DBName>TESTVAR123</DBName>
<Name>MAIN.TESTVAR123</Name>
<Type>LREAL</Type>
<IGroup>16448</IGroup>
<IOffset>172536</IOffset>
<BitSize>64</BitSize>
<DBLogMode>3</DBLogMode>
</Symbol>
</Symbols>
</SymbolGroup>
</SymbolGroups>
</Configuration>
Tag „Log“:
Additional option: You can activate the error log mode for tests, to log occurred error descriptions into a text
file "TcDBSrvErrorlog.txt".
Tag „LogPath“:
Additional option: For tests it is possible to activate the error log mode see tag "Log". The path of the text file
is declared in this tag.
Tag „Impersonate“:
Additional option: To activate the "Impersonate" - option you have to add this tag.
"StartUp" tag:
Start mode setting.
"Autostart" option: The server starts immediately with tasks specified in the configuration file (e.g. writing of
ADS data into the database).
"Manual" option: The server initially remains passive and is triggered via the "FB_DBCyclicRdWrt" function
block.
"PwdInfos" tag:
Contains all passwords which are needed for the communication with the databases. All passwords are
crypted and consequently nonreadable.
"Databases" tag:
Configuration of the individual databases:
"AdsDevices" tag:
Declaration of ADS devices. Each runtime system is assigned a unique ID. The ADS devices are identified
through NetID, port and timeout.
"SymbolGroups" tag:
Definition of symbol groups: Specifies which database is linked with which ADS device. In addition the
direction of the data flow is specified (from the TwinCAT system to the database or from the database to the
TwinCAT system).
The cycle time determines at which intervals data are read from the database or written to the database.
"Symbol" tag:
Definition of the individual symbols with the following parameters:
DBName: Symbol name used in the database
Name: Symbol name used in the PLC
Optional: Type: Data type of the symbol
Optional: IGroup / IOffset: Storage location of the symbol
Optional: BitSize: Size of the symbol
DBLogMode: Optional: Specifies whether the symbols are checked cyclically or after a change.
6 API
6.1.1 Tc2_Database
Overview
The Tc2_Database library contains function blocks for controlling and configuring the TC3 Database Server.
Function Blocks
Name Description
FB_GetStateTcDatabase [} 78] Call state information
Data Types
Name
ST_DBColumnCfg [} 106]
ST_DBXMLCfg [} 106]
ST_ADSDevXMLCfg [} 107]
ST_DBSQLError [} 107]
ST_DBParameter [} 108]
E_DbColumnTypes [} 108]
E_DBTypes [} 109]
E_DBValueType [} 109]
E_DBWriteModes [} 109]
E_DBParameterTypes [} 110]
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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 : Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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: Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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 : Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.4 FB_DBOdbcConnectionAdd
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: Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.5 FB_AdsDeviceConnectionAdd
VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetID;
sADSDevNetID : T_AmsNetID;
nADSDevPort : UINT;
tADSDevTimeout : TIME;
bExecute : BOOL;
tTimeout : TIME;
END_VAR
sNetID: Is a string containing the AMS network identifier of the target device to which the ADS command is
directed.
sADSDevNetID: Is a string containing the AMS network identifier of the added Ads-device.
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: Supplies the ADS Error Code when the bError output is set.
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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 : Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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 : Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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 : Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState : Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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 : Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.10 FB_DBCreate
The FB_DBCreate function block allows databases to be created. This block can be used to create 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: Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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: Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState : Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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: Is a string containing the AMS network identifier of the target device to which the ADS command is
directed.
bExecute: A rising edge starts the read/write cycle, while a falling edge stops it.
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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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: Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.14 FB_DBWrite
The FB_DBWrite function block can be used to write the values of individual variables into databases.
The table structure have to contain the columns "Timestamp", "Name" and "Value". see SQL Compact
Database [} 52]. To use the function block, you have to declare the required database and ADS device 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: Is a string containing the AMS network identifier of the target device to 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 datasets or whether the existing
datasets are to be updated.
tRingBufferTime: Indicates the maximum age of datasets in a table. (only for Ringbuffer_WriteMode)
nRingBufferCount: Indicates the maximum number of datasets 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.15 FB_DBRecordDelete
The function block FB_DBRecordDelete can be used to delete individual datasets from a database. This
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 datasets 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: Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.16 FB_DBRecordInsert_EX
The FB_DBRecordInsert_EX function block allows individual data records to be written into a database. The
length of the SQL - command could be till 10000 symbols. For using this function block you have to declare
the database, you want to write to, 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: Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.17 FB_DBRecordArraySelect
The FB_DBRecordArraySelect allows some individual data records to be read from a database. The length
of the SQL-command could be till 10000 Symbols.
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: Is a string containing the AMS network identifier of the target device to 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 datasets are to be written.
VAR_OUTPUT
VAR_OUTPUT
bBusy : BOOL;
bError : BOOL;
nErrID : UDINT;
sSQLState: ST_DBSQLError;
nRecords : UDINT;
END_VAR
ST_DBSQLError [} 107]
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 [} 155] 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 datasets are to be read has the following structure (see table),
The library TcUtilities.lib must be integrated in order to be able to use the data type T_ULARGE_INTEGER.
For ARM processors the data types have to be arranged differently due to the byte alignment, and a "dummy
byte" has to be added.
TYPE ST_Record :
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Value : LREAL;
Name : STRING(80);
Dummy : BYTE;
END_STRUCT
END_TYPE
PROGRAM MAIN
VAR
FB_DBRecordArraySelect1 : FB_DBRecordArraySelect;
cmd : T_Maxstring := 'SELECT * FROM myTable';
(* Unter ARM*)
(*cmd : T_Maxstring := 'SELECT ID,Timestamp,Value,Name FROM myTable'*)
(*----------*)
recordArray : ARRAY [1..5] OF ST_Record;
busy : BOOL;
err : BOOL;
errid : UDINT;
sqlstate : ST_DBSQLError;
recAnz : UDINT;
END_VAR
PLC program
FB_DBRecordArraySelect1(
sNetID:= ,
hDBID:= 1,
cbCmdSize:= SIZEOF(cmd),
pCmdAddr:= ADR(cmd),
nStartIndex:= 0,
nRecordCount:= 5,
cbRecordArraySize:= SIZEOF(recordArray),
pDestAddr:= ADR(recordArray),
bExecute:= TRUE,
tTimeout:= T#15s,
bBusy=> busy,
bError=> err,
nErrID=> errid,
sSQLState=> sqlstate,
nRecords=> recAnz);
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.18 FB_DBStoredProcedures
With this function block FB_DBStoredProcedures you are able to start stored procedures. It is possible to
declare parameters which will be 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: Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.19 FB_DBStoredProceduresRecordArray
The function block FB_DBStoredProceduresRecordArray can be used to call stored procedures for returning
datasets. In contrast to the FB_DBStoredProceduresRecordReturn block, this block can be used to return
several datasets 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: Is a string containing the AMS network identifier of the target device to which the ADS command is
directed.
pDestAddr: Indicates the address of the structure array into which the datasets 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.20 Obsolete
6.1.2.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: Is a string containing the AMS network identifier of the target device to 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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.20.2 FB_DBRecordInsert
The FB_DBRecordInsert function block allows individual data records to be written into a database. For
using this function block you have to declare the database, you want to write to, in the XML - configuration
file.
VAR_INPUT
VAR_INPUT
sNetID : T_AmsNetId;
hDBID : UDINT;
sInsertCmd: T_MaxString;
bExecute : BOOL;
tTimeout : TIME;
END_VAR
sNetID: Is a string containing the AMS network identifier of the target device to 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.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: Is a string containing the AMS network identifier of the target device to which the ADS command is
directed.
pDestAddr: Indicates the address of the structure to which the data set 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Sample in ST:
Since the table from which the data set is to be read has the following structure (see table),
The library TcUtilities.lib must be integrated in order to be able to use the data type T_ULARGE_INTEGER.
For ARM processors the data types have to be arranged differently due to the byte alignment, and a "dummy
byte" has to be added.
TYPE ST_Record :
STRUCT
ID : T_ULARGE_INTEGER;
Timestamp: DT;
Value : LREAL;
Name : STRING;
Dummy : BYTE;
END_STRUCT
END_TYPE
PROGRAM MAIN
VAR
FB_DBRecordSelect1: FB_DBRecordSelect;
cmd : T_Maxstring := 'SELECT * FROM myTable';
(* Unter ARM*)
(*cmd : T_Maxstring := 'SELECT ID,Timestamp,Value,Name FROM myTable'*)
(*----------*)
record : ST_Record;
busy : BOOL;
err : BOOL;
errid : UDINT;
recAnz : DINT;
END_VAR
PLC program
FB_DBRecordSelect1(
sNetID := ,
hDBID := 2,
sSelectCmd := cmd,
nRecordIndex:= 0,
cbRecordSize:= SIZEOF(record),
pDestAddr := ADR(record),
bExecute := TRUE,
tTimeout := T#15s,
bBusy => busy,
bError => err,
nErrID => errid,
nRecords => recAnz);
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.20.4 FB_DBRecordSelect_EX
The FB_DBRecordSelect_EX allows individual data records to be read from a database. The length of the
SQL-command could be till 10000 Symbols.
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: Is a string containing the AMS network identifier of the target device to 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 data set 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.2.20.5 FB_DBStoredProceduresRecordReturn
With this function block FB_DBStoredProcedures you are able to start stored procedures which return a data
record. It is possible to declare parameters which will be 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: Is a string containing the AMS network identifier of the target device to which the ADS command is
directed.
pRecordAddr: Indicates the address of the structure to which the data set 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 [} 155] if the bError output is set.
sSQLState: Returns the SQL error code [} 107] of the corresponding database type
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.1 ST_DBColumnCfg
VAR_INPUT
TYPE ST_DBColumnCfg :
STRUCT
sColumnName : STRING(59);
sColumnProperty: STRING(59);
eColumnType : E_DbColumnTypes;
END_STRUCT
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.2 ST_DBXMLCfg
VAR_INPUT
TYPE ST_DBXMLCfg :
STRUCT
sDBName : STRING;
sDBTable: STRING;
nDBID : DINT;
eDBType : E_DBTypes;
END_STRUCT
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.3 ST_ADSDevXMLCfg
VAR_INPUT
TYPE ST_ADSDevXMLCfg :
STRUCT
sAdsDevNetID : T_AmsNetID;
tAdsDevTimeout: TIME;
nAdsDevID : DINT;
nAdsDevPort : UINT;
END_STRUCT
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.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,
eDBType_NET_MySQL := 12
);
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.8 E_DBValueType
TYPE E_DBValueType :
(
eDBValue_Double:= 0,
eDBValue_Bytes := 1
);
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.9 E_DBWriteModes
TYPE E_DBWriteModes :
(
eDBWriteMode_Update := 0,
eDBWriteMode_Append := 1,
eDBWriteMode_RingBuffer_Time := 2,
eDBWriteMode_RingBuffer_Count:= 3
);
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.3.10 E_DBParameterTypes
TYPE E_DBParameterTypes :
(
eDBParameter_Input := 0,
eDBParameter_Output := 1,
eDBParameter_InputOutput := 2,
eDBParameter_ReturnValue := 3,
eDBParameter_OracleCursor:= 4
);
END_TYPE
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
6.1.4.1 Constants
VAR_GLOBAL_CONSTANT
AMSPORT_DATABASESRV : UINT := 21372;
END_VAR
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
Global_Version
VAR_GLOBAL CONSTANT
stLibVersion_TC3_Database_Server : ST_LibVersion;
END_VAR
To compare the existing version to a required version the function F_CmpLibVersion (defined in Tc2_System
library) is offered.
7 Samples
All sample applications for the TwinCAT 3 Database Server were consolidated in a solution. The solution can
be downloaded here from a central location:
TcDBSrv_InfoSysSamples.zip
In addition to the tszip 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 adapted individually with
the configurator.
In addition to the individual samples, there is a Quick Start [} 112] guide for the TwinCAT Database Server.
Two options are available for configuring the TwinCAT Database Server:
• with the TwinCAT Database Server XML configuration file editor [} 113]
• from the PLC [} 120]
2. Add a new database by right-clicking on “Database / Add Database” or the corresponding icon in the
toolbar.
3. Configure your database by selecting the type (in this example DBType ASCII). The declarations for all
supported database types can be found in the information system.
4. If only alphanumeric and Boolean data types are to be logged, select DBValueType "Double", if
structures and strings are to be logged select "Bytes".
5. Under “Database URL” enter the path for the database (this is sufficient for an ASCII database). Later
you will need the database ID (DBID), which can be found here.
6. Add an AdsDevice and enter your AdsNetID (not required if you use a local system) and your AdsPort.
Later you will need the AdsID, which can be found here. To create a configuration for a remote system,
select the required system from the table on the right.
7. Add a symbol group with the variables from your PLC project.
8. Before you can configure your symbol groups you have to compile your PLC project. To this end open
TwinCAT PLC Control with the file PLCVariableSample.pro and then select Project -> Compile. This is
important for creation of the TPY file.
9. In the database editor use the "Import Symbols" button to look for variables.
10. For the example select the first five variables from the icon collection. You can change the LogMode for
each variable. Now set the AdsID and the DBID, as described above.
12. To use the Database Server without the PLC (only PLC variables are logged), the option AutoStart must
be set. In this case the Database Server starts configuring the connections to the declared databases
and ADS devices directly after a TwinCAT start.
To this end you must have generated a boot project via the program "PLCVariableSample.pro", and the
generated configuration must be saved in directory "C:\TwinCAT\Boot".
13. To test the configuration enter PLC Control and start the PLC. Generate a boot project and restart
TwinCAT. Now examine the test database "TestDB" under "C:\TwinCAT\TcDatabaseSrv\Samples".
16. declare all other required variables, particularly the table structure. Relevant instructions for the
Microsoft Access database can be found in the information system.
An AutoID is generated in the "ID" column. The value in this column is always incremented by 1. The
"Timestamp" column contains the time at which the data set was stored. The name of the variable is
stored in the third column. Under "Value" you can find the variable value. The variables that are familiar
from the next image can be used.
17. FB_DBCreate:
Add the FB_DBCreate in status number 1. The path to the database must be transferred to the function
block.
NOTE! Ensure that the database does not yet exist at this stage. Otherwise an error message is
issued.
In status 11 you have to wait until the output "bBusy" is no longer TRUE.
18. FB_DBConnectionAdd:
In this function block enter the DBType and the DBValueType (bytes or double). Enter a name for your
table. Refer to the image for the other settings for Access databases.
19. FB_DBTableCreate:
One of the inputs for the function block is "hDBID". For this input enter the value received from
FB_DBConnectionAdd. Enter the size and the address of the table structure.
20. FB_DBWrite:
FB_DBWrite can be used to write the current variable value "iLogVariable" into the database at any
time. Please note that only 100 variable values are stored if the nRingBufferCount is set to 100.
ð At the end of the program code you can see how the variable is incremented by 1 for each PLC cycle.
CAUTION
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
Download: TcDBSrv_InfoSysSamples.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);
END_IF
3:
(*The FB_DBConnectionAdd adds the connection information to the
XML configuration file*)
FB_DBConnectionAdd1(
sNetID := ,
eDBType := eDBType_Access,
eDBValueType:= eDBValue_Double,
sDBServer := ,
sDBProvider := 'Microsoft.Jet.OLEDB.4.0',
sDBUrl := 'C:\TwinCAT\TcDatabaseSrv\Samples\TestDB1000SPS.mdb',
sDBTable := 'myTable',
bExecute := TRUE,
tTimeout := T#15s,
bBusy => bBusy_ConnAdd,
bError => bErr,
nErrID => nErrid,
hDBID => nDBid);
In order to use this sample, you only need to transfer the NetID of the ADS device (on which the TwinCAT
Database Server is installed) to the sNetID input.
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
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 rising edge at the bExecute input.
A falling edge will end the process again.
ST_MyStruct structure
TTYPE ST_MyStruct :
STRUCT
iValue1 : INT;
iValue2 : UINT;
iValue3 : BOOL;
iValue4 : REAL;
END_STRUCT
END_TYPE
Variable Declaration
PROGRAM MAIN
VAR
fbDBCyclicRdWrt1: FB_DBCyclicRdWrt;
bCyclic : BOOL :=TRUE;
bBusy_Cyclic : BOOL;
bErr : BOOL;
nErrID : UDINT;
sSQLState : ST_DBSQLError;
END_VAR
PLC program
DataTypes;
fbDBCyclicRdWrt(
sNetID := ,
bExecute := bCyclic,
tTimeout := t#15s,
bBusy => bBusy_Cyclic,
bError => bErr,
nErrID => nErrID,
sSQLState => sSQLState);
In order to use this sample, you only need to transfer the NetID of the ADS device (on which the TwinCAT
Database Server is installed) to the sNetID input.
When you run the program and set the bCyclic variable to TRUE, all the variables that are declared in the
symbol group of the XML configuration file are logged.
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
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). Also, please 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 rising 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
SPS Programm
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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
Variable Declaration
(* Declaration *)PROGRAMMAIN
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);
(*Create the SQL-INSERT command*)
FB_FormatString1(
sFormat := 'INSERT INTO tbl_Test VALUES($'%S$',%F,%F,%F,$'%S$')',
arg1 := F_STRING(sDateTimeString),
arg2 := F_REAL(TestValue1),
arg3 := F_REAL(TestValue2),
arg4 := F_REAL(TestValue3),
arg5 := F_STRING(TestValue4),
sOut => sInsertString,
bError => bError,
nErrId => nErrid);
(*Write the record to the database*)
FB_DBRecordInsert1(
sNetID := ,
hDBID := 1,
sInsertCmd:= sInsertString,
bExecute := bStartstopInsert,
tTimeout := T#15s,
bBusy => bBusyInsert,
bError => bErrInsert,
nErrID => nErridInsert,
sSQLState => stSQLStateInsert);
eSQL_SELECT:
(*Read one record from the database*)
FB_DBRecordSelect1(
sNetID := ,
hDBID := 1,
sSelectCmd:= 'SELECT * FROM tbl_Test',
nRecordIndex:= nRecIndex,
cbRecordSize:= SIZEOF(stRecord),
pDestAddr := ADR(stRecord),
bExecute := bStartstopSelect,
tTimeout := T#15s,
bBusy => bBusySelect,
bError => bErrorSelect,
nErrID => nErrIDSelect,
sSQLState => stSQLStateSelect,
nRecords => nRecordCount);
END_CASE
To use this sample, you have to declare the Access database "Sample7.mdb" in the XML configuration file.
A data set with the four PLC values and the timestamp is created in the database by generating a positive
edge at the variable "bStartstopInsert".
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
Download: TcDBSrv_InfoSysSamples.zip
The following sample illustrates the call in a simple stored procedure with an input parameter and return data
set. 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,
Visualization
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
This sample demonstrates how an XML database is created, filled with the block FB_DBWrite and
subsequently read with an SQL SELECT command and the FB_DBRecordSelect block.
Download: TcDBSrv_InfoSysSamples.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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
Download: TcDBSrv_InfoSysSamples.zip
<Employe_Count>6</Employe_Count>
<Manager>Max Mustermann</Manager>
</Factory_Info>
<Employees>
<Employeeid="10001" name="Julia Kingston" department="Development" position="Worker"
hired="2001-08-01" />
<Employeeid="10002" name="Jens Marx" department="Import" position="Worker" hired="2003-08-01" />
<Employeeid="10003" name="Justus Kaiser" department="Export" position="Worker" hired="2003-08-01" />
<Employeeid="10004" name="Marc Klein" department="Production" position="Worker" hired="2005-08-01" /
>
<Employeeid="10005" name="Matt Bloomberg" department="Production" position="Worker"
hired="2005-08-01" />
<Employeeid="10006" name="Frida Hundt" department="Production" position="Worker"
hired="2010-08-01" />
</Employees>
</Factory_XY>
ST_FactoryInfo structure
TYPEST_FactoryInfo :
STRUCT
sStreet : T_MaxString;
sCity : T_MaxString;
sCountry : T_MaxString;
sOffice_Count : T_MaxString;
sEmploye_Count: T_MaxString;
sManager : T_MaxString;
END_STRUCT
END_TYPE
ST_Employee structure
TYPEST_Employee :
STRUCT
sID : T_MaxString;
sName : T_MaxString;
sDepartment : T_MaxString;
sPosition : T_MaxString;
sHired : T_MaxString;
END_STRUCT
END_TYPE
MAIN program
PROGRAMMAIN
VAR
bSTART : BOOL;
R_TRIG1 : R_TRIG;
nState : INT;
R_TRIG1(CLK:=bSTART);
IF R_TRIG1.Q THEN
bSTART:=FALSE;
fbDBRecordArraySelect(bExecute:=FALSE);
nState:=1;
END_IFCASE nState OF
0://IDLE
;
1://Read Factory Name
sXPath:= 'XPATH#Factory_XY/Name';
fbDBRecordArraySelect(
sNetID := ,
hDBID := 7,
pCmdAddr := ADR(sXPath),
cbCmdSize := SIZEOF(sXPath),
nStartIndex := 0,
nRecordCount := 1,
pDestAddr := ADR(sFactoryName),
cbRecordArraySize:= SIZEOF(sFactoryName),
bExecute := TRUE,
tTimeout := T#15S,
bBusy => bBusy_ReadFactoryName,
bError => bError_ReadFactoryName,
nErrID => nErrID_ReadFactoryName,
sSQLState => stSQLState,
nRecords => );
IF NOT bBusy_ReadFactoryName THEN
fbDBRecordArraySelect(bExecute:=FALSE);
IF NOT bError_ReadFactoryName THEN
nState :=2;
ELSE
nState :=255;
END_IFEND_IF
2://Read Factory Info
sXPath := 'XPATH#Factory_XY/Factory_Info';
fbDBRecordArraySelect(
sNetID := ,
hDBID := 7,
pCmdAddr := ADR(sXPath),
cbCmdSize := SIZEOF(sXPath),
nStartIndex := 0,
nRecordCount := 1,
pDestAddr := ADR(stFactoryInfo),
cbRecordArraySize := SIZEOF(stFactoryInfo),
bExecute := TRUE,
tTimeout := T#15S,
bBusy => bBusy_ReadFactoryInfo,
bError => bError_ReadFactoryInfo,
nErrID => nErrID_ReadFactoryInfo,
sSQLState => stSQLState,
nRecords => );
IF NOT bBusy_ReadFactoryInfo THEN
fbDBRecordArraySelect(bExecute:=FALSE);
IF NOT bError_ReadFactoryInfo THEN
nState :=3;
ELSE
nState :=255;
END_IF
END_IF
3://Read Employees
sXPath := 'XPATH#Factory_XY/Employees/Employee';
fbDBRecordArraySelect(
sNetID := ,
hDBID := 7,
pCmdAddr := ADR(sXPath),
cbCmdSize := SIZEOF(sXPath),
nStartIndex := 0,
nRecordCount := 10,
pDestAddr := ADR(aEmployees),
cbRecordArraySize := SIZEOF(aEmployees),
bExecute := TRUE,
tTimeout := T#15S,
bBusy => bBusy_ReadEmployee,
bError => bError_ReadEmployee,
nErrID => nErrID_ReadEmployee,
sSQLState => stSQLState,
nRecords => );
IF NOT bBusy_ReadEmployee THEN
fbDBRecordArraySelect(bExecute:=FALSE);
IF NOT bError_ReadEmployee THEN
nState :=0;
ELSE
nState :=255;
END_IFEND_IF
255://Error State
;
END_CASE
A positive edge at the variable "bStart" triggers issuing of the XPath commands and reading of the individual
elements from the XML file. The results will then be in the variables "sFactoryName", "stFactoryInfo" and
"aEmployees".
Requirements
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
In this sample, FB_DBRecordArraySelect is used to read two different subtags from an XML file with
corresponding XML schema.
Download: TcDBSrv_InfoSysSamples.zip
Structure 1 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
Structure 2 ST_TestStruct2
TYPE ST_TestStruct2 :
STRUCT
sSTRING: T_MaxString;
bBOOL : BOOL;
nINT32 : DINT;
END_STRUCT
END_TYPE
MAIN program
PROGRAMMAIN
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
Development environment Target system type PLC libraries to be linked
TwinCAT v3.0.0 PC or CX (x86) Tc2_Database
8 Appendix
8.1 Errorcodes
If an error occurs at executing an SQL statement, one of the declared errorcodes from the top of this site will
be displayed at the output "nErrID". The specified errorcode of the database will be displayed at the
"sSQLState" Output of the function block. The output "sSQLState" has the data type ST_DBSQLError [} 107].
The "sSQLState" can supply an errorcode for each database type.
At the following link you can find a list of SQLStates und their discribtion: http://msdn.microsoft.com/en-us/
library/ms714687(VS.85).aspx (SQLStates)
HRESULT Describtion
0x80040E00 Invalid accessor
0x80040E01 Creating another row would have exceeded the total
number of active rows supported by the rowset
0x80040E02 Unable to write with a read-only accessor
0x80040E03 Given values violate the database schema
0x80040E04 Invalid row handle
0x80040E05 An object was open
0x80040E06 Invalid chapter
0x80040E07 A literal value in the command could not be
converted to the correct type due to a reason other
than data overflow
0x80040E08 Invalid binding info
0x80040E09 Permission denied
0x80040E0A Specified column does not contain bookmarks or
chapters
0x80040E0B Some cost limits were rejected
0x80040E0C No command has been set for the command object
0x80040E0D Unable to find a query plan within the given cost limit
0x80040E0E Invalid bookmark
0x80040E0F Invalid lock mode
0x80040E10 No value given for one or more required parameters
0x80040E11 Invalid column ID
0x80040E12 Invalid ratio
0x80040E13 Invalid value
0x80040E14 The command contained one or more errors
0x80040E15 The executing command cannot be canceled
0x80040E16 The provider does not support the specified dialect
0x80040E17 A data source with the specified name already exists
0x80040E18 The rowset was builtover a live data feed and cannot
be restarted
0x80040E19 No key matching the described characteristics could
be found within the current range
0x80040E1A Ownership of this tree has been given to the provider
0x80040E1B The provider is unable to determine identity for newly
inserted rows
0x80040E1C No nonzero weights specified for any goals
supported, so goal was rejected; current goal was not
changed
0x80040E1D Requested conversion is not supported
0x80040E1E lRowsOffset would position you past either end of the
rowset, regardless of the cRows value specified;
cRowsObtained is 0
0x80040E1F Information was requested for a query, and the query
was not set
0x80040E20 Provider called a method from IRowsetNotify in the
consumer and NT
0x80040E21 Errors occurred
0x80040E22 A non-NULL controlling IUnknown was specified and
the object being created does not support
aggregation
0x80040E23 A given HROW referred to a hard- or soft-deleted row
0x80040E24 The rowset does not support fetching backwards
HRESULT Describtion
0x80040E25 All HROWs must be released before new ones can
be obtained
0x80040E26 One of the specified storage flags was not supported
0x80040E27 The comparison operator was invalid
0x80040E28 The specified status flag was neither
DBCOLUMNSTATUS_OK nor
DBCOLUMNSTATUS_ISNUL
0x80040E29 The rowset cannot scroll backwards
0x80040E2A Invalid region handle
0x80040E2B The specified set of rows was not contiguous to or
overlapping the rows in the specified watch region
0x80040E2C A transition from ALL* to MOVE* or EXTEND* was
specified
0x80040E2D The specified region is not a proper subregion of the
region identified by the given watch region handle
0x80040E2E The provider does not support multi-statement
commands
0x80040E2F A specified value violated the integrity constraints for
a column or table
0x80040E30 The given type name was unrecognized
0x80040E31 Execution aborted because a resource limit has been
reached; no results have been returned
0x80040E32 Cannot clone a command object whose command
tree contains a rowset or rowsets
0x80040E33 Cannot represent the current tree as text
0x80040E34 The specified index already exists
0x80040E35 The specified index does not exist
0x80040E36 The specified index was in use
0x80040E37 The specified table does not exist
0x80040E38 The rowset was using optimistic concurrency and the
value of a column has been changed since it was last
read
0x80040E39 Errors were detected during the copy
0x80040E3A A specified precision was invalid
0x80040E3B A specified scale was invalid
0x80040E3C Invalid table ID
0x80040E3D A specified type was invalid
0x80040E3E A column ID was occurred more than once in the
specification
0x80040E3F The specified table already exists
0x80040E40 The specified table was in use
0x80040E41 The specified locale ID was not supported
0x80040E42 The specified record number is invalid
0x80040E43 Although the bookmark was validly formed, no row
could be found to match it
0x80040E44 The value of a property was invalid
0x80040E45 The rowset was not chaptered
0x80040E46 Invalid accessor
0x80040E47 Invalid storage flags
0x80040E48 By-ref accessors are not supported by this provider
0x80040E49 Null accessors are not supported by this provider
HRESULT Describtion
0x80040E4A The command was not prepared
0x80040E4B The specified accessor was not a parameter
accessor
0x80040E4C The given accessor was write-only
0x80040E4D Authentication failed
0x80040E4E The change was canceled during notification; no
columns are changed
0x80040E4F The rowset was single-chaptered and the chapter
was not released
0x80040E50 Invalid source handle
0x80040E51 The provider cannot derive parameter info and
SetParameterInfo has not been called
0x80040E52 The data source object is already initialized
0x80040E53 The provider does not support this method
0x80040E54 The number of rows with pending changes has
exceeded the set limit
0x80040E55 The specified column did not exist
0x80040E56 There are pending changes on a row with a reference
count of zero
0x80040E57 A literal value in the command overflowed the range
of the type of the associated column
0x80040E58 The supplied HRESULT was invalid
0x80040E59 The supplied LookupID was invalid
0x80040E5A The supplied DynamicErrorID was invalid
0x80040E5B Unable to get visible data for a newly-inserted row
that has not yet been updated
0x80040E5C Invalid conversion flag
0x80040E5D The given parameter name was unrecognized
0x80040E5E Multiple storage objects can not be open
simultaneously
0x80040E5F The requested filter could not be opened
0x80040E60 The requested order could not be opened
0x80040E61 Bad tuple
0x80040E62 Bad coordinate
0x80040E63 The given axis was not valid for this Dataset
0x80040E64 One or more of the given cell ordinals was invalid
0x80040E65 The supplied columnID was invalid
0x80040E67 The supplied command does not have a DBID (Note:
DBID is SQL shorthand for Database ID.)
0x80040E68 The supplied DBID already exists
0x80040E69 The maximum number of Sessions supported by the
provider has already been created. The consumer
must release one or more currently held Sessions
before obtaining a new Session object
0x80040E72 The index ID is invalid
0x80040E73 The initialization string does not conform to
specification
0x80040E74 The OLE DB root enumerator did not return any
providers that matched an of the SOURCES_TYPEs
requested
0x80040E75 The initialization string specifies a provider which
does not match the currently active provider.
HRESULT Describtion
0x80040E76 The specified DBID is invalid
0x80040E6A Invalid trustee value
0x80040E6B The trustee is not for the current data source
0x80040E6C The trustee does not support memberships/
collections
0x80040E6D The object is invalid or unknown to the provider
0x80040E6E No owner exists for the object
0x80040E6F The access entry list supplied is invalid
0x80040E70 The trustee supplied as owner is invalid or unknown
to the provider
0x80040E71 The permission supplied in the access entry list is
invalid
0x80040E77 The ConstraintType was invalid or not supported by
the provider.
0x80040E78 The ConstraintType was not
CONSTRAINTTYPE_FOREIGNKEY and
cForeignKeyColumns was not zero
0x80040E79 The Deferrability was invalid or the value was not
supported by the provider
0x80040E80 The MatchType was invalid or the value was not
supported by the provider
0x80040E8A The UpdateRule or DeleteRule was invalid or the
value was not supported by the provider
0x80040E8B The pConstraintID did not exist in the data source
0x80040E8C The dwFlags was invalid
0x80040E8D The rguidColumnType pointed to a GUID that does
not match the object type of this column or this
column was not set
0x80040E8E The requested URL was out-of-scope
0x80040E90 The provider could not drop the object
0x80040E91 There is no source row
0x80040E92 The OLE DB object represented by this URL is
locked by one or more other processes
0x80040E93 The client requested an object type that is only valid
for a collection
0x80040E94 The caller requested write access to a read-only
object
0x80040E95 The provider could not connect to the server for this
object
0x80040E96 The provider could not connect to the server for this
object
0x80040E97 The attempt to bind to the object timed out
0x80040E98 The provider was unable to create an object at this
URL because an object named by this URL already
exists
0x80040E99 The provider could not drop the object
0x80040E9A The provider was unable to create an object at this
URL because the server was out of physical storage
0x00040EC0 Fetching requested number of rows would have
exceeded total number of active rows supported by
the rowset
0x00040EC1 One or more column types are incompatible;
conversion errors will occur during copying
HRESULT Describtion
0x00040EC2 Parameter type information has been overridden by
caller
0x00040EC3 Skipped bookmark for deleted or non-member row
0x00040EC4 Errors found in validating tree
0x00040EC5 There are no more rowsets
0x00040EC6 Reached start or end of rowset or chapter
0x00040EC7 The provider re-executed the command
0x00040EC8 Variable data buffer ful
0x00040EC9 There are no more results
0x00040ECA Server cannot release or downgrade a lock until the
end of the transaction
0x00040ECB Specified weight was not supported or exceeded the
supported limit and was set to 0 or the supported limit
0x00040ECC Consumer is uninterested in receiving further
notification calls for this reason
0x00040ECD Input dialect was ignored and text was returned in
different dialect
0x00040ECE Consumer is uninterested in receiving further
notification calls for this phase
0x00040ECF Consumer is uninterested in receiving further
notification calls for this reason
0x00040ED0 The operation is being processed asynchronously
0x00040ED1 In order to reposition to the start of the rowset, the
provider had to reexecute the query; either the order
of the columns changed or columns were added to or
removed from the rowset
0x00040ED2 The method had some errors; errors have been
returned in the error array
0x00040ED3 Invalid row handle
0x00040ED4 A given HROW referred to a hard-deleted row
0x00040ED5 The provider was unable to keep track of all the
changes; the client must refetch the data associated
with the watch region using another method
0x00040ED6 Execution stopped because a resource limit has been
reached; results obtained so far have been returned
but execution cannot be resumed
0x00040ED7 The bind failed because the provider was unable to
satisfy all of the bind flags or properties
0x00040ED8 A lock was upgraded from the value specified
0x00040ED9 One or more properties were changed as allowed by
provider
0x00040EDA Errors occurred
0x00040EDB A specified parameter was invalid
0x00040EDC Updating this row caused more than one row to be
updated in the data source
0x00040EDD The row has no row-specific columns
3. Which data types are supported by the TwinCAT 3 Database Server? [} 163]
4. Is it possible to log more than one variable of a symbolgroup in one data record? [} 163]
5. How do I write or read single variables out of an existing database structure? [} 163]
6. Is it possible to log several data records at the same time into a database? [} 163]
7. Which network topologies are supported by the TF6420 Database Server? [} 163]
8. Which functionalities of the TwinCAT 3 Database Server can be used for the database type "XML"? [} 163]
?Is it possible to log more than one variable of a symbolgroup in one data record?
! Symbolgroups will be created at the TF6420 Database Server Configuration Editor. The declared symbols
can only be logged separately into the database. To log several variable into one data record, use the
function block FB_DBRecordInsert_Ex [} 94] out of the PLC.
?Is it possible to log several data records at the same time into a database?
! This depends on the used database. The database type "Microsoft SQL Database" supports this in
conjunction with the function block FB_DBRecordInsert_Ex. You only have to separate the different SQL
INSERT commands with ";".
?Which functionalities of the TwinCAT 3 Database Server can be used for the database type "XML"?
! The database type "XML" supports the full functionality of the TF6420 Database Server. Only Stored
Procedures and Delete SQL commands are not supported. You can work with the XML file like every other
database with SQL commands, or with the cyclic write mode of the PLC values. An additional functionality is
the possibility to use XPath commands and read XML-Tags. Further information can be found here [} 66].