FB_SocketCloseAll
If TwinCAT is restarted or stopped, the TwinCAT TCP/IP Connection Server is also stopped. Any open sockets (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 closed properly.
The function block FB_SocketCloseAll can be used to close all connection handles (TCP/IP and UDP sockets) that were opened by a PLC runtime system. This means that, if FB_SocketCloseAll is called in one of the tasks of the first runtime systems (port 801), all sockets that were opened in the first runtime system are closed. In each PLC runtime system that uses the socket function blocks, an instance of FB_SocketCloseAll should be called during the PLC start (see below).
VAR_INPUT
VAR_INPUT
sSrvNetId : T_AmsNetId := '';
bExecute : BOOL;
tTimeout : TIME := T#5s;
END_VAR
sSrvNetId: String containing the network address of the TwinCAT TCP/IP Connection Server. For the local computer (default) an empty string may be specified.
bExecute: The block is activated by a rising edge at this input.
tTimeout: Maximum time allowed for the execution of the function block.
VAR_OUTPUT
VAR_OUTPUT
bBusy :BOOL;
bError :BOOL;
nErrId :UDINT;
END_VAR
bBusy: When the function block is activated this output is set. It remains set until and acknowledgement is received.
bError: If an error should occur during the transfer of the command, then this output is set once the bBusy output was reset.
nErrId : If the bError output is set, this parameter returns the TwinCAT TCP/IP Connection Server error number.
Example of an implementation in ST:
The following program code is used to properly close the connection handles (sockets) that were open before a "PLC reset" or "Download" before a PLC restart.
PROGRAM MAIN
VAR
fbSocketCloseAll : FB_SocketCloseAll;
bCloseAll : BOOL := TRUE;
END_VAR
IF 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_IFIFNOT fbSocketCloseAll.bBusy THEN(*...
... continue program execution...
...*)
END_IF
Requirements
Development environment | Target system type | PLC libraries to be linked |
---|---|---|
TwinCAT version 2.8.0 or higher | PC or CX (x86) | TcpIp.Lib ( Standard.Lib; TcBase.Lib; TcSystem.Lib are included automatically ) |
TwinCAT v2.10.0 Build >= 1301 | CX (ARM) |