Manual TwinCAT 3 | TCP/IP

95
Manual | EN TF6310 TwinCAT 3 | TCP/IP 2021-05-06 | Version: 1.4

Transcript of Manual TwinCAT 3 | TCP/IP

Manual | EN

TF6310TwinCAT 3 | TCP/IP

2021-05-06 | Version: 1.4

Table of contents

TF6310 3Version: 1.4

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

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

2 Overview..................................................................................................................................................... 72.1 Comparison TF6310 TF6311 ............................................................................................................ 7

3 Installation.................................................................................................................................................. 83.1 System requirements......................................................................................................................... 83.2 Installation ......................................................................................................................................... 83.3 Installation Windows CE.................................................................................................................. 113.4 Licensing ......................................................................................................................................... 133.5 Migration from TwinCAT 2............................................................................................................... 18

4 Technical introduction ............................................................................................................................ 21

5 PLC API..................................................................................................................................................... 235.1 Function blocks................................................................................................................................ 23

5.1.1 FB_SocketConnect..........................................................................................................  235.1.2 FB_SocketClose ..............................................................................................................  245.1.3 FB_SocketCloseAll ..........................................................................................................  255.1.4 FB_SocketListen..............................................................................................................  265.1.5 FB_SocketAccept ............................................................................................................  275.1.6 FB_SocketSend...............................................................................................................  285.1.7 FB_SocketReceive ..........................................................................................................  305.1.8 FB_SocketUdpCreate......................................................................................................  315.1.9 FB_SocketUdpSendTo ....................................................................................................  325.1.10 FB_SocketUdpReceiveFrom ...........................................................................................  345.1.11 FB_SocketUdpAddMulticastAddress...............................................................................  365.1.12 FB_SocketUdpDropMulticastAddress .............................................................................  375.1.13 Helper ..............................................................................................................................  38

5.2 Functions ......................................................................................................................................... 455.2.1 F_CreateServerHnd.........................................................................................................  455.2.2 HSOCKET_TO_STRING.................................................................................................  465.2.3 HSOCKET_TO_STRINGEX ............................................................................................  475.2.4 SOCKETADDR_TO_STRING .........................................................................................  475.2.5 [Obsolete] ........................................................................................................................  48

5.3 Data types ....................................................................................................................................... 495.3.1 E_SocketAcceptMode .....................................................................................................  495.3.2 E_SocketConnectionState...............................................................................................  495.3.3 E_SocketConnectionlessState ........................................................................................  495.3.4 E_WinsockError...............................................................................................................  505.3.5 ST_SockAddr...................................................................................................................  515.3.6 T_HSERVER ...................................................................................................................  525.3.7 T_HSOCKET ...................................................................................................................  52

5.4 Global constants .............................................................................................................................. 535.4.1 Global Variables ..............................................................................................................  53

Table of contents

TF63104 Version: 1.4

5.4.2 Library version .................................................................................................................  54

6 Samples.................................................................................................................................................... 556.1 TCP.................................................................................................................................................. 55

6.1.1 Sample01: "Echo" client/server (base blocks) .................................................................  556.1.2 Sample02: “Echo“ client /server.......................................................................................  746.1.3 Sample03: “Echo” client/server........................................................................................  756.1.4 Sample04: Binary data exchange....................................................................................  776.1.5 Sample05: Binary data exchange....................................................................................  79

6.2 UDP ................................................................................................................................................. 816.2.1 Sample01: Peer-to-peer communication .........................................................................  816.2.2 Sample02: Multicast ........................................................................................................  89

7 Appendix .................................................................................................................................................. 907.1 OSI model........................................................................................................................................ 907.2 KeepAlive configuration................................................................................................................... 907.3 Error codes ...................................................................................................................................... 91

7.3.1 Overview of the error codes.............................................................................................  917.3.2 Internal error codes of the TwinCAT TCP/IP Connection Server ....................................  927.3.3 Troubleshooting/diagnostics ............................................................................................  92

7.4 Support and Service ........................................................................................................................ 93

Foreword

TF6310 5Version: 1.4

1 Foreword

1.1 Notes on the documentationThis description is only intended for the use of trained specialists in control and automation engineering whoare familiar with applicable national standards.It is essential that the documentation and the following notes and explanations are followed when installingand commissioning the components. It is the duty of the technical personnel to use the documentation published at the respective time of eachinstallation and commissioning.

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

Disclaimer

The documentation has been prepared with care. The products described are, however, constantly underdevelopment.We reserve the right to revise and change the documentation at any time and without prior announcement.No claims for the modification of products that have already been supplied may be made on the basis of thedata, diagrams and descriptions in this documentation.

Trademarks

Beckhoff®, TwinCAT®, EtherCAT®, EtherCAT G®, EtherCAT G10®, EtherCAT P®, Safety over EtherCAT®,TwinSAFE®, XFC®, XTS® and XPlanar® are registered trademarks of and licensed by Beckhoff AutomationGmbH.Other designations used in this publication may be trademarks whose use by third parties for their ownpurposes could violate the rights of the owners.

Patent Pending

The EtherCAT Technology is covered, including but not limited to the following patent applications andpatents:EP1590927, EP1789857, EP1456722, EP2137893, DE102015105702with corresponding applications or registrations in various other countries.

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

Copyright

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

Foreword

TF63106 Version: 1.4

1.2 Safety instructions

Safety regulations

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

Exclusion of liability

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

Personnel qualification

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

Description of symbols

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

DANGERSerious risk of injury!Failure to follow the safety instructions associated with this symbol directly endangers the life and health ofpersons.

WARNINGRisk of injury!Failure to follow the safety instructions associated with this symbol endangers the life and health of per-sons.

CAUTIONPersonal injuries!Failure to follow the safety instructions associated with this symbol can lead to injuries to persons.

NOTEDamage to the environment or devicesFailure to follow the instructions associated with this symbol can lead to damage to the environment orequipment.

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

Overview

TF6310 7Version: 1.4

2 OverviewThe TwinCAT TCP/IP Connection Server enables the implementation/realisation of one or more TCP/IPserver/clients in the TwinCAT PLC. With its help, own TCP/IP based protocols (application layer) may bedeveloped directly in a PLC program.

Product components

The product TF6310 TCP/IP consists of the following components, which will be delivered by the setup:

• PLC library: Tc2_TcpIp library (implements basic TCP/IP and UDP/IP functionalities).• Background program: TwinCAT TCP/IP Connection Server (process which is used for

communication).

2.1 Comparison TF6310 TF6311The products TF6310 "TCP/IP" and TF6311 "TCP/UDP Realtime" offer similar functionality.

This page provides an overview of similarities and differences of the products:

TF 6310 TF 6311TwinCAT TwinCAT 2 / 3 TwinCAT 3Client/Server Both BothLarge / unknown networks ++ +Determinism + ++High-volume data transfer ++ +Programming languages PLC PLC and C++Operating system Win32/64, CE5/6/7 Win32/64, CE7UDP-Mutlicast Yes NoTrial license Yes YesProtocols TCP, UDP TCP, UDP, Arp/PingHardware requirements Variable TwinCAT-compatible network cardSocket configuration See operating system (WinSock) TCP/UDP RT TcCom Parameters

The Windows firewall cannot be used, since the TF6311 is directly integrated in the TwinCAT system. Inlarger / unknown networks we recommend using the TF6310.

Installation

TF63108 Version: 1.4

3 Installation

3.1 System requirementsThe following system requirements must be met for the function TF6310 TCP/IP to work properly.

Operating systems:

Windows XP Pro SP3

Windows 7 Pro (32-bit and 64-bit)

Windows 10 Pro (32-bit and 64-bit)

Windows XP Embedded

Windows Embedded Standard 2009

Windows Embedded 7

Windows CE6

Windows CE7

TwinCAT:

TwinCAT 3 XAR Build 3098 (or higher)

TwinCAT 3 XAE Build 3098 (or higher)

3.2 InstallationThe following section describes how to install the TwinCAT 3 Function for Windows-based operatingsystems.

ü The TwinCAT 3 Function setup file was downloaded from the Beckhoff website.1. Run the setup file as administrator. To do this, select the command Run as administrator in the context

menu of the file.ð The installation dialog opens.

Installation

TF6310 9Version: 1.4

2. Accept the end user licensing agreement and click Next.

3. Enter your user data.

Installation

TF631010 Version: 1.4

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

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

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

Installation

TF6310 11Version: 1.4

6. Confirm the dialog with Yes.

7. Select Finish to exit the setup.

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

3.3 Installation Windows CEThis section describes, how you can install the TwinCAT 3 Function TF6310 TCP/IP on a BeckhoffEmbedded PC Controller based on Windows CE.

The setup process consists of four steps:

• Download of the setup file [} 12]

• Installation on a host computer [} 12]

• Transferring the executable to the Windows CE device [} 12]

• Software installation [} 12]

The last paragraph of this section describes the Software upgrade [} 13].

Installation

TF631012 Version: 1.4

Download of the setup file

The CAB installation files for Windows CE are part of the TF6310 TCP/IP setup. Therefore you only need todownload one setup file from www.beckhoff.com which contains binaries for Windows XP, Windows 7 andWindows CE (x86 and ARM).

The installation procedure of the TF6310 TCP/IP setup is described in the regular installation article (seeInstallation [} 8]).

Installation on a host computer

After installation, the install folder contains three directories - each one for a different hardware platform:

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

The CE-ARM and CE-X86 folders contain the TF6310 CAB files for Windows CE corresponding to thehardware platform of your Windows CE device. This file needs to be transferred to the Windows CE device.

Transferring the executable to the Windows CE device

Transfer the corresponding executable to you Windows CE device. This can be done via one of the followingways:

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

For more information, please consult the "Windows CE" section in the Beckhoff Information System.

Software installation

After the file has been transferred via one of the above methods, execute the file and acknowledge thefollowing dialog with Ok. Restart your Windows CE device after the installation has finished.

After the restart has been completed, the executable files of TF6310 are started automatically in thebackground.

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

\Hard Disk\TwinCAT\Functions\TF6310-TCP-IP

Installation

TF6310 13Version: 1.4

Upgrade instructions

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

1. Open the CE Explorer by clicking on Start > Run and entering "explorer".2. Navigate to \Hard Disk\TwinCAT\Functions\TF6310-TCP-IP\Server.3. Rename TcpIpServer.exe to TcpIpServer.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 TcpIpServer.old.8. Restart the Windows CE device.ð After the restart is complete, the new version is active.

3.4 LicensingThe TwinCAT 3 Function can be activated as a full version or as a 7-day test version. Both license types canbe activated via the TwinCAT 3 development environment (XAE).

The licensing of a TwinCAT 3 Function is described below. The description is divided into the followingsections:

• Licensing a 7-day test version [} 13]

• Licensing a full version [} 15]

Further information on TwinCAT 3 licensing can be found in the “Licensing” documentation in the BeckhoffInformation System (TwinCAT 3 > Licensing).

Licensing a 7-day test version1. Start the TwinCAT 3 development environment (XAE).2. Open an existing TwinCAT 3 project or create a new project.3. If you want to activate the license for a remote device, set the desired target system. To do this, select

the target system from the Choose Target System drop-down list in the toolbar.ð The licensing settings always refer to the selected target system. When the project is activated on

the target system, the corresponding TwinCAT 3 licenses are automatically copied to this system.4. In the Solution Explorer, double-click License in the SYSTEM subtree.

ð The TwinCAT 3 license manager opens.

Installation

TF631014 Version: 1.4

5. Open the Manage Licenses tab. In the Add License column, check the check box for the license youwant to add to your project (e.g. “TF6420: TC3 Database Server“).

6. Open the Order Information (Runtime) tab.ð In the tabular overview of licenses, the previously selected license is displayed with the status

“missing”.

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

ð A dialog box opens, prompting you to enter the security code displayed in the dialog.8. Enter the code exactly as it appears, confirm it and acknowledge the subsequent dialog indicating

successful activation.ð In the tabular overview of licenses, the license status now indicates the expiration date of the license.

9. Restart the TwinCAT system.

Installation

TF6310 15Version: 1.4

ð The 7-day trial version is enabled.

Licensing a full version1. Start the TwinCAT 3 development environment (XAE).2. Open an existing TwinCAT 3 project or create a new project.3. If you want to activate the license for a remote device, set the desired target system. To do this, select

the target system from the Choose Target System drop-down list in the toolbar.ð The licensing settings always refer to the selected target system. When the project is activated on

the target system, the corresponding TwinCAT 3 licenses are automatically copied to this system.4. In the Solution Explorer, double-click License in the SYSTEM subtree.

ð The TwinCAT 3 license manager opens.5. Open the Manage Licenses tab. In the Add License column, check the check box for the license you

want to add to your project (e.g. “TE1300: TC3 Scope View Professional”).

6. Open the Order Information tab.

Installation

TF631016 Version: 1.4

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

A TwinCAT 3 license is generally linked to two indices describing the platform to be licensed:System ID: Uniquely identifies the devicePlatform level: Defines the performance of the deviceThe corresponding System Id and Platform fields cannot be changed.

7. Enter the order number (License Id) for the license to be activated and optionally a separate ordernumber (Customer Id), plus an optional comment for your own purposes (Comment). If you do notknow your Beckhoff order number, please contact your Beckhoff sales contact.

8. Click the Generate File... button to create a License Request File for the listed missing license.ð A window opens, in which you can specify where the License Request File is to be stored. (We

recommend accepting the default settings.)9. Select a location and click Save.

Installation

TF6310 17Version: 1.4

ð A prompt appears asking whether you want to send the License Request File to the Beckhoff licenseserver for verification:

• Click Yes to send the License Request File. A prerequisite is that an email program is installed on yourcomputer and that your computer is connected to the internet. When you click Yes, the systemautomatically generates a draft email containing the License Request File with all the necessaryinformation.

• Click No if your computer does not have an email program installed on it or is not connected to theinternet. Copy the License Request File onto a data storage device (e.g. a USB stick) and send the filefrom a computer with internet access and an email program to the Beckhoff license server([email protected]) by email.

10. Send the License Request File.ð The License Request File is sent to the Beckhoff license server. After receiving the email, the server

compares your license request with the specified order number and returns a License Response Fileby email. The Beckhoff license server returns the License Response File to the same email addressfrom which the License Request File was sent. The License Response File differs from the LicenseRequest File only by a signature that documents the validity of the license file content. You can viewthe contents of the License Response File with an editor suitable for XML files (e.g. “XML Notepad”).The contents of the License Response File must not be changed, otherwise the license file becomesinvalid.

11. Save the License Response File.12. To import the license file and activate the license, click License Response File... in the Order

Information tab.

Installation

TF631018 Version: 1.4

13. Select the License Response File in your file directory and confirm the dialog.

ð The License Response File is imported and the license it contains is activated. Existing demo licenses will be removed.

14. Restart the TwinCAT system.ð The license becomes active when TwinCAT is restarted. The product can be used as a full version.

During the TwinCAT restart the license file is automatically copied to the directory ...\TwinCAT\3.1\Target\License on the respective target system.

3.5 Migration from TwinCAT 2If you would like to migrate an existing TwinCAT 2 PLC project which uses one of the TCP/IP Server's PLClibraries, you need to perform some manual steps to ensure that the TwinCAT 3 PLC converter can processthe TwinCAT 2 project file (*.pro). In TwinCAT 2, the Function TCP/IP Server is delivered with three PLClibraries:

• TcpIp.lib• TcSocketHelper.lib• TcSnmp.lib

By default, these library files are installed in C:\TwinCAT\Plc\Lib\. Depending on the library used in your PLCproject, you need to copy the corresponding library file to C:\TwinCAT3\Components\Plc\Converter\Lib andthen perform the following steps:

1. Open the TwinCAT Engineering.2. Create a new TwinCAT 3 solution.

Installation

TF6310 19Version: 1.4

3. Right-click on the "PLC" node and select Add Existing Item in the context menu that opens.

4. In the Open dialog, select the file type "Plc 2.x Project Import (*.pro)", browse to the folder containingyour TwinCAT 2 PLC project and select the corresponding.pro file and click Open.

Installation

TF631020 Version: 1.4

ð TwinCAT 3 starts the converter process and finally displays the converted PLC project under the “PLC“node.

Technical introduction

TF6310 21Version: 1.4

4 Technical introductionThis section will give a general overview about the transport protocols TCP and UDP and will also link to thecorresponding PLC libraries needed to implement each protocol. Both transport protocols are part of theInternet Protocol suite and therefore an important part of our everyday communication, e.g. the Internet.

Transmission Control Protocol (TCP)

TCP is a connection-oriented transport protocol (OSI layer 4) that can be compared to a telephoneconnection, where participants have to establish the connection first before data can be transmitted. TCPprovides a reliable and ordered delivery of a stream of bytes, therefore it is considered to be a “stream-oriented transport protocol”. The TCP protocol is used for network applications where a receive confirmationis required for the data sent by a client or server. The TCP protocol is well suited for sending larger dataquantities and transports a data stream without a defined start and end. For the transmitter this is not aproblem since he knows how many data bytes are transmitted. However, the receiver is unable to detectwhere a message ends within the data stream and where the next data stream starts. A read call on thereceiver side only supplies the data currently in the receive buffer (this may be less or more than the datablock sent by the other device). Therefore the transmitter has to specify a message structure that is known tothe receiver and can be interpreted. In simple cases the message structure may consist of the data and afinal control character (e.g. carriage return). The final control character indicates the end of a message. Apossible message structure which is indeed often used for transferring binary data with a variable lengthcould be defined as follows: The first data bytes contain a special control character (a so-called startdelimiter) and the data length of the subsequent data. This enables the receiver to detect the start and end ofthe message.

TCP/IP client

A minimum TCP/IP client implementation within the PLC requires the following function blocks:

• An instance of the FB_SocketConnect [} 23] and FB_SocketClose [} 24] function blocks forestablishing and closing the connection to the remote server (Hint: FB_ClientServerConnection [} 38]encapsulates the functionality of both function blocks)

• An instance of the FB_SocketSend [} 28] and/or FB_SocketReceive [} 30] function block for the dataexchange with the remote server

TCP/IP server

A minimum TCP/IP server implementation within the PLC requires the following function blocks:

• An instance of the FB_SocketListen [} 26] function block for opening the listener socket.

• An instance of the FB_SocketAccept [} 27] and FB_SocketClose [} 24] function blocks for establishingand closing the connection(s) to the remote clients (Hint: FB_ServerClientConnection [} 40]encapsulates the functionality of all three function block)

• An instance of the FB_SocketSend [} 28] and/or FB_SocketReceive [} 30] function block for the dataexchange with the remote clients

• An instance of the FB_SocketCloseAll [} 25] function block is required in each PLC runtime system, inwhich a socket is opened.

The instances of the FB_SocketAccept [} 27] and FB_SocketReceive [} 30] function blocks are calledcyclically (polling), all others are called as required.

User Datagram Protocol (UDP)

