You are on page 1of 78

MQTT client for

S7-1200 / S7-1500
CPUs for connecting
to MindSphere
Siemens
Blocks for S7-1200 / S7-1500 CPUs Industry
Online
https://support.industry.siemens.com/cs/ww/en/view/109772284 Support
Legal information

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 2019 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.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 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 ................................................................................ 8
2 Engineering ........................................................................................................ 9
2.1 Block description .................................................................................. 9
2.1.1 FB "LMindConn_MQTT" interface description ..................................... 9
2.1.2 FC "MindSphereDataStringCollector" interface description ............... 12
2.1.3 FC "ConvertValueToMsString" interface description ......................... 13
2.1.4 Overview of data types ....................................................................... 14
2.2 Configuration ...................................................................................... 17
2.2.1 Connecting components..................................................................... 17
2.2.2 Create TIA Portal Project ................................................................... 17
2.3 Integrating FB and Fcs into the user program ................................... 20
2.3.1 Opening "LMindConn_MQTT" Global Library .................................... 20
2.3.2 Copying FB, FCs into the user program ............................................. 22
2.3.3 Calling FB "LMindConn_MQTT" in the user program ........................ 23
2.3.4 Calling FC "MindSphereDataStringCollector" in the user
program .............................................................................................. 26
2.3.5 Creating global data blocks ................................................................ 28
© Siemens AG 2019 All rights reserved

2.3.6 Create instance data block (Instance DB) of the FB


"LMQTT_Client" ................................................................................. 40
2.3.7 Populate the inputs and outputs of FB "LMindConn_MQTT" and
FC "MindSphereDataStringCollector" ................................................ 41
2.4 Configuration of the security functions ............................................... 43
2.4.1 Using the global certificate manager in the TIA Portal ....................... 43
2.4.2 Using the local certificate manager of the CPU ................................. 46
2.5 Setting up MindSphere ....................................................................... 49
2.5.1 Asset Manager ................................................................................... 49
2.5.2 MindConnect IoT Extension ............................................................... 55
2.5.3 Fleet Manager .................................................................................... 65
2.6 Parameter assignment and operation ................................................ 67
2.6.1 Setting the parameters ....................................................................... 67
2.6.2 Operation ............................................................................................ 68
2.7 Error handling ..................................................................................... 70
3 Useful information ........................................................................................... 71
3.1 Structure of the MindSphere-conformant string ................................. 71
3.1.1 Structure of the MQTT control packets .............................................. 71
3.1.2 Send data to MindSphere via MQTT .................................................. 71
3.1.3 Receiving MindSphere-bound data via MQTT ................................... 73
3.2 Detailed functional description of the FB "LMindConn_MQTT" ......... 73
3.2.1 Requirements and implementation .................................................... 73
3.2.2 Overview............................................................................................. 74
4 Appendix .......................................................................................................... 77
4.1 Service and support ........................................................................... 77
4.2 Links and literature ............................................................................. 78
4.3 Change documentation ...................................................................... 78

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 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.

Slim and quick: MQTT


The MQTT is a simple built-in binary publish and subscribe protocol at the TCP/IP
level. It is suitable for messaging between low-functionality devices and
transmission over unreliable, low-bandwidth, high-latency networks. With these
characteristics, MQTT plays an important role for IoT and in M2M communication.

Features of MQTT
The MQTT protocol is distinguished by the following features:
© Siemens AG 2019 All rights reserved

• Lightweight protocol with low transport overhead


• Minimal need for network bandwidth through push mechanism
• Reconnect function after termination of connection
• Resending of messages after disconnection
• Mechanism for notifying prospects of an unforeseen disconnection of a client
• Easy to use and implement with a small set of command commands
• Quality Assurance (QoS level) with different levels of message delivery
reliability
• Optional encryption of messages with SSL/TLS
• Authentication of publishers and subscribers with username and password

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 4
1 Introduction

Applicative implementation
MindSphere is the cloud-based, open IoT operating system from Siemens. Using
the "MindConnect IoT Extension" upgrade, it is possible to connect devices to
MindSphere over MQTT.
In order to implement the MQTT protocol in a SIMATIC S7 CPU and transmit data
to MindSphere, the library "LMindConn_MQTT" offers you an adequate solution.
The "LMindConn_MQTT" library provides you with function blocks for the
SIMATIC S7-1500 and the SIMATIC S7-1200 CPUs. The function blocks integrate
the MQTT client function. It enables the following functions:
• Transmitting MQTT messages to "MindConnect IoT Extension" (publisher role)
• Receive messages from "MindConnect IoT Extension" (subscriber role)
The communication can be secured via a TLS connection.

Note The MQTT client supports MQTT protocol version 3.1.1.

Note When transmitting characters (Char) and character sequences (String), only
UTF-8 Chars are permitted.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 5
1 Introduction

1.2 Principle of operation


Schematic representation
The following figure shows the most important relationships between the
components involved and the steps required for secured MQTT communication
(MQTT over TLS).
Figure 1-1

Engineering MindSphere

Cert_xy MindConnect IoT Extension


STEP 7 (TIA Portal)
(MQTT-Broker)
2

Certificate Store
idx Cert_Name 1
1 Cert_xy

Topic x Topic z
S7-CPU 3 Message Message
(MQTT-Client) Topic y
Message
Topic y
Message
© Siemens AG 2019 All rights reserved

Publish

Subscribe

MQTT over TLS


4

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 "LMindConn_MQTT" takes over the following functions:
• Conversion of data points to a MindSphere-conformant string
• Establish connection to the MQTT broker "MindConnect IoT
Extension" in MindSphere
• Publisher to send MQTT messages to MindSphere
• Subscriber to receive MQTT messages from MindSphere

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 6
1 Introduction

The figure below shows an overview of the "LMindConn_MQTT" library.


Figure 1-2

Connection LMindConn_ LMQTT_


parameters MQTT Client

MindSphere
DataString

Data point MindSphere Convert


DataString ValueToMs
model
Collector String
3 2

Values
© Siemens AG 2019 All rights reserved

Table 1-2
No. FB / FC Description
1 FB "LMindConnMQTT" Controls the communication
between S7 CPU and
MindSphere based on MQTT
protocol.
2 FC "ConvertValueToMsString" This function converts the value
of a data point to a MindSphere-
conformant string (MQTT
payload).
3 FC "MindSphereDataStringCollector" This function generates a
MindSphere-conformant string in
order to send the values of up to
50 data points to MindSphere.

Note A detailed functional description of the "LMindConn_MQTT" library and


information on MindSphere-conformant Strings can be found in chapter 3.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 7
1 Introduction

1.3 Components used


