Sample for MQTT communication via a secure TLS connection and PSK (PreSharedKey)

This sample illustrates the communication with an MQTT broker that requires authentication via TLS PSK. The sample is basically limited to establishing the connection and publishing of values.

Project structure

1. Create a TwinCAT project with a PLC and add Tc3_IotBase as library reference.
2. Create a program block and declare an instance of FB_IotMqttClient and two auxiliary variables to control the program sequence, if required.
  fbMqttClient    : FB_IotMqttClient;
  bSetParameter   : BOOL := TRUE;
  bConnect : BOOL := TRUE;
3. Declare two variables (for topic and payload) for the MQTT message to be sent. In the sample a message is to be sent every second. 
sTopicPub   : STRING(255) := 'MyTopic';
sPayloadPub : STRING(255);
i : UDINT;
fbTimer : TON := (PT:=T#1S);
4. In the program part the MQTT client must be triggered cyclically, in order to ensure that a connection to the broker is established and maintained. Set the parameters of the desired connection and initialize the connection with the transfer parameter bConnect := TRUE. In the sample the parameters are assigned once in the program code before the client call. Since this is usually only required once, the parameters can already be specified in the declaration part during instantiation of the MQTT client. Not all parameters have to be assigned. In the sample the broker is local. The IP address or the name can also be specified.
IF bSetParameter THEN
  bSetParameter                   := FALSE;
  fbMqttClient.stTLS.sPskIdentity := 'my_Identity';
  fbMqttClient.stTLS.aPskKey      := cMyPskKey;
  fbMqttClient.stTLS.nPskKeyLen   := 15;
  fbMqttClient.nHostPort          := 8883;

5. The structure element aPskKey receives the PreSharedKey, which is required for establishing a connection to the broker. Accordingly, this must be specified as an ARRAY OF BYTE with a length of 64. The actual length of the keys is then transferred to the structure element nPskKeyLen.
6. Once the connection to the broker is established, the client should send a message to a particular topic every second.
IF fbMqttClient.bConnected THEN
  IF fbTimer.Q THEN // publish new payload every second
    i := i + 1;
    sPayloadPub := CONCAT('MyMessage', TO_STRING(i));
    fbMqttClient.Publish(sTopic:= sTopicPub, 
                      pPayload:= ADR(sPayloadPub),
                      nPayloadSize:= LEN2(ADR(sPayloadPub))+1,
                      eQoS:= TcIotMqttQos.AtMostOnceDelivery,
                      bRetain:= FALSE,
                      bQueue:= FALSE);




Development environment

Target platform

PLC libraries to include

TwinCAT v3.1.4022.0

IPC or CX (x86, x64, ARM)

Tc2_Utilities (>= v3.3.19.0)