UDP is a connection-less protocol, which means that data is sent between network devices without anexplicit connection. UDP uses a simple transmission model without implicitly defining workflows forhandshaking, reliability, data ordering or congestion control. However, even as this implies that UDPdatagrams may arrive out of order, appear duplicated, or congest the wire, UDP is in some cases prefferedto TCP, especially in realtime communication because all mentioned features (which are implemented in

Technical introduction

TF631022 Version: 1.4

TCP) require processing power and therefore time. Because of its connection-less nature, the UDP protocolis well suited for sending small data quantities. UDP is a “packet-oriented/message-oriented transportprotocol”, i.e. the sent data block is received on the receiver side as a complete data block.

The following function blocks are required for a minimum UDP client/server implementation:

• An instance of the FB_SocketUdpCreate [} 31] and FB_SocketClose [} 24] function blocks for openingand closing an UDP socket (Hint: FB_ConnectionlessSocket [} 44] encapsulates the functionality ofboth function)

• An instance of the FB_SocketUdpSendTo [} 32] and/or FB_SocketUdpReceiveFrom [} 34] functionblocks for the data exchange with other devices;

• An instance of the FB_SocketCloseAll [} 25] function block in each PLC runtime system, in which aUDP socket is opened

The instances of the FB_SocketUdpReceiveFrom [} 34] function block are called cyclically (polling), all othersare called as required.

See also: Samples [} 55]

PLC API

TF6310 23Version: 1.4

5 PLC API

5.1 Function blocks

5.1.1 FB_SocketConnect

Using the function block FB_SocketConnect, a local client can establish a new TCP/IP connection to aremote server via the TwinCAT TCP/IP Connection Server. If successful, a new socket is opened, and theassociated connection handle is returned at the hSocket output. The connection handle is required by thefunction blocks FB_SocketSend [} 28] and FB_SocketReceive [} 30], for example, in order to exchange datawith a remote server. If a connection is no longer required, it can be closed with the function blockFB_SocketClose [} 24]. Several clients can establish a connection with the remote server at the same time.For each new client, a new socket is opened and a new connection handle is returned. The TwinCAT TCP/IP Connection Server automatically assigns a new IP port number for each client.

VAR_INPUTVAR_INPUT    sSrvNetId   : T_AmsNetId := '';    sRemoteHost : T_IPv4Addr := '';    nRemotePort : UDINT;    bExecute    : BOOL;    tTimeout    : TIME := T#45s;(*!!!*)END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP

Connection Server. For the local computer (default) an empty stringmay be specified.

sRemoteHost T_IPv4Addr IP address (Ipv4) of the remote server in the form of a string (e.g.,'172.33.5.1'). An empty string can be entered on the local computer fora server.

nRemotePort UDINT IP port number of the remote server (e.g., 200).bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

Setting the maximum execution time of the function blockDo not set the value "tTimeout" too low, as timeout times of > 30 s can occur in case of a networkinterruption. If the value is too low, command execution would be interrupted prematurely, and ADSerror code 1861 (timeout elapsed) would be returned instead of the Winsocket error WSAETIMED-OUT.

VAR_OUTPUTVAR_OUTPUT    bBusy      : BOOL;    bError     : BOOL;    nErrId     : UDINT;    hSocket    : T_HSOCKET;END_VAR

PLC API

TF631024 Version: 1.4

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active

until acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this

output is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].hSocket T_HSOCKET TCP/IP connection handle [} 52] for the newly opened local client

socket.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.2 FB_SocketClose

The function block FB_SocketClose can be used to close an open TCP/IP or UDP socket.

TCP/IP: The listener socket is opened with the function block FB_SocketListen [} 26], a local client socketwith FB_SocketConnect [} 23] and a remote client socket with FB_SocketAccept [} 27].

UDP: The UDP socket is opened with the function block FB_SocketUdpCreate [} 31].

VAR_INPUTVAR_INPUT    sSrvNetId   : T_AmsNetId := '';    hSocket     : T_HSOCKET;    bExecute    : BOOL;    tTimeout    : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/

IP Connection Server. For the local computer (default) an empty string maybe specified.

hSocket T_HSOCKET • TCP/IP: Connection handle [} 52] of the listener, remote or local clientsocket to be closed.

• UDP: Connection handle of the UDP socket.bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;END_VAR

PLC API

TF6310 25Version: 1.4

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output is

set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.3 FB_SocketCloseAll

If TwinCAT is restarted or stopped, the TwinCAT TCP/IP Connection Server is also stopped. Any opensockets (TCP/IP and UDP connection handles) are closed automatically. The PLC program is reset after a"PLC reset", a "Rebuild all..." or a new "Download", and the information about already opened sockets(connection handles) is no longer available in the PLC. Any open connections can then no longer be closedproperly.

The function block FB_SocketCloseAll can be used to close all connection handles (TCP/IP and UDPsockets) that were opened by a PLC runtime system. This means that, if FB_SocketCloseAll is called in oneof the tasks of the first runtime systems (port 801), all sockets that were opened in the first runtime systemare closed. In each PLC runtime system that uses the socket function blocks, an instance ofFB_SocketCloseAll should be called during the PLC start (see below).

VAR_INPUTVAR_INPUT    sSrvNetId     : T_AmsNetId := '';    bExecute      : BOOL;    tTimeout      : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP Connection

Server. For the local computer (default) an empty string may be specified.bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;END_VAR

PLC API

TF631026 Version: 1.4

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output is

set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/IP

connection server error number [} 91].

Example of an implementation in ST

The following program code is used to properly close the connection handles (sockets) that were openbefore a "PLC reset" or "Download" before a PLC restart.PROGRAM MAINVAR    fbSocketCloseAll : FB_SocketCloseAll;    bCloseAll        : BOOL := TRUE;END_VARIF bCloseAll THEN(*On PLC reset or program download close all old connections *)    bCloseAll := FALSE;    fbSocketCloseAll( sSrvNetId:= '', bExecute:= TRUE, tTimeout:= T#10s );ELSE    fbSocketCloseAll( bExecute:= FALSE );END_IFIF NOT fbSocketCloseAll.bBusy THEN(*...... continue program execution......*)END_IF

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.4 FB_SocketListen

Using the function block FB_SocketListen, a new listener socket can be opened via the TwinCAT TCP/IP Connection Server. Via a listener socket, the TwinCAT TCP/IP Connection Server can 'listen' for incomingconnection requests from remote clients. If successful, the associated connection handle is returned at thehListener output. This handle is required by the function block FB_SocketAccept [} 27]. If a listener socket isno longer required, it can be closed with the function block FB_SocketClose [} 24]. The listener sockets on anindividual computer must have unique IP port numbers.

VAR_INPUTVAR_INPUT    sSrvNetId   : T_AmsNetId := '';    sLocalHost  : T_IPv4Addr := '';    nLocalPort  : UDINT;    bExecute    : BOOL;    tTimeout    : TIME := T#5s;END_VAR

PLC API

TF6310 27Version: 1.4

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP Connection

Server. For the local computer (default) an empty string may be specified.sLocalHost T_IPv4Addr Local server IP address (Ipv4) in the form of a string (e.g., '172.13.15.2'). For a

server on the local computer (default), an empty string may be entered.nLocalPort UDINT Local server IP port (e.g., 200).bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy      : BOOL;    bError     : BOOL;    nErrId     : UDINT;    hListener  : T_HSOCKET;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output is

set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/IP connection

server error number [} 91].hListener T_HSOCKE

TConnection handle [} 52] for the new listener socket.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.5 FB_SocketAccept

The remote client connection requests arriving at the TwinCAT TCP/IP Connection Server have to beacknowledged (accepted). The function block FB_SocketAccept accepts the incoming remote clientconnection requests, opens a new remote client socket and returns the associated connection handle. Theconnection handle is required by the function blocks FB_SocketSend [} 28] and FB_SocketReceive [} 30] inorder to exchange data with the remote client, for example. All incoming connection requests first have to beaccepted. If a connection is no longer required or undesirable, it can be closed with the function blockFB_SocketClose [} 24].

A server implementation requires at least one instance of this function block. This instance has to be calledcyclically (polling) from a PLC task. The function block can be activated via a positive edge at the bExecuteinput (e.g., every 5 seconds).

If successful, the bAccepted output is set, and the connection handle to the new remote client is returned atthe hSocket output. No error is returned if there are no new remote client connection requests. Severalremote clients can establish a connection with the server at the same time. The connection handles of

PLC API

TF631028 Version: 1.4

several remote clients can be retrieved sequentially via several function block calls. Each connection handlefor a remote client can only be retrieved once. It is recommended to keep the connection handles in a list(array). New connections are added to the list, and closed connections must be removed from the list.

VAR_INPUTVAR_INPUT    sSrvNetId     : T_AmsNetId := '';    hListener     : T_HSOCKET;    bExecute      : BOOL;    tTimeout      : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/

IP Connection Server. For the local computer (default) an empty string may bespecified.

hListener T_HSOCKET

Connection handle [} 52] of the listener sockets. This handle must first berequested via the function block FB_SocketListen [} 26].

bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bAccepted : BOOL;    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;    hSocket   : T_HSOCKET;END_VAR

Name Type DescriptionbAccepted BOOL This output is set if a new connection to a remote client was established.bBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output is

set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server  [} 91]error number.hSocket T_HSOCKE

TConnection handle [} 52] of a new remote client.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.6 FB_SocketSend

PLC API

TF6310 29Version: 1.4

Using the function block FB_SocketSend, data can be sent to a remote client or remote server via theTwinCAT TCP/IP Connection Server. A remote client connection will first have to be established via thefunction block FB_SocketAccept [} 27], or a remote server connection via the function blockFB_SocketConnect [} 23].

VAR_INPUTVAR_INPUT    sSrvNetId  : T_AmsNetId := '';    hSocket    : T_HSOCKET;    cbLen      : UDINT;    pSrc       : POINTER TO BYTE;    bExecute   : BOOL;    tTimeout   : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP

Connection Server. For the local computer (default) an empty string maybe specified.

hSocket T_HSOCKET Connection handle [} 52] of the communication partner to which dataare to be sent.

cbLen UDINT Number of date to be sent in bytes.pSrc POINTER TO BYT

EAddress (pointer) of the send buffer.

bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

Setting the execution time of the function blockIf the transmit buffer of the socket is full, for example because the remote communication partnerreceives the transmitted data not quickly enough or large quantities of data are transmitted, theFB_SocketSend function block will return ADS timeout error 1861 after the tTimeout time. In thiscase, the value of the tTimeout input variable has to be increased accordingly.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active

until acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this

output is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

PLC API

TF631030 Version: 1.4

5.1.7 FB_SocketReceive

Using the function block FB_SocketReceive, data from a remote client or remote server can be received viathe TwinCAT TCP/IP Connection Server. A remote client connection will first have to be established via thefunction block FB_SocketAccept [} 27], and a remote server connection via the function blockFB_SocketConnect [} 23]. The data can be received or sent in fragmented form (i.e. in several packets) withina TCP/IP network. It is therefore possible that not all data may be received with a single call of theFB_SocketReceive instance. For this reason, the instance has to be called cyclically (polling) within the PLCtask, until all required data have been received. During this process, an rising edge is generated at thebExecute input, e.g. every 100 ms. If successful, the data received last are copied into the receive buffer.The nRecBytes output returns the number of the last successfully received data bytes. If no new data couldbe read during the last call, the function block returns no error and nRecBytes == zero.

In a simple protocol for receiving, for example, a zero-terminated string on a remote server, the functionblock FB_SocketReceive, for example, will have to be called repeatedly until the zero termination wasdetected in the data received.

Timeout value setupIf the remote device was disconnected from the TCP/IP network (on the remote side only) while thelocal device is still connected to the TCP/IP network, the FB_SocketReceive function block returnsno error and no data. The socket is still open, but no data are received. In this case, the applicationmay possibly wait for remaining data bytes indefinitely. It is recommended to implement timeoutmonitoring in the PLC application. If not all data were received after a certain period, e.g. 10 sec-onds, the connection has to be closed and reinitialised.

VAR_INPUTVAR_INPUT    sSrvNetId  : T_AmsNetId := '';    hSocket    : T_HSOCKET;    cbLen      : UDINT;    pDest      : POINTER TO BYTE;    bExecute   : BOOL;    tTimeout   : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP Connection

Server. For the local computer (default) an empty string may be specified.hSocket T_HSOCKET Connection handle [} 52] of the communication partner from which data

are to be received.cbLen UDINT Maximum available buffer size (in bytes) for the data to be read.pDest POINTER TO BY

TEAddress (pointer) of the receive buffer.

bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;

PLC API

TF6310 31Version: 1.4

    nErrId    : UDINT;    nRecBytes : UDINT;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this

output is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number.nRecBytes UDINT Number of the last successfully received data bytes.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

Also see about this2 Overview of the error codes [} 91]

5.1.8 FB_SocketUdpCreate

The function block FB_SocketUdpCreate can be used to open a client/server socket for the User DatagramProtocol (UDP). If successful, a new socket is opened, and the associated socket handle is returned at thehSocket output. The handle is required by the function blocks FB_SocketUdpSendTo [} 32] andFB_SocketUdpReceiveFrom [} 34] in order to exchange data with a remote server, for example. If a UDPsocket is no longer required, it can be closed with the function block FB_SocketClose [} 24]. The port addressnLocalHost is internally reserved by the TCP/IP Connection Server for the UDP protocol (a "bind" is carriedout). Several network adapters may exist in a PC. The input parameter sLocalHost determines the networkadapter to be used. If the sLocalHost input variable is ignored (empty string), the TCP/IP Connection Serveruses the default network adapter. This is usually the first network adapter from the list of the networkadapters in the Control Panel.

Automatically created network connectionsIf an empty string was specified for sLocalHost when FB_SocketUdpCreate was called and the PCwas disconnected from the network, the system will open a new socket under the software loopbackIP address: '127.0.0.1'.

Automatically created network connections with several network adaptersIf two or more network adapters are installed in the PC and an empty string was specified as sLo-calHost, and the default network adapter was then disconnected from the network, the new socketwill be opened under the IP address of the second network adapter.

Setting a network addressIn order to prevent the sockets from being opened under a different IP address, you can specify thesLocalHost address explicitly or check the returned address in the handle variable (hSocket), closethe socket and re-open it.

PLC API

TF631032 Version: 1.4

VAR_INPUTVAR_INPUT    sSrvNetId  : T_AmsNetId := '';    sLocalHost : T_IPv4Addr := '';    nLocalPort : UDINT;    bExecute   : BOOL;    tTimeout   : TIME:= T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP Connection

Server. For the local computer (default) an empty string may be specified.sLocalHost T_IPv4Addr Local IP address (Ipv4) of the UDP client/server socket as a string (e.g.,

'172.33.5.1'). An empty string may be specified for the default networkadapter.

nLocalPort UDINT Local IP port number of the UDP client/server socket (e.g., 200).bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;    hSocket   : T_HSOCKET;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output

is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].hSocket T_HSOCKET Handle of the newly opened UDP client/server socket [} 52].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.9 FB_SocketUdpSendTo

The function block FB_SocketUdpSendTo can be used to send UDP data to a remote device via theTwinCAT TCP/IP Connection Server. The UDP socket must first be opened with the function blockFB_SocketUdpCreate [} 31].

PLC API

TF6310 33Version: 1.4

VAR_INPUTVAR_INPUT    sSrvNetId   : T_AmsNetId := '';    hSocket     : T_HSOCKET;    sRemoteHost : T_IPv4Addr;    nRemotePort : UDINT;    cbLen       : UDINT;    pSrc        : POINTER TO BYTE;    bExecute    : BOOL;    tTimeout    : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP

Connection Server. For the local computer (default) an empty stringmay be specified.

hSocket T_HSOCKET

Handle of an opened UDP socket [} 52].

sRemoteHost T_IPv4Addr IP address (Ipv4) in string form (e.g., '172.33.5.1') of the remotedevice to which data is to be sent. An empty string can be enteredon the local computer for a device.

nRemotePort UDINT IP port number (e.g., 200) of the remote device to which data is tobe sent.

cbLen UDINT Number of date to be sent in bytes. The maximum number of databytes to be sent is limited to 8192 bytes (constantTCPADS_MAXUDP_BUFFSIZE in the library in order to savememory space).

pSrc POINTERTO BYTE

Address (pointer) of the send buffer.

bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

Setting the size of the received data bytesAvailable in product version: TwinCAT TCP/IP Connection Server v1.0.50 or higher: The maximumnumber of data bytes to be received can be increased (only when absolutely unavoidable).

TwinCAT 2

1. Redefine global constants in the PLC project (in the example, the maximum number of data bytes tobe received is to be increased to 32000):VAR_GLOBAL CONSTANT    TCPADS_MAXUDP_BUFFSIZE : UDINT := 32000;END_VAR

2. Activate the option Replace constants in the dialog of the TwinCAT PLC controller (Project > Op-tions ... > Build).

3. Rebuild Project.

TwinCAT 3

In TwinCAT 3, this value can be edited via a parameter list of the PLC library (from version 3.3.4.0).

PLC API

TF631034 Version: 1.4

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains

active until acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this

output is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.10 FB_SocketUdpReceiveFrom

Using the function block FB_SocketUdpReceiveFrom, data from an open UDP socket can be received viathe TwinCAT TCP/IP Connection Server. The UDP socket must first be opened with the function blockFB_SocketUdpCreate [} 31]. The instance of the FB_SocketUdpReceive function block has to be calledcyclically (polling) within the PLC task. During this process, an rising edge is generated at the bExecute

PLC API

TF6310 35Version: 1.4

input, e.g. every 100ms. If successful, the data received last are copied into the receive buffer. ThenRecBytes output returns the number of the last successfully received data bytes. If no new data could beread during the last call, the function block returns no error and nRecBytes == zero.

VAR_INPUTVAR_INPUT    sSrvNetId : T_AmsNetId := '';    hSocket   : T_HSOCKET;    cbLen     : UDINT;     pDest     : POINTER TO BYTE;    bExecute  : BOOL;    tTimeout  : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP Connection

Server. For the local computer (default) an empty string may be specified.hSocket T_HSOCKE

THandle of an opened UDP socket [} 52], whose data are to be received.

cbLen UDINT Maximum available buffer size (in bytes) for the data to be read. The maximumnumber of data bytes to be received is limited to 8192 bytes (constantTCPADS_MAXUDP_BUFFSIZE in the library in order to save memory space).

pDest POINTERTO BYTE

Address (pointer) of the receive buffer.

bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

Setting the size of the received data bytesAvailable in product version: TwinCAT TCP/IP Connection Server v1.0.50 or higher: The maximumnumber of data bytes to be received can be increased (only when absolutely unavoidable).

TwinCAT 2

1. Redefine global constants in the PLC project (in the example, the maximum number of data bytes tobe received is to be increased to 32000):VAR_GLOBAL CONSTANT    TCPADS_MAXUDP_BUFFSIZE : UDINT := 32000;END_VAR

2. Activate the option Replace constants in the dialog of the TwinCAT PLC controller (Project > Op-tions ... > Build).

3. Rebuild Project.

TwinCAT 3

In TwinCAT 3, this value can be edited via a parameter list of the PLC library (from version 3.3.4.0).

PLC API

TF631036 Version: 1.4