The following hardware and software components were used to create this
application example:
Table 1-3
Components Quantity Article number Note
CPU1513-1 PN 1 6ES7513-1AL01-0AB0 Alternatively, you can use
another S7 1500 CPU or
ET 200 CPU (ET 200SP,
ET 200pro). At least firmware
version 2.0 is required for
secure MQTT communication
via TLS.
CPU1214C 1 6ES7214-1AG40-0XB0 Alternatively, you can use one
of the following components:
• Another S7-1200 CPU with
firmware V4.4 or higher
• CP 1243-1
(6GK7243-1BX30-0XE0)
with firmware V3.2 or
higher
• CP 1243-7 LTE
(6GK7243-7KX30-0XE0 /
6GK7243-7SX30-0XE0)
© Siemens AG 2019 All rights reserved

with firmware V3.2 or


higher
TIA Portal V16 1 DVD:
6ES7822-1AA06-0YA5
Download:
6ES7822-1AE06-0YA5
TIA Portal V15.1 − DVD: −
Upd3 6ES7822-1AA05-0YA5
Download:
6ES7822-1AE05-0YA5
MindSphere − − −
account
MindConnect IoT − − −
Extension

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 8
2 Engineering

2 Engineering
2.1 Block description

Note In TIA Portal V16 the FB and the FCs from the "LMindConn_MQTT" library are
available for S7-1500 CPUs and S7-1200 CPUs.
In STEP 7 V15.1 the FB and the FCs from the "LMindConn_MQTT" library are
available for S7-1500 CPUs.
The FB and the Fcs are designed for "optimized block access".

2.1.1 FB "LMindConn_MQTT" interface description

The parameters of the function block FB "LMindConn_MQTT" are explained below.

Input parameters
Table 2-1
Parameter Data type Description
connect Bool Control input
© Siemens AG 2019 All rights reserved

True: The FB establishes a connection to the MQTT


broker "MindConnect IoT Extension" and maintains it.
The S7 CPU is registered as a device in the MQTT
broker "MindConnect IoT Extension", in other words, a
message with template 100 is sent one time, e.g.
"100,devicename,devicetype".
sendMessageDataOnce Bool True: For a positive edge at the
"sendMessageDataOnce" input, the FB sends a
PUBLISH packet to MindSphere, in order to transfer
data one time and immediately.
sendMessageDataPeriodically Bool True: Within a certain time interval, the FB sends
PUBLISH packets to MindSphere in order to
continuously transmit data.
periodicMessageInterval Time Time interval for continuous sending of PUBLISH
packets to MindSphere
openCommandShell Bool True: The FB creates a shell in the MQTT broker
"MindConnect IoT Extension" and receives messages
on the topic "s/ds".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 9
2 Engineering

Output parameters
Table 2-2
Parameter Data type Description
connectionEstablished Bool True if following conditions are met:
• TCP connection is established
(instLMQTT_Client.tcpEstablished = true)
• MQTT connection is established
(instLMQTT_Client.mqttEstablished = true)
The FB is ready to send PUBLISH packets.
done Bool True for a cycle if the job for sending a PUBLISH
packet was successfully completed.
busy Bool TRUE if one of the following jobs is running:
• Connection setup
• Sending PUBLISH packet (one-time or
continuous)
• Creating shell in MQTT broker "MindConnect
IoT Extension" and receiving messages on
the topic "s/ds"
error Bool TRUE for a cycle if an error occurs, e.g.
• while the connection is being established
• for a current job
• connection is broken
© Siemens AG 2019 All rights reserved

status Word Status display: Information on the error that has


occurred in the FB "LMindConn_MQTT" (see
chapter 2.7).
diagnostics "LMindConn_MQTT_ Additional information on the error that has
typeDiagnostics" occurred in the FB "LMindConn_MQTT"
(diagnostic information).
You can find detailed information on the structure
of the PLC data type
"LMindConn_typeDiagnostics" in chapter 2.1.4.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 10
2 Engineering

In/out parameters
Table 2-3
Parameter Data type Description
mindSphereDataMessage WString MindSphere-conformant string (MQTT payload),
which is assembled in the FC
"MindSphereDataStringCollector".
receivedData "LMindConn_MQTT_ Received data from MQTT broker "MindConnect
typeMindSphere IoT Extension" (topic and message)
Message" You can find detailed information on the structure
of the PLC data type
"LMindConn_typeMindSphereMessage" in
chapter 2.1.4.
userParams "LMindConn_MQTT_ Data structure containing parameters for carrying
typeUserData" out the following functions:
• actively establish a connection to MQTT
broker "MindConnect IoT Extension"
• register device in MQTT broker "MindConnect
IoT Extension"
You can find detailed information on the structure
of the PLC data type "LMindConn_typeUserData"
in chapter 2.1.4.
instParamMqttClient "LMQTT_Client" Instance DB of the FB "LMQTT_Client"
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 11
2 Engineering

2.1.2 FC "MindSphereDataStringCollector" interface description

The parameters of the Function FC "MindSphereDataStringCollector" are


explained below.

Output parameters
Table 2-4
Parameter Data Description
type
Ret_val Word Status display:
• 16#8200: The length of the MindSphere-conformant string is greater
than the maximum allowed length of the MQTT payload (16384 bytes).
done Bool TRUE if the task of the Function (FC) was completed successfully, meaning
that the task of creating a MindSphere-conformant string was completed
successfully.
error Bool TRUE for a cycle if an error occurs
errorID DInt ID of data point that originated the error. Possible causes for an error are:
• The value that you want to transmit to MindSphere is not supported by
MindSphere.
• No data point for the value has been defined in MindSphere.
• When converting to a MindSphere-conformant string, the value was
assigned no template (200 or 400).
© Siemens AG 2019 All rights reserved

In/out parameters
Table 2-5
Parameter Data type Description
mindSphereDataString WString MindSphere-conformant string
containing all defined data points.
datapointDefinition Array[*] of "LMindConn_MQTT_ Display of MindSphere data points
typeMindsphereDatapoint" You can find detailed information on the
structure of the PLC data type
"LMindConn_MQTT_
typeMindsphereDatapoint" in
chapter 2.1.4.
value1 Variant Value to be sent to MindSphere. Define
"NULL" if the value is not used.
value2 Variant Value to be sent to MindSphere. Define
"NULL" if the value is not used.
value3 Variant Value to be sent to MindSphere. Define
"NULL" if the value is not used.

value50 Variant Value to be sent to MindSphere. Define
"NULL" if the value is not used.

Note In order to transmit more than 50 values to MindSphere, it is necessary to extend


the FC "MindSphereDataStringCollector".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 12
2 Engineering

2.1.3 FC "ConvertValueToMsString" interface description

The parameters of the Function FC "ConvertValueToMsString" are explained


below.

Input parameters
Table 2-6
Parameter Data type Description
value Variant Value to be sent to MindSphere.

Output parameters
Table 2-7
Parameter Data type Description
error Bool TRUE if an error occurs
status Word Status display:
• 16#8100: Data type of the value to be transmitted is
not supported by MindSphere.
• 16#8102: No data point has been defined for the
value, or the MindSphere-conformant contains no
"200" or "400" template.
© Siemens AG 2019 All rights reserved

