MQTT Client DOKU V3-0 en
MQTT Client DOKU V3-0 en
MQTT Client DOKU V3-0 en
Legal information
Use of application examples
Application examples illustrate the solution of automation tasks through an interaction of several
components in the form of text, graphics and/or software modules. The application examples are
a free service by Siemens AG and/or a subsidiary of Siemens AG ("Siemens"). They are
non-binding and make no claim to completeness or functionality regarding configuration and
equipment. The application examples merely offer help with typical tasks; they do not constitute
customer-specific solutions. You yourself are responsible for the proper and safe operation of the
products in accordance with applicable regulations and must also check the function of the
respective application example and customize it for your system.
Siemens grants you the non-exclusive, non-sublicensable and non-transferable right to have the
application examples used by technically trained personnel. Any change to the application
examples is your responsibility. Sharing the application examples with third parties or copying the
application examples or excerpts thereof is permitted only in combination with your own products.
The application examples are not required to undergo the customary tests and quality inspections
of a chargeable product; they may have functional and performance defects as well as errors. It is
your responsibility to use them in such a manner that any malfunctions that may occur do not
result in property damage or injury to persons.
Disclaimer of liability
Siemens shall not assume any liability, for any legal reason whatsoever, including, without
limitation, liability for the usability, availability, completeness and freedom from defects of the
application examples as well as for related information, configuration and performance data and
any damage caused thereby. This shall not apply in cases of mandatory liability, for example
under the German Product Liability Act, or in cases of intent, gross negligence, or culpable loss of
life, bodily injury or damage to health, non-compliance with a guarantee, fraudulent
non-disclosure of a defect, or culpable breach of material contractual obligations. Claims for
damages arising from a breach of material contractual obligations shall however be limited to the
© Siemens AG 2021 All rights reserved
foreseeable damage typical of the type of agreement, unless liability arises from intent or gross
negligence or is based on loss of life, bodily injury or damage to health. The foregoing provisions
do not imply any change in the burden of proof to your detriment. You shall indemnify Siemens
against existing or future claims of third parties in this connection except where Siemens is
mandatorily liable.
By using the application examples you acknowledge that Siemens cannot be held liable for any
damage beyond the liability provisions described.
Other information
Siemens reserves the right to make changes to the application examples at any time without
notice. In case of discrepancies between the suggestions in the application examples and other
Siemens publications such as catalogs, the content of the other documentation shall have
precedence.
The Siemens terms of use (https://support.industry.siemens.com) shall also apply.
Security information
Siemens provides products and solutions with Industrial Security functions that support the secure
operation of plants, systems, machines and networks.
In order to protect plants, systems, machines and networks against cyber threats, it is necessary
to implement – and continuously maintain – a holistic, state-of-the-art industrial security concept.
Siemens’ products and solutions constitute one element of such a concept.
Customers are responsible for preventing unauthorized access to their plants, systems, machines
and networks. Such systems, machines and components should only be connected to an
enterprise network or the Internet if and to the extent such a connection is necessary and only
when appropriate security measures (e.g. firewalls and/or network segmentation) are in place.
For additional information on industrial security measures that may be implemented, please visit
https://www.siemens.com/industrialsecurity.
Siemens’ products and solutions undergo continuous development to make them more secure.
Siemens strongly recommends that product updates are applied as soon as they are available
and that the latest product versions are used. Use of product versions that are no longer
supported, and failure to apply the latest updates may increase customer’s exposure to cyber
threats.
To stay informed about product updates, subscribe to the Siemens Industrial Security RSS Feed
at: https://www.siemens.com/industrialsecurity .
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 2
Table of Contents
Table of Contents
Legal information ......................................................................................................... 2
1 Introduction ........................................................................................................ 4
1.1 Overview............................................................................................... 4
1.2 Principle of Operation ........................................................................... 6
1.3 Components Used ................................................................................ 7
2 Engineering ........................................................................................................ 9
2.1 Block Description .................................................................................. 9
2.2 Configuration ...................................................................................... 10
2.2.1 Create TIA Portal Project ................................................................... 10
2.3 Integration of the Function Block in the User Program ...................... 11
2.3.1 Opening the "LMQTT" Global Library ................................................ 11
2.3.2 Copying Function Blocks and Data Types to the User Program ....... 13
2.3.3 Creating Global Data Block ................................................................ 14
2.3.4 Calling Function Blocks in the User Program .................................... 19
2.4 Configuration of the Security Feature ................................................ 21
2.4.1 Using the TIA Portal Global Certificate Manager ............................... 22
2.4.2 Using the Local CPU Certificate Manager ......................................... 26
2.5 Parameterization and Operation ........................................................ 29
2.6 Error Handling .................................................................................... 35
3 Useful Information ........................................................................................... 36
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 3
1 Introduction
1 Introduction
1.1 Overview
Motivation
Digitization has a major impact on the economy and society and is progressing
inexorably. The "Internet of Things" (short: IoT) is one of the main drivers of
digitization. The term "Internet of Things" is synonymous with one of the biggest
current dynamics of change: the increasing networking and automation of devices,
machines and products.
The protocol "Message Queue Telemetry Transport" (short: MQTT) is used in the
"Internet of Things" as a communication protocol. Its lightweight approach opens
up new possibilities for automation.
Criteria of MQTT
The MQTT protocol is distinguished by the following criteria:
© Siemens AG 2021 All rights reserved
Applicative implementation
To implement the MQTT protocol in a SIMATIC S7 Controller, the "LMQTT" library
offers an adequate solution.
The "LMQTT" library provides a function block for the SIMATIC S7-1500 and
SIMATIC S7-1200. The function block "LMQTT_Client" integrates the MQTT Client
function and allows you to submit MQTT messages to a broker (Publisher role) and
to create subscriptions (Subscriber role). The communication can be secured via a
TLS connection.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 4
1 Introduction
Figure 1-1
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 5
1 Introduction
Cert_xy
STEP 7 (TIA Portal) MQTT-Server
2
Certificate Store
idx Cert_Name 1
1 Cert_xy
Topic x Topic z
3
S7 CPU Message Message
Topic y
(MQTT Client) Message
Topic y
© Siemens AG 2021 All rights reserved
Message
Publish
(Un)Subscribe
Table 1-1
Step Description
1 Determine the CA certificate of the MQTT Broker.
2 Importing the third-party certificate into STEP 7 (TIA Portal). The certificate is
now in the global certificate manager of STEP 7.
3 You must assign the imported certificate to the S7 CPU. To recognize the
certificate as valid, the time of the S7-CPU must be current.
4 The function block "LMQTT_Client" assumes the following roles:
• Publisher to send MQTT messages to the MQTT Broker
• Subscriber to subscribe to MQTT messages or end subscriptions
The MQTT message is encrypted via a secure connection (MQTT over TLS).
Note A more detailed functional description of the function block "LMQTT_Client" and
information on the MQTT protocol can be found in section 3.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 6
1 Introduction
– CP 1543SP-1
(6GK7543-6WX00-0XE0)
– CP 1243-1
(6GK7243-1BX30-0XE0)
with firmware V3.2 or
higher
– CP 1243-8 IRC
(6GK7243-8RX30-0XE0)
with firmware V3.2 or
higher
– CP 1243-7 LTE
(6GK7243-7KX30-0XE0 /
6GK7243-7SX30-0XE0)
with firmware V3.2 or
higher
TIA Portal V16 - DVD: -
6ES7822-1AA06-0YA5
Download:
6ES7822-1AE06-0YA5
MQTT Broker - - If you want to encrypt the
communication, the MQTT Broker
must support SSL/TLS.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 7
1 Introduction
Note With S7-1500 CPUs (firmware V2.0 or higher) or S7-1200 CPUs (firmware V4.4
or higher), you can reach the MQTT Broker via a static IP address or a domain
name ("Qualified Domain Name", short: QDN) if you use the "LMQTT" library.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 8
2 Engineering
2 Engineering
Note The engineering in this section focuses on the MQTT Client function, which
realizes this application example.
It is assumed that you have already installed and configured the MQTT Broker.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 9
2 Engineering
2.2 Configuration
The application example in entry 109748872 shows the configuration.
1. Create a TIA Portal project with the CPU that you want to use for the
application example.
2. Parameterize the Ethernet interface of the CPU with an IP address that lies in
the same subnet as the MQTT Broker.
3. If you are using a cloud service like AWS, parameterize a router and a DNS
server.
4. Connect the CPU and the MQTT Broker via Ethernet.
Note For secured MQTT communication via TLS, you need an S7-1500 CPU with
firmware version 2.0 or higher, or an S7-1200 CPU with firmware V4.4 or higher.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 10
2 Engineering
1. In the TIA Portal project, click the "Libraries" task card and open the "Global
Libraries" palette.
2. Click on the "Open global library" button.
The “Open global library” dialog is opened.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 11
2 Engineering
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 12
2 Engineering
2.3.2 Copying Function Blocks and Data Types to the User Program
2. Insert the function block for your CPU via drag & drop into the folder "Program
blocks" of your device, e.g. S7-1500 CPU.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 13
2 Engineering
3. The data types used by the FB "LMQTT_Client" are automatically inserted into
the folder "PLC data types" on your device (e.g., an S7-1500 CPU).
© Siemens AG 2021 All rights reserved
This section shows you how to create a global data block (DB). This DB is used to
store the following data:
• TCP connection parameters
• MQTT connection parameters
• Topic and message to be sent to the MQTT Broker (publish)
• Received data, i.e. message and name of the subscribed topic (subscribe)
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 14
2 Engineering
3. Make the following settings and then confirm your entries with the "OK" button.
– Select the symbol "Data block".
– Select "Global DB" as the type.
– Enter the name of the DB.
– Enable the "Automatic" radio button for automatic number assignment. The
number of the global DB is assigned by the TIA Portal.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 15
2 Engineering
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 16
2 Engineering
Result
The following figure shows the tags in the DB "MqttDb" for switching the inputs and
outputs of the FB "MQTT_Client".
Figure 2-1
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 17
2 Engineering
Figure 2-2
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 18
2 Engineering
1. In the "Project tree" open the folder "Program blocks" of your CPU
2. Double-click the block "Main [OB1]" to open the corresponding program editor.
3. Drag & drop the FB "LMQTT_Client" from the project navigation to any OB1
network.
6. Assign the tags that you have created in the global data block to the inputs and
outputs of the FB (see section 2.3.3).
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 19
2 Engineering
Result
The following figure shows the linking of the DB "MqttDb" tags on the FB
"MQTT_Client".
Figure 2-3
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 20
2 Engineering
Note You only need to configure the security feature if you are using a secure MQTT
connection via TLS.
Note In this application example, the MQTT Broker does not authenticate the MQTT
Client. Only the CA certificate of the MQTT Broker is required to authenticate the
MQTT Broker.
If you have configured the MQTT Broker to require MQTT Client authentication,
you must also import the client certificate.
The client certificate must be signed by the same CA as the server certificate.
Encryption via SSL/TLS works via certificates. A certificate is a public key signed
by its owner that guarantees its authenticity and integrity. To authenticate the
broker, the MQTT Client requires the CA certificate of the broker.
This section shows you how to import the certificate of the MQTT Broker into the
CPU (MQTT Client). Encrypted MQTT communication is only possible with this
certificate.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 21
2 Engineering
You must import the CA certificate of the MQTT Broker into STEP 7 (TIA Portal).
In the TIA Portal, the certificates are managed in the global certificate manager.
The certificate manager contains an overview of all certificates used in the project.
In the certificate manager, for example, you can import new certificates and export,
renew, or replace existing certificates. Each certificate is assigned an ID that can
be used to reference the certificate in the program blocks.
2. In the area navigation of the "Properties" tab, select "Protection & Security >
Certificate Manager". Enable the option "Use global security settings for
certificate manager".
© Siemens AG 2021 All rights reserved
Result
The new entry "Security Settings" appears in the project navigation.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 22
2 Engineering
Logging on users
After you have enabled the global security settings for the certificate manager, you
must log in to the security settings. You cannot access the global certificate
manager without logging in.
Log on as a security user for the security settings as described below:
1. Double-click the entry "Settings" in the project navigation under "Security
settings".
2. The user administration editor opens and the project protection area is
displayed.
Click the "Protect this project" button.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 23
2 Engineering
Result
You have activated the user administration. You are logged in as a project
administrator and can use the security settings.
If you have logged in, a line "Certificate manager" appears under the entry
"Security settings > Security features".
Figure 2-4
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 24
2 Engineering
2. Select the appropriate registry for the certificate you want to import, for
example, "Trusted certificates and core certification authorities".
Result
The CA certificate of the MQTT Broker is now located in the global certificate
manager.
Figure 2-5
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 25
2 Engineering
Note If the MQTT Broker also requires authentication of the MQTT Client, you must
import the client certificate.
Observe the following information:
The CA certificate is currently only located in the global certificate manager of the
TIA Portal. Certificates imported via the certificate manager into the global security
settings are not automatically assigned to the corresponding modules.
To authenticate the MQTT Broker, you have to load the CA certificate into the
CPU. Only those device certificates that you have assigned to the module as
device certificates via the local certificate manager are loaded onto the module.
This assignment is made in the local security settings of the module in the entry
"Certificate manager" via the table editor "Device certificates". The certificates of
the global certificate manager are available for the certificate assignment.
The following steps show you how to assign the CA certificate from the global
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 26
2 Engineering
© Siemens AG 2021 All rights reserved
4. Click in the new row. The selection for new certificates opens. Select the
previously imported CA certificate from the global certificate manager and click
the green check mark.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 27
2 Engineering
Result
The selected certificate was assigned to the CPU and provided with an ID. The ID
is the number of the certificate. Enter this value in the connection parameters for
the "brokerCert" parameter (see Figure 2-2).
Figure 2-6
© Siemens AG 2021 All rights reserved
Note If the MQTT Broker additionally requires authentication of the MQTT Client, you
must also assign the imported client certificate to the CPU (section "Device
certificates"). Enter the value of the ID in the connection parameters for the
"clientCert" parameter (see Figure 2-2).
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 28
2 Engineering
Above all, you must enter your own value for the following parameters:
• Connection number
• IPv4 address or domain name of the MQTT Broker. The domain name must
end with a ".".
• Port on which the MQTT Broker receives the messages
– unsecured connection: remote port 1883
– secured connection: remote port 8883
• Parameters for secure communication
–
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 29
2 Engineering
The following table shows the tags in the DB "MqttDb" to interconnect the inputs
and outputs of the FB "MQTT_Client".
Table 2-1
Tag Data type Note
control Struct This data structure contains the
tags for controlling the jobs of the
FB "LMQTT_Client".
connect Bool This tag controls the connection
establishment.
• Set the tag to the value "1" to
establish the TCP and MQTT
connection.
• If the value of the tag changes
from "1" to "0" (negative edge),
the TCP and MQTT connection
is disconneted.
publish Bool Use this tag to start a job to send a
PUBLISH packet.
subscribe Bool Use this tag to start a job to send a
SUBSCRIBE packet.
unsubscribe Bool Use this tag to start a job to send a
UNSUBSCRIBE packet.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 30
2 Engineering
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 31
2 Engineering
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 32
2 Engineering
Table 2-2
Parameters Data type Note
hwId HW_ANY Enter the hardware identifier of
the PN/IE interface for
establishing the connection.
If the tag has the value "0", a
suitable hardware identifier is
automatically selected.
connId CONN_OUC Connection ID for establishing
the connection.
mqttBrockerAddress Struct This data structure contains the
address parameters of the
MQTT Broker.
qdnAddress String Enter the domain name of the
MQTT Broker. The domain name
must end with a ".".
If this parameter is used, the IP
address entry can be omitted.
ipAddress IP_V4 Enter the IP address of the
MQTT Broker.
port UInt Enter the MQTT port.
© Siemens AG 2021 All rights reserved
Note If the TCP connection will be established via the fully qualified domain name, you
must configure a DNS server in the CPU.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 33
2 Engineering
• MQTT message received for a subscribed topic: Trigger the input tag
"subscribe".
If the connection to the MQTT Broker is interrupted (status = 16#9000), the
connection is automatically re-established. After a disconnection, it is
necessary to perform a "subscribe" job for the subscribed topics.
• Unsubscribe yourself from subscribed topics: Trigger the tag "unsubscribe".
If the connection to the MQTT Broker is not established, check the output tag
"status" and "diagnostics" to diagnose the error.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 34
2 Engineering
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 35
3 Useful Information
3 Useful Information
3.1 Fundamentals of MQTT
3.1.1 Terminology
The most important terms in the MQTT telemetry protocol are explained below.
MQTT message
A message with MQTT consists of several parts:
• A defined subject ("Topic")
• An assigned criterion for "Quality of Service"
• The message text
MQTT Client
An MQTT Client is a program or device that uses MQTT. A client always actively
establishes the connection to the broker. A client can perform the following
© Siemens AG 2021 All rights reserved
functions:
• Send messages with a defined subject ("Topic"), in which other clients might
be interested, to the MQTT Broker (Publish mechanism)
• Subscribe messages which follow a certain topic (Subscriber mechanism) at
the MQTT Broker
• Unsubscribe yourself from subscribed messages
• Disconnect from the broker
Note The function block "LMQTT_Client" in this application example supports the
following functions:
• Logging into the MQTT Broker
• Publish mechanism
• Subscribe and unsubscribe mechanisms
• Ping mechanism
• Unsubscribe from the MQTT Broker.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 36
3 Useful Information
MQTT Broker
An MQTT Broker is the central component of MQTT and can be a program or a
device. The MQTT Broker acts as an intermediary between the sending MQTT
Client and the subscribing MQTT Client. The MQTT Broker manages the topics
including the messages contained therein and regulates the access to the topics.
The MQTT Broker has the following functions:
• Accept network connections from the MQTT Clients
• Receive messages from an MQTT Client
• Edit subscription requests from MQTT Clients
• Forward messages to the MQTT Clients that match your subscription
Note The MQTT Broker is not part of this application example and is assumed to be
given.
Topics
MQTT messages are organized in topics. A topic "describes" a subject area. The
topics can be subscribed to by the MQTT Clients (subscriber mechanism). The
sender of a message (Publisher mechanism) is responsible for defining content
and topic when sending the message. The broker then takes care that the
© Siemens AG 2021 All rights reserved
Subscribers get the news from the subscribed topics. The topics follow a defined
scheme. They are similar to a directory path and represent a hierarchy.
ISO standard
MQTT defines an OASIS or ISO standard (ISO/IEC PRF 20922).
Depending on the security protocols used, MQTT runs on different access ports.
Ports offered are:
• 1883: MQTT, unencrypted
• 8883: MQTT, encrypted
• 8884: MQTT, encrypted, Client Certificate required
• 8080: MQTT via WebSockets, unencrypted
• 8081: MQTT via WebSockets, encrypted
Architecture
The MQTT is a publish and subscribe protocol. This mechanism decouples a client
sending messages (Publishers) from one or more clients receiving the messages
(Subscribers). This also means that the "Publishers" know nothing about the
existence of the "Subscribers" (and vice versa).
There is a third component in the MQTT architecture, the MQTT Broker. The
MQTT Broker is located between "Publisher" and "Subscriber". The MQTT Broker
controls the communication.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 37
3 Useful Information
3.1.3 Features
Quality of Service
The MQTT specification provides three service qualities for message transmission
quality assurance:
• QoS "0": The lowest level 0 is a "fire'n'forget" method. This means that there is
no guarantee that the message will arrive at all.
• QoS "1": The QoS level 1 ensures that the message ends up in the topic queue
at least once. The MQTT Broker acknowledges receipt of the message.
• QoS "2": In the highest level 2, the MQTT Broker guarantees by multiple
handshake with the MQTT Client that the message is exactly filed once.
Last will
MQTT supports the "Last Will and Testament" feature. This feature is used to notify
other MQTT Clients if the connection to a MQTT Client has been disconnected
accidentally.
Each MQTT Client can specify its last will while connecting to the MQTT Broker
and notify the MQTT Broker. This last will is built like a normal MQTT message,
including topic, QoS and payload. The MQTT Broker saves the last will. As soon as
the MQTT Broker notices that the connection with the MQTT Client in question has
© Siemens AG 2021 All rights reserved
been abruptly terminated, the MQTT Broker sends the last will as an MQTT
message to all subscribers who have registered for the topic. In this way, the
subscribers also learn that the MQTT Client has been disconnected.
Keep-Alive
MQTT supports the "Keep-Alive" feature. This ensures that the connection is still
open and the MQTT Client and MQTT Broker are connected.
For the Keep-Alive, the MQTT Clients define a time interval and communicate it to
the MQTT Broker during their connection setup. This interval is the largest possible
tolerated time period in which the MQTT Client and the MQTT Broker may remain
without contact. If the time is exceeded, the MQTT Broker must disconnect.
That means that, as long as the MQTT Client periodically sends messages to the
broker within the Keep-Alive interval, the MQTT Client does not need to take any
special action to maintain the connection. However, if the MQTT Client does not
send any messages within the Keep-Alive interval, they must ping the MQTT
Broker before the deadline expires. With this ping, the MQTT Client signals to the
MQTT Broker that it is still available.
When a message or a ping packet has been sent to the MQTT Broker, timing for
the Keep-Alive interval begins again.
Note • The client determines the Keep-Alive interval. It can therefore adjust the
interval of his environment, e.g. because of a slow bandwidth.
• The maximum value for the Keep-Alive interval is 18 h 12 m 15 s.
• When the client sets the Keep-Alive interval to "0", the Keep-Alive
mechanism is disabled.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 38
3 Useful Information
Message persistence
If the connection to an MQTT Client is interrupted, the broker can cache new
messages for this client for later delivery.
Retained messages
The first time an MQTT Client subscribes to a topic, it usually gets a message only
when another MQTT Client sends a message with the subscribed topic the next
time. With "Retained messages", the subscriber receives the last value sent to the
topic prior to its subscription request, delivered immediately.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 39
3 Useful Information
Most MQTT control packets work according to the handshake procedure. The
MQTT Client is always the active element and creates a job for the MQTT Broker.
The broker confirms the request depending on the job.
The structure of an MQTT control packet is fixed. The following diagram shows the
structure:
Figure 3-1
Fixed header
Mandatory for all control packages
Variable header
Mandatory for some control packages
Payload
Mandatory for all control packages
The "Variable header" is required only for some control packets. The content of the
variable header depends on the control packet type.
The payload is mandatory for most control packets. Again, the content depends on
the control packet type. For each type of control packet, there are clear rules with
what and in what order the payload can be filled.
Note A detailed description of MQTT control packets can be found in the MQTT
specification description (see \3\ in section 4.3).
The MQTT control packets from this application example are briefly explained
below.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 40
3 Useful Information
An MQTT connection is always made between an MQTT Client and the MQTT
Broker. A direct client-client connection is not possible.
The connection is initiated by an MQTT Client as soon as the MQTT Client sends a
"CONNECT" packet to the MQTT Broker. If positive, the MQTT Broker replies with
a "CONNACK" packet and a status code.
The MQTT Broker immediately closes the connection in the following cases:
• If the "CONNECT" packet is faulty
• If the structure of the "CONNECT" packet does not meet the specification
• If the connection takes too long
Byte 2 Remaining length: The number of following bytes after the "fixed header" =
"variable header" + "payload"
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 41
3 Useful Information
Table 3-2 shows the structure of the "variable header" of the "CONNECT" packet.
Table 3-2
Variable header
Bit 7 6 5 4 3 2 1 0
Report name
Byte 1 MSB length = 0 (dec)
Byte 2 LSB length = 4 (dec)
Byte 3 'M'
0 1 0 0 1 1 0 1
Byte 4 'Q'
0 1 0 1 0 0 0 1
Byte 5 'T'
0 1 0 1 0 1 0 0
Byte 6 'T'
0 1 0 1 0 1 0 0
Report level
Byte 7 Report level = 4 (dec)
Connect flags
Byte 8 User Password Will Will QoS flag Will Clean Reserve
name flag retain flag session
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 42
3 Useful Information
Table 3-4 shows the structure of the "variable header" of the "CONNACK" packet.
Table 3-4
Variable header
Bit 7 6 5 4 3 2 1 0
Connect acknowledge flags
Byte 1 Reserve Session
Present
Connect Return Code
Byte 2 • 0x00 = The MQTT Broker accepts the connection. The MQTT Broker
© Siemens AG 2021 All rights reserved
does not support the level of the MQTT protocol requested by the
client.
• 0x01 = The MQTT Broker does not support the level of the MQTT
protocol requested by the MQTT Client.
• 0x02: The MQTT Broker does not allow the client ID.
• 0x03: The MQTT service is not available.
• 0x04: The data in the username and password are incorrect.
• 0x05: The MQTT Client is not authorized to connect.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 43
3 Useful Information
Once an MQTT Client connects to the MQTT Broker, it can send messages to the
MQTT Broker. To do this, the client uses the "PUBLISH" packet. Because MQTT
messages are filtered and managed based on topics, each MQTT message must
contain a topic. The topic is part of the "Variable Header". The actual message text
is contained in the "payload".
"PUBLISH" packet
Table 3-5 shows the structure of the "fixed header" of the "PUBLISH" packet.
Table 3-5
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control DUP QoS level Retain
packet type = 3 (dec) flag flag
0 0 1 1 X X X X
Byte 2 Remaining length: The number of following bytes after the "fixed header" =
"variable header" + payload
Depending on the quality assurance setting ("QoS"), the push mechanism ends at
© Siemens AG 2021 All rights reserved
Note You can find further information on Quality Assurance QoS in section 3.1.3.
The "variable header" of the "Publish" packet contains the following fields:
• Name of the topic
• Packet ID
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 44
3 Useful Information
The "variable header" of the "PUBACK" packet contains the packet ID.
The "PUBACK" packet has no "payload".
Table 3-7 shows the structure of the "fixed header" of the "PUBREC" packet.
Table 3-7
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 5 (dec)
0 1 0 1 0 0 0 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" =
"variable header" = 2 bytes
The "variable header" of the "PUBREC" packet contains the packet ID.
The "PUBREC" packet has no "payload".
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 45
3 Useful Information
Note The reserve bits in the "fixed header" must be set as follows:
• Bit 3 = 0
• Bit 2 = 0
• Bit 1 = 1
• Bit 0 = 0
© Siemens AG 2021 All rights reserved
The "variable header" of the "PUBREL" packet contains the packet ID.
The "PUBREL" packet has no "payload".
The "variable header" of the "PUBCOMP" packet contains the packet ID.
The "PUBCOMP" packet has no "payload".
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 46
3 Useful Information
Once an MQTT Client has connected to the MQTT Broker, it can create or
unsubscribe from subscriptions.
"SUBSCRIBE" packet
To create a subscription, the MQTT Client uses the "SUBSCRIBE" packet. A list of
the topics that the MQTT Client would like to subscribe to is stored in the
"Payload".
Table 3-10 shows the structure of the "fixed header" of the "SUBSCRIBE" packet.
Table 3-10
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 8 (dec)
1 0 0 0 0 0 1 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" =
"variable header" + "payload"
© Siemens AG 2021 All rights reserved
Note The reserve bits in the "fixed header" must be set as follows:
• Bit 3 = 0
• Bit 2 = 0
• Bit 1 = 1
• Bit 0 = 0
The "variable header" of the "SUBSCRIBE" packet contains the packet ID.
Table 3-11 shows the structure of the "payload" of the "SUBSCRIBE" packet.
Table 3-11
Payload
Bit 7 6 5 4 3 2 1 0
Topic name
Byte 1 MSB length
Byte 2 LSB length
Byte Topic name
3…n
Requested service quality QoS
Byte Reserve QoS level
n+1 Possible values:
• 0 (dec)
• 1 (dec)
• 2 (dec)
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 47
3 Useful Information
The "variable header" of the "SUBACK" packet contains the packet ID.
Table 3-13 shows the structure of the "payload" of the "SUBACK" packet.
Table 3-13
Payload
Bit 7 6 5 4 3 2 1 0
© Siemens AG 2021 All rights reserved
Return code
Byte 1 • 0x00: Successful: Maximum service quality QoS 0
• 0x01: Successful: Maximum service quality QoS 1
• 0x02: Successful: Maximum service quality QoS 2
• 0x80: Error
"UNSUBSCRIBE" packet
To unsubscribe from a subscription, the MQTT Client uses the "UNSUBSCRIBE"
packet. A list of the topics that the MQTT Client would like to unsubscribe from is
stored in the "Payload".
Table 3-14 shows the structure of the "fixed header" of the "UNSUBSCRIBE"
packet.
Table 3-14
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 10 (dec)
1 0 1 0 0 0 1 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" =
"variable header" + "payload"
Note The reserve bits in the "fixed header" must be set as follows:
• Bit 3 = 0
• Bit 2 = 0
• Bit 1 = 1
• Bit 0 = 0
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 48
3 Useful Information
The "variable header" of the "UNSUBSCRIBE" packet contains the packet ID.
Table 3-15 shows the structure of the "payload" of the "UNSUBSCRIBE" packet.
Table 3-15
Payload
Bit 7 6 5 4 3 2 1 0
Topic name
Byte 1 MSB length
Byte 2 LSB length
Byte Topic name
3…n
"UNSUBACK" packet
The MQTT Broker responds to the "UNSUBSCRIBE" packet with the
"UNSUBACK" packet.
Table 3-16 shows the structure of the "fixed header" of the "UNSUBACK" packet.
Table 3-16
© Siemens AG 2021 All rights reserved
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 11 (dec)
1 0 1 1 0 0 0 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" =
"variable header" = 2 bytes.
The "variable header" of the "UNSUBACK" packet contains the packet ID.
The "UNSUBACK" packet has no "payload".
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 49
3 Useful Information
If the Keep-Alive interval is greater than "0", the Keep-Alive function is active. If the
Keep-Alive function is active, the MQTT Client must send at least one message to
the MQTT Broker within the Keep-Alive interval. If this is not the case, the MQTT
Broker must terminate the connection to the MQTT Client. To prevent this type of
forced abort, the MQTT Client must ping the MQTT Broker before the Keep-Alive
time expires. The control packet "PINGREQ" is used for this.
"PINGREQ" packet
Table 3-17 shows the structure of the "fixed header" of the "PINGREQ" packet
Table 3-17
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 12 (dec)
1 1 0 0 0 0 0 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" = 0
bytes.
"PINGRESP" packet
The MQTT Broker responds to the "PINGREQ" packet with the "PINGRESP"
packet and thus signals its availability to the MQTT Client.
Note This application example assumes an active Keep-Alive function. The Keep-Alive
interval must be greater than two seconds.
Table 3-18 shows the structure of the "fixed header" of the "PINGRESP" packet.
Table 3-18
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 13 (dec)
1 1 0 1 0 0 0 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" = 0
bytes.
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 50
3 Useful Information
"DISCONNECT" packet
Table 3-19 shows the structure of the "fixed header" of the "DISCONNECT"
packet.
Table 3-19
Fixed header
Bit 7 6 5 4 3 2 1 0
Byte 1 Identifier number for MQTT control Reserve
packet type = 14 (dec)
1 1 1 0 0 0 0 0
Byte 2 Remaining length: The number of following bytes after the "fixed header" = 0
bytes.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 51
3 Useful Information
Note An MQTT connection setup is only possible if the TCP connection to the MQTT
Broker is successfully established and then maintained.
An MQTT message or Keep-Alive can only be sent if there is a TCP and MQTT
connection to the MQTT Broker.
© Siemens AG 2021 All rights reserved
Overview
To fulfill the mentioned requirements, several state machines were realized in the
program:
• State machine "STATE_MACHINE_FUNCTION_BLOCK_TCP": Management
of the TCP connection
• State machine "MQTT_STATE_MACHINE": Management of the MQTT
connection, the sending and receiving process
• State machine "MQTT_COMMANDS": MQTT Control Package Management
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 52
3 Useful Information
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 53
3 Useful Information
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 54
3 Useful Information
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 55
3 Useful Information
• MQTT_COMMAND_STATE_BUILD_UNSUBSCRIBE
• MQTT_COMMAND_STATE_SEND_UNSUBSCRIBE
• MQTT_COMMAND_STATE_SEND_PING
• MQTT_COMMAND_STATE_PING_RESP
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 56
3 Useful Information
Table 3-22
State Description
MQTT_COMMAND_ As long as there is no send trigger and the Keep-
NO_PROCESSING Alive interval does not expire, the state is always
"MQTT_COMMAND_NO_PROCESSING".
MQTT_COMMAND_STATE_ If a positive edge is detected at the "publish" input in
BUILD_PUBLISH the "MQTT_CONNECT_STATE_CONNECTED"
state, the internal state machine
"MQTT_COMMANDS" is set to the state
"MQTT_COMMAND_STATE_BUILD_PUBLISH".
If no other send job is running, a "PUBLISH" packet
or a "PUBREL" packet is assembled and then sent to
the MQTT Broker with the block "TSEND_C".
The output "status" is set to the value "16#7006" to
signal that the MQTT push mechanism is running.
The state machine changes to the state
"MQTT_COMMAND_STATE_SEND_PUBLISH".
MQTT_COMMAND_STATE_ Depending on the QoS level, the MQTT Client may
SEND_PUBLISH expect one of the following MQTT control packets as
acknowledgement of the PUBLISH packet.
• QoS = 0 (dec): The send job ends here.
• QoS = 1 (dec): "PUBACK" packet". When the
MQTT Broker has confirmed receipt of the
"PUBLISH" packet with a "PUBACK" packet, the
send job is finished.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 57
3 Useful Information
State Description
MQTT_COMMAND_STATE_ If a positive edge is detected at the "subscribe" input
BUILD_SUBSCRIBE in the "MQTT_CONNECT_STATE_CONNECTED"
state, the internal state machine
"MQTT_COMMANDS" is set to the state
"MQTT_COMMAND_STATE_BUILD_SUBSCRIBE".
If no other send job is running, a "SUBSCRIBE"
packet is assembled and then sent to the MQTT
Broker with the block "TSEND_C".
The output "status" is set to the value "16#7008" to
signal that the MQTT sub-mechanism is running.
The state machine changes to the state
"MQTT_COMMAND_STATE_SEND_SUBSCRIBE".
MQTT_COMMAND_STATE_ The MQTT Client expects a "SUBACK" packet from
SEND_SUBSCRIBE the MQTT Broker to acknowledge the "SUBSCRIBE"
packet.
When the MQTT Broker has acknowledged receipt of
the "SUBSCRIBE" packet with a "SUBACK" packet,
the following actions are performed:
• The output "status" is set to the value "16#0000"
for 1 cycle before it is set again to the value
"16#7004". The status display "16#7004"
indicates that the MQTT connection is
established and no job is active.
• The output "done" is set to the value "true". Only
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 58
3 Useful Information
State Description
MQTT_COMMAND_STATE_ The MQTT Client expects an "UNSUBACK" packet
SEND_UNSUBSCRIBE from the MQTT Broker to acknowledge the
"UNSUBSCRIBE" packet.
When the MQTT Broker has acknowledged receipt of
the "UNSUBSCRIBE" packet with a "UNSUBACK"
packet, the following actions are performed:
• The output "status" is set to the value "16#0000"
for 1 cycle before it is set again to the value
"16#7004". The status display "16#7004"
indicates that the MQTT connection is
established and no job is active.
• The output "done" is set to the value "true". Only
when the input "unsubscribe" is reset to the
value "false", is the output "done" of the
FB "LMQTT_Client" also reset to the value
"false".
• The state machine changes to the state
"MQTT_COMMAND_STATE_NO_
PROCESSING".
MQTT_COMMAND_STATE_ If the Keep-Alive interval has expired in the state
SEND_PING "MQTT_CONNECT_STATE_CONNECTED", the
internal state machine "MQTT_COMMANDS" is set
to the state
"MQTT_COMMAND_STATE_SEND_PING" and the
Keep-Alive interval is restarted.
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 59
3 Useful Information
The following figure shows the diagram of the operation with the three state
machines.
Figure 3-2
enable
enable enable=0 MQTT_STATE_MACHINE
enable 1 -> 0
0 -> 1
MQTT_CONNECT_STATE_
BUILD_CONNECT
FB_STATE_ FB_STATE_NO_
DISABLING PROCESSING
MQTT_CONNECT_STATE_SEND_
PACKET_WAIT_FOR_CONNACK
TSEND_C.
ERROR CONNACK. CONNACK.
FB_STATE_TCP_CONNECTING ERROR SUCCESS
TSEND_C.DONE
MQTT_CONNECT_STATE_
TSEND_C.DONE CONNECTED
© Siemens AG 2021 All rights reserved
FB_STATE_OPERATING_
MONITOR_TCP
MQTT_STATE_MACHINE
FB_STATE_RECONNECTING
MQTT_CONNECT_STATE_CONNECTED
Keep alive or
KeepAlive-Timer publish or
subscribe or
unsubsribe
MQTT_COMMAND_NO_PRCESSING
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 60
4 Appendix
4 Appendix
4.1 Service and support
Industry Online Support
Do you have any questions or need assistance?
Siemens Industry Online Support offers round the clock access to our entire
service and support know-how and portfolio.
The Industry Online Support is the central address for information about our
products, solutions and services.
Product information, manuals, downloads, FAQs, application examples and videos
– all information is accessible with just a few mouse clicks:
support.industry.siemens.com
Technical Support
The Technical Support of Siemens Industry provides you fast and competent
support regarding all technical queries with numerous tailor-made offers
– ranging from basic support to individual support contracts.
Please send queries to Technical Support via Web form:
support.industry.siemens.com/cs/my/src
© Siemens AG 2021 All rights reserved
Service offer
Our range of services includes the following:
• Plant data services
• Spare parts services
• Repair services
• On-site and maintenance services
• Retrofitting and modernization services
• Service programs and contracts
You can find detailed information on our range of services in the service catalog
web page:
support.industry.siemens.com/cs/sc
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 61
4 Appendix
The Siemens Industry Mall is the platform on which the entire siemens Industry
product portfolio is accessible. From the selection of products to the order and the
delivery tracking, the Industry Mall enables the complete purchasing processing –
directly and independently of time and location:
mall.industry.siemens.com
© Siemens AG 2021 All rights reserved
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 62
4 Appendix
LMQTT_Client
Entry ID: 109748872, V3.0, 03/2021 63