VAR_OUTPUTVAR_OUTPUT    bBusy       : BOOL;    bError      : BOOL;    nErrId      : UDINT;    sRemoteHost : T_IPv4Addr := '';    nRemotePort : UDINT;    nRecBytes   : UDINT;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output is

set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].sRemoteHost T_IPv4Addr If successful, IP address (Ipv4) of the remote device whose data were received.nRemotePort UDINT If successful, IP port number of the remote device whose data were received

(e.g., 200).nRecBytes UDINT Number of data bytes last successfully received.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.11 FB_SocketUdpAddMulticastAddress

PLC API

TF6310 37Version: 1.4

Binds the Server to a Multicast IP address so that Multicast UDP packets can be received. This functionblocks requires a previously established UDP socket handle, which can be requested using the functionblock FB_SocketUdpCreate [} 31].

VAR_INPUTVAR_INPUT    sSrvNetId      : T_AmsNetId := '';    hSocket        : T_HSOCKET;    sMulticastAddr : STRING(15);    bExecute       : BOOL;    tTimeout       : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetId String containing the network address of the TwinCAT TCP/IP Connection

Server. For the local computer (default) an empty string may be specified.hSocket T_HSOCKE

TConnection handle [} 52] of the listener socket. This handle must first berequested with the function block FB_SocketUdpCreate [} 31].

sMulticastAddr T_IPv4Addr Multicast IP address to which the binding should take place.bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this

output is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/IP

connection server error number [} 91].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.12 FB_SocketUdpDropMulticastAddress

Removes the binding to a Multicast IP address, which has been added previously via the function blockFB_SocketUdpAddMulticastAddress [} 36].

PLC API

TF631038 Version: 1.4

VAR_INPUTVAR_INPUT    sSrvNetId      : T_AmsNetId := '';    hSocket        : T_HSOCKET;    sMulticastAddr : STRING(15);    bExecute       : BOOL;    tTimeout       : TIME := T#5s;END_VAR

Name Type DescriptionsSrvNetId T_AmsNetI

dString containing the network address of the TwinCAT TCP/IP ConnectionServer. For the local computer (default) an empty string may be specified.

hSocket T_HSOCKET

Connection handle [} 52] of the listener socket. This handle must first berequested with the function block FB_SocketUdpCreate [} 31].

sMulticastAddr T_IPv4Addr

Multicast IP address to which the binding should take place.

bExecute BOOL The function block is activated by a positive edge at this input.tTimeout TIME Maximum time allowed for the execution of the function block.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrId    : UDINT;END_VAR

Name Type DescriptionbBusy BOOL This output is active if the function block is activated. It remains active until

acknowledgement.bError BOOL If an error should occur during the transfer of the command, then this output

is set once the bBusy output was reset.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.13 Helper

5.1.13.1 FB_ClientServerConnection

The function block FB_ClientServerConnection can be used to manage (establish or remove) a clientconnection. FB_ClientServerConnection simplifies the implementation of a client application byencapsulating the functionality of the two function blocks FB_SocketConnect [} 23] and FB_SocketClose [} 24]

PLC API

TF6310 39Version: 1.4

internally. The integrated debugging output of the connection status facilitates troubleshooting in the event ofconfiguration or communication errors. In addition, a minimum client application only requires an instance ofthe FB_SocketSend [} 28] function block and/or an instance of the FB_SocketReceive [} 30] function block.

In the first step, a typical client application establishes the connection with the server via theFB_ClientServerConnection function block. In the next step instances of FB_SocketSend and/orFB_SocketReceive can be used to exchange data with the server. When a connection is closed depends onthe requirements of the application.

VAR_INPUTVAR_INPUT    sSrvNetID   : T_AmsNetID := '';    nMode       : DWORD := 0;    sRemoteHost : T_IPv4Addr := '';    nRemotePort : UDINT;    bEnable     : BOOL;    tReconnect  : TIME := T#45s;(*!!!*)END_VAR

Name Type DescriptionsSrvNetID T_AmsNetI

DString containing the AMS network address of the TwinCAT TCP/IP Connection Server. For the local computer (default) an empty string may bespecified.

nMode DWORD parameter flags (modes). The permissible parameters are listed here and can becombined by ORing:CONNECT_MODE_ENABLEDBG:Activates logging of debugging messages in the application log. In order to viewthe debugging messages open the TwinCAT System Manager and activate logview.

sRemoteHost T_IPv4Addr

IP address (Ipv4) of the remote server in the form of a string (e.g., '172.33.5.1').An empty string can be entered on the local computer for a server.

nRemotePort UDINT IP port number of the remote server (e.g., 200).bEnable BOOL As long as this input is TRUE, the system attempts to establish a new

connection at regular intervals until a connection was established successfully.Once established, a connection can be closed again with FALSE.

tReconnect TIME Cycle time used by the function block to try and establish the connection.

Setting the cycle time for the connectionThe tReconnect value should not be set too low, since timeout periods of > 30 s may occur in theevent of a network interruption. If the value is too low, command execution would be interruptedprematurely, and ADS error code 1861 (timeout elapsed) would be returned instead of theWinsocket error WSAETIMEDOUT.

VAR_OUTPUTVAR_OUTPUT    bBusy      : BOOL;    bError     : BOOL;    nErrId     : UDINT;    hSocket    : T_HSOCKET;    eState     : E_SocketConnectionState := eSOCKET_DISCONNECTED;END_VAR

PLC API

TF631040 Version: 1.4

Name Type DescriptionbBusy BOOL TRUE, as long as the function block is active.bError BOOL Becomes TRUE if an error code occurs.nErrID UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].hSocket T_HSOCKET Connection handle [} 52] for the newly opened local client socket. If

successful, this variable is transferred to the instances of the functionblocks FB_SocketSend [} 28] and/or FB_SocketReceive [} 30].

eState E_SocketConnectionState

Returns the current connection status [} 49].

Example of a call in FBDPROGRAM MAINVAR    fbClientConnection1 : FB_ClientServerConnection;    bConnect1           : BOOL;    bBusy1              : BOOL;    bError1             : BOOL;    nErrID1             : UDINT;    hSocket1            : T_HSOCKET;    eState1             : E_SocketConnectionState;END_VAR

You can find further applications examples (and source code) here: Examples [} 55]

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.1.13.2 FB_ServerClientConnection

The function block FB_ServerClientConnection can be used to manage (establish or remove) a serverconnection. FB_ServerClientConnection simplifies the implementation of a server application byencapsulating the functionality of the three function blocks FB_SocketListen [} 26], FB_SocketAccept [} 27]and FB_SocketClose [} 24] internally. The integrated debugging output of the connection status facilitatestroubleshooting in the event of configuration or communication errors. In addition, a minimum serverapplication only requires an instance of the FB_SocketSend [} 28] function block and/or an instance of theFB_SocketReceive [} 30] function block.

PLC API

TF6310 41Version: 1.4

In the first step, a typical server application establishes the connection with the client via theFB_ServerClientConnection function block (more precisely, the server application accepts the incomingconnection request). In the next step, instances of FB_SocketSend and/or FB_SocketReceive can be usedto exchange data with the server. When a connection is closed depends on the requirements of theapplication.

VAR_IN_OUTVAR_IN_OUT    hServer     : T_HSERVER;END_VAR

Name Type DescriptionhServer hServer Server handle [} 52]. This input variable has to be initialized via the

F_CreateServerHnd [} 45] function.

VAR_INPUTVAR_INPUT    eMode       : E_SocketAcceptMode := eACCEPT_ALL;    sRemoteHost : T_IPv4Addr := '';    nRemotePort : UDINT := 0;    bEnable     : BOOL;    tReconnect  : TIME := T#1s;END_VAR

Name Type DescriptioneMode E_SocketAcceptM

odeDefines whether all or only certain connections are to be accepted [} 49].

sRemoteHost

T_IPv4Addr IP address (Ipv4) in string form (e.g., '172.33.5.1') of the remote client whoseconnection is to be accepted. For a client on the local computer an emptystring may be specified.

nRemotePort

UDINT IP port number (e.g., 200) of the remote client whose connection is to beaccepted.

bEnable BOOL As long as this input is TRUE, the system attempts to establish a newconnection at regular intervals until a connection was established successfully.Once established, a connection can be closed again with FALSE.

tReconnect

TIME Cycle time used by the function block to try and establish a connection.

VAR_OUTPUTVAR_OUTPUT    bBusy     : BOOL;    bError    : BOOL;    nErrID    : UDINT;    hSocket   : T_HSOCKET;    eState    : E_SocketConnectionState := eSOCKET_DISCONNECTED; END_VAR

Name Type DescriptionbBusy BOOL TRUE, as long as the function block is active.bError BOOL Becomes TRUE if an error code occurs.nErrId UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].hSocket T_HSOCKET Connection handle [} 52] for the newly opened remote client socket. If

successful, this variable is transferred to the instances of the functionblocks FB_SocketSend [} 28] and/or FB_SocketReceive [} 30].

eState E_SocketConnectionState

Returns the current connection status [} 49].

PLC API

TF631042 Version: 1.4

Example in FBD

The following example illustrates initialization of a server handle variable. The server handle is thentransferred to three instances of the FB_ServerClientConnection function block.PROGRAM MAINVAR    hServer             : T_HSERVER;    bListen             : BOOL;

    fbServerConnection1 : FB_ServerClientConnection;    bConnect1           : BOOL;    bBusy1              : BOOL;    bError1             : BOOL;    nErrID1             : UDINT;    hSocket1            : T_HSOCKET;    eState1             : E_SocketConnectionState;

    fbServerConnection2 : FB_ServerClientConnection;    bConnect2           : BOOL;    bBusy2              : BOOL;    bError2             : BOOL;    nErrID2             : UDINT;    hSocket2            : T_HSOCKET;    eState2             : E_SocketConnectionState;

    fbServerConnection3 : FB_ServerClientConnection;    bConnect3           : BOOL;    bBusy3              : BOOL;    bError3             : BOOL;    nErrID3             : UDINT;    hSocket3            : T_HSOCKET;    eState3             : E_SocketConnectionState;END_VAR

Online View:

PLC API

TF6310 43Version: 1.4

The first connection is activated (bConnect1 = TRUE), but the connection has not yet been established(passive open).

The second connection has not yet been activated (bConnect2 = FALSE) (closed).

The third connection has been activated (bConnect3 = TRUE) and a connection to the remote client hasbeen established.

You can find further applications examples (and source code) here: Examples [} 55]

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

PLC API

TF631044 Version: 1.4

5.1.13.3 FB_ConnectionlessSocket

A UDP socket can be managed (opened/generated and closed) with the function blockFB_ConnectionlessSocket. FB_ConnectionlessSocket simplifies the implementation of a UDP application byencapsulating the functionality of the two function blocks FB_SocketUdpCreate [} 31] and FB_SocketClose[} 24] internally. The integrated debugging output of the socket status facilitates troubleshooting in the eventof configuration or communication errors. In addition, a minimum UDP application only requires an instanceof the FB_SocketUdpSendTo [} 32] function block and/or an instance of the FB_SocketUdpReceiveFrom [} 34]function block.

In the first step, a typical UDP application opens a connection-less UDP socket with theFB_ConnectionlessSocket function block. In the next step, instances of FB_SocketUdpSendTo and/orFB_SocketUdpReceiveFrom can be used for exchanging data with another communication device. When aUDP socket is closed depends on the requirements of the application (e.g. in the event of a communicationerror).

VAR_INPUTVAR_INPUT    sSrvNetID    : T_AmsNetID := '';    nMode        : DWORD := 0;    sLocalHost   : T_Ipv4Addr := '';    nLocalPort   : UDINT;    bEnable      : BOOL;    tReconnect   : TIME := T#45s;(*!!!*)END_VAR

Name Type DescriptionsSrvNetID T_AmsNetI

DString containing the AMS network address of the TwinCAT TCP/IP Connection Server. For the local computer (default) an empty string may bespecified.

nMode DWORD parameter flags (modes). The permissible parameters are listed here and can becombined by ORing.CONNECT_MODE_ENABLEDBG:Activates logging of debugging messages in the application log. In order to viewthe debugging messages open the TwinCAT System Manager and activate logview.

sLocalHost T_Ipv4Addr

IP address (Ipv4) in string form (e.g., '172.33.5.1') of the local network adapter. Anempty string may be specified for the default network adapter.

nLocalPort UDINT IP port number (e.g., 200) on the local computer.bEnable BOOL As long as this input is TRUE, attempts are made cyclically to open a UDP socket

until a connection has been established. An open UDP socket can be closedagain with FALSE.

tReconnect TIME Cycle time with which the function block tries to open the UDP socket.

Setting the cycle time for the connectionThe tReconnect value should not be set too low, since timeout periods of > 30 s may occur in theevent of a network interruption. If the value is too low, command execution would be interruptedprematurely, and ADS error code 1861 (timeout elapsed) would be returned instead of theWinsocket error WSAETIMEDOUT.

PLC API

TF6310 45Version: 1.4

VAR_OUTPUTVAR_OUTPUT    bBusy   : BOOL;    bError  : BOOL;    nErrId  : UDINT;    hSocket : T_HSOCKET;    eState  : E_SocketConnectionlessState := eSOCKET_CLOSED;END_VAR

Name Type DescriptionbBusy BOOL TRUE, as long as the function block is active.bError BOOL Becomes TRUE if an error code occurs.nErrID UDINT If an bError output is set, this parameter returns the TwinCAT TCP/

IP Connection Server error number [} 91].hSocket T_HSOCKET Connection handle [} 52] for the newly opened UDP socket. If

successful, this variable is transferred to the instances of thefunction blocks FB_SocketUdpSendTo [} 32] and/orFB_SocketUdpReceiveFrom [} 34].

eState E_SocketConnectionlessState

Returns the current connection status [} 49].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.2 Functions

5.2.1 F_CreateServerHnd

The function F_CreateServerHnd is used to initialise/set the internal parameters of a server handle variablehServer. The server handle is then transferred to the instances of the FB_ServerClientConnection [} 40]function block via VAR_IN_OUT. An instance of the FB_ServerClientConnection function block can be usedto manage (establish or remove) a sever connection in a straightforward manner. The same server handlecan be transferred to several instances of the FB_ServerClientConnection function block, in order to enablethe server to establish several concurrent connections.

FUNCTION F_CreateServerHnd : BOOLVAR_IN_OUT    hServer         : T_HSERVER; END_VARVAR_INPUT    sSrvNetID       : T_AmsNetID := '';     sLocalHost      : STRING(15) := '';     nLocalPort      : UDINT := 0;    nMode           : DWORD := LISTEN_MODE_CLOSEALL (* OR CONNECT_MODE_ENABLEDBG*); bEnable            : BOOL := TRUE;END_VAR

PLC API

TF631046 Version: 1.4

Name Type DescriptionhServer T_HSERVE

RServer handle [} 52] variable whose internal parameters are to be initialized.

sSrvNetID T_AmsNetID String containing the AMS network address of the TwinCAT TCP/IP Connection Server. For the local computer (default) an empty string may bespecified.

sLocalHost T_IPv4Addr Local server IP address (Ipv4) in the form of a string (e.g. '172.13.15.2'). For aserver on the local computer (default), an empty string may be entered.

nLocalPort UDINT Local server IP port (e.g. 200).nMode DWORD parameter flags (modes). The permissible parameters are listed here and can be

combined by ORing.LISTEN_MODE_CLOSEALL:All previously opened socket connections are closed (default).CONNECT_MODE_ENABLEDBG:Activates logging of debugging messages in the application log. In order to viewthe debugging messages open the TwinCAT System Manager and activate logview.

bEnable BOOL This input determines the behavior of the listener socket. A listener socketopened beforehand remains open as long as this input is TRUE. If this input isFALSE, the listener socket is closed automatically, but only once the last(previously) accepted connection was also closed.

Return value

TRUE No errorFALSE Error – incorrect parameter value

Example:

See FB_ServerClientConnection [} 40].

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.2.2 HSOCKET_TO_STRING

The function converts the connection handle of type T_HSOCKET to a string (e.g. for debug outputs).

The returned string has the following format: "Handle:0xA[BCD] Local:a[aa].b[bb].c[cc].d[dd]:portRemote:a[aa].b[bb].c[cc].d[dd]:port".

Example: "Handle:0x4001 Local:172.16.6.195:28459 Remote:172.16.6.180:2404"

FUNCTION HSOCKET_TO_STRING : STRINGVAR_INPUT    hSocket : T_HSOCKET;END_VAR

Name Type DescriptionhSocket T_HSOCKET The connection handle [} 52] to be converted.

PLC API

TF6310 47Version: 1.4

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.2.3 HSOCKET_TO_STRINGEX

The function converts the connection handle of type T_HSOCKET to a string (e.g. for debug outputs).

The returned string has the following format: "Handle:0xA[BCD] Local:a[aa].b[bb].c[cc].d[dd]:portRemote:a[aa].b[bb].c[cc].d[dd]:port".

Example: "Handle:0x4001 Local:172.16.6.195:28459 Remote:172.16.6.180:2404"

The parameters bLocal and bRemote determine whether the local and/or remote address information shouldbe included in the returned string.

FUNCTION HSOCKET_TO_STRINGEX : STRINGVAR_INPUT    hSocket : T_HSOCKET;    bLocal  : BOOL;    bRemote : BOOL;END_VAR

Name Type DescriptionhSocket T_HSOCKET The connection handle [} 52] to be converted.bLocal BOOL TRUE: include the local address, FALSE: exclude the local address.bRemote BOOL TRUE: include the remote address, FALSE: exclude the remote address.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.2.4 SOCKETADDR_TO_STRING

The function converts a variable of type ST_SockAddr to a string (e.g. for debug outputs).

The returned string has the following format: "a[aa].b[bb].c[cc].d[dd]:port"

Example: "172.16.6.195:80"

FUNCTION SOCKETADDR_TO_STRING : STRINGVAR_INPUT    stSockAddr : ST_SockAddr;END_VAR

PLC API

TF631048 Version: 1.4

Name Type DescriptionstSockeAddr ST_SockAddr The variable to be converted.

See ST_SockAddr [} 51]

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.2.5 [Obsolete]

5.2.5.1 F_GetVersionTcpIp

This function can be used to read PLC library version information.

FUNCTION F_GetVersionTcpIp : UINTVAR_INPUT    nVersionElement : INT;END_VAR

nVersionElement : Version element to be read. Possible parameters:

• 1 : major number;• 2 : minor number;• 3 : revision number;

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.2.5.2 F_GetVersionTcSocketHelper

This function reads version information from the PLC library.

FUNCTION F_GetVersionTcSocketHelper : UINTVAR_INPUT    nVersionElement : INT;END_VAR

nVersionElement : Version element, that is to be read. Possible parameters:

• 1 : major number;• 2 : minor number;

PLC API

TF6310 49Version: 1.4

• 3 : revision number;

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3 Data types

5.3.1 E_SocketAcceptModeTYPE E_SocketAcceptMode:(* Connection accept modes *)(    eACCEPT_ALL, (* Accept connection to all remote clients *)    eACCEPT_SEL_HOST, (* Accept connection to selected host address *)    eACCEPT_SEL_PORT, (* Accept connection to selected port address *)    eACCEPT_SEL_HOST_PORT (* Accept connection to selected host and port address *));END_TYPE