In/out parameters
Table 2-8
Parameter Data type Description
datapoint "LMindConn_MQTT_ Display of MindSphere data point
typeMindsphereDatapoint" You can find detailed information on the structure of the
PLC data type
"LMindConn_MQTT_typeMindsphereDatapoint" in
chapter 2.1.4.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 13
2 Engineering

2.1.4 Overview of data types

To structure the data clearly, several data types have been created. The data types
used in the program are shown in the following list:
• "LMindConn_MQTT_typeDiagnostics"
• "LMindConn_MQTT_typeMindSphereMessage"
• "LMindConn_MQTT_typeUserData"
• "LMindConn_MQTT_typeMindsphereDatapoint"

"LMindConn_MQTT_typeDiagnostics"
This data type contains additional information on the error that has occurred in the
FB "LMindConn_MQTT".
The following table shows the structure of the
"LMindConn_MQTT_typeDiagnostics" data type.
Table 2-9
Parameter Data type Start value Description
subFBStatus DWord 16#0 Status display of the
FB "LMQTT_Client"
Detailed information can be found in
the Application Example at the Article
© Siemens AG 2019 All rights reserved

ID 109748872.
stateNumber DInt 0 Status number in the state machine
of the FB "LMindConn_MQTT" where
the error occurred.
You can find an overview of the
FB "LMindConn_MQTT" in
chapter 3.2.2.
subFBstateNumber DInt 0 Status number in the state machine
of the FB "LMQTT_Client" where the
error occurred.
Detailed information can be found in
the Application Example at the Article
ID 109748872.

"LMindConn_MQTT_typeMindSphereMessage"
This data type contains the received data from MQTT broker "MindConnect IoT
Extension" (topic and message).
The following table shows the structure of the
"LMindConn_MQTT_typeMindSphereMessage" data type.
Table 2-10
Parameter Data type Start value Description
topic WString[25] 'WSTRING#' Topic of the message that was
received.
message WString[300] WSTRING#'' Message that was received from the
MQTT broker "MindConnect IoT
Extension".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 14
2 Engineering

Note It is necessary that the parameters "topic" and "message" in the


"LMindConn_MQTT_typeMindSphereMessage" data type have the same length
as the parameters "receivingTopic" and "receivedMessageData" in the data type
"LMQTT_typeSubscriptionData" that is used by the FB "LMQTT_Client".

"LMindConn_MQTT_typeUserData"
This data type contains parameters in order to execute the following functions:
• actively establish a connection to MQTT broker "MindConnect IoT Extension"
and maintain it
• register user in MQTT broker "MindConnect IoT Extension"
• register device in MQTT broker "MindConnect IoT Extension"
The following table shows the structure of the "LMindConn_MQTT_typeUserData"
data type.
Table 2-11
Parameter Data type Start value Description
hwInterfaceId HW_ANY 0 HW ID of the PROFINET interface
of CPU or CP
connID CONN_OUC 16#0 ID of the TCP connection
ipAddressBroker Array[0..3] of ipAddressBroker[0] = IP address of the MQTT broker, e.g.
© Siemens AG 2019 All rights reserved

USInt 0 192.168.0.10
ipAddressBroker[1] = ipAddressBroker[0] = 192
0 ipAddressBroker[1] = 168
ipAddressBroker[2] = ipAddressBroker[2] = 0
0 ipAddressBroker[3] = 10
ipAddressBroker[3] =
0
urlAddressBroker String "" URL of the MQTT broker. The URL
must end with a dot (".").
Use the URL of MindConnect IoT
Extension, e. g.
mciotextension.eu1.mindsphere.io.
activateSecureComm Bool True True: Communication is secured via
TLS.
idTlsServerCertificate UInt 0 ID of the X.509 V3 certificate
(usually a CA certificate) to validate
the TLS server authentication. If this
parameter is "0", the TLS client
uses all (CA) certificates currently
loaded in the client's certificate store
to validate server authentication.
Only relevant when
"activateSecureConn" equals "true".
mqttUsername String[100] "" User name for logging on to the
MQTT broker.
Usually the e-mail address is used
as username to log into
MindConnect IoT Extension.
Set the username in following form:
"tenant/username".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 15
2 Engineering

Parameter Data type Start value Description


mqttPassword String[200] '' Password for logging on to the
MQTT broker
deviceName String[25] 'SIMATIC S7 – xxxx'' Device name with which the device
is created in the MQTT broker
"MindConnect IoT Extension".
deviceType String[25] 'MCIoT_MQTTdevice' This parameter is needed to record
the device type in the MQTT broker
"MindConnect IoT Extension".
publishQoS Int 0 Defines the QoS level for the MQTT
message.
Possible values are:
• "0" for QoS level 0
• "1" for QoS level 1
• "2" for QoS level 2
subscriptionQoS Int 0 Defines the QoS level for the MQTT
message in the subscriber.
Possible values are:
• "0" for QoS level 0
• "1" for QoS level 1

"LMindConn_MQTT_typeMindsphereDatapoint"
© Siemens AG 2019 All rights reserved

This data type contains the definition of a data point.


The following table shows the structure of the
"LMindConn_MQTT_typeMindsphereDatapoint" data type.
Table 2-12
Parameter Data type Start value Description
asset WString[20] WSTRING#'' The "asset" parameter is the digital
representation of an element, e.g. a
motor, pump, wind turbine, etc.
type WString[20] WSTRING#'' The "type" parameter is the element
property, e.g. temperature, power,
velocity, etc.
unit WString[5] WSTRING#'' Measurement unit, e.g. m/s

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 16
2 Engineering

2.2 Configuration
2.2.1 Connecting components

Connect the components as illustrated in:


Figure 2-1

MindSphere
Internet

Internet
S7 CPU connection

Industrial Ethernet
Router
© Siemens AG 2019 All rights reserved

2.2.2 Create TIA Portal Project

1. Create a TIA Portal project with the S7 CPU that you want to use for the
Application Example.
2. In the hardware and network editor, open the device view of the S7 CPU.
3. Select the S7 CPU. The properties of the S7 CPU are displayed in the
Inspector window.
4. In the "General" tab, navigate to "PROFINET interface [X1] > Ethernet
addresses" and enter the IP address and subnet mask for the Ethernet
interface of the CPU.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 17
2 Engineering

5. Because the cloud service (MindSphere) will be used, it is necessary to enter


parameters for a router and DNS server.
In the "General" tab, navigate to "PROFINET interface [X1] > Ethernet
addresses" and enter the IP address of the router.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 18
2 Engineering

6. In the "General" tab, navigate to "DNS configuration" and enter the IP address
of the DNS server.
© Siemens AG 2019 All rights reserved

Note For the secured MQTT communication via TLS you need one of the following
components:

• S7-1500 CPU with firmware V2.0 or higher


• S7-1200 CPU with firmware V4.4 or higher
• CP 1243-1 with firmware V3.2 or higher
• CP 1243-7 LTE with firmware V3.2 or higher

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 19
2 Engineering

2.3 Integrating FB and Fcs into the user program


The FB and the FCs, as well as the necessary data types, are available to you in
the "LMindConn_MQTT" library.

