ClientID
When establishing a connection with the message broker, the client transmits a so-called ClientID, which is used to uniquely identify the client on the message broker. The MQTT communication driver from TwinCAT3 automatically generates its own ClientID, which is based on the following naming scheme:
PlcProjectName-TcMqttClient%n
%n is an incremental counter for the number of the respective MQTT client instance. Each instance of the FB_IotMqttClient function block increments this counter. In most cases, using this ClientID format is sufficient. In special cases, e.g. depending on the message broker or also due to the own MQTT application, an application-specific ClientID must be assigned. This can be done via a corresponding input at the function blocks FB_IotMqttClient and FB_IotMqtt5Client.
If a unique ClientID is to be generated automatically at the start of the PLC project, the use of a GUID is recommended, which can be generated via the function block FB_CreateGuid from the library Tc2_System. The following sample code illustrates the use of this function block.
PROGRAM MAIN
VAR
fbGuid : FB_CreateGUID;
objGuid : GUID;
sGuid : STRING;
nState : UINT;
bStart : BOOL; // set to TRUE to start this sample
END_VAR
CASE nState OF
0 :
IF bStart THEN
bStart := FALSE;
nState := nState + 1;
END_IF
1 : // create GUID using FB_CreateGuid from Tc2_System library
fbGuid(bExecute := TRUE, pGuidBuffer := ADR(objGuid), nGuidBufferSize := SIZEOF(objGuid));
IF NOT fbGuid.bBusy THEN
fbGuid(bExecute := FALSE);
IF NOT fbGuid.bError THEN
nState := nState + 1;
ELSE
nState := 255; // go to error state
END_IF
END_IF
2: // GUID has been created, now convert to STRING
sGuid := GUID_TO_STRING(objGuid);
nState := nState + 1;
3: // done
255: // error state
END_CASE
After execution of this State Machine the variable sGuid contains the generated GUID as STRING. This can then be used at the function blocks FB_IotMqttClient and FB_IotMqtt5Client as ClientID.