The variable E_SocketAcceptMode defines which connections are to be accepted by a server.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3.2 E_SocketConnectionStateTYPE E_SocketConnectionState:(    eSOCKET_DISCONNECTED,    eSOCKET_CONNECTED,    eSOCKET_SUSPENDED);END_TYPE

TCP/IP Socket Connection Status (eSOCKET_SUSPENDED == the status changes e.g. fromeSOCKET_CONNECTED => eSOCKET_DISCONNECTED).

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3.3 E_SocketConnectionlessStateTYPE E_SocketConnectionlessState:(    eSOCKET_CLOSED,    eSOCKET_CREATED,    eSOCKET_TRANSIENT);END_TYPE

Status information of a connection-less UDP socket (eSOCKET_TRANSIENT == the status changes fromeSOCKET_CREATED => eSOCKET_CLOSED, for example).

PLC API

TF631050 Version: 1.4

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3.4 E_WinsockErrorTYPE E_WinsockError : (    WSOK,    WSAEINTR        := 10004 ,(* A blocking operation was interrupted by a call to WSACancelBlockingCall. *)    WSAEBADF        := 10009 ,(* The file handle supplied is not valid. *)    WSAEACCES     := 10013 ,(* An attempt was made to access a socket in a way forbidden by its access permissions. *)    WSAEFAULT     := 10014 ,(* The system detected an invalid pointer address in attempting to use a pointer argument in a call. *)    WSAEINVAL     := 10022 ,(* An invalid argument was supplied. *)    WSAEMFILE     := 10024 ,(* Too many open sockets. *)    WSAEWOULDBLOCK     := 10035 ,(* A non-blocking socket operation could not be completed immediately. *)    WSAEINPROGRESS     := 10036 ,(* A blocking operation is currently executing. *)    WSAEALREADY     := 10037 ,(* An operation was attempted on a non-blocking socket that already had an operation in progress. *)    WSAENOTSOCK     := 10038 ,(* An operation was attempted on something that is not a socket. *)    WSAEDESTADDRREQ     := 10039 ,(* A required address was omitted from an operation on a socket. *)    WSAEMSGSIZE     := 10040 ,(* A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself. *)    WSAEPROTOTYPE     := 10041 ,(* A protocol was specified in the socket function call that does not support the semantics of the socket type requested. *)    WSAENOPROTOOPT     := 10042 ,(* An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call. *)    WSAEPROTONOSUPPORT := 10043 ,(* The requested protocol has not been configured into the system, or no implementation for it exists. *)    WSAESOCKTNOSUPPORT := 10044 ,(* The support for the specified socket type does not exist in this address family. *)    WSAEOPNOTSUPP     := 10045 ,(* The attempted operation is not supported for the type of object referenced. *)    WSAEPFNOSUPPORT     := 10046 ,(* The protocol family has not been configured into the system or no implementation for it exists. *)    WSAEAFNOSUPPORT     := 10047 ,(* An address incompatible with the requested protocol was used. *)    WSAEADDRINUSE     := 10048 ,(* Only one usage of each socket address (protocol/network address/port) is normally permitted. *)    WSAEADDRNOTAVAIL    := 10049 ,(* The requested address is not valid in its context. *)    WSAENETDOWN     := 10050 ,(* A socket operation encountered a dead network. *)    WSAENETUNREACH     := 10051 ,(* A socket operation was attempted to an unreachable network. *)    WSAENETRESET     := 10052 ,(* The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. *)    WSAECONNABORTED     := 10053 ,(* An established connection was aborted by the software in your host machine. *)    WSAECONNRESET     := 10054 ,(* An existing connection was forcibly closed by the remote host. *)    WSAENOBUFS     := 10055 ,(* An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full. *)    WSAEISCONN     := 10056 ,(* A connect request was made on an already connected socket. *)    WSAENOTCONN     := 10057 ,(* A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied. *)    WSAESHUTDOWN     := 10058 ,(* A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call. *)    WSAETOOMANYREFS     := 10059 ,(* Too many references to some kernel object. *)      WSAETIMEDOUT     := 10060 ,(* A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. *)    WSAECONNREFUSED     := 10061 ,(* No connection could be made because the target machine actively refused it. *)

PLC API

TF6310 51Version: 1.4

    WSAELOOP        := 10062 ,(* Cannot translate name. *)    WSAENAMETOOLONG     := 10063 ,(* Name component or name was too long. *)    WSAEHOSTDOWN     := 10064 ,(* A socket operation failed because the destination host was down. *)    WSAEHOSTUNREACH     := 10065 ,(* A socket operation was attempted to an unreachable host. *)    WSAENOTEMPTY     := 10066 ,(* Cannot remove a directory that is not empty. *)    WSAEPROCLIM     := 10067 ,(* A Windows Sockets implementation may have a limit on the number of applications that may use it simultaneously. *)    WSAEUSERS     := 10068 ,(* Ran out of quota. *)    WSAEDQUOT     := 10069 ,(* Ran out of disk quota. *)    WSAESTALE     := 10070 ,(* File handle reference is no longer available. *)    WSAEREMOTE     := 10071 ,(* Item is not available locally. *)    WSASYSNOTREADY     := 10091 ,(* WSAStartup cannot function at this time because the underlying system it uses to provide networkservices is currently unavailable. *)    WSAVERNOTSUPPORTED := 10092 ,(* The Windows Sockets version requested is not supported. *)    WSANOTINITIALISED := 10093 ,(* Either the application has not called WSAStartup, or WSAStartup failed. *)    WSAEDISCON     := 10101 ,(* Returned by WSARecv or WSARecvFrom to indicate the remote party has initiated a graceful shutdown sequence. *)    WSAENOMORE     := 10102 ,(* No more results can be returned by WSALookupServiceNext. *)    WSAECANCELLED     := 10103 ,(* A call to WSALookupServiceEnd was made while this call was still processing. The call has been canceled. *)    WSAEINVALIDPROCTABLE := 10104 ,(* The procedure call table is invalid. *)    WSAEINVALIDPROVIDER := 10105 ,(* The requested service provider is invalid. *)    WSAEPROVIDERFAILEDINIT := 10106 ,(* The requested service provider could not be loaded or initialized. *)    WSASYSCALLFAILURE := 10107 ,(* A system call that should never fail has failed. *)    WSASERVICE_NOT_FOUND := 10108 ,(* No such service is known. The service cannot be found in the specified name space. *)    WSATYPE_NOT_FOUND := 10109 ,(* The specified class was not found. *)    WSA_E_NO_MORE     := 10110 ,(* No more results can be returned by WSALookupServiceNext. *)    WSA_E_CANCELLED     := 10111 ,(* A call to WSALookupServiceEnd was made while this call was still processing. The call has been canceled. *)    WSAEREFUSED     := 10112 ,(* A database query failed because it was actively refused. *)    WSAHOST_NOT_FOUND := 11001 ,(* No such host is known. *)    WSATRY_AGAIN     := 11002 ,(* This is usually a temporary error during hostname resolution and means that the local server didnot receive a response from an authoritative server. *)    WSANO_RECOVERY     := 11003 ,(* A non-recoverable error occurred during a database lookup. *)    WSANO_DATA     := 11004 (* The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. *) );END_TYPE

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3.5 ST_SockAddrStructure with address information for an open socket.TYPE ST_SockAddr : (* Local or remote endpoint address *)STRUCT    nPort : UDINT; (* Internet Protocol (IP) port. *)    sAddr : STRING(15); (* String containing an (Ipv4) Internet Protocol dotted address. *)END_STRUCTEND_TYPE

Name Type DescriptionnPort UDINT Internet Protocol (IP) portsAddr STRING(15) Internet Protocol address separated by periods (Ipv4) in the form of a string e.g.:

"172.34.12.3"

PLC API

TF631052 Version: 1.4

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3.6 T_HSERVERThe variable of this type represents a TCP/IP Server Handle. The Handle has to be initialized withF_CreateServerHnd [} 45] bevor it can be used. In doing so the internal parameters of variables T_HSERVERare set.

Preserve the default structure elementsThe structure elements are not to be written or changed.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.3.7 T_HSOCKETVariables of this type represent a connection handle or a handle of an open socket. Via this handle, data canbe sent to or received from a socket. The handle can be used to close an open socket.TYPE T_HSOCKETSTRUCT    handle     : UDINT;    localAddr  : ST_SockAddr; (* Local address *)    remoteAddr : ST_SockAddr; (* Remote endpoint address *)END_STRUCTEND_TYPE

Name Type Descriptionhandle UDINT Internal TwinCAT TCP/IP Connection Server socket handlelocalAddr ST_SockAddr Local socket address [} 51]remoteAddr ST_SockAddr Remote socket address [} 51]

The following sockets can be opened and closed via the TwinCAT TCP/IP Connection Server: listenersocket, remote client socket, or local client socket. Depending on which of these sockets was opened by theTwinCAT TCP/IP Connection Server, suitable address information is entered into the localAddr andremoteAddr variables.

Connection handle on the server side

• The function block FB_SocketListen [} 26] opens a listener socket and returns the connection handle ofthe listener socket.

• The connection handle of the listener sockets is transferred to the function block FB_SocketAccept[} 27]. FB_SocketAccept will then return the connection handles of the remote clients.

• The function block FB_SocketAccept returns a new connection handle for each connected remoteclient.

• The connection handle is then transferred to the function blocks FB_SocketSend [} 28] and/orFB_SocketReceive [} 30], in order to be able to exchange data with the remote clients.

• A connection handle of a remote client that is not desirable or no longer required is transferred to thefunction block FB_SocketClose [} 24], which closes the remote client socket.

PLC API

TF6310 53Version: 1.4

• A listener socket connection handle that is no longer required is also transferred to the function blockFB_SocketClose, which closes the listener socket.

Connection handle on the client side

• The function block FB_SocketConnect [} 23] returns the connection handle of a local client socket.

• The connection handle is then transferred to the function blocks FB_SocketSend [} 28] andFB_SocketReceive [} 30], in order to be able to exchange data with a remote server.

• The same connection handle is then transferred to the function block FB_SocketClose [} 24], in order toclose a connection that is no longer required.

The function block FB_SocketCloseAll [} 25] can be used to close all connection handles (sockets) that wereopened by a PLC runtime system. This means that, if FB_SocketCloseAll is called in one of the tasks of thefirst runtime systems (port 801), all sockets that were opened in the first runtime system are closed.

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

5.4 Global constants

5.4.1 Global VariablesVAR_GLOBAL CONSTANT    AMSPORT_TCPIPSRV              : UINT := 10201;

    TCPADS_IGR_CONLIST            : UDINT := 16#80000001;    TCPADS_IGR_CLOSEBYHDL         : UDINT := 16#80000002;    TCPADS_IGR_SENDBYHDL          : UDINT := 16#80000003;    TCPADS_IGR_PEERBYHDL          : UDINT := 16#80000004;    TCPADS_IGR_RECVBYHDL          : UDINT := 16#80000005;    TCPADS_IGR_RECVFROMBYHDL      : UDINT := 16#80000006;    TCPADS_IGR_SENDTOBYHDL        : UDINT := 16#80000007;    TCPADS_IGR_MULTICAST_ADDBYHDL : UDINT := 16#80000008;    TCPADS_IGR_MULTICAST_DROPBYHDL: UDINT := 16#80000009;

    TCPADSCONLST_IOF_CONNECT  : UDINT := 1;    TCPADSCONLST_IOF_LISTEN   : UDINT := 2;    TCPADSCONLST_IOF_CLOSEALL : UDINT := 3;    TCPADSCONLST_IOF_ACCEPT   : UDINT := 4;    TCPADSCONLST_IOF_UDPBIND  : UDINT := 5;

    TCPADS_MAXUDP_BUFFSIZE    : UDINT := 16#2000; (8192 bytes)

    TCPADS_NULL_HSOCKET : T_HSOCKET := ( handle := 0, remoteAddr := ( nPort := 0, sAddr := '' ), localAddr :=  ( nPort := 0, sAddr := '' ) );(* Empty (not initialized) socket *)

    LISTEN_MODE_CLOSEALL   : DWORD := 16#00000001 (* FORCED close of all previous opened sockets *)    LISTEN_MODE_USEOPENED  : DWORD := 16#00000002 (* Try to use allready opened listener socket *)    CONNECT_MODE_ENABLEDBG : DWORD := 16#80000000 (* Enables/Disables debugging messages *)END_VAR

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

PLC API

TF631054 Version: 1.4

5.4.2 Library versionAll libraries have a specific version. This version is shown in the PLC library repository too.A global constant contains the library version information:

Global_Version

VAR_GLOBAL CONSTANT    stLibVersion_Tc2_TcpIp : ST_LibVersion;END_VAR

To compare the existing version to a required version the function F_CmpLibVersion (defined in Tc2_Systemlibrary) is offered.

TwinCAT 2 compatibilityAll other possibilities known from TwinCAT2 libraries to query a library version are obsolete!

Requirements

Development environment Target system type PLC libraries to include (cate-gory group)

TwinCAT v3.1.0 PC, or CX (x86, X64, ARM) Tc2_TcpIp (communication)

Samples

TF6310 55Version: 1.4

6 SamplesSample code and configurations for this product can be obtained from the corresponding repository onGitHub: https://github.com/Beckhoff/TF6310_Samples . There you have the option to clone the repository ordownload a ZIP file containing the sample.

6.1 TCP

6.1.1 Sample01: "Echo" client/server (base blocks)

6.1.1.1 Overview

The following example shows an implementation of an "echo" client/server. The client sends a test string tothe server at certain intervals (e.g. every second). The remote server then immediately resends the samestring to the client.

In this sample, the client is implemented in the PLC and as a .NET application written in C#. The PLC clientcan create several instances of the communication, simulating several TCP connections at once. The .NETsample client only establishes one concurrent connection. The server is able to communicate with severalclients.

In addition, several instances of the server may be created. Each server instance is then addressed via adifferent port number which can be used by the client to connect to a specific server instance. The serverimplementation is more difficult if the server has to communicate with more than one client.

Feel free to use and customize this sample to your needs.

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP• If two computers are used to execute the sample (one client and one server), the Function TF6310

needs to be installed on both computers• If one computer is used to execute the sample, e.g. client and server running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks

Samples

TF631056 Version: 1.4

• To run the .NET sample client, only .NET Framework 4.0 is needed

Project downloads

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/TCP/Sample01

https://github.com/Beckhoff/TF6310_Samples/tree/master/C%23/SampleClient

Project description

The following links provide documentation for the three components. Additionally, an own article explainshow to start the PLC samples with step-by-step instructions.

• Integration in TwinCAT and Test [} 57] (Starting the PLC samples)

• PLC Client [} 60] (PLC client documentation: FB_LocalClient function block [} 60])

• PLC Server [} 64] (PLC serve documentation: FB_LocalServer function block [} 64])

• .NET client [} 70] (.NET client documentation: .NET sample client [} 70])

Auxiliary functions in the PLC sample projects

In the example projects, several functions, constants and function blocks are used, which are brieflydescribed below:LogError functionFUNCTION LogError : DINT

The function writes a message with the error code into the log book of the operating system (Event Viewer).The global variable bLogDebugMessages must first be set to TRUE.

LogMessage functionFUNCTION LogMessage : DINT

The function writes a message into the log book of the operating system (Event Viewer) if a new socket wasopened or closed. The global variable bLogDebugMessages must first be set to TRUE.

SCODE_CODE functionFUNCTION SCODE_CODE : DWORD

The function masks the lower 16 bits of a Win32 error code returns them.

Samples

TF6310 57Version: 1.4

Global variables

Name Default value DescriptionbLogDebugMessages TRUE Activates/deactivates writing of messages into the

log book of the operating systemMAX_CLIENT_CONNECTIONS 5 Max. number of remote clients, that can connect

to the server at the same time.MAX_PLCPRJ_RXBUFFER_SIZE 1000 Max. length of the internal receive bufferPLCPRJ_RECONNECT_TIME T#3s Once this time has elapsed, the local client will

attempt to re-establish the connection with theremote server

PLCPRJ_SEND_CYCLE_TIME T#1s The test string is sent cyclically at these intervalsfrom the local client to the remote server

PLCPRJ_RECEIVE_POLLING_TIME

T#1s The client reads (polls) data from the server usingthis cycle

PLCPRJ_RECEIVE_TIMEOUT T#10s After this time has elapsed, the local client abortsthe reception if no data bytes could be receivedduring this time

PLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW

16#8101 Sample project error code: Too many characterswithout zero termination were received

PLCPRJ_ERROR_RECEIVE_TIMEOUT

16#8102 Sample project error code: No new data could bereceived within the timeout time(PLCPRJ_RECEIVE_TIMEOUT)

6.1.1.2 Integration in TwinCAT and Test

The following section describes how to prepare and start the PLC server and client. The PLC samples aredelivered as TwinCAT 3 PLC project files. To import a PLC project into TwinCAT XAE, first create a newTwinCAT 3 Solution. Then select the command Add Existing Item in the context menu of the PLC node andselect the downloaded sample file (Plc 3.x Project archive (*.tpzip) as file type) in the dialog that opens. Afterconfirming the dialog, the PLC project is added to the solution.

PLC server sample

Create a new TwinCAT 3 solution in TwinCAT XAE and import the TCP/IP server project. Select a targetsystem. Make sure that you have created licenses for TF6310 and that the Function is also installed on theselected target system. Leave the TwinCAT 3 solution open.

Samples

TF631058 Version: 1.4

PROGRAM MAINVAR    fbServer         : FB_LocalServer := ( sLocalHost := '127.0.0.1' (*own IP address!*), nLocalPort := 200 );    bEnableServer    : BOOL := TRUE;    fbSocketCloseAll : FB_SocketCloseAll := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    bCloseAll        : BOOL := TRUE;END_VAR

IF bCloseAll THEN (*On PLC reset or program download close all old connections *)    bCloseAll := FALSE;    fbSocketCloseAll( bExecute:= TRUE );ELSE    fbSocketCloseAll( bExecute:= FALSE );END_IF

IF NOT fbSocketCloseAll.bBusy THEN    fbServer( bEnable := bEnableServer );END_IF

PLC client sample

In the same TwinCAT 3 solution, import the TCP/IP client project as a second PLC project. Link this PLCproject to another task than the server sample. The server's IP address has to be adapted to your remotesystem (initialization values of the sRemoteHost variables). In this case, the server is located on the samemachine, therefore enter 127.0.0.1. Activate the configuration, then login and start both PLC projects,beginning with the server.PROGRAM MAINVAR    fbClient1     : FB_LocalClient := ( sRemoteHost:= '127.0.0.1' (* IP address of remote server! *), nRemotePort:= 200 );    fbClient2     : FB_LocalClient := ( sRemoteHost:= '127.0.0.1', nRemotePort:= 200 );    fbClient3     : FB_LocalClient := ( sRemoteHost:= '127.0.0.1', nRemotePort:= 200 );    fbClient4     : FB_LocalClient := ( sRemoteHost:= '127.0.0.1', nRemotePort:= 200 );    fbClient5     : FB_LocalClient := ( sRemoteHost:= '127.0.0.1', nRemotePort:= 200 );

    bEnableClient1 : BOOL := TRUE;    bEnableClient2 : BOOL := FALSE;    bEnableClient3 : BOOL := FALSE;    bEnableClient4 : BOOL := FALSE;    bEnableClient5 : BOOL := FALSE;

    fbSocketCloseAll    : FB_SocketCloseAll := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    bCloseAll     : BOOL := TRUE;

    nCount     : UDINT;END_VAR