2.3.1 Opening "LMindConn_MQTT" Global Library

Requirement
• STEP 7 (TIA Portal) is open.
• You have created a new project in STEP 7 (TIA Portal) or have opened an
existing project.
• You have imported the certificate "QuoVadis Root CA 2 G3.cer" for
MindSphere into your STEP 7 project. Instructions on how to import the
certificate "QuoVadis Root CA 2 G3.cer" into STEP 7 (TIA Portal) can be found
in chapter 2.4.

Instructions
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 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 20
2 Engineering

3. Select the global library "LMindConn_MQTT" and confirm the selection by


clicking "Open".

4. The library "LMindConn_MQTT" is opened and displayed under the palette


"Global libraries".
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 21
2 Engineering

2.3.2 Copying FB, FCs into the user program

1. In the "LMindConn_MQTT" library you will find the FB and the FCs for the
S7-1500 CPUs and S7-1200 CPUs under "Types > 01_Blocks".
In the "LMindConn_MQTT" library you will find the used PLC data types under
"Types > 02_Types".
Figure 2-2
© Siemens AG 2019 All rights reserved

2. Insert the FB and the FCs for your S7 CPU via drag & drop into the folder
"Program blocks" of your device, e.g. S7-1500 CPU.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 22
2 Engineering

3. The data types that are used by the FB and the FCs are automatically inserted
into the folder "PLC data types" on your device, e.g. the S7-1500 CPU.
4. The FB "LMQTT_Client", which is used by the FB "LMindConn_MQTT", is
automatically inserted into the "Program blocks" folder of your device, e.g. the
S7-1500 CPU.
© Siemens AG 2019 All rights reserved

2.3.3 Calling FB "LMindConn_MQTT" in the user program

1. In the "Project tree" open the folder "Program blocks" of your CPU.
2. Double-click on the block "Main [OB1]" to open the corresponding program
editor.
3. Drag & drop the FB "LMindConn_MQTT" from the project tree to any OB 1
network.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 23
2 Engineering

4. The dialog "Call options" for generating the instance DB of the FB


"LMinConn_MQTT" opens automatically.
5. Make the following settings:
– Enter the name of the instance DB, for example "InstLMindConn_MQTT".
– Activate the "Automatic" radio button for automatic number assignment.
The number of the instance DB is assigned by the TIA Portal.
– Accept the settings with "OK".
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 24
2 Engineering

6. Populate the inputs and outputs of the function block with the tags that you
created in the data block (see chapter 2.3.3 and 2.3.6).
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 25
2 Engineering

2.3.4 Calling FC "MindSphereDataStringCollector" in the user program

1. In the "Project tree" open the folder "Program blocks" of your CPU.
2. Double-click on the block "Main [OB1]" to open the corresponding program
editor.
3. Drag & drop the FC "MindSphereDataStringCollector" from the project tree to
any OB 1 network.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 26
2 Engineering

4. Populate the inputs and outputs of the function block with the tags that you
created in the data block (see chapter 2.3.3).
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 27
2 Engineering

2.3.5 Creating global data blocks

This chapter shows you how to create global data blocks. These DBs have the
following functions:
• Definition of connection parameters
• Control and monitoring of communication with MindSphere
• Saving of MindSphere-conformant Strings (MQTT payload)
• Definition of tags whose values are sent to MindSphere
• Saving of received data
• Defining data points

Definition of connection parameters


1. Navigate in the "Project tree" to the device folder of the S7 CPU.
2. Open the "Program blocks" folder and double-click the "Add new block"
command.
The dialog "Add new block" opens.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 28
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, e.g. "ConnectionData".
– Activate the "Automatic" radio button for automatic number assignment.
The number of the global DB is assigned by the TIA Portal.
© Siemens AG 2019 All rights reserved

4. Double-click the newly inserted global data block to open it.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 29
2 Engineering

5. Double-click "<Add new>" to create a tag of the data


type"LMindConn_MQTT_typeUserData" (see chapter 2.1.4).
© Siemens AG 2019 All rights reserved

6. Adjust the initial values of the parameters to suit your application.

7. Interconnect the tag with the FB "LMindConn_MQTT".


Table 2-13
Name Data type Interconnection at the
FB
ConnectionData "LMindConn_MQTT_typeUserData" In/out parameter
"userParams"

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 30
2 Engineering

Control and monitoring of communication with MindSphere


1. Navigate in the "Project tree" to the device folder of the S7 CPU.
2. Open the "Program blocks" folder and double-click the "Add new block"
command.
The dialog "Add new block" opens.

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, e.g. "ControlAndDiagnostic".
– Activate the "Automatic" radio button for automatic number assignment.
The number of the global DB is assigned by the TIA Portal.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 31
2 Engineering

4. Double-click the newly inserted global data block to open it.

5. Double-click "<Add new>" to create the tags accordingly.


© Siemens AG 2019 All rights reserved

6. Adjust the initial value of the parameter "periodicMessageInterval" to suit your


application.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 32
2 Engineering

7. Interconnect the tags with the FB "LMindConn_MQTT" and the


FC "MindSphereDataStringCollector".
Table 2-14
Name Data type Interconnection at the
FB / FC
connect Bool Input FB "connect"
sendMessageDataOnce Bool Input FB
"sendMessageDataOnce"
sendMessageDataPeriodically Bool Input FB
"sendMessageData
Periodically"
periodicMessageInterval Time Input FB
"periodicMessage
Interval"
openCommandShell Bool Input FB
"openCommandShell"
outMindConnMqtt Struct −
connectionEstablished Bool Output FB "connection
Established"
done Bool Output FB "done"
busy Bool Output FB "busy"
error Bool Output FB "error"
© Siemens AG 2019 All rights reserved

status Word Output FB "status"


diagnostics "LMindConn_MQTT_ Output FB "diagnostics"
typeDiagnostics"
outMindSphereDataString Struct −
Collector
retVal Word Output FC "Ret_Val"
done Bool Output FC "done"
error Bool Output FC "error"
errorID DInt Output FC "errorID"

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 33
2 Engineering

Save MindSphere-conformant Strings and receive data


1. Navigate in the "Project tree" to the device folder of the S7 CPU.
2. Open the "Program blocks" folder and double-click the "Add new block"
command.
The dialog "Add new block" opens.
Figure 2-3

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, e.g. "MindSphereData".
– Activate the "Automatic" radio button for automatic number assignment.
© Siemens AG 2019 All rights reserved

The number of the global DB is assigned by the TIA Portal.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 34
2 Engineering

4. Double-click the newly inserted global data block to open it.

5. Double-click "<Add new>" to create the tags accordingly.


© Siemens AG 2019 All rights reserved

6. Interconnect the tags with the FB "LMindConn_MQTT" and the


FC "MindSphereDataStringCollector".
Table 2-15
Parameter Data type Interconnection at the
FB / FC
MindSphereDataString WString[3250] Int/out parameter
FB and FC
"mindSphereDataString"
receivedMessage "LMindConn_MQTT_ In/out parameter
typeMindSphereMessage" FB "receivedData"

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 35
2 Engineering

Defining data points


1. Navigate in the "Project tree" to the device folder of the S7 CPU.
2. Open the "Program blocks" folder and double-click the "Add new block"
command.
The dialog "Add new block" opens.

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, e.g. "MindSphereDatapoints".
– Activate the "Automatic" radio button for automatic number assignment.
The number of the global DB is assigned by the TIA Portal.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 36
2 Engineering

4. Double-click the newly inserted global data block to open it.

5. Double-click "<Add new>" to create a tag of the data type


"Array[1.."MAX_DATAPOINTS"] of
"LMindConn_MQTT_typeMindsphereDatapoint"" (see chapter 2.1.4).
© Siemens AG 2019 All rights reserved

6. Adjust the initial values for your data points to suit your application. In this
Application Example, 5 data points are defined.
7. Interconnect the tags with the FC "MindSphereDataStringCollector".
Table 2-16
Name Data type Interconnection at the
FC
datapoints Array[1.."MAX_DATAPOINTS"] of In/out parameter
"LMindConn_MQTT_ "datapointDefinition"
typeMindSphereDatapoint"

Note The tag "MAX_DATAPOINTS" is a user constant with a value of "50".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 37
2 Engineering

Definition of tags whose values are sent to MindSphere


1. Navigate in the "Project tree" to the device folder of the S7 CPU.
2. Open the "Program blocks" folder and double-click the "Add new block"
command.
The dialog "Add new block" opens.

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, e.g. "Values".
– Activate the "Automatic" radio button for automatic number assignment.
The number of the global DB is assigned by the TIA Portal.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 38
2 Engineering

4. Double-click the newly inserted global data block to open it.

5. Double-click "<Add new>" to create the tags accordingly.


© Siemens AG 2019 All rights reserved

6. Adjust the initial values for your numbers to suit your application.
7. Interconnect the tags with the FC "MindSphereDataStringCollector".
Table 2-17
Name Data type Interconnection at the
FC
motorSpeed Real Input "value1"
motortemperature Int Input "value2"
eventWarning String Input "value3"
sensorLifetime DInt Input "value4"
sensorStatus DWord Input "value5"
getValuesAndGenerateString Bool Input "EN"

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 39
2 Engineering

2.3.6 Create instance data block (Instance DB) of the FB "LMQTT_Client"

1. Navigate in the "Project tree" to the device folder of the S7 CPU.


2. Open the "Program blocks" folder and double-click the "Add new block"
command.
The dialog "Add new block" opens.
Figure 2-4

3. Make the following settings and then confirm your entries with the "OK" button.
– Select the symbol "Data block".
– Select "LMQTT_Client" as type.
– Enter the name of the DB, e.g. "InstLMQTT_Client".

© Siemens AG 2019 All rights reserved

Activate the "Automatic" radio button for automatic number assignment.


The number of the global DB is assigned by the TIA Portal.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 40
2 Engineering

4. Interconnect the instance DB with the FB "LMindConn_MQTT".


Table 2-18
Name Data type Interconnection at the FB
InstLMQTT_Client "LMQTT_Client" In/out parameter
"instParamMqttClient"

2.3.7 Populate the inputs and outputs of FB "LMindConn_MQTT" and


FC "MindSphereDataStringCollector"

Populate the inputs and outputs of FB "LMindConn_MQTT" and


FC "MindSphereDataStringCollector" with the tags that you created in the data
blocks (see chapter 2.3.5 and 2.3.6).

FB "LMindConn_MQTT"
Figure 2-5
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 41
2 Engineering

FC "MindSphereDataStringCollector"
Figure 2-6
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 42
2 Engineering

2.4 Configuration of the security functions


2.4.1 Using the global certificate manager in the TIA Portal

In order to encrypt the MQTT communication between the S7 CPU and


MindSphere via TLS, it is necessary to import the CA certificate "QuoVadis Root
CA 2 G3" into STEP 7 (TIA Portal).
In 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.

Activating the global certificate manager


If you do not use the certificate manager in the security settings, you only have
access to the local certificate store of the CPU. You then have no access to
imported certificates from external devices.
To import and use the CA certificate of the MQTT broker "MindConnect IoT
Extension", you must activate the global certificate manager.
1. Select the CPU in the device or network view. The properties of the CPU are
displayed in the inspection window.
2. In the area navigation of the "Properties" tab, select "Protection & Security >
Certificate Manager". Activate the function "Use global security settings for
© Siemens AG 2019 All rights reserved

certificate manager".

Result
The new entry "Security Settings" appears in the project navigation.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 43
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 "Settings" in the project navigation under "Security settings".
The user management editor opens, and the project protection area is
displayed.
2. Click the "Protect this project" button.
This opens the dialog "Protect Project".

3. Enter a username and password.


© Siemens AG 2019 All rights reserved

The password must comply with the following guidelines:


– Password length: A minimum of eight characters, a maximum of 128
characters
– At least one upper-case letter
– At least one special character (special characters § and ß are not allowed)
– At least one number
4. Enter the password again to confirm.
5. You may enter a comment if required.
6. Confirm your entries with "OK".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 44
2 Engineering

Result
User administration is active. 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".
© Siemens AG 2019 All rights reserved

Using the global certificate manager


With the global certificate manager, you now have the option of importing third-
party certificates into the TIA portal. By double-clicking on the line "Certificate
manager" you gain access to all certificates in the project, divided into the following
tabs:
• "Certification authority (CA)"
• "Device certificates"
• "Trusted certificates and core certification authorities"
1. Double-click on the "Certificate manager" entry in the project navigation under
"Security settings > Security features".
2. Select the appropriate registry for the certificate you want to import, for
example, "Trusted certificates and core certification authorities".
3. To open the context menu, right-click in the tab. Click "Import".

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 45
2 Engineering

4. Select the export format of the certificate:


– CER, DER, CRT or PEM for certificates without a private key
– P12 (PKCS12 archive) for certificates with a private key.
Click on "Open" to import the certificate.

Result
The CA certificate of the MQTT broker "MindConnect IoT Extension" is located in
the global certificate manager.
Figure 2-7

2.4.2 Using the local certificate manager of the CPU

The CA certificate is currently only located in the global certificate manager of the
TIA Portal. Certificates imported via the certificate manager in the global security
© Siemens AG 2019 All rights reserved

settings are not automatically assigned to the corresponding modules.


In order to authenticate the MQTT broker "MindConnect IoT Extension", it is
necessary to load the CA certificate "QuoVadis Root CA 2 G3" into the S7 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". When assigning
certificates, the certificates from the global certificate manager are available.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 46
2 Engineering

The following steps show you how to assign the CA certificate


"QuoVadis Root CA 2 G3" from the global certificate manager to the S7 CPU.
1. Select your CPU in the device or network view. The properties of the CPU are
displayed in the inspection window.
2. To add the CA certificate, select the entry "Certificate manager" in the area
navigation of the "Properties" tab under "Protection & Security".