IF bCloseAll THEN (*On PLC reset or program download close all old connections *)    bCloseAll := FALSE;    fbSocketCloseAll( bExecute:= TRUE );ELSE    fbSocketCloseAll( bExecute:= FALSE );END_IF

IF NOT fbSocketCloseAll.bBusy THEN    nCount := nCount + 1;    fbClient1( bEnable := bEnableClient1, sToServer := CONCAT( 'CLIENT1-', UDINT_TO_STRING( nCount ) ) );    fbClient2( bEnable := bEnableClient2, sToServer := CONCAT( 'CLIENT2-', UDINT_TO_STRING( nCount ) ) );    fbClient3( bEnable := bEnableClient3, sToServer := CONCAT( 'CLIENT3-', UDINT_TO_STRING( nCount ) ) );    fbClient4( bEnable := bEnableClient4 );    fbClient5( bEnable := bEnableClient5 );END_IF

Up to five client instances can be activated by setting the bEnableClientX variable. Each client sends a string(default: 'TEST') to the server approximately every second. The server returns the same string to the client(echo). For the test, a string with a counter value is generated automatically for the first three instances. Thefirst client is activated automatically when the program is started. Set the bEnableClient4 variable in theclient project to TRUE. The new client instance will then attempt to establish a connection with the server. Ifsuccessful, the 'TEST' string is sent cyclically. Now open the fbClient4 instance of the FB_LocalClientfunction block. Double-click to open the dialog for writing the sToString variable. Change the value of thestring variable, for example to 'Hello'.

Samples

TF6310 59Version: 1.4

Close the dialog with OK. Write the new value into the PLC. Shortly afterwards, the value is send back bythe server can also be seen online.

Now open the fbServer instance of the FB_LocalServer function block in the server project. Our string: 'Hello'can be seen in the online data of the server.

Samples

TF631060 Version: 1.4

6.1.1.3 PLC Client

6.1.1.3.1 FB_LocalClient

If the bEnable input is set, the system will keep trying to establish the connection to the remote server oncethe PLCPRJ_RECONNECT_TIME has elapsed. The remote server is identified via the sRemoteHost IPaddress and the nRemotePort IP port address. The data exchange with the server was encapsulated in aseparate function block (FB_ClientDataExcha [} 62]). Data exchange is always cyclic oncePLCPRJ_SEND_CYCLE_TIME has elapsed. The sToServer string variable is sent to the server, and thestring sent back by the server is returned at output sFormServer. Another implementation, in which theremote server is addressed as required is also possible. In the event of an error, the existing connection isclosed, and a new connection is established.

InterfaceFUNCTION_BLOCK FB_LocalClientVAR_INPUT    sRemoteHost     : STRING(15) := '127.0.0.1';(* IP adress of remote server *)    nRemotePort     : UDINT := 0;    sToServer       : T_MaxString:= 'TEST';    bEnable         : BOOL;END_VARVAR_OUTPUT    bConnected      : BOOL;    hSocket         : T_HSOCKET;    bBusy           : BOOL;    bError          : BOOL;    nErrId          : UDINT;    sFromServer     : T_MaxString;END_VAR

Samples

TF6310 61Version: 1.4