3. Go to the section "Certificates of the partner devices". Click "Add" in the table
© Siemens AG 2019 All rights reserved

of certificates. This inserts a new row into the table.

4. Click in the new row. The selection for new certificates opens.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 47
2 Engineering

5. Select the previously imported CA certificate from the global certificate


manager and click the green check mark.
© Siemens AG 2019 All rights reserved

Result
The selected certificate was assigned to the S7 CPU and provided with an ID. The
ID is the number of the certificate. You enter this value in the connection
parameters for the parameter "idTlsServerCertificate" (see Table 2-11).
Figure 2-8

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 48
2 Engineering

2.5 Setting up MindSphere


You need the following applications to integrate the S7 CPU as a device into
MindSphere and view the data.
• MindConnect IoT Extension
• Asset Manager
• Fleet Manager
You can order the application via the MindSphere Store.

2.5.1 Asset Manager

Log in to MindSphere and open the "Asset Manager" using the MindSphere
Launchpad.
Figure 2-9
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 49
2 Engineering

Creating an aspect
1. Select "Aspects" in the menu bar and click on "Create aspect" to create an
aspect.
© Siemens AG 2019 All rights reserved

2. Enter a name for the aspect, e.g. "myAspectForIoT".


3. Click the "Add variable" command. Insert the required variables based on the
data points created in chapter 2.3.3.
4. Click the "Save" button to save the settings.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 50
2 Engineering
© Siemens AG 2019 All rights reserved

5. Create a type.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 51
2 Engineering

Creating a type
1. Select "Types" in the menu bar and click on "Create type" to create a type.

2. Enter a name for the type, e.g. "myTypeForIoTDevice".


3. Click "Add aspect" in the aspects list. Select the previously created aspect in
order to assign the aspect to the type.
4. Click the "Save" button to save the settings.
© Siemens AG 2019 All rights reserved

5. Create an asset.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 52
2 Engineering

Asset creation
1. Select "Assets" in the menu bar and click on "Create asset" to create an asset.

2. Select the newly created type.


© Siemens AG 2019 All rights reserved

3. Enter a name for the asset, e.g. "myAssetForIoTDevice".


4. Click the "Save" button to save the settings.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 53
2 Engineering
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 54
2 Engineering

2.5.2 MindConnect IoT Extension

Register device
1. Open the MindConnect IoT Extension via the MindSphere Launchpad.

2. If the FB "LMindConn_MQTT" has completed the following actions, then the


drive will be displayed under "Devices > All devices":
– Establish connection to device.
© Siemens AG 2019 All rights reserved

– Send the MQTT control packet with the topic "s/us" and the message text
for device registration.
3. Click on the device to open it.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 55
2 Engineering

4. Adjust the update interval (e.g. 1 minute) to monitor the connection and display
connection-related data.
The device data display the device name and device type that you entered in
STEP 7 (TIA Portal) in the connection parameters.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 56
2 Engineering

Display measurements and events


1. The numerical values are displayed under "Measurements".

2. Char and String appear in "Events".


© Siemens AG 2019 All rights reserved

Note The Measurements item is not available until the data points have been sent for
the first time.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 57
2 Engineering

Create a group
1. Under "Groups" click "Add group".
2. Enter the group name, e.g. "MyGroup".
3. Click "Add group" to create a group.

4. Open the registered device under "Devices > All devices" and click "Edit".
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 58
2 Engineering
© Siemens AG 2019 All rights reserved

5. Check the newly created group and click "Assign" to assign the device to a
group.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 59
2 Engineering

6. Click the "Save" button to apply the settings.


© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 60
2 Engineering

Device mapping
1. Under "Device mapping > Device mapping", assign the newly created asset
and the tags to the device and the data points.
2. In the "Devices" section, click on the newly created group. The assigned
device is displayed.
3. Select the device.
4. In the "Assets" section, select the newly created asset.
5. In the "Mappings" section, select the "Measurement mapping" options to
execute the assignment for numerical values, then click the command "Add
mapping". The "Add mapping" dialog opens.
© Siemens AG 2019 All rights reserved

6. Select the "Measurement mapping" option.


7. Select the data point as source.
8. For a target, select the aspect and the tag to which the data point will be
assigned.
9. Click the "Add" button to add the assignment.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 61
2 Engineering
© Siemens AG 2019 All rights reserved

Result
All measurement mappings that were created are shown in the "Mappings"
section. Status is "NEW".

10. In the "Mappings" section, select the "Event-data mapping" option to execute
the assignment for characters and Strings, then click the command "Add
mapping". The "Add mapping" dialog opens.
11. Select the "Event-data mapping" option.
12. Select the data point as source.
13. For a target, select the aspect and the tag to which the data point will be
assigned.
14. Click the "Add" button to add the assignment.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 62
2 Engineering

11

12
© Siemens AG 2019 All rights reserved

13

14

Result
All created Event-data mappings are displayed in the "Mappings" section.
Status is "NEW".

15. In the "Mappings" section, click "Commit changes".


The mappings that you have created and committed have the status "ACTIVE".

15

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 63
2 Engineering

Sending messages to device


1. Open the registered device under "Devices > All devices".
2. If the input "openCommandShell" of the FB "LMindConn_MQTT" is set to
"true", then the topic "s/ds" will be subscribed to and a shell for the registered
device will be created in the MQTT broker "MindConnect IoT Extension".
3. Enter the message you want to send to the S7 CPU.
4. Click on the "Execute" button to carry out the send order.
© Siemens AG 2019 All rights reserved

Result
The sent notification is displayed in the received data of the S7 CPU.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 64
2 Engineering

2.5.3 Fleet Manager

1. Open the Fleet Manager from the MindSphere Launchpad.

2. Select your asset.


© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 65
2 Engineering

3. Expand the asset.


4. All assigned measurements are displayed. You can also select individual
measurements via an expandable list.

5. The assigned Chars and Strings are displayed in the table view.
Figure 2-10
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 66
2 Engineering

2.6 Parameter assignment and operation


2.6.1 Setting the parameters

Before you can test the Application Example, you must set the parameters for the
secured or unsecured TCP connection to the MQTT broker "MindConnect IoT
Extension" and for MQTT according to your specifications.
All parameters which you can define yourself are located in the global data block
"ConnectionData". Set the parameters in the "Start value" column.
Above all, you must enter your own value for the following parameters:
• IPv4 address or domain name of the MQTT Broker (URL of the MindConnect
IoT Extension). The domain name must end with a ".".
• Parameters for secure communication
– Status of the security feature (On/Off) for this connection. The security
function is activated by default.
– ID of the CA certificate (only relevant for a secure connection)
• MQTT parameters, e.g.
– Logon information to the MQTT broker "MindConnect IoT Extension": User
name and password
– Device name: Here, enter the name that will be created as a device name
for the device in MQTT broker "MindConnect IoT Extension".
© Siemens AG 2019 All rights reserved