VAR    fbConnect       : FB_SocketConnect := ( sSrvNetId := '' );    fbClose         : FB_SocketClose := ( sSrvNetId := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbClientDataExcha : FB_ClientDataExcha;

    fbConnectTON     : TON := ( PT := PLCPRJ_RECONNECT_TIME );    fbDataExchaTON   : TON := ( PT := PLCPRJ_SEND_CYCLE_TIME );    eStep            : E_ClientSteps;END_VAR

ImplementationCASE eStep OF    CLIENT_STATE_IDLE:        IF bEnable XOR bConnected THEN            bBusy := TRUE;            bError := FALSE;            nErrid := 0;            sFromServer := '';            IF bEnable THEN                fbConnectTON( IN := FALSE );                eStep := CLIENT_STATE_CONNECT_START;            ELSE                eStep := CLIENT_STATE_CLOSE_START;            END_IF        ELSIF bConnected THEN            fbDataExchaTON( IN := FALSE );            eStep := CLIENT_STATE_DATAEXCHA_START;        ELSE            bBusy := FALSE;        END_IF

    CLIENT_STATE_CONNECT_START:        fbConnectTON( IN := TRUE, PT := PLCPRJ_RECONNECT_TIME );        IF fbConnectTON.Q THEN            fbConnectTON( IN := FALSE );            fbConnect( bExecute := FALSE );                fbConnect(sRemoteHost := sRemoteHost,                nRemotePort := nRemotePort,                bExecute        := TRUE );            eStep := CLIENT_STATE_CONNECT_WAIT;        END_IF

    CLIENT_STATE_CONNECT_WAIT:        fbConnect( bExecute := FALSE );        IF NOT fbConnect.bBusy THEN            IF NOT fbConnect.bError THEN                bConnected := TRUE;                hSocket         := fbConnect.hSocket;                eStep     := CLIENT_STATE_IDLE;                LogMessage( 'LOCAL client CONNECTED!', hSocket );            ELSE                LogError( 'FB_SocketConnect', fbConnect.nErrId );                nErrId := fbConnect.nErrId;                eStep := CLIENT_STATE_ERROR;            END_IF           END_IF

    CLIENT_STATE_DATAEXCHA_START:        fbDataExchaTON( IN := TRUE, PT := PLCPRJ_SEND_CYCLE_TIME );        IF fbDataExchaTON.Q THEN            fbDataExchaTON( IN := FALSE );            fbClientDataExcha( bExecute := FALSE );            fbClientDataExcha( hSocket := hSocket,                    sToServer := sToServer,                    bExecute    := TRUE );            eStep := CLIENT_STATE_DATAEXCHA_WAIT;        END_IF

    CLIENT_STATE_DATAEXCHA_WAIT:        fbClientDataExcha( bExecute := FALSE );        IF NOT fbClientDataExcha.bBusy THEN            IF NOT fbClientDataExcha.bError THEN                sFromServer := fbClientDataExcha.sFromServer;                eStep     := CLIENT_STATE_IDLE;            ELSE                (* possible errors are logged inside of fbClientDataExcha function block *)                nErrId := fbClientDataExcha.nErrId;                     eStep :=CLIENT_STATE_ERROR;

Samples

TF631062 Version: 1.4

            END_IF        END_IF

    CLIENT_STATE_CLOSE_START:        fbClose( bExecute := FALSE );        fbClose(    hSocket:= hSocket,            bExecute:= TRUE );        eStep := CLIENT_STATE_CLOSE_WAIT;

    CLIENT_STATE_CLOSE_WAIT:        fbClose( bExecute := FALSE );        IF NOT fbClose.bBusy THEN            LogMessage( 'LOCAL client CLOSED!', hSocket );            bConnected := FALSE;            MEMSET( ADR(hSocket), 0, SIZEOF(hSocket));            IF fbClose.bError THEN                LogError( 'FB_SocketClose (local client)', fbClose.nErrId );                nErrId := fbClose.nErrId;                eStep := CLIENT_STATE_ERROR;            ELSE                bBusy := FALSE;                bError := FALSE;                     nErrId := 0;                eStep := CLIENT_STATE_IDLE;            END_IF        END_IF

    CLIENT_STATE_ERROR: (* Error step *)        bError := TRUE;        IF bConnected THEN            eStep := CLIENT_STATE_CLOSE_START;        ELSE            bBusy := FALSE;            eStep := CLIENT_STATE_IDLE;        END_IFEND_CASE

6.1.1.3.2 FB_ClientDataExcha

In the event of an rising edge at the bExecute input, a zero-terminated string is sent to the remote server,and a string returned by the remote server is read. The function block will try reading the data until zerotermination was detected in the string received. Reception is aborted in the event of an error, and if no newdata were received within the PLCPRJ_RECEIVE_TIMEOUT timeout time. Data are attempted to be readagain after a certain delay time, if no new data could be read during the last read attempt. This reduces thesystem load.

InterfaceFUNCTION_BLOCK FB_ClientDataExchaVAR_INPUT    hSocket     : T_HSOCKET;    sToServer   : T_MaxString;    bExecute    : BOOL;END_VARVAR_OUTPUT    bBusy       : BOOL;    bError      : BOOL;    nErrId      : UDINT;    sFromServer : T_MaxString;END_VARVAR    fbSocketSend : FB_SocketSend := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbSocketReceive : FB_SocketReceive := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbReceiveTON : TON;    fbDisconnectTON : TON;    RisingEdge : R_TRIG;

Samples

TF6310 63Version: 1.4

    eStep     : E_DataExchaSteps;    cbReceived, startPos, endPos, idx : UDINT;    cbFrame     : UDINT;    rxBuffer    : ARRAY[0..MAX_PLCPRJ_RXBUFFER_SIZE] OF BYTE;END_VAR

ImplementationRisingEdge( CLK := bExecute );CASE eStep OF    DATAEXCHA_STATE_IDLE:        IF RisingEdge.Q THEN            bBusy := TRUE;            bError := FALSE;            nErrid := 0;            cbReceived := 0;            fbReceiveTON( IN := FALSE, PT := T#0s ); (* don't wait, read the first answer data immediately *)            fbDisconnectTON( IN := FALSE, PT := T#0s );(* disable timeout check first *)            eStep := DATAEXCHA_STATE_SEND_START;        END_IF

    DATAEXCHA_STATE_SEND_START:        fbSocketSend( bExecute := FALSE );        fbSocketSend( hSocket := hSocket,                pSrc := ADR( sToServer ),                cbLen := LEN( sToServer ) + 1,(* string length inclusive zero delimiter *)                bExecute:= TRUE );        eStep := DATAEXCHA_STATE_SEND_WAIT;

    DATAEXCHA_STATE_SEND_WAIT:        fbSocketSend( bExecute := FALSE );        IF NOT fbSocketSend.bBusy THEN            IF NOT fbSocketSend.bError THEN                eStep := DATAEXCHA_STATE_RECEIVE_START;            ELSE                     LogError( 'FB_SocketSend (local client)', fbSocketSend.nErrId );                nErrId := fbSocketSend.nErrId;                eStep := DATAEXCHA_STATE_ERROR;            END_IF        END_IF

    DATAEXCHA_STATE_RECEIVE_START:        fbDisconnectTON( );        fbReceiveTON( IN := TRUE );        IF fbReceiveTON.Q THEN            fbReceiveTON( IN := FALSE );            fbSocketReceive( bExecute := FALSE );            fbSocketReceive( hSocket:= hSocket,                    pDest:= ADR( rxBuffer ) + cbReceived,                    cbLen:= SIZEOF( rxBuffer ) - cbReceived,                    bExecute:= TRUE );            eStep := DATAEXCHA_STATE_RECEIVE_WAIT;        END_IF

    DATAEXCHA_STATE_RECEIVE_WAIT:        fbSocketReceive( bExecute := FALSE );        IF NOT fbSocketReceive.bBusy THEN            IF NOT fbSocketReceive.bError THEN                     IF (fbSocketReceive.nRecBytes > 0) THEN(* bytes received *)                    startPos        := cbReceived;(* rxBuffer array index of first data byte *)                    endPos         := cbReceived + fbSocketReceive.nRecBytes - 1;(* rxBuffer array index of last data byte *)                    cbReceived := cbReceived + fbSocketReceive.nRecBytes;(* calculate the number of received data bytes *)                    cbFrame     := 0;(* reset frame length *)                    IF cbReceived < SIZEOF( sFromServer ) THEN(* no overflow *)                        fbReceiveTON( PT := T#0s ); (* bytes received => increase the read (polling) speed *)                        fbDisconnectTON( IN := FALSE );(* bytes received => disable timeout check *)                        (* search for string end delimiter *)                        FOR idx := startPos TO endPos BY 1 DO                                    IF rxBuffer[idx] = 0 THEN(* string end delimiter found *)                                cbFrame := idx + 1;(* calculate the length of the received string (inclusive the end delimiter) *)                                MEMCPY( ADR( sFromServer ), ADR( rxBuffer ), cbFrame );(* copy the received string to the output variable (inclusive the end delimiter) *)                                MEMMOVE( ADR( rxBuffer ), ADR( rxBuffer[cbFrame] ), cbReceived - cbFrame );(* move the reamaining data bytes *)

Samples

TF631064 Version: 1.4

                                cbReceived := cbReceived - cbFrame;(* recalculate the remaining data byte length *)                                bBusy := FALSE;                                eStep := DATAEXCHA_STATE_IDLE;                                EXIT;                                    END_IF                        END_FOR                    ELSE(* there is no more free read buffer space => the answer string should be terminated *)                        LogError( 'FB_SocketReceive (local client)', PLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW );                        nErrId := PLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW;(* buffer overflow !*)                        eStep := DATAEXCHA_STATE_ERROR;                    END_IF                ELSE(* no bytes received *)                    fbReceiveTON( PT := PLCPRJ_RECEIVE_POLLING_TIME );(* no bytes received => decrease the read (polling) speed *)                    fbDisconnectTON( IN := TRUE, PT := PLCPRJ_RECEIVE_TIMEOUT );(* no bytes received => enable timeout check*)                    IF fbDisconnectTON.Q THEN (* timeout error*)                               fbDisconnectTON( IN := FALSE );                        LogError( 'FB_SocketReceive (local client)', PLCPRJ_ERROR_RECEIVE_TIMEOUT );                        nErrID := PLCPRJ_ERROR_RECEIVE_TIMEOUT;                        eStep := DATAEXCHA_STATE_ERROR;                    ELSE(* repeat reading *)                        eStep := DATAEXCHA_STATE_RECEIVE_START; (* repeat reading *)                    END_IF                END_IF            ELSE(* receive error *)                LogError( 'FB_SocketReceive (local client)', fbSocketReceive.nErrId );                nErrId := fbSocketReceive.nErrId;                eStep := DATAEXCHA_STATE_ERROR;            END_IF           END_IF

    DATAEXCHA_STATE_ERROR:(* error step *)        bBusy := FALSE;        bError := TRUE;        cbReceived := 0;        eStep := DATAEXCHA_STATE_IDLE;END_CASE

6.1.1.4 PLC Server

6.1.1.4.1 FB_LocalServer

The server must first be allocated a unique sLocalHost IP address and an nLocaPort IP port number. If thebEnable input is set, the local server will repeatedly try to open the listener socket once thePLCPRJ_RECONNECT_TIME has elapsed. The listener socket can usually be opened at the first attempt, ifthe TwinCAT TCP/IP Connection Server resides on the local PC. The functionality of a remote client wasencapsulated in the function block FB_RemoteClient [} 66]. The remote client instances are activated oncethe listener socket was opened successfully. Each instance of the FB_RemoteClient corresponds to aremote client, with which the local server can communicate simultaneously. The maximum number of remoteclients communicating with the server can be modified via the value of the MAX_CLIENT_CONNECTIONSconstant. In the event of an error, first all remote client connections are closed, followed by the listenersockets. The nAcceptedClients output provides information about the current number of connected clients.

Samples

TF6310 65Version: 1.4

InterfaceFUNCTION_BLOCK FB_LocalServerVAR_INPUT    sLocalHost       : STRING(15) := '127.0.0.1';(* own IP address! *)    nLocalPort       : UDINT := 0;    bEnable          : BOOL;END_VARVAR_OUTPUT    bListening       : BOOL;    hListener        : T_HSOCKET;    nAcceptedClients : UDINT;    bBusy            : BOOL;    bError           : BOOL;    nErrId           : UDINT;END_VARVAR    fbListen        : FB_SocketListen := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbClose         : FB_SocketClose := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbConnectTON    : TON := ( PT := PLCPRJ_RECONNECT_TIME );    eStep           : E_ServerSteps;    fbRemoteClient  : ARRAY[1..MAX_CLIENT_CONNECTIONS ] OF FB_RemoteClient;    i               : UDINT;END_VAR

ImplementationCASE eStep OF

    SERVER_STATE_IDLE:        IF bEnable XOR bListening THEN            bBusy := TRUE;            bError := FALSE;            nErrId := 0;            IF bEnable THEN                fbConnectTON( IN := FALSE );                eStep := SERVER_STATE_LISTENER_OPEN_START;            ELSE                eStep := SERVER_STATE_REMOTE_CLIENTS_CLOSE;            END_IF        ELSIF bListening THEN            eStep := SERVER_STATE_REMOTE_CLIENTS_COMM;        END_IF

    SERVER_STATE_LISTENER_OPEN_START:        fbConnectTON( IN := TRUE, PT := PLCPRJ_RECONNECT_TIME );        IF fbConnectTON.Q THEN            fbConnectTON( IN := FALSE );            fbListen( bExecute := FALSE );            fbListen( sLocalHost:= sLocalHost,                nLocalPort:= nLocalPort,                bExecute    := TRUE );                eStep := SERVER_STATE_LISTENER_OPEN_WAIT;        END_IF

    SERVER_STATE_LISTENER_OPEN_WAIT:        fbListen( bExecute := FALSE );        IF NOT fbListen.bBusy THEN            IF NOT fbListen.bError THEN                bListening := TRUE;                hListener := fbListen.hListener;                eStep     := SERVER_STATE_IDLE;                LogMessage( 'LISTENER socket OPENED!', hListener );            ELSE                LogError( 'FB_SocketListen', fbListen.nErrId );                nErrId := fbListen.nErrId;                eStep := SERVER_STATE_ERROR;            END_IF        END_IF

    SERVER_STATE_REMOTE_CLIENTS_COMM:        eStep := SERVER_STATE_IDLE;        nAcceptedClients := 0;        FOR i:= 1 TO MAX_CLIENT_CONNECTIONS DO            fbRemoteClient[ i ]( hListener := hListener, bEnable := TRUE );            IF NOT fbRemoteClient[ i ].bBusy AND fbRemoteClient[ i ].bError THEN (*FB_SocketAccept returned error!*)                     eStep := SERVER_STATE_REMOTE_CLIENTS_CLOSE;                EXIT;

Samples

TF631066 Version: 1.4

            END_IF            (* count the number of connected remote clients *)            IF fbRemoteClient[ i ].bAccepted THEN                nAcceptedClients := nAcceptedClients + 1;            END_IF        END_FOR

    SERVER_STATE_REMOTE_CLIENTS_CLOSE:        nAcceptedClients := 0;        eStep := SERVER_STATE_LISTENER_CLOSE_START; (* close listener socket too *)        FOR i:= 1 TO MAX_CLIENT_CONNECTIONS DO            fbRemoteClient[ i ]( bEnable := FALSE );(* close all remote client (accepted) sockets *)            (* check if all remote client sockets are closed *)            IF fbRemoteClient[ i ].bAccepted THEN                eStep := SERVER_STATE_REMOTE_CLIENTS_CLOSE; (* stay here and close all remote clients first *)                nAcceptedClients := nAcceptedClients + 1;            END_IF        END_FOR

    SERVER_STATE_LISTENER_CLOSE_START:        fbClose( bExecute := FALSE );        fbClose(    hSocket := hListener,                     bExecute:= TRUE );        eStep := SERVER_STATE_LISTENER_CLOSE_WAIT;

    SERVER_STATE_LISTENER_CLOSE_WAIT:        fbClose( bExecute := FALSE );        IF NOT fbClose.bBusy THEN            LogMessage( 'LISTENER socket CLOSED!', hListener );            bListening := FALSE;            MEMSET( ADR(hListener), 0, SIZEOF(hListener));            IF fbClose.bError THEN                LogError( 'FB_SocketClose (listener)', fbClose.nErrId );                nErrId := fbClose.nErrId;                eStep := SERVER_STATE_ERROR;            ELSE                bBusy := FALSE;                bError := FALSE;                nErrId := 0;                eStep := SERVER_STATE_IDLE;            END_IF        END_IF

    SERVER_STATE_ERROR:        bError := TRUE;           IF bListening THEN            eStep := SERVER_STATE_REMOTE_CLIENTS_CLOSE;        ELSE            bBusy := FALSE;            eStep := SERVER_STATE_IDLE;        END_IF

END_CASE

6.1.1.4.2 FB_RemoteClient

If the bEnable input is set, an attempt is made to accept the connection request of a remote client, once thePLCPRJ_ACCEPT_POOLING_TIME has elapsed. The data exchange with the remote client wasencapsulated in a separate function block (FB_ServerDataExcha [} 68]). Once the connection wasestablished successfully, the instance is activated via the FB_ServerDataExcha function block. In the eventof an error, the accepted connection is closed, and a new connection is established.

Samples

TF6310 67Version: 1.4

InterfaceFUNCTION_BLOCK FB_RemoteClientVAR_INPUT    hListener     : T_HSOCKET;    bEnable       : BOOL;END_VARVAR_OUTPUT    bAccepted     : BOOL;    hSocket       : T_HSOCKET;    bBusy         : BOOL;    bError        : BOOL;    nErrID        : UDINT;    sFromClient   : T_MaxString;END_VARVAR    fbAccept            : FB_SocketAccept := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbClose             : FB_SocketClose := ( sSrvNetID := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbServerDataExcha     : FB_ServerDataExcha;    fbAcceptTON     : TON := ( PT := PLCPRJ_ACCEPT_POLLING_TIME );    eStep         : E_ClientSteps;END_VAR

ImplementationCASE eStep OF

    CLIENT_STATE_IDLE:        IF bEnable XOR bAccepted THEN            bBusy := TRUE;            bError := FALSE;            nErrId := 0;            sFromClient := '';            IF bEnable THEN                fbAcceptTON( IN := FALSE );                eStep := CLIENT_STATE_CONNECT_START;            ELSE                eStep := CLIENT_STATE_CLOSE_START;            END_IF        ELSIF bAccepted THEN            eStep := CLIENT_STATE_DATAEXCHA_START;        ELSE            bBusy := FALSE;        END_IF

    CLIENT_STATE_CONNECT_START:        fbAcceptTON( IN := TRUE, PT := PLCPRJ_ACCEPT_POLLING_TIME );        IF fbAcceptTON.Q THEN            fbAcceptTON( IN := FALSE );            fbAccept( bExecute := FALSE );            fbAccept( hListener := hListener,                               bExecute:= TRUE );            eStep := CLIENT_STATE_CONNECT_WAIT;        END_IF

    CLIENT_STATE_CONNECT_WAIT:        fbAccept( bExecute := FALSE );        IF NOT fbAccept.bBusy THEN            IF NOT fbAccept.bError THEN                IF fbAccept.bAccepted THEN                    bAccepted := TRUE;                    hSocket := fbAccept.hSocket;                    LogMessage( 'REMOTE client ACCEPTED!', hSocket );                END_IF                eStep := CLIENT_STATE_IDLE;            ELSE                LogError( 'FB_SocketAccept', fbAccept.nErrId );                nErrId := fbAccept.nErrId;                eStep := CLIENT_STATE_ERROR;                END_IF        END_IF

    CLIENT_STATE_DATAEXCHA_START:        fbServerDataExcha( bExecute := FALSE );        fbServerDataExcha( hSocket := hSocket,                bExecute := TRUE );        eStep := CLIENT_STATE_DATAEXCHA_WAIT;

    CLIENT_STATE_DATAEXCHA_WAIT:

Samples

TF631068 Version: 1.4

        fbServerDataExcha( bExecute := FALSE, sFromClient=>sFromClient );        IF NOT fbServerDataExcha.bBusy THEN            IF NOT fbServerDataExcha.bError THEN                eStep := CLIENT_STATE_IDLE;            ELSE                (* possible errors are logged inside of fbServerDataExcha function block *)                nErrId := fbServerDataExcha.nErrID;                eStep := CLIENT_STATE_ERROR;            END_IF        END_IF

    CLIENT_STATE_CLOSE_START:        fbClose( bExecute := FALSE );        fbClose(    hSocket:= hSocket,                bExecute:= TRUE );        eStep := CLIENT_STATE_CLOSE_WAIT;

    CLIENT_STATE_CLOSE_WAIT:        fbClose( bExecute := FALSE );           IF NOT fbClose.bBusy THEN            LogMessage( 'REMOTE client CLOSED!', hSocket );            bAccepted := FALSE;            MEMSET( ADR( hSocket ), 0, SIZEOF( hSocket ) );            IF fbClose.bError THEN                LogError( 'FB_SocketClose (remote client)', fbClose.nErrId );                nErrId := fbClose.nErrId;                eStep := CLIENT_STATE_ERROR;            ELSE                bBusy := FALSE;                bError := FALSE;                nErrId := 0;                eStep := CLIENT_STATE_IDLE;            END_IF        END_IF

    CLIENT_STATE_ERROR:        bError := TRUE;        IF bAccepted THEN            eStep := CLIENT_STATE_CLOSE_START;        ELSE            eStep := CLIENT_STATE_IDLE;                bBusy := FALSE;        END_IF

END_CASE

6.1.1.4.3 FB_ServerDataExcha

In the event of an rising edge at the bExecute input, a zero-terminated string is read by the remote client andreturned to the remote client, if zero termination was detected. The function block will try reading the datauntil zero termination was detected in the string received. Reception is aborted in the event of an error, and ifno new data were received within the PLCPRJ_RECEIVE_TIMEOUT timeout time. Data are attempted to beread again after a certain delay time, if no new data could be read during the last read attempt. This reducesthe system load.

InterfaceFUNCTION_BLOCK FB_ServerDataExchaVAR_INPUT    hSocket     : T_HSOCKET;    bExecute    : BOOL;END_VARVAR_OUTPUT    bBusy       : BOOL;    bError      : BOOL;    nErrID      : UDINT;    sFromClient : T_MaxString;

Samples

TF6310 69Version: 1.4

END_VARVAR    fbSocketReceive : FB_SocketReceive := ( sSrvNetId := '', tTimeout := DEFAULT_ADS_TIMEOUT );    fbSocketSend : FB_SocketSend := ( sSrvNetId := '', tTimeout := DEFAULT_ADS_TIMEOUT );    eStep     : E_DataExchaSteps;    RisingEdge : R_TRIG;    fbReceiveTON : TON;    fbDisconnectTON     : TON;    cbReceived, startPos, endPos, idx : UDINT;    cbFrame     : UDINT;    rxBuffer        : ARRAY[0..MAX_PLCPRJ_RXBUFFER_SIZE] OF BYTE;END_VAR

ImplementationRisingEdge( CLK := bExecute );CASE eStep OF

    DATAEXCHA_STATE_IDLE:        IF RisingEdge.Q THEN            bBusy := TRUE;            bError := FALSE;            nErrId := 0;            fbDisconnectTON( IN := FALSE, PT := T#0s );(* disable timeout check first *)            fbReceiveTON( IN := FALSE, PT := T#0s ); (* receive first request immediately *)            eStep := DATAEXCHA_STATE_RECEIVE_START;        END_IF

    DATAEXCHA_STATE_RECEIVE_START: (* Receive remote client data *)        fbReceiveTON( IN := TRUE );        IF fbReceiveTON.Q THEN            fbReceiveTON( IN := FALSE );            fbSocketReceive( bExecute := FALSE );            fbSocketReceive(    hSocket := hSocket,                    pDest := ADR( rxBuffer ) + cbReceived,                    cbLen := SIZEOF( rxBuffer ) - cbReceived,                    bExecute    := TRUE );            eStep := DATAEXCHA_STATE_RECEIVE_WAIT;        END_IF

    DATAEXCHA_STATE_RECEIVE_WAIT:        fbSocketReceive( bExecute := FALSE );           IF NOT fbSocketReceive.bBusy THEN            IF NOT fbSocketReceive.bError THEN

                IF (fbSocketReceive.nRecBytes > 0) THEN(* bytes received *)

                    startPos        := cbReceived;(* rxBuffer array index of first data byte *)                    endPos         := cbReceived + fbSocketReceive.nRecBytes - 1;(* rxBuffer array index of last data byte *)                    cbReceived := cbReceived + fbSocketReceive.nRecBytes;(* calculate the number of received data bytes *)                    cbFrame     := 0;(* reset frame length *)

                    IF cbReceived < SIZEOF( sFromClient ) THEN(* no overflow *)

                        fbReceiveTON( IN := FALSE, PT := T#0s ); (* bytes received => increase the read (polling) speed *)                        fbDisconnectTON( IN := FALSE, PT := PLCPRJ_RECEIVE_TIMEOUT );(* bytes received => disable timeout check *)

                        (* search for string end delimiter *)                        FOR idx := startPos TO endPos BY 1 DO                                    IF rxBuffer[idx] = 0 THEN(* string end delimiter found *)                                cbFrame := idx + 1;(* calculate the length of the received string (inclusive the end delimiter) *)                                MEMCPY( ADR( sFromClient ), ADR( rxBuffer ), cbFrame );(* copy the received string to the output variable (inclusive the end delimiter) *)                                MEMMOVE( ADR( rxBuffer ), ADR( rxBuffer[cbFrame] ), cbReceived - cbFrame );(* move the reamaining data bytes *)                                cbReceived := cbReceived - cbFrame;(* recalculate the reamaining data byte length *)                                eStep := DATAEXCHA_STATE_SEND_START;                                EXIT;                            END_IF                               END_FOR

                    ELSE(* there is no more free read buffer space => the answer string should be terminated *)

Samples

TF631070 Version: 1.4

                        LogError( 'FB_SocketReceive (remote client)', PLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW );                        nErrId := PLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW;(* buffer overflow !*)                        eStep := DATAEXCHA_STATE_ERROR;                    END_IF

                ELSE(* no bytes received *)                    fbReceiveTON( IN := FALSE, PT := PLCPRJ_RECEIVE_POLLING_TIME );(* no bytes received => decrease the read (polling) speed *)                    fbDisconnectTON( IN := TRUE, PT := PLCPRJ_RECEIVE_TIMEOUT );(* no bytes received => enable timeout check*)                    IF fbDisconnectTON.Q THEN (* timeout error*)                        fbDisconnectTON( IN := FALSE );                               LogError( 'FB_SocketReceive (remote client)', PLCPRJ_ERROR_RECEIVE_TIMEOUT );                        nErrID := PLCPRJ_ERROR_RECEIVE_TIMEOUT;                        eStep := DATAEXCHA_STATE_ERROR;                    ELSE(* repeat reading *)                        eStep := DATAEXCHA_STATE_RECEIVE_START; (* repeat reading *)                    END_IF                END_IF            ELSE(* receive error *)                LogError( 'FB_SocketReceive (remote client)', fbSocketReceive.nErrId );                nErrId := fbSocketReceive.nErrId;                eStep := DATAEXCHA_STATE_ERROR;            END_IF        END_IF

    DATAEXCHA_STATE_SEND_START:        fbSocketSend( bExecute := FALSE );        fbSocketSend( hSocket := hSocket,                               pSrc := ADR( sFromClient ),                        cbLen := LEN( sFromClient ) + 1,(* string length inclusive the zero delimiter *)                        bExecute:= TRUE );        eStep := DATAEXCHA_STATE_SEND_WAIT;

    DATAEXCHA_STATE_SEND_WAIT:        fbSocketSend( bExecute := FALSE );        IF NOT fbSocketSend.bBusy THEN            IF NOT fbSocketSend.bError THEN                bBusy := FALSE;                eStep := DATAEXCHA_STATE_IDLE;            ELSE                LogError( 'fbSocketSend (remote client)', fbSocketSend.nErrId );                nErrId := fbSocketSend.nErrId;                eStep := DATAEXCHA_STATE_ERROR;            END_IF        END_IF

    DATAEXCHA_STATE_ERROR:        bBusy := FALSE;        bError := TRUE;        cbReceived := 0;(* reset old received data bytes *)           eStep := DATAEXCHA_STATE_IDLE;END_CASE

6.1.1.5 .NET client

This project example shows how a client for the PLC TCP/IP server can be realized by writing a .NET4.0application using C#.

Samples

TF6310 71Version: 1.4

This sample client makes use of the .NET libraries System.Net and System.Net.Sockets which enable aprogrammer easy access to socket functionalities. By pressing the button Enable, the application attempts tocyclically (depending on the value of TIMERTICK in [ms]) establish a connection with the server. Ifsuccessful, a string with a maximum length of 255 characters can be sent to the server via the "Send" button.The server will then take this string and send it back to the client. On the server side, the connection isclosed automatically if the server was unable to receive new data from the client within a defined period, asspecified by PLCPRJ_RECEIVE_TIMEOUT in the server sample - by default 50 seconds.using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net; using System.Net.Sockets;

/* ##########################################################################################  * This sample TCP/IP client connects to a TCP/IP-Server, sends a message and waits for the  * response. It is being delivered together with our TCP-Sample, which implements an echo server  * in PLC.  * ########################################################################################## */namespace TcpIpServer_SampleClient{ publicpartialclassForm1 : Form {    /* ##########################################################################################         * Constants     

Samples

TF631072 Version: 1.4

    * ########################################################################################## */privateconstint RCVBUFFERSIZE = 256; // buffer size for receive bufferprivateconststring DEFAULTIP = "127.0.0.1";    privateconststring DEFAULTPORT = "200";    privateconstint TIMERTICK = 100;     /* ##########################################################################################         * Global variables         * ########################################################################################## */privatestaticbool _isConnected; // signals whether socket connection is active or notprivatestaticSocket _socket; // object used for socket connection to TCP/IP-ServerprivatestaticIPEndPoint _ipAddress; // contains IP address as entered in text fieldprivatestaticbyte[] _rcvBuffer; // receive buffer used for receiving response from TCP/IP-Serverpublic Form1()    {     InitializeComponent();    }     privatevoid Form1_Load(object sender, EventArgs e)    {     _rcvBuffer = newbyte[RCVBUFFERSIZE];      /* ##########################################################################################          * Prepare GUI          * ########################################################################################## */     cmd_send.Enabled = false;     cmd_enable.Enabled = true;     cmd_disable.Enabled = false;     rtb_rcvMsg.Enabled = false;     rtb_sendMsg.Enabled = false;     rtb_statMsg.Enabled = false;     txt_host.Text = DEFAULTIP;     txt_port.Text = DEFAULTPORT;      timer1.Enabled = false;     timer1.Interval = TIMERTICK;     _isConnected = false;    }     privatevoid cmd_enable_Click(object sender, EventArgs e)    {     /* ##########################################################################################          * Parse IP address in text field, start background timer and prepare GUI          * ########################################################################################## */try     {        _ipAddress = newIPEndPoint(IPAddress.Parse(txt_host.Text), Convert.ToInt32(txt_port.Text));        timer1.Enabled = true;        cmd_enable.Enabled = false;        cmd_disable.Enabled = true;        rtb_sendMsg.Enabled = true;        cmd_send.Enabled = true;        txt_host.Enabled = false;        txt_port.Enabled = false;        rtb_sendMsg.Focus();     }     catch (Exception ex)       {        MessageBox.Show("Could not parse entered IP address. Please check spelling and retry. " + ex);     }    }     /* ##########################################################################################         * Timer periodically checks for connection to TCP/IP-Server and reestablishes if not connected         * ########################################################################################## */privatevoid timer1_Tick(object sender, EventArgs e)    {     if (!_isConnected)        connect();    }     privatevoid connect()    {     /* ##########################################################################################     

Samples

TF6310 73Version: 1.4

     * Connect to TCP/IP-Server using the IP address specified in the text field          * ########################################################################################## */try     {        _socket = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);        _socket.Connect(_ipAddress);        _isConnected = true;        if (_socket.Connected)         rtb_statMsg.AppendText(DateTime.Now.ToString() + ": Connectection to host established!\n");        else         rtb_statMsg.AppendText(DateTime.Now.ToString() + ": A connection to the host could not be established!\n");     }     catch (Exception ex)     {        MessageBox.Show("An error occured while establishing a connection to the server: " + ex);     }    }     privatevoid cmd_send_Click(object sender, EventArgs e)    {     /* ##########################################################################################          * Read message from text field and prepare send buffer, which is a byte[] array. The last          * character in the buffer needs to be a termination character, so that the TCP/IP-Server knows          * when the TCP stream ends. In this case, the termination character is '0'.          * ########################################################################################## */ASCIIEncoding enc = newASCIIEncoding();     byte[] tempBuffer = enc.GetBytes(rtb_sendMsg.Text);     byte[] sendBuffer = newbyte[tempBuffer.Length + 1];     for (int i = 0; i < tempBuffer.Length; i++)        sendBuffer[i] = tempBuffer[i];     sendBuffer[tempBuffer.Length] = 0;      /* ##########################################################################################            * Send buffer content via TCP/IP connection          * ########################################################################################## */try     {        int send = _socket.Send(sendBuffer);        if (send == 0)         thrownewException();        else        {         /* ##########################################################################################                 * As the TCP/IP-Server returns a message, receive this message and store content in receive buffer.                  * When message receive is complete, show the received message in text field.                  * ########################################################################################## */         rtb_statMsg.AppendText(DateTime.Now.ToString() + ": Message successfully sent!\n");         IAsyncResult asynRes = _socket.BeginReceive(_rcvBuffer, 0, 256, SocketFlags.None, null, null);         if (asynRes.AsyncWaitHandle.WaitOne())         {            int res = _socket.EndReceive(asynRes);            char[] resChars = newchar[res + 1];            Decoder d = Encoding.UTF8.GetDecoder();            int charLength = d.GetChars(_rcvBuffer, 0, res, resChars, 0, true);            String result = newString(resChars);            rtb_rcvMsg.AppendText("\n" + DateTime.Now.ToString() + ": " + result);            rtb_sendMsg.Clear();         }        }     }     catch (Exception ex)       {        MessageBox.Show("An error occured while sending the message: " + ex);     }    }     privatevoid cmd_disable_Click(object sender, EventArgs e)    {     /* ##########################################################################################          * Disconnect from TCP/IP-Server, stop the timer and prepare GUI     

Samples

TF631074 Version: 1.4

     * ########################################################################################## */     timer1.Enabled = false;     _socket.Disconnect(true);     if (!_socket.Connected)     {        _isConnected = false;        cmd_disable.Enabled = false;        cmd_enable.Enabled = true;        txt_host.Enabled = true;        txt_port.Enabled = true;        rtb_sendMsg.Enabled = false;        cmd_send.Enabled = false;        rtb_statMsg.AppendText(DateTime.Now.ToString() + ": Connectection to host closed!\n");        rtb_rcvMsg.Clear();        rtb_statMsg.Clear();     }    } }}

6.1.2 Sample02: “Echo“ client /serverThis sample is based on the functionality offered by the former TcSocketHelper.Lib, which is now part ofTc2_TcpIp library. It realizes a Client/Server PLC application based on the functionality provided by theformer SocketHelper library.

The client cyclically sends a test string (sToServer) to the remote server. The server returns the same stringunchanged to the client (sFromServer).

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP• If two computers are used to execute the sample (one client and one server), the Function TF6310

needs to be installed on both computers• If one computer is used to execute the sample, e.g. client and server running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks.

Project downloads

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/TCP/Sample02

Samples

TF6310 75Version: 1.4

Project information

The default communication settings used in the above samples are as follows:

• PLC client application: Port and IP address of the remote server: 200, '127.0.0.1'• PLC server application: Port and IP address of the local server: 200, '127.0.0.1'

To test the client and server application on two different PCs, you have to adjust the port and the IP addressaccordingly.

However, you can also test the client and server samples with the default values on a single computer byloading the client application into the first PLC runtime system and the server application into the secondPLC runtime system.

The behavior of the PLC project sample is determined by the following global variables/constants.

Constant Value DescriptionPLCPRJ_MAX_CONNECTIONS 5 Max. number of server → client connections. A server

can establish connections to more than one client. Aclient can establish a connection to only one server at atime.

PLCPRJ_SERVER_RESPONSE_TIMEOUT

T#10s Max. delay time (timeout time) after which a servershould send a response to the client.

PLCPRJ_CLIENT_SEND_CYCLE_TIME

T#1s Cycle time based on which a client sends send data(TX) to the server.

PLCPRJ_RECEIVER_POLLING_CYCLE_TIME

T#200ms Cycle time based on which a client or server polls forreceive data (RX).

PLCPRJ_BUFFER_SIZE 10000 Max. internal buffer size for RX/TX data.

The PLC samples define and use the following internal error codes:

Error code Value DescriptionPLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW

16#8101 The internal receive buffer reports an overflow.

PLCPRJ_ERROR_SEND_BUFFER_OVERFLOW

16#8102 The internal send buffer reports an overflow.

PLCPRJ_ERROR_RESPONSE_TIMEOUT

16#8103 The server has not sent the response within thespecified timeout time.

PLCPRJ_ERROR_INVALID_FRAME_FORMAT

16#8104 The telegram formatting is incorrect (size, faulty databytes etc.).

The client and server applications (FB_ServerApplication, FB_ClientApplication) were implemented asfunction blocks. The application and the connection can thus be instanced repeatedly.

6.1.3 Sample03: “Echo” client/serverThis sample is based on the functionality offered by the former TcSocketHelper.Lib, which is now part ofTc2_TcpIp library. It realizes a Client/Server PLC application based on the functionality provided by theformer SocketHelper library.

The client cyclically sends a test string (sToServer) to the remote server. The server returns the same stringunchanged to the client (sFromServer). The difference between this sample and sample02 is that the servercan establish up to five connections and the client application may start five client instances. Each instanceestablishes a connection to the server.

Samples

TF631076 Version: 1.4

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP• If two computers are used to execute the sample (one client and one server), the Function TF6310

needs to be installed on both computers• If one computer is used to execute the sample, e.g. client and server running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks

Project downloads

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/TCP/Sample03

Project information

The default communication settings used in the above samples are as follows:

• PLC client application: Port and IP address of the remote server: 200, '127.0.0.1'• PLC server application: Port and IP address of the local server: 200, '127.0.0.1'

To test the client and server application on two different PCs, you have to adjust the port and the IP addressaccordingly.

However, you can also test the client and server samples with the default values on a single computer byloading the client application into the first PLC runtime system and the server application into the secondPLC runtime system.

The behavior of the PLC project sample is determined by the following global variables/constants.

Constant Value DescriptionPLCPRJ_MAX_CONNECTIONS 5 Max. number of server->client connections. A server

can establish connections to more than one client. Aclient can establish a connection to only one server at atime.

PLCPRJ_SERVER_RESPONSE_TIMEOUT

T#10s Max. delay time (timeout time) after which a servershould send a response to the client.

PLCPRJ_CLIENT_SEND_CYCLE_TIME

T#1s Cycle time based on which a client sends send data(TX) to the server.

PLCPRJ_RECEIVER_POLLING_CYCLE_TIME

T#200ms Cycle time based on which a client or server polls forreceive data (RX).

PLCPRJ_BUFFER_SIZE 10000 Max. internal buffer size for RX/TX data.

Samples

TF6310 77Version: 1.4

The PLC samples define and use the following internal error codes:

Error code Value DescriptionPLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW

16#8101 The internal receive buffer reports an overflow.

PLCPRJ_ERROR_SEND_BUFFER_OVERFLOW

16#8102 The internal send buffer reports an overflow.

PLCPRJ_ERROR_RESPONSE_TIMEOUT

16#8103 The server has not sent the response within thespecified timeout time.

PLCPRJ_ERROR_INVALID_FRAME_FORMAT

16#8104 The telegram formatting is incorrect (size, faulty databytes etc.).

The client and server applications (FB_ServerApplication, FB_ClientApplication) were implemented asfunction blocks. The application and the connection can thus be instanced repeatedly.

6.1.4 Sample04: Binary data exchangeThis sample is based on the functionality offered by the former TcSocketHelper.Lib, which is now part ofTc2_TcpIp library. It realizes a Client/Server PLC application based on the functionality provided by theformer SocketHelper library.

This sample offers a client-server application for the exchange of binary data. To achieve this, a simplesample protocol is implemented. The length of the binary data and a frame counter for the sent and receivedtelegrams are transferred in the protocol header.

The structure of the binary data is defined by the PLC structure ST_ApplicationBinaryData. The binary dataare appended to the headers and transferred. The instances of the binary structure are called toServer,fromServer on the client side and toClient, fromClient on the server side.

The structure declaration on the client and server sides can be adapted as required. The structuredeclaration must be identical on both sides.

The maximum size of the structure must not exceed the maximum buffer size of the send/receive Fifos. Themaximum buffer size is determined by a constant.

The server functionality is implemented in the function block FB_ServerApplication and the clientfunctionality in the function block FB_ClientApplication.

In the standard implementation the client cyclically sends the data of the binary structure to the server andwaits for a response from the server. The server modifies some data and returns them to the client.

If you require a functionality, you have to modify the function blocks FB_ServerApplication andFB_ClientApplication accordingly.

Samples

TF631078 Version: 1.4

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP• If two computers are used to execute the sample (one client and one server), the Function TF6310

needs to be installed on both computers• If one computer is used to execute the sample, e.g. client and server running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks.

Project downloads

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/TCP/Sample04

Project information

The default communication settings used in the above samples are as follows:

• PLC client application: Port and IP address of the remote server: 200, '127.0.0.1'• PLC server application: Port and IP address of the local server: 200, '127.0.0.1'

To test the client and server application on two different PCs, you have to adjust the port and the IP addressaccordingly.

However, you can also test the client and server samples with the default values on a single computer byloading the client application into the first PLC runtime system and the server application into the secondPLC runtime system.

The behavior of the PLC project sample is determined by the following global variables/constants.

Constant Value DescriptionPLCPRJ_MAX_CONNECTIONS 5 Max. number of server->client connections. A server

can establish connections to more than one client. Aclient can establish a connection to only one server at atime.

PLCPRJ_SERVER_RESPONSE_TIMEOUT

T#10s Max. delay time (timeout time) after which a servershould send a response to the client.

PLCPRJ_CLIENT_SEND_CYCLE_TIME

T#1s Cycle time based on which a client sends send data(TX) to the server.

PLCPRJ_RECEIVER_POLLING_CYCLE_TIME

T#200ms Cycle time based on which a client or server polls forreceive data (RX).

PLCPRJ_BUFFER_SIZE 10000 Max. internal buffer size for RX/TX data.

Samples

TF6310 79Version: 1.4

The PLC samples define and use the following internal error codes:

Error code Value DescriptionPLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW

16#8101 The internal receive buffer reports an overflow.

PLCPRJ_ERROR_SEND_BUFFER_OVERFLOW

16#8102 The internal send buffer reports an overflow.

PLCPRJ_ERROR_RESPONSE_TIMEOUT

16#8103 The server has not sent the response within thespecified timeout time.

PLCPRJ_ERROR_INVALID_FRAME_FORMAT

16#8104 The telegram formatting is incorrect (size, faulty databytes etc.).

The client and server applications (FB_ServerApplication, FB_ClientApplication) were implemented asfunction blocks. The application and the connection can thus be instanced repeatedly.

6.1.5 Sample05: Binary data exchangeThis sample is based on the functionality offered by the former TcSocketHelper.Lib, which is now part ofTc2_TcpIp library. It realizes a Client/Server PLC application based on the functionality provided by theformer SocketHelper library.

This sample offers a client-server application for the exchange of binary data. To achieve this, a simplesample protocol is implemented. The length of the binary data and a frame counter for the sent and receivedtelegrams are transferred in the protocol header.

The structure of the binary data is defined by the PLC structure ST_ApplicationBinaryData. The binary dataare appended to the headers and transferred. The instances of the binary structure are called toServer,fromServer on the client side and toClient, fromClient on the server side.

The structure declaration on the client and server sides can be adapted as required. The structuredeclaration must be identical on both sides.

The maximum size of the structure must not exceed the maximum buffer size of the send/receive Fifos. Themaximum buffer size is determined by a constant.

The server functionality is implemented in the function block FB_ServerApplication and the clientfunctionality in the function block FB_ClientApplication.

In the standard implementation the client cyclically sends the data of the binary structure to the server andwaits for a response from the server. The server modifies some data and returns them to the client.

If you require a functionality, you have to modify the function blocks FB_ServerApplication andFB_ClientApplication accordingly.

The difference between this sample and sample04 is that the server can establish up to 5 connections andthe client application may have 5 client instances. Each instance establishes a connection to the server.

Samples

TF631080 Version: 1.4

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP• If two computers are used to execute the sample (one client and one server), the Function TF6310

needs to be installed on both computers• If one computer is used to execute the sample, e.g. client and server running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks.

Project downloads

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/TCP/Sample05

Project information

The default communication settings used in the above samples are as follows:

• PLC client application: Port and IP address of the remote server: 200, '127.0.0.1'• PLC server application: Port and IP address of the local server: 200, '127.0.0.1'

To test the client and server application on two different PCs, you have to adjust the port and the IP addressaccordingly.

However, you can also test the client and server samples with the default values on a single computer byloading the client application into the first PLC runtime system and the server application into the secondPLC runtime system.

The behavior of the PLC project sample is determined by the following global variables/constants.

Constant Value DescriptionPLCPRJ_MAX_CONNECTIONS 5 Max. number of server->client connections. A server can

establish connections to more than one client. A clientcan establish a connection to only one server at a time.

PLCPRJ_SERVER_RESPONSE_TIMEOUT

T#10s Max. delay time (timeout time) after which a servershould send a response to the client.

PLCPRJ_CLIENT_SEND_CYCLE_TIME

T#1s Cycle time based on which a client sends send data (TX)to the server.

PLCPRJ_RECEIVER_POLLING_CYCLE_TIME

T#200ms Cycle time based on which a client or server polls forreceive data (RX).

PLCPRJ_BUFFER_SIZE 10000 Max. internal buffer size for RX/TX data.

Samples

TF6310 81Version: 1.4

The PLC samples define and use the following internal error codes:

Error code Value DescriptionPLCPRJ_ERROR_RECEIVE_BUFFER_OVERFLOW

16#8101 The internal receive buffer reports an overflow.

PLCPRJ_ERROR_SEND_BUFFER_OVERFLOW

16#8102 The internal send buffer reports an overflow.

PLCPRJ_ERROR_RESPONSE_TIMEOUT

16#8103 The server has not sent the response within the specifiedtimeout time.

PLCPRJ_ERROR_INVALID_FRAME_FORMAT

16#8104 The telegram formatting is incorrect (size, faulty databytes etc.).

The client and server applications (FB_ServerApplication, FB_ClientApplication) were implemented asfunction blocks. The application and the connection can thus be instanced repeatedly.

6.2 UDP

6.2.1 Sample01: Peer-to-peer communication

6.2.1.1 Overview

The following example demonstrates the implementation of a simple Peer-to-Peer application in the PLC andconsists of two PLC projects (PeerA and PeerB) plus a .NET application which also acts as a separate peer.All peer applications send a test string to a remote peer and at the same time receive strings from a remotepeer. The received strings are displayed in a message box on the monitor of the target computer. Feel freeto use and customize this sample to your needs.

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP• If two computers are used to execute the sample, the Function TF6310 needs to be installed on both

computers• If one computer is used to execute the sample, e.g. Peer A und Peer B running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks• To run the .NET sample client, only .NET Framework 4.0 is needed

Project downloads

The sources of the two PLC devices only differ in terms of different IP addresses of the remotecommunication partners.

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/UDP/Sample01

https://github.com/Beckhoff/TF6310_Samples/tree/master/C%23/SampleClientUdp

Project description

The following links provide documentation for each component. Additionally, an own article explains how tostart the PLC samples with step-by-step instructions.

• Integration in TwinCAT and Test [} 83] (Starting the PLC samples)

• PLC devices A and B [} 84] (Peer-to-Peer PLC application)

• .NET communication [} 88] (.NET sample client)

Samples

TF631082 Version: 1.4

Auxiliary functions in the PLC sample projects

In the PLC samples, several functions, constants and function blocks are used, which are briefly describedbelow:

Fifo function blockFUNCTION_BLOCK FB_FifoVAR_INPUT    new : ST_FifoEntry;END_VARVAR_OUTPUT    bOk : BOOL;    old : ST_FifoEntry;END_VAR

A simple Fifo function block. One instance of this block is used as "send Fifo", another one as "receive Fifo".The messages to be sent are stored in the send Fifo, the received messages are stored in the receive Fifo.The bOk output variable is set to FALSE if errors occurred during the last action (AddTail or RemoveHead)(Fifo empty or overfilled).

A Fifo entry consists of the following components:TYPE ST_FifoEntry :STRUCT    sRemoteHost : STRING(15); (* Remote address. String containing an (Ipv4) Internet Protocol dotted address. *)    nRemotePort : UDINT; (* Remote Internet Protocol (IP) port. *)    msg         : STRING; (* Udp packet data *)END_STRUCTEND_TYPE

LogError functionFUNCTION LogError : DINT

The function writes a message with the error code into the log book of the operating system (Event Viewer).The global variable bLogDebugMessages must first be set to TRUE.

LogMessage functionFUNCTION LogMessage : DINT

The function writes a message into the log book of the operating system (Event Viewer) if a new socket wasopened or closed. The global variable bLogDebugMessages must first be set to TRUE.

SCODE_CODE functionFUNCTION SCODE_CODE : DWORD

The function masks the lower 16 bits of a Win32 error code returns them.

Also see about this

Samples

TF6310 83Version: 1.4

2 .NET communication [} 88]

6.2.1.2 Integration in TwinCAT and Test

The PLC samples are delivered as a TwinCAT 3 PLC project file. Therefore you need to create a newTwinCAT 3 solution before importing a sample. You can then import the PLC sample in TwinCAT XAE byright-clicking on the PLC node, selecting Add existing item and then navigating to the downloaded samplefile (please choose Plc 3.x Project archive (*.tpzip) as the file type).

Starting this sample requires two computers. Alternatively, the test may also be carried out with two runtimesystems on a single computer. The constants with the port numbers and the IP addresses of thecommunication partners have to be modified accordingly.

Sample configuration with two computers:• Device A is located on the local computer and has the IP address '10.1.128.21'• Device B is located on the remote computer and has the IP address '172.16.6.195' 10.1.128.

Device A

Please perform the following steps to configure the sample on device A:

• Create a new TwinCAT 3 solution in TwinCAT XAE and import the Peer-to-Peer PLC project for deviceA.

• Set the constant REMOTE_HOST_IP in POU MAIN to the real IP address of the remote system(device B - in our example: '10.1.128.').

• Activate the configuration and start the PLC runtime. (Don't forget to create a license for TF6310 TCP/IP)

Device B

Please perform the following steps to configure the sample on device B:

• Create a new TwinCAT 3 solution in TwinCAT XAE and import the Peer-to-Peer PLC project for deviceB.

• Set the constant REMOTE_HOST_IP in POU MAIN to the IP address of device A (in our example:'10.1.128.21').

• Activate the configuration and start the PLC runtime. (Don't forget to create a license for TF6310 TCP/IP.)

• Login to the PLC runtime and write the value TRUE to the Boolean variable bSendOnceToRemote inPOU MAIN.

Samples

TF631084 Version: 1.4

• Shortly afterwards, a message box with the test string should appear on device A. You can now alsorepeat the same step on device A. As a result, the message box should then appear on device B.

6.2.1.3 PLC devices A and B

The required functionality was encapsulated in the function block FB_PeerToPeer. Each of thecommunication partners uses an instance of the FB_PeerToPeer function block. The block is activatedthrough a rising edge at the bEnable input. A new UDP socket is opened, and data exchange commences.The socket address is specified via the variables sLocalHost and nLocalPort. A falling edge stops the dataexchange and closes the socket. The data to be sent are transferred to the block through a reference(VAR_IN_OUT) via the variable sendFifo. The data received are stored in the variable receiveFifo.

Name Default value Descriptiong_sTcIpConnSvrAddr '' Network address of the TwinCAT TCP/IP Connection

Server. Default: Empty string (the server is located onthe local PC);

bLogDebugMessages TRUE Activates/deactivates writing of messages into the logbook of the operating system;

PLCPRJ_ERROR_SENDFIFO_OVERFLOW

16#8103 Sample project error code: The send Fifo is full.

PLCPRJ_ERROR_RECFIFO_OVERFLOW

16#8104 Sample project error code: The receive Fifo is full.

FUNCTION_BLOCK FB_PeerToPeer

InterfaceVAR_IN_OUT    sendFifo    : FB_Fifo;    receiveFifo : FB_Fifo;END_VARVAR_INPUT    sLocalHost  : STRING(15);    nLocalPort  : UDINT;    bEnable     : BOOL;END_VARVAR_OUTPUT

Samples

TF6310 85Version: 1.4

    bCreated    : BOOL;    bBusy       : BOOL;    bError      : BOOL;    nErrId      : UDINT;END_VARVAR    fbCreate    : FB_SocketUdpCreate;    fbClose     : FB_SocketClose;    fbReceiveFrom : FB_SocketUdpReceiveFrom;    fbSendTo    : FB_SocketUdpSendTo;    hSocket     : T_HSOCKET;    eStep       : E_ClientServerSteps;    sendTo      : ST_FifoEntry;    receivedFrom : ST_FifoEntry;END_VAR

ImplementationCASE eStep OF    UDP_STATE_IDLE:        IF bEnable XOR bCreated THEN            bBusy := TRUE;            bError := FALSE;            nErrid := 0;            IF bEnable THEN                eStep := UDP_STATE_CREATE_START;            ELSE                eStep := UDP_STATE_CLOSE_START;            END_IF        ELSIF bCreated THEN            sendFifo.RemoveHead( old => sendTo );            IF sendFifo.bOk THEN                eStep := UDP_STATE_SEND_START;            ELSE (* empty *)                eStep := UDP_STATE_RECEIVE_START;            END_IF        ELSE            bBusy := FALSE;        END_IF

    UDP_STATE_CREATE_START:        fbCreate( bExecute := FALSE );        fbCreate( sSrvNetId:= g_sTcIpConnSvrAddr,                sLocalHost:= sLocalHost,            nLocalPort:= nLocalPort,            bExecute:= TRUE );        eStep := UDP_STATE_CREATE_WAIT;

    UDP_STATE_CREATE_WAIT:        fbCreate( bExecute := FALSE );        IF NOT fbCreate.bBusy THEN            IF NOT fbCreate.bError THEN                bCreated := TRUE;                hSocket := fbCreate.hSocket;                eStep := UDP_STATE_IDLE;                LogMessage( 'Socket opened (UDP)!', hSocket );            ELSE                LogError( 'FB_SocketUdpCreate', fbCreate.nErrId );                nErrId := fbCreate.nErrId;                eStep := UDP_STATE_ERROR;            END_IF        END_IF

    UDP_STATE_SEND_START:        fbSendTo( bExecute := FALSE );        fbSendTo( sSrvNetId:=g_sTcIpConnSvrAddr,            sRemoteHost := sendTo.sRemoteHost,                nRemotePort := sendTo.nRemotePort,            hSocket:= hSocket,            pSrc:= ADR( sendTo.msg ),            cbLen:= LEN( sendTo.msg ) + 1, (* include the end delimiter *)         bExecute:= TRUE );        eStep := UDP_STATE_SEND_WAIT;

    UDP_STATE_SEND_WAIT:        fbSendTo( bExecute := FALSE );        IF NOT fbSendTo.bBusy THEN            IF NOT fbSendTo.bError THEN                eStep := UDP_STATE_RECEIVE_START;

Samples

TF631086 Version: 1.4

            ELSE                LogError( 'FB_SocketSendTo (UDP)', fbSendTo.nErrId );                nErrId := fbSendTo.nErrId;                eStep := UDP_STATE_ERROR;            END_IF        END_IF

    UDP_STATE_RECEIVE_START:        MEMSET( ADR( receivedFrom ), 0, SIZEOF( receivedFrom ) );     fbReceiveFrom( bExecute := FALSE );        fbReceiveFrom( sSrvNetId:=g_sTcIpConnSvrAddr,                hSocket:= hSocket,                pDest:= ADR( receivedFrom.msg ),                     cbLen:= SIZEOF( receivedFrom.msg ) - 1, (*without string delimiter *)             bExecute:= TRUE );        eStep := UDP_STATE_RECEIVE_WAIT;

    UDP_STATE_RECEIVE_WAIT:        fbReceiveFrom( bExecute := FALSE );        IF NOT fbReceiveFrom.bBusy THEN            IF NOT fbReceiveFrom.bError THEN                IF fbReceiveFrom.nRecBytes > 0 THEN                    receivedFrom.nRemotePort := fbReceiveFrom.nRemotePort;                    receivedFrom.sRemoteHost := fbReceiveFrom.sRemoteHost;                    receiveFifo.AddTail( new := receivedFrom );                    IF NOT receiveFifo.bOk THEN(* Check for fifo overflow *)                     LogError( 'Receive fifo overflow!', PLCPRJ_ERROR_RECFIFO_OVERFLOW );                    END_IF                END_IF                eStep := UDP_STATE_IDLE;            ELSIF fbReceiveFrom.nErrId = 16#80072746 THEN                     LogError( 'The connection is reset by remote side.', fbReceiveFrom.nErrId );                eStep := UDP_STATE_IDLE;            ELSE                LogError( 'FB_SocketUdpReceiveFrom (UDP client/server)', fbReceiveFrom.nErrId );                nErrId := fbReceiveFrom.nErrId;                eStep := UDP_STATE_ERROR;            END_IF        END_IF

    UDP_STATE_CLOSE_START:        fbClose( bExecute := FALSE );        fbClose(    sSrvNetId:= g_sTcIpConnSvrAddr,            hSocket:= hSocket,            bExecute:= TRUE );        eStep := UDP_STATE_CLOSE_WAIT;

    UDP_STATE_CLOSE_WAIT:        fbClose( bExecute := FALSE );        IF NOT fbClose.bBusy THEN            LogMessage( 'Socket closed (UDP)!', hSocket );            bCreated := FALSE;            MEMSET( ADR(hSocket), 0, SIZEOF(hSocket));            IF fbClose.bError THEN                LogError( 'FB_SocketClose (UDP)', fbClose.nErrId );                     nErrId := fbClose.nErrId;                eStep := UDP_STATE_ERROR;            ELSE                bBusy := FALSE;                bError := FALSE;                nErrId := 0;                eStep := UDP_STATE_IDLE;            END_IF        END_IF

    UDP_STATE_ERROR: (* Error step *)        bError := TRUE;        IF bCreated THEN            eStep := UDP_STATE_CLOSE_START;        ELSE            bBusy := FALSE;            eStep := UDP_STATE_IDLE;        END_IFEND_CASE

Samples

TF6310 87Version: 1.4

MAIN program

Previously opened sockets must be closed after a program download or a PLC reset. During PLC start‑up,this is done by calling an instance of the FB_SocketCloseAll [} 25] function block. If one of the variablesbSendOnceToItself or bSendOnceToRemote has a raising edge, a new Fifo entry is generated and stored inthe send Fifo. Received messages are removed from the receive Fifo and displayed in a message box.PROGRAM MAINVAR CONSTANT    LOCAL_HOST_IP      : STRING(15)     := '';    LOCAL_HOST_PORT    : UDINT         := 1001;    REMOTE_HOST_IP     : STRING(15)     := '172.16.2.209';    REMOTE_HOST_PORT   : UDINT         := 1001;END_VARVAR    fbSocketCloseAll    : FB_SocketCloseAll;    bCloseAll     : BOOL := TRUE;

    fbPeerToPeer     : FB_PeerToPeer;    sendFifo        : FB_Fifo;    receiveFifo     : FB_Fifo;    sendToEntry     : ST_FifoEntry;    entryReceivedFrom : ST_FifoEntry;    tmp         : STRING;

    bSendOnceToItself : BOOL;    bSendOnceToRemote : BOOL;END_VAR

IF bCloseAll THEN (*On PLC reset or program download close all old connections *) bCloseAll := FALSE;    fbSocketCloseAll( sSrvNetId:= g_sTcIpConnSvrAddr, bExecute:= TRUE, tTimeout:= T#10s );ELSE    fbSocketCloseAll( bExecute:= FALSE );END_IF

IF NOT fbSocketCloseAll.bBusy AND NOT fbSocketCloseAll.bError THEN

    IF bSendOnceToRemote THEN        bSendOnceToRemote         := FALSE;                 (* clear flag *)     sendToEntry.nRemotePort         := REMOTE_HOST_PORT;         (* remote host port number*)     sendToEntry.sRemoteHost         := REMOTE_HOST_IP;             (* remote host IP address *)     sendToEntry.msg             := 'Hello remote host!';            (* message text*);     sendFifo.AddTail( new := sendToEntry );                 (* add new entry to the send queue*)     IF NOT sendFifo.bOk THEN                            (* check for fifo overflow*)         LogError( 'Send fifo overflow!', PLCPRJ_ERROR_SENDFIFO_OVERFLOW );        END_IF    END_IF        IF bSendOnceToItself THEN        bSendOnceToItself         := FALSE;                 (* clear flag *)     sendToEntry.nRemotePort         := LOCAL_HOST_PORT;         (* nRemotePort == nLocalPort => send it to itself *)       sendToEntry.sRemoteHost         := LOCAL_HOST_IP;             (* sRemoteHost == sLocalHost =>send it to itself *)     sendToEntry.msg             := 'Hello itself!';         (* message text*);     sendFifo.AddTail( new := sendToEntry );                 (* add new entry to the send queue*)     IF NOT sendFifo.bOk THEN                            (* check for fifo overflow*)         LogError( 'Send fifo overflow!', PLCPRJ_ERROR_SENDFIFO_OVERFLOW );        END_IF    END_IF     (* send and receive messages *) fbPeerToPeer( sendFifo := sendFifo, receiveFifo := receiveFifo, sLocalHost := LOCAL_HOST_IP, nLocalPort := LOCAL_HOST_PORT, bEnable := TRUE );     (* remove all received messages from receive queue *) REPEAT        receiveFifo.RemoveHead( old => entryReceivedFrom );        IF receiveFifo.bOk THEN            tmp := CONCAT( 'RECEIVED from: ', entryReceivedFrom.sRemoteHost );            tmp := CONCAT( tmp, ', Port: ' );            tmp := CONCAT( tmp, UDINT_TO_STRING( entryReceivedFrom.nRemotePort ) );            tmp := CONCAT( tmp, ', msg: %s' );            ADSLOGSTR( ADSLOG_MSGTYPE_HINT OR ADSLOG_MSGTYPE_MSGBOX, tmp, entryReceivedFrom.msg );        END_IF    UNTIL NOT receiveFifo.bOk

Samples

TF631088 Version: 1.4

    END_REPEAT

END_IF

6.2.1.4 .NET communication

This sample demonstrates how a .NET communication partner for PLC samples Peer-to-Peer device A or Bcan be realized.

The .NET Sample Client can be used to send single UPD data packages to a UPD Server, in this case thePLC project PeerToPeerA.

Download

Download the test client.

Unpack the ZIP file; the .exe file runs on a Windows system.

How it works

The sample uses the .Net libraries System.Net and System.Net.Sockets to implement a UDP client (classUdpClient). While listening for incoming UDP packets in a background thread, a string can be sent to aremote device by specifying its IP address and port number and clicking the Send button.

For a better understanding of this article, imagine the following setup:

• The PLC project Peer-to-Peer device A is running on a computer with IP address 10.1.128.21• The .NET application is running on a computer with IP address 10.1.128.30

Description

The client itself uses port 11000 for sending. At the same time it opens this port and displays receivedmessages in the upper part of the interface as a log:

Samples

TF6310 89Version: 1.4

Together with the PLC / C++ examples, this results in an echo example: A UDP message is sent from the client port 11000 to the server port 10000, which returns the same data tothe sender.

The client can be configured via the interface:

• Destination: IP address• Port: The port that is addressed in the destination• Source: Sender network card (IP address).

"OS-based" operating system deals with selection of the appropriate network card.• Message

TF6311 “TCP/UDP Realtime” does not allow local communication. However, for testing purposes a differentnetwork interface can be selected via "Source", so that the UDP packet leaves the computer through onenetwork card and arrives on the other network card ("loop cable").

6.2.2 Sample02: MulticastThis sample demonstrates how to send and receive Multicast packages via UDP.

Client and Server cyclically send a value to each other via a Multicast IP address.

Client and Server are realized by two PLC applications and delivered within a single TwinCAT 3 solution.

System requirements• TwinCAT 3 Build 3093 or higher• TwinCAT 3 Function TF6310 TCP/IP version 1.0.64 or higher• TwinCAT 3 Library Tc2_TcpIp version 3.2.64.0 or higher• If one computer is used to execute the sample, e.g. client and server running in two separate PLC

runtimes, both PLC runtimes need to run in separate tasks.

Project download

https://github.com/Beckhoff/TF6310_Samples/tree/master/PLC/UDP/Sample02

Appendix

TF631090 Version: 1.4

7 Appendix

7.1 OSI modelThe following article is a short introduction into the OSI model and describes how this model takes part in oureveryday network communication. Note that the ambition to create this article was not to replace moredetailed documentations or books about this topic, therefore please only consider it to be a very superficialintroduction.

The OSI (Open Systems Interconnection) model describes a standardization of the functionalities in acommunication system via abstract layers. Each layer defines an own set of functionalities during thecommunication between network devices and only communicates with the layer above and below.

Example: If you use your web browser to navigate to http://wwwbeckhoff.com, this communication uses thefollowing protocols from each layer, starting at layer 7: HTTP → TCP → IP → Ethernet. On the other hand,entering https://www.beckhoff.com would use HTTP → SSL → TCP → IP → Ethernet.

The TwinCAT 3 Function TF6310 TCP/IP provides functionalities to develop network-enabled PLC programsusing either the transport protocols TCP or UDP. Therefore, PLC programmers may implement their ownapplication layer protocol, defining an own message structure to communicate with remote systems.

7.2 KeepAlive configurationThe transmission of TCP KeepAlive messages verifies if an idle TCP connection is still active. Since version1.0.47 of the TwinCAT TCP/IP Server (TF6310), the KeepAlive configuration of the Windows operatingsystem is used, which can be configured via the following registry keys:

The following documentation is an excerpt of a Microsoft Technet article.

KeepAliveTime

HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

Data type Range Default valueREG_DWORD 0x1–0xFFFFFFFF ( milliseconds ) 0x6DDD00 ( 7,200,000

milliseconds = 2 hours )

Appendix

TF6310 91Version: 1.4

Description

Determines how often TCP sends keep-alive transmissions. TCP sends keep-alive transmissions to verifythat an idle connection is still active.This entry is used when the remote system is responding to TCP.Otherwise, the interval between transmissions is determined by the value of the KeepAliveInterval entry. Bydefault, keep-alive transmissions are not sent. The TCP keep-alive feature must be enabled by a program,such as Telnet, or by an Internet browser, such as Internet Explorer.

KeepAliveInterval

HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

Data type Range Default valueREG_DWORD 0x1–0xFFFFFFFF ( milliseconds ) 0x3E8 ( 1,000 milliseconds = 1

second )

Description

Determines how often TCP repeats keep-alive transmissions when no response is received. TCP sendskeep-alive transmissions to verify that idle connections are still active. This prevents TCP from inadvertentlydisconnecting active lines.

7.3 Error codes

7.3.1 Overview of the error codesCodes (hex) Codes (dec) Error source Description0x00000000-0x00007800 0-30720 TwinCAT system error

codesTwinCAT system error(including ADS errorcodes)

0x00008000-0x000080FF 32768-33023 Internal TwinCAT TCP/IPConnection Server errorcodes [} 92]

Internal error of theTwinCAT TCP/IPConnection Server

0x80070000-0x8007FFFF 2147942400-2148007935 Error source = Code -0x80070000 = Win32system error codes

Win32 system error(including Windowssockets error codes)

Requirements

Development environment Target system type PLC libraries to includeTwinCAT v3.1 PC, CX (x86) or CX (ARM) Tc2_TcpIp

Appendix

TF631092 Version: 1.4

7.3.2 Internal error codes of the TwinCAT TCP/IP ConnectionServer

Code (hex) Code (dec) Symbolic constant Description0x00008001 32769 TCPADSERROR_NOMO

REENTRIESNo new sockets can becreated (forFB_SocketListen andFB_SocketConnect).

0x00008002 32770 TCPADSERROR_NOTFOUND

Socket handle is invalid(for FB_SocketReceive,FB_SocketAccept,FB_SocketSend etc.).

0x00008003 32771 TCPADSERROR_ALREADYEXISTS

Is returned whenFB_SocketListen is called,if the TcpIp port listeneralready exists.

0x00008004 32772 TCPADSERROR_NOTCONNECTED

Is returned whenFB_SocketReceive iscalled, if the client socketis no longer connectedwith the server.

0x00008005 32773 TCPADSERROR_NOTLISTENING

Is returned whenFB_SocketAccept iscalled, if an error wasregistered in the listenersocket.

Requirements

Development environment Target system type PLC libraries to includeTwinCAT v3.1 PC, CX (x86) or CX (ARM) Tc2_TcpIp

7.3.3 Troubleshooting/diagnostics• In the event of connection problems the PING command can be used to ascertain whether the external

communication partner can be reached via the network connection. If this is not the case, check thenetwork configuration and firewall settings.

• Sniffer tools such as Wireshark enable logging of the entire network communication. The log can thenbe analysed by Beckhoff support staff.

• Check the hardware and software requirements described in this documentation (TwinCAT version, CEimage version etc.).

• Check the software installation hints described in this documentation (e.g. installation of CAB files onCE plattform).

• Check the input parameters that are transferred to the function blocks (network address, port number,data etc, connection handle.) for correctness. Check whether the function block issues an error code.The documentation for the error codes can be found here: Overview of error codes [} 91].

• Check if the other communication partner/software/device issues an error code.• Activate the debug output integrated in the TcSocketHelper.Lib during connection establishment/

disconnect process (keyword: CONNECT_MODE_ENABLEDBG). Open the TwinCAT SystemManager and activate the LogView window. Analyze/check the debug output strings.

Requirements

Development environment Target system type PLC libraries to includeTwinCAT v3.1 PC, CX (x86) or CX (ARM) Tc2_TcpIp

Appendix

TF6310 93Version: 1.4

7.4 Support and ServiceBeckhoff and their partners around the world offer comprehensive support and service, making available fastand competent assistance with all questions related to Beckhoff products and system solutions.

Beckhoff's branch offices and representatives

Please contact your Beckhoff branch office or representative for local support and service on Beckhoffproducts!

The addresses of Beckhoff's branch offices and representatives round the world can be found on her internetpages:http://www.beckhoff.com

You will also find further documentation for Beckhoff components there.

Beckhoff Headquarters

Beckhoff Automation GmbH & Co. KG

Huelshorstweg 2033415 VerlGermany

Phone: +49(0)5246/963-0Fax: +49(0)5246/963-198e-mail: [email protected]

Beckhoff Support

Support offers you comprehensive technical assistance, helping you not only with the application ofindividual Beckhoff products, but also with other, wide-ranging services:

• support• design, programming and commissioning of complex automation systems• and extensive training program for Beckhoff system components

Hotline: +49(0)5246/963-157Fax: +49(0)5246/963-9157e-mail: [email protected]

Beckhoff Service

The Beckhoff Service Center supports you in all matters of after-sales service:

• on-site service• repair service• spare parts service• hotline service

Hotline: +49(0)5246/963-460Fax: +49(0)5246/963-479e-mail: [email protected]

Beckhoff Automation GmbH & Co. KGHülshorstweg 2033415 VerlGermanyPhone: +49 5246 [email protected]

More Information: www.beckhoff.com/tf6310