– Device type: Here, enter the name that will be created as a device type for
the device in MQTT broker "MindConnect IoT Extension".
• Set the clock time of the S7 CPU.
Then load the project into your CPU.

Note If the TCP connection is established via the fully qualified domain name, you
must configure a DNS server in the CPU (see chapter 2.2.2).

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 67
2 Engineering

2.6.2 Operation

1. Set the "connect" input of the FB "LMindConn_MQTT" to "true".


The outputs of the FB "LMindConn_MQTT" are set as follows:
– "connectionEstablished" = true:
TCP and MQTT connection successfully established to MindSphere
– "status" = 16#7002:
S7 CPU is successfully registered in MQTT broker "MindConnect IoT
Extension"
2. Set the "EN" input of the FC "MindSphereDataStringCollector" to "true", e.g.
reset the "EN" input back to "false" every 6 seconds if the function was
completed with "done" = "true" or "error" = "true".
3. Adjust the time interval for continuous sending of data.
4. Set the input "sendMessageDataOnce" or the input
"sendMessageDataPeriodically" to "true" in order to send data.
5. Set the input "openCommandShell" to "true" in order to create a shell in MQTT
broker and receive messages from MQTT broker.
© Siemens AG 2019 All rights reserved

6. In the FB "LMQTT_Client", customize the following parameters depending on


the number of data points that you are sending to MindSphere.
– MAX_SENDBUFFER
– MAX_PUBLISH_MESSAGE

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 68
2 Engineering

7. In the data type "LMQTT_typePublishData", customize the following


parameters depending on the number of data points that you are sending to
MindSphere.
– publishMessageData

Note MindSphere accepts a "payload" in the MQTT control packets with a maximum
length of 16384 bytes.
© Siemens AG 2019 All rights reserved

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 69
2 Engineering

2.7 Error handling


If an error occurs in the FB "LMindConn_MQTT" the current status of the state
machines and the cause of the error are written to the output parameters "status"
and "diagnostics".

"status"
The output parameter "status" displays the error code:
Table 2-19
status Description Remedy
16#8300 User name and password for logon Enter the logon data in the
to MQTT broker "MindConnect IoT parameters "mqttUsername" and
Extension" are not defined. "mqttPassword" of the data type
"LMindConn_MQTT_typeUserData".
16#8400 The MindSphere-conformant string MindConnect IoT Extension supports
is too long. a max. message length of
16384 bytes.
16#8500 Multiple tasks are triggered at the In each case only trigger one task.
same time:
• "connect" and
"sendMessageDataOnce"
• "connect" and
"openCommandShell"
© Siemens AG 2019 All rights reserved

• "sendMessageDataOnce" and
"openCommandShell"
16#8600 An error has occurred in the Evaluate the "diagnostics" output.
FB "LMQTT_Client". You can find detailed information on
the "diagnostics" output in
chapter 2.1.4.
16#7000 FB "LMindConn_MQTT" is not Status information
active. Activate the FB "LMindConn_MQTT"
by setting the "connect" input to
"true".
16#7001 Connection to MQTT broker Status information
"MindConnect IoT Extension" is
established. It is possible to register
the device.
16#7002 Device is registered in MQTT Status information
broker "MindConnect IoT
Extension". Data can be sent and
received via MQTT.

"diagnostics"
You can find detailed information on the "diagnostics" output in chapter 2.1.4.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 70
3 Useful information

3 Useful information
3.1 Structure of the MindSphere-conformant string
3.1.1 Structure of the MQTT control packets

The following figure shows the structure of an MQTT control packet.


Figure 3-1

Fixed header
Req'd for all control packets

Variable header
Req'd for some control packets

Payload
Req'd for all control packets

Note MindSphere accepts a "payload" in the MQTT control packets with a maximum
© Siemens AG 2019 All rights reserved

length of 16384 bytes.

3.1.2 Send data to MindSphere via MQTT

Once an MQTT client connects to the MQTT broker, it can send messages to the
MQTT broker.
To do this, the MQTT 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".
The topic "s/us" is used to send data to MindSphere via MQTT. The message text
is arranged in a strictly defined structure.

Registering device in MQTT broker "MindConnect IoT Extension"


The figure below shows the structure of the message text for registering the device
in MQTT broker "MindConnect IoT Extension". The template "100" is used for
device registration.
Figure 3-2

Template, Devicename, Devicetype,

100, TestDevice, MyIoTdevice

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 71
3 Useful information

Sending values
The figure below shows the structure of the message text for sending numeric
values. The template "200" is used for sending numeric values.
Figure 3-3

Template, Asset, Type Value Unit (optional)

200, motor, speed, 50.5, km/h

The figure below shows the structure of the message text for sending characters
(Char) and character sequences (String). The template "400" is used for sending
characters (Char) and character sequences (String).
Figure 3-4

Template, Asset, Type Value Unit (optional)

400, Event, EventMotorType, Message


© Siemens AG 2019 All rights reserved

Note When sending characters (Char) and character sequences (String), only UTF-8
Chars are permitted.

Creating a shell in MQTT broker "MindConnect IoT Extension"


The figure below shows the structure of the message text for creating the shell in
MQTT broker "MindConnect IoT Extension". The template "114" is used for
creating the shell in MQTT broker "MindConn IoT Extension".
Figure 3-5

Template, c8y_Command

114, c8y_Command

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 72
3 Useful information

3.1.3 Receiving MindSphere-bound data via MQTT

Once an MQTT client has connected to the MQTT broker, it can create
subscriptions.
To create a subscription, the MQTT client uses the "SUBSCRIBE" packet. In order
to receive data from MindSphere via MQTT, the topic "s/ds" is subscribed to.
The topic "s/ds", to which the MQTT client would like to subscribe, is stored in the
"Payload".

Note Only UTF-8 Chars are allowed in the message to the subscribed topic "s/ds".

3.2 Detailed functional description of the


FB "LMindConn_MQTT"
3.2.1 Requirements and implementation

The following conditions must be met for a communication relationship between


S7 CPU and an MQTT broker "MindConnect IoT Extension":
1. The input "connect" of the FB "LMindConn_MQTT" has the value "true".
2. The FB "LMQTT_Client" has successfully established the TCP connection to
© Siemens AG 2019 All rights reserved

MQTT broker "MindConnect IoT Extension", has logged on to the MQTT


broker as an MQTT client, and is now connected with it
(Status: connectionEstablished = true).
3. The trigger for one-time or continuous sending of messages is active.
Depending on the desired quality assurance, messages on the topic "s/us" are
sent to the MQTT broker over the existing MQTT connection.
4. A message with the template "100" on the topic "s/us" was sent in order to
register the device.
5. The trigger for receipt of messages is active.

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 can only be sent or received if there is a TCP and MQTT
connection to the MQTT broker.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 73
3 Useful information

3.2.2 Overview

In order to meet the aforementioned requirements, the FB "LMQTT_Client" is


called cyclically and realized in the program of the state machine
"STATE_MACHINE".
The state machine "STATE_MACHINE" is initialized with the state
"CONNECTING" and is started when the following conditions are met:
• A positive edge is recognized at the input parameter "connect".
• The FB "LMQTT_Client" has been successfully initialized with the connection
parameters to establish the TCP and MQTT connection. The connection set-up
is started for a positive edge at the input parameter "connect".
This state machine has the following functions:
• It monitors the existing TCP and MQTT connection for connection errors.
• It runs the following tasks:
– Register device in MQTT broker "MindConnect IoT Extension".
– Send messages with the topic "s/us" (publish)
– Subscribe to topic "s/ds" in order to receive messages (subscribe)
– Creating a shell in MQTT broker "MindConnect IoT Extension"
• If an error occurs, this is displayed via the output parameters.
• If a negative edge has been detected at the input parameter "connect", it resets
all static tags and switches to a defined state.
© Siemens AG 2019 All rights reserved

The states of the state machine "STATE_MACHINE" are numbered sequentially.


The following table shows an overview of the states.
Table 3-1
Value Description
0 IDLE
6 CONNECTING
1 CONENCTED
2 DEVICE_REGISTER
3 OPEN_SHELL_TUNNEL
4 PUBLISH
5 SUBSCRIBE
10 DISCONNECTED
-1 ERROR_STATE

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 74
3 Useful information

The meaning of the states is listed in the following table:


Table 3-2
State Description
IDLE The FB "LMindConn_MQTT" waits in standby mode until
the state machine is started.
CONNECTING In this state, it is checked whether the
FB "LMQTT_CLIENT" has successfully established the
TCP and MQTT connection to MQTT broker
"MindConnect IoT Extension".
If the connections were established successfully, the
FB "LMindConn_MQTT" switches to the "CONNECTED"
state.
If an error occurs while establishing the connection, the
FB "LMindConn_MQTT" switches to the
"STATE_ERROR" state.
CONNECTED In this state, the connections are monitored.
In the event the connection is broken, the
FB "MindConn_LMQTT" switches to the state
"STATE_ERROR".
If the connections have been established, it is checked
which of the following tasks should be run:
• Before messages can be sent or received, it is
necessary to register the device in MQTT broker
"MindConnect IoT Extension". The
© Siemens AG 2019 All rights reserved

FB "LMindConn_MQTT" switches to the


"DEVICE_REGISTER" state.
• If a message is to be sent one time or continuously at
a certain time interval (publish), the following actions
are executed:
– The MindSphere-conformant String is handed off
to the FB "LMQTT_CLIENT" for it to be sent
(publish).
– The FB "LMindConn_MQTT" switches to the
"PUBLISH" state.
• If the topic "s/ds" is to be subscribed to and a shell in
MQTT broker "MindConnect IoT Extension" is to be
created in order to receive messages (subscribe),
then the FB "LMindConn_MQTT" switches to the
"OPEN_SHELL_TUNNEL" state.
DEVICE_REGISTER In this state, the MindSphere-conformant String for
registering the device is assembled.
• "100,devicename,devicetype"
The FB "LMindConn_MQTT" switches to the "PUBLISH"
state in order to send the MindSphere-conformant String
and thereby register the device.
OPEN_SHELL_TUNNEL In this state, the MindSphere-conformant String for
creating a shell is assembled.
• "114,c8y_Command"
The FB "LMindConn_MQTT" switches to the
"SUBSCRIBE" state.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 75
3 Useful information

State Description
PUBLISH In this state, the task for sending the message is started.
If the message has been sent successfully, the
FB "LMindConn_MQTT" switches to the "CONNECTED"
state.
If an error occurs while sending the message, the
FB "LMindConn_MQTT" switches to the
"STATE_ERROR" state.
SUBSCRIBE In this state, the task for subscribing to the topic "s/ds" is
started.
If the topic was successfully subscribed, the
FB "LMindConn_MQTT" switches to the "PUBLISH" state
in order to send the MindSphere-conformant String
needed for creating a shell.
The FB "LMindConn_MQTT" now receives messages on
the topic "s/ds".
If an error occurs while subscribing to the topic "s/ds", the
FB "LMindConn_MQTT" switches to the
"STATE_ERROR" state.
DISCONNECTED The FB "LMindConn_MQTT" switches to this state when a
negative edge is identified at the input parameter
"connect".
In this state, all parameters are reset. The
FB "LMindConn_MQTT" switches to the "IDLE" state
without any other step enabling condition.
© Siemens AG 2019 All rights reserved

ERROR_STATE If an error occurs, then the state "ERROR_STATE" is the


catch-all. Here, the required parameters (static tags and
output tags) are set or reset.
In addition, the following actions are carried out:
• If the error occurred in the FB "LMQTT_Client", the
value "16x8600" is output at the "status" output
parameter.
You can find detailed information on the error in the
diagnostic data of the "diagnostics" output parameter
(see Table 2-9).
• The FB "LMindConn_MQTT" remains in this state
until a negative edge is identified at the input
parameter "connect", whereupon it switches into the
"DISCONNECTED" state.
• It is necessary to re-start the state machine with a
positive edge at the "connect" input.

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 76
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:
https://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:
www.siemens.com/industry/supportrequest
© Siemens AG 2019 All rights reserved

SITRAIN – Training for Industry


We support you with our globally available training courses for industry with
practical experience, innovative learning methods and a concept that’s tailored to
the customer’s specific needs.
For more information on our offered trainings and courses, as well as their
locations and dates, refer to our web page:
www.siemens.com/sitrain

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:
https://support.industry.siemens.com/cs/sc

Industry Online Support app


You will receive optimum support wherever you are with the "Siemens Industry
Online Support" app. The app is available for Apple iOS, Android and Windows
Phone:
https://support.industry.siemens.com/cs/ww/en/sc/2067

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 77
4 Appendix

4.2 Links and literature


Table 4-1
No. Subject
\1\ Siemens Industry Online Support
https://support.industry.siemens.com
\2\ Link to the article page of the Application Example
https://support.industry.siemens.com/cs/ww/en/view/109772284
\3\ MindConnect IoT Extension Getting Started
https://documentation.mindsphere.io/resources/html/mindconnect-iot-extension-
gs/en-US/index.html
\4\ MQTT integration via MindConnect IoT Extension
https://developer.mindsphere.io/howto/howto-mqtt-mciot.html
\5\ Device integration when using MQTT
https://cumulocity.com/guides/device-sdk/mqtt/
\6\ Application Example "Configuring CloudConnect 7 with MindSphere and Microsoft
Azure"
https://support.industry.siemens.com/cs/ww/en/view/109766675

4.3 Change documentation


© Siemens AG 2019 All rights reserved

Table 4-2
Version Date Change
V1.0 12/2019 First edition
V1.1 03/2020 • CP1243-1 and CP1243-7 LTE are added in
chapter 1.3 "Components used"
• The order is changed in chapter 2.3
• The screenshots are updated which have still shown
"LMQTT_instClient"

MQTT-Client zur Anbindung an MindSphere


Article ID: 109772284, V1.0, 12/2019 78

You might also like