Stand with Ukraine flag
Try it now Pricing
IoT Gateway
Documentation > Configuration guides > MQTT Connector
Getting Started
Installation
On this page

MQTT Connector Configuration

This guide will help you to get familiar with MQTT Connector configuration for ThingsBoard IoT Gateway. Use general configuration to enable this Connector. The purpose of this Connector is to connect to an external MQTT broker and subscribe to data feed from devices. The connector is also able to push data to MQTT brokers based on the updates/commands from ThingsBoard.

This connector is useful when you have local MQTT broker in your facility or corporate network, and you would like to push data from this broker to ThingsBoard.

We will describe connector configuration file below.

Doc info icon

Please note: If you are new to IoT Gateway, use the “Basic” configuration mode. If you are familiar with configuring IoT Gateway, you can use the “Advanced” configuration mode.

Connector configuration

Connector configuration is a UI form that contains information about how to connect to external MQTT broker, what topics to use when subscribing to data feed and how to process the data. Let’s take a comprehensive look at all the possible settings. We will go through each option in detail to ensure that we thoroughly understand their functions and implications. By doing so, we can make well-informed decisions about which settings will best suit our needs and preferences.

Section “General”

This configuration section contains general connector settings, such as:

  • Name - connector name for logs and saving to persistent devices;
  • Logs configuration:
    • Enable remote logging - enabling remote logging for connector;
    • Logging level - logging level for local and remote logs: INFO, DEBUG, WARNING, ERROR, CRITICAL, NONE;
  • Send data only on change - sending only if data changed from last check, if not – data will be sent after every check.

image

Doc info icon

The settings are the same for both the basic and advanced configurations.

Section “Connection to broker”

Section “Connection to broker” offers detailed connection configuration options and contains several important fields, including host, port, MQTT version, client ID, and security settings. The host field specifies the address of the broker, while the port field indicates the communication port. The MQTT version field ensures compatibility with the protocol version being used. The client ID uniquely identifies the client, and the security settings provides configuration for client authorization at MQTT Broker.

This configuration section contains settings of the connection to broker, such as:

  • Host - MQTT broker hostname or ip address;
  • Port - MQTT port on the broker;
  • MQTT version - MQTT protocol version;
  • Client ID - this is the client ID. It must be unique for each session;
  • Security - configuration for client authorization at MQTT Broker (anonymous, basic, or certificates).

image

This configuration section contains settings of the connection to broker, such as:

Parameter Default value Description
name Default Local Broker Broker name for logs and saving to persistent devices.
host 127.0.0.1 MQTT broker hostname or ip address.
port 1883 MQTT port on the broker.
version 5 MQTT protocol version may be 3 (3.1), 4(3.11) or 5(5)
clientId tb_gw_li06e This is the client ID. It must be unique for each session.
security anonymous This is the configuration for client authorization at MQTT Broker.

Example:

1
2
3
4
5
6
7
8
9
10
"broker": {
    "name": "Default Local Broker",
    "host": "127.0.0.1",
    "port": 1883,
    "version": 5,
    "clientId": "tb_gw_li06e",
    "security": {
      "type": "anonymous"
    }
},

image

Subsection “Security”

Subsection “Security” provides configuration for client authorization at MQTT Broker.

Firstly, select basic or advanced MQTT configuration:

Now select the security type:

Anonymous auth is the most simple option. It is useful for testing on public MQTT brokers, like test.mosquitto.org.

image

One type of security configuration is basic. For authorization, a combination of username and password provided in this section, in config will be used.

image

The table below describes the parameters required to configure authorization on MQTT broker.

Parameter Default value Description
type certificates Type of authorization.
pathToCACert /etc/thingsboard-gateway/ca.pem Path to CA file.
pathToPrivateKey /etc/thingsboard-gateway/privateKey.pem Path to private key file.
pathToClientCert /etc/thingsboard-gateway/certificate.pem Path to certificate file.

image

Now select the security type:

Anonymous auth is the most simple option. It is useful for testing on public MQTT brokers, like test.mosquitto.org.

Parameter Default value Description
type anonymous Type of authorization.

Security subsection in configuration file will look like this:

1
2
3
    "security": {
      "type": "anonymous"
    }

image

One type of security configuration is basic. For authorization, a combination of username and password provided in this section, in config will be used.

Parameter Default value Description
type basic Type of authorization.
username username Username for authorization.
password password Password for authorization.

Security subsection in configuration file will look like this:

1
2
3
4
5
    "security": {
      "type": "basic",
      "username": "username",
      "password": "password"
    }

image

The table below describes the parameters required to configure authorization on MQTT broker.

Parameter Default value Description
type certificates Type of authorization.
pathToCACert /etc/thingsboard-gateway/ca.pem Path to CA file.
pathToPrivateKey /etc/thingsboard-gateway/privateKey.pem Path to private key file.
pathToClientCert /etc/thingsboard-gateway/certificate.pem Path to certificate file.

Security subsection in configuration file will look like this:

1
2
3
4
5
6
"security":{
    "type": "certificates",
    "pathToCACert": "/etc/thingsboard-gateway/ca.pem",
    "pathToPrivateKey": "/etc/thingsboard-gateway/privateKey.pem",
    "pathToClientCert": "/etc/thingsboard-gateway/certificate.pem"
}

image

Section “Data mapping”

This configuration section contains an array of topics that the gateway will subscribe to after connecting to the broker, along with settings about processing incoming messages (converter).

Select basic or advanced MQTT configuration:

For adding new data mapping, click the “plus” icon:

image

Opened modal window provide the following fields: topic filter, QoS, payload type:

image

The Topic filter - topic address for subscribing. The Topic filter supports special symbols: ‘#’ and ‘+’, allowing to subscribe to multiple topics.

Also, MQTT connector supports shared subscriptions. To create shared subscription you need to add “$share/” as a prefix for topic filter and shared subscription group name. For example to subscribe to the my-shared-topic in group my-group-name you can set the topic filter to “$share/my-group-name/my-shared-topic”.

MQTT Quality of Service (QoS) is an agreement between the message sender and receiver that defines the level of delivery guarantee for a specific message. (0-At most once, 1-At least once, 2-Exactly once)

Parameter Default value Description
topicFilter sensor/data Topic address for subscribing.
QoS 1 An agreement between the message sender and receiver that defines the level of delivery guarantee for a specific message. (0-At most once, 1-At least once, 2-Exactly once)

The topicFilter supports special symbols: ‘#’ and ‘+’, allowing to subscribe to multiple topics.

Also, MQTT connector supports shared subscriptions. To create shared subscription you need to add “$share/” as a prefix for topic filter and shared subscription group name. For example to subscribe to the my-shared-topic in group my-group-name you can set the topic filter to “$share/my-group-name/my-shared-topic”.

image

Let’s assume we would like to subscribe and process the following data from Thermometer device:

Example NameTopicTopic FilterPayloadComments
Example 1 sensor/data sensor/data {"serialNumber": "SN-001", "sensorType": "Thermometer", "sensorModel": "T1000", "temp": 42, "hum": 58} Device Name is part of the payload
Example 2 sensor/SN-001/data sensor/+/data {"sensorType": "Thermometer", "sensorModel": "T1000", "temp": 42, "hum": 58} Device Name is part of the topic

In this case the following messages are valid:

Example 1:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/data" -m '{"serialNumber": "SN-001", "sensorType": "Thermometer", "sensorModel": "T1000", "temp": 42, "hum": 58}'

Example 2:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/SN-001/data" -m '{"sensorType": "Thermometer", "sensorModel": "T1000", "temp": 42, "hum": 58}'

Now let’s review how we can configure JSON converter to parse this data.

Subsection “Data conversion”

This subsection contains configurations for processing incoming messages.

The types of MQTT converters are as follows:

  • JSON – Default converter;
  • Bytes – Raw default converter;
  • Custom – Custom converter (You can write it yourself, and it will be used to convert incoming data from the broker).

Select the MQTT configuration you are using:

Now select the payload type:

Converter for this payload type processes MQTT messages in JSON format. It uses JSON Path expressions to extract vital details such as device names, device profile names, attributes, and time series from the message. And regular expressions to get device details from topics.

  • Select “JSON” payload type, and fill in the fields in the “Device” section. Then click “pencil” icon of the “Attributes” section to add new attribute key;

  • In the opened window click “Add attribute”. Enter the key name, select the type and enter the value of the key. Click “Apply”;

  • Now click on the “pencil” icon of the “Time series” section to add new time series key;

  • In the opened window click “Add time series”. Enter the key name, select the type and enter the value of the key. Click “Apply”;

  • Click “Add”.

Converter for this payload type designed for binary MQTT payloads, this converter directly interprets binary data to retrieve device names and device profile names, along with attributes and time series, using specific byte positions for data extraction.

  • Select “Bytes” payload type, and fill in the fields in the “Device” section. Then click “pencil” icon of the “Attributes” section to add new attribute key;

  • In the opened window click “Add attribute”. Enter the key name, select the type and enter the value of the key. Click “Apply”;

  • Now click on the “pencil” icon of the “Time series” section to add new time series key;

  • In the opened window click “Add time series”. Enter the key name, select the type and enter the value of the key. Click “Apply”;

  • Click “Add”.

This option allows you to use a custom converter for specific data tasks. You need to add your custom converter to the extension folder and enter its class name in the UI settings. Any keys you provide will be sent as configuration to your custom converter.

  • Select “Custom” payload type, and fill in the fields in the “Device” section. Then click “pencil” icon of the “Keys” section to add new key;

  • In the opened window click “Add key”. Enter the key name and its value. Click “Apply”;

  • Click “Add”.

Now select the payload type:

Json converter is the default converter, it looks for ‘deviceName’, ‘deviceType’, attributes and telemetry in the incoming message from the broker, following the rules described in this subsection:

Parameter Default value Description
type json Provides information to connector that default converter is to be used for converting data from topic.
deviceNameExpression ${serialNumber} Simple JSON expression, is used for looking up device name in the incoming message (parameter “serialNumber” will be used as the device name).
deviceProfileExpression ${sensorType} Simple JSON expression, is used for looking up device type in the incoming message (parameter “sensorType” will be used as the device type).
timeout 60000 Timeout for triggering “Device Disconnected” event
attributes:   This subsection contains parameters of the incoming message, to be interpreted as attributes for the device.
… type string Type of incoming data for a current attribute.
… key model Attribute name, to be sent to ThingsBoard instance.
… value ${sensorModel} Simple JSON expression, is used for looking up value in the incoming message, to be sent to ThingsBoard instance as the value of key parameter.
     
… type string Type of incoming data for a current attribute.
… key ${sensorModel} Simple JSON expression, is used for looking up value in the incoming message, to be used as attribute name.
… value on Attribute value, to be sent to ThingsBoard instance.
timeseries:   This subsection contains parameters of the incoming message, to be interpreted as telemetry for the device.
… type integer Type of incoming data for a current telemetry.
… key temperature Telemetry name, to be sent to ThingsBoard instance.
… value ${temp} Simple JSON expression, is used for looking up value in the incoming message, to be sent to ThingsBoard instance as the value of key parameter.
     
… type integer Type of incoming data for a current telemetry.
… key humidity Telemetry name, to be sent to ThingsBoard instance.
… value ${hum} Simple JSON expression, is used for looking up value in the incoming message, to be sent to ThingsBoard instance as the value of key parameter.
Doc info icon

Parameters in attributes and telemetry section may differ from those presented above, but will follow the same structure.

Doc info icon

Note: The device profile is set when the device is created. Changing the device profile using a Gateway is not supported.

Mapping subsection for Example 1 will look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
  "topicFilter": "sensor/data",
  "subscriptionQos": 1,
  "converter": {
    "type": "json",
    "deviceInfo": {
      "deviceNameExpressionSource": "message",
      "deviceNameExpression": "${serialNumber}",
      "deviceProfileExpressionSource": "message",
      "deviceProfileExpression": "${sensorType}"
    },
    "sendDataOnlyOnChange": false,
    "timeout": 60000,
    "attributes": [
      {
        "type": "string",
        "key": "model",
        "value": "${sensorModel}"
      },
      {
        "type": "string",
        "key": "${sensorModel}",
        "value": "on"
      }
    ],
    "timeseries": [
      {
        "type": "string",
        "key": "temperature",
        "value": "${temp}"
      },
      {
        "type": "double",
        "key": "humidity",
        "value": "${hum}"
      },
      {
        "type": "string",
        "key": "combine",
        "value": "${hum}:${temp}"
      }
    ]
  }
}

image

Mapping for Example 2 will look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"topicFilter": "sensor/+/data",
  "subscriptionQos": 1,
  "converter": {
    "type": "json",
    "deviceInfo": {
      "deviceNameExpressionSource": "topic",
      "deviceNameExpression": "(?<=sensor/)(.*?)(?=/data)",
      "deviceProfileExpressionSource": "constant",
      "deviceProfileExpression": "Thermometer"
    },
    "sendDataOnlyOnChange": false,
    "timeout": 60000,
    "attributes": [
      {
        "type": "string",
        "key": "model",
        "value": "${sensorModel}"
      }
    ],
    "timeseries": [
      {
        "type": "double",
        "key": "temperature",
        "value": "${temp}"
      },
      {
        "type": "string",
        "key": "humidity",
        "value": "${hum}"
      }
    ]
  }
}

image

Bytes converter is the default converter, it looks for ‘deviceName’, ‘deviceType’, attributes and telemetry in the incoming message from the broker, following the rules described in this subsection:

Parameter Default value Description
type bytes Provides information to connector that default converter is to be used for converting data from topic.
deviceNameExpression [0:4] The expression that is used to find device name in the incoming message.
deviceProfileExpression [1:3] The expression that is used to find device type in the incoming message.
timeout 60000 Timeout for triggering “Device Disconnected” event.
attributes:   This subsection contains parameters of the incoming message, to be interpreted as attributes for the device.
… type raw Type of incoming data for a current attribute.
… key temp Attribute name, to be sent to ThingsBoard instance.
… value [:] Final view of data that will be sent to ThingsBoard, [:] - will replace to device data using python slice rules.
timeseries:   This subsection contains parameters of the incoming message, to be interpreted as telemetry for the device.
… type raw Type of incoming data for a current telemetry.
… key rawData Telemetry name, to be sent to ThingsBoard instance.
… value [4:] Final view of data that will be sent to ThingsBoard, [:] - will replace to device data using python slice rules.
Doc info icon

Parameters in attributes and telemetry section may differ from those presented above, but will have the same structure.

Note: The device profile is set when the device is created. Changing the device profile using a Gateway is not supported.

Mapping subsection will look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
  "topicFilter": "sensor/raw_data",
  "subscriptionQos": 1,
  "converter": {
    "type": "bytes",
    "deviceInfo": {
      "deviceNameExpressionSource": "message",
      "deviceNameExpression": "[0:4]",
      "deviceProfileExpressionSource": "constant",
      "deviceProfileExpression": "default"
    },
    "sendDataOnlyOnChange": false,
    "timeout": 60000,
    "attributes": [
      {
        "type": "raw",
        "key": "rawData",
        "value": "[:]"
      }
    ],
    "timeseries": [
      {
        "type": "raw",
        "key": "temp",
        "value": "[4:]"
      }
    ]
  }
}

image

A custom converter is converter written for some device:

Parameter Default value Description
type custom Provides information to connector that a custom converter will be used for converting data from the topic.
extension CustomMqttUplinkConverter Name of custom converter class.
extension-config   This subsection is a configuration for the custom converter. In default example it contains the number of bytes and keys for telemetry.
temperatureBytes 2 In the default example, first 2 bytes from received message will be interpreted as temperature key of telemetry (Substring “Bytes” will remove if exists).
humidityBytes 2 In the default example, the second and third byte from received message will be interpreted as humidity key of telemetry (Substring “Bytes” will remove if exists).
batteryLevelBytes 1 In the default example, the fifth byte from received message will be interpreted as batteryLevel key of telemetry (Substring “Bytes” will removed if exists).
Doc info icon

All parameters from this subsection and topic will be transferred as dictionary during initialization to the converter object.

Converter subsection in the configuration will look like:

1
2
3
4
5
6
7
8
9
10
11
12
"topicFilter": "custom/sensors/+",
  "subscriptionQos": 1,
  "converter": {
    "type": "custom",
    "extension": "CustomMqttUplinkConverter",
    "cached": true,
    "extensionConfig": {
      "temperature": 2,
      "humidity": 2,
      "batteryLevel": 1
    }
  }

image

Doc info icon

Note: You can specify multiple mapping objects inside the array.

Also, you can combine values from MQTT message in attributes, telemetry and serverSideRpc section, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
    {
        "topicFilter": "sensor/data",
        "subscriptionQos": 1,
        "converter": {
            "type": "json",
            "deviceInfo": {
            "deviceNameExpressionSource": "message",
            "deviceNameExpression": "${serialNumber}",
            "deviceProfileExpressionSource": "message",
            "deviceProfileExpression": "${sensorType}"
            "timeout": 60000,
            "attributes": [],
            "timeseries": [
                {
                    "type": "integer",
                    "key": "temperature",
                    "value": "${temp}"
                },
                {
                    "type": "integer",
                    "key": "humidity",
                    "value": "${hum}"
                },
                {
                    "type": "string",
                    "key": "combine",
                    "value": "${hum}:${temp}"
                }
            ]
        }
    }
}

Mapping process subscribes to the MQTT topics using topicFilter parameter of the mapping object. Each message that is published to this topic by other devices or applications is analyzed to extract device name, type and data (attributes and/or timeseries values). By default, gateway uses Json converter, but it is possible to provide custom converter. See examples in the source code.

Doc info icon

Connector won’t pass the ‘None’ value from the converter

Now let’s review an example of sending data from “SN-001” thermometer device.

Let’s assume MQTT broker is installed locally on your server.

Use terminal to simulate sending message from the device to the MQTT broker:

1
mosquitto_pub -h 127.0.0.1 -p 1883 -t "sensor/data" -m '{"serialNumber": "SN-001", "sensorType": "Thermometer", "sensorModel": "T1000", "temp": 42, "hum": 58}'

image

The device will be created and displayed in ThingsBoard based on the passed parameters.

image

image

Requests mapping

This section of the configuration outlines an array that includes all the supported requests for both the gateway and ThingsBoard:

  • connect requests;
  • disconnect requests;
  • attribute requests;
  • attribute updates;
  • RPC commands.

Firstly, select basic or advanced MQTT configuration:

For adding new requests mapping, click “plus” icon:

image

Modal window will open. Select request type, set a topic filter, fill in the entities fields of the “Device” section. Then, click “Add”.

image

image

Below we go through all the supported requests for both Gateway and ThingsBoard.

Subsection “Connect request”

ThingsBoard allows sending RPC commands and notifications about device attribute updates to the device. But in order to send them, the platform needs to know if the target device is connected and what gateway or session is used to connect the device at the moment. If your device is constantly sending telemetry data - ThingsBoard already knows how to push notifications. If your device just connects to MQTT broker and waits for commands/updates, you need to send a message to the Gateway and inform that device is connected to the broker.

Also, it is possible to configure where to get the device name: from the topic or from the message body.

Select basic or advanced MQTT configuration:

To adding new requests mapping, navigate to the “Requests mapping” tab and click the “plus” icon. In the open modal window, select the “Connect request” type, set a topic filter, and fill in the “Name” and “Profile name” fields of the “Device” section. Then, click “Add”.

Device name from the message body:

image

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/connect" -m '{"serialNumber":"SN-001"}'

Device name from the topic:

image

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/SN-001/connect" -m ''

This section in configuration looks like:

1
2
3
4
5
6
7
8
9
10
11
"connectRequests": [
  {
    "topicFilter": "sensor/connect",
    "deviceInfo": {
      "deviceNameExpressionSource": "message",
      "deviceNameExpression": "${serialNumber}",
      "deviceProfileExpressionSource": "constant",
      "deviceProfileExpression": "Thermometer"
    }
  }        
]

image

Device name from the message body:

Parameter Default value Description
topicFilter sensor/connect Topic address on the broker, where the broker sends information about new connected devices.
deviceNameExpression ${serialNumber} JSON-path expression, for looking the new device name.

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/connect" -m '{"serialNumber":"SN-001"}'

Device name from the topic:

Parameter Default value Description
topicFilter sensor/+/connect Topic address on the broker, where the broker sends information about new connected devices.
deviceNameTopicExpression (?<=sensor\/)(.*?)(?=\/connect) Regular expression for looking the device name in topic path.

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/SN-001/connect" -m ''

Now let’s review an example.

Use a terminal to simulate sending a message from the device to the MQTT broker:

1
mosquitto_pub -h 127.0.0.1 -p 1883 -t "sensor/connect" -m '{"serialNumber": "SN-001"}'

image

Your ThingsBoard instance will get information from the broker about last connecting time of the device. You can see this information under the “Server attributes” scope in the “Attributes” tab.

image

Subsection “Disconnect request”

This configuration section is optional. Configuration, provided in this section will be used to get information from the broker about disconnecting device. If your device just disconnects from MQTT broker and waits for commands/updates, you need to send a message to the Gateway and inform it that device is disconnected from the broker.

Select basic or advanced MQTT configuration:

To adding new requests mapping, navigate to the “Requests mapping” tab and click the “plus” icon. In the open modal window, select the “Disconnect request” type, set a topic filter, and fill in the “Name” field of the “Device” section. Then, click “Add”.

Name in a message from broker:

image

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/disconnect" -m '{"serialNumber":"SN-001"}'

Name in topic address:

image

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/SN-001/disconnect" -m ''

This section in configuration file looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"disconnectRequests": [
  {
    "topicFilter": "sensor/disconnect",
    "deviceInfo": {
      "deviceNameExpressionSource": "message",
      "deviceNameExpression": "${serialNumber}"
  }
},
  {
    "topicFilter": "sensor/+/disconnect",
    "deviceInfo": {
      "deviceNameExpressionSource": "topic",
      "deviceNameExpression": "(?<=sensor/)(.*?)(?=/connect)"
      }
  }
]

image

Name in a message from broker:

Parameter Default value Description
topicFilter sensor/disconnect Topic address on the broker, where the broker sends information about disconnected devices.
deviceNameExpression ${serialNumber} JSON-path expression, for looking the new device name.

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/disconnect" -m '{"serialNumber":"SN-001"}'

Name in topic address:

Parameter Default value Description
topicFilter sensor/+/disconnect Topic address on the broker, where the broker sends information about disconnected devices.
deviceNameTopicExpression (?<=sensor\/)(.*?)(?=\/connect) Regular expression for looking the device name in topic path.

In this case the following messages are valid:

1
mosquitto_pub -h YOUR_MQTT_BROKER_HOST -p YOUR_MQTT_BROKER_PORT -t "sensor/SN-001/disconnect" -m ''

Now let’s review an example.

Use a terminal to simulate sending a message from the device to MQTT broker:

1
mosquitto_pub -h 127.0.0.1 -p 1883 -t "sensor/disconnect" -m '{"serialNumber": "SN-001"}'

image

Your ThingsBoard instance will get information from the broker about last disconnecting time of the device. You can see this information under the “Server attributes” scope in the “Attributes” tab.

image

Subsection “Attribute requests”

This configuration section is optional.

In order to request client-side or shared device attributes to ThingsBoard server node, Gateway allows sending attribute requests.

Select basic or advanced MQTT configuration:

To adding new requests mapping, navigate to the “Requests mapping” tab and click the “plus” icon. In the open modal window, select the “Attribute request” type, set a topic filter. Fill in the fields of the “Input request parsing” and “Output request parsing” sections. Then, click “Add”.

image

This section in configuration file looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"attributeRequests": [
  {
    "retain": false, 
    "topicFilter": "v1/devices/me/attributes/request", 
    "deviceInfo": {
      "deviceNameExpressionSource": "message",
      "deviceNameExpression": "${serialNumber}"
    },
    "attributeNameExpressionSource": "message",
    "attributeNameExpression": "${versionAttribute}",
    "topicExpression": "devices/${deviceName}/attrs",
    "valueExpression": "${attributeKey}: ${attributeValue}"
  }
]

Also, you can request multiple attributes at once. Simply add one more JSON-path to attributeNameExpression parameter. For example, we want to request two shared attributes in one request, our config will look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"attributeRequests": [
  {
    "retain": false,
    "topicFilter": "v1/devices/me/attributes/request",
    "deviceInfo": {
      "deviceNameExpressionSource": "message",
      "deviceNameExpression": "${serialNumber}"
    },
    "attributeNameExpressionSource": "message",
    "attributeNameExpression": "${versionAttribute}, ${pduAttribute}",
    "topicExpression": "devices/${deviceName}/attrs",
    "valueExpression": "${attributeKey}: ${attributeValue}"
  }
]

image

Parameter Default value Description
retain false If set to true, the message will be set as the “last known good”/retained message for the topic.
topicFilter v1/devices/me/attributes/request Topic for attribute request
deviceNameExpression ${serialNumber} JSON-path expression, for looking the device name in topicFilter message
attributeNameExpression ${versionAttribute} JSON-path expression, for looking the attribute name in topicFilter message
topicExpression devices/${deviceName}/attrs JSON-path expression, for formatting reply topic
valueExpression ${attributeKey}: ${attributeValue} Message that will be sent to topic from topicExpression

Subsection “Attribute updates”

This configuration section is optional.
ThingsBoard allows to provision device attributes and fetch some of them from the device application. You can treat this as a remote configuration for devices. Your devices are able to request shared attributes from ThingsBoard. See user guide for more details.

The “attributeUpdates” configuration allows configuring the format of the corresponding attribute request and response messages.

Select basic or advanced MQTT configuration:

To adding new requests mapping, navigate to the “Requests mapping” tab and click the “plus” icon. In the open modal window, select the “Attribute update” type, and set a device name filter, attribute filter, response value expression, and response topic expression. Then, click “Add”.

image

This section in configuration file looks like:

1
2
3
4
5
6
7
8
9
  "attributeUpdates": [
    {
      "retain": false,
      "deviceNameFilter": ".*",
      "attributeFilter": "firmwareVersion",
      "topicExpression": "sensor/${deviceName}/${attributeKey}",
      "valueExpression": "{\"${attributeKey}\":\"${attributeValue}\"}"
    }
  ]

image

Parameter Default value Description
retain false If set to true, the message will be set as the “last known good”/retained message for the topic.
deviceNameFilter .* Regular expression device name filter, used to determine, which function to execute.
attributeFilter uploadFrequency Regular expression attribute name filter, used to determine, which function to execute.
topicExpression sensor/${deviceName}/${attributeKey} JSON-path expression used for creating topic address to send a message.
valueExpression {\”${attributeKey}\”:\”${attributeValue}\”} JSON-path expression used for creating the message data that will send to topic.

Let’s look at an example.

Run the command below to start the mosquitto_sub client, subscribing to the topic “sensor/SN-001/firmwareVersion” of the local broker. Start waiting for new messages from ThingsBoard server to broker.

1
mosquitto_sub -h 127.0.0.1 -p 1883 -t sensor/SN-001/firmwareVersion

image

Update device attribute value on the ThingsBoard server following these steps:

  • Open the “Devices” page;
  • Click on your device and navigate to the “Attributes” tab;
  • Choose “Shared attributes” scope and click on the “pencil” icon next to “firmwareVersion” attribute.

image

  • Change firmware version value from “1.1” to “1.2”. Then click “Update” button.

image

The firmware version has been updated to “1.2”.

image

Broker received new message from the ThingsBoard server about updating attribute “FirmwareVersion” to “1.2”.

image

Server side RPC commands

ThingsBoard allows sending RPC commands to the device that is connected to ThingsBoard directly or via Gateway. Configuration, provided in this section is used for sending RPC requests from ThingsBoard to device.

Select basic or advanced MQTT configuration:

There are 2 options for RPC request: With a response – If the configuration includes a responseTopicExpression, the gateway will attempt to subscribe to it and wait for a response.

To adding new requests mapping, navigate to the “Requests mapping” tab and click the “plus” icon. In the open modal window, select the “RPC command” request type, and set a device name filter, method filter, request topic expression, value expression, response topic expression, response topic QoS and response timeout. Then, click “Add”.

image

Without a response – If the configuration does not include a responseTopicExpression, the gateway will simply send the message without waiting for a response.

To adding new requests mapping, navigate to the “Requests mapping” tab and click the “plus” icon. In the open modal window, select the “RPC command” request type, toggle “Without response” option, and set a device name filter, method filter, and value expression. Then, click “Add”.

image

Parameter Default value Description
deviceNameFilter .* Regular expression device name filter, is used to determine, which function to execute.
methodFilter echo Regular expression method name filter, is used to determine, which function to execute.
requestTopicExpression sensor/${deviceName}/request/${methodName}/${requestId} JSON-path expression, is used for creating topic address to send RPC request.
responseTopicExpression sensor/${deviceName}/response/${methodName}/${requestId} JSON-path expression, is used for creating topic address to subscribe for response message.
responseTimeout 10000 Value in milliseconds. If there is no response within this period after sending the request, gateway will unsubscribe from the response topic.
valueExpression ${params} JSON-path expression, is used for creating data for sending to broker.

You can use device name filter and method filter to apply different mapping rules for various devices/methods. Once Gateway receives RPC request from the server to the device, it will publish the corresponding message based on request topic expression and value expression. In case you expect a reply to the request from the device, you should also specify response topic expression and response timeout. The Gateway will subscribe to the “response” topic and wait for a device reply until “responseTimeout” is reached (in milliseconds).

Here is an example of an RPC request (rpc-request.json) that needs to be sent from the server:

1
2
3
4
5
6
{
  "method": "echo",
  "params": {
    "message": "Hello!"
  }
}

Also, every telemetry and attribute parameter has built-in GET and SET RPC methods out of the box, so you don’t need to configure it manually. To use them, make sure you set all the required parameters (in the case of MQTT Connector, these are the following: request topic expression, response topic expression, response timeout, value expression). See the guide.

This section in configuration file looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"serverSideRpc": [
   {
      "type": "twoWay",
      "deviceNameFilter": ".*",
      "methodFilter": "echo",
      "requestTopicExpression": "sensor/${deviceName}/request/${methodName}/${requestId}",
      "responseTopicExpression": "sensor/${deviceName}/response/${methodName}/${requestId}",
      "responseTopicQoS": 1,
      "responseTimeout": 10000,
      "valueExpression": "${params}"
   },
   {
      "type": "oneWay",
      "deviceNameFilter": ".*",
      "methodFilter": "no-reply",
      "requestTopicExpression": "sensor/${deviceName}/request/${methodName}/${requestId}",
      "valueExpression": "${params}"
   }
]

image

Parameter Default value Description
deviceNameFilter .* Regular expression device name filter, is used to determine, which function to execute.
methodFilter echo Regular expression method name filter, is used to determine, which function to execute.
requestTopicExpression sensor/${deviceName}/request/${methodName}/${requestId} JSON-path expression, is used for creating topic address to send RPC request.
responseTopicExpression sensor/${deviceName}/response/${methodName}/${requestId} JSON-path expression, is used for creating topic address to subscribe for response message.
responseTimeout 10000 Value in milliseconds. If there is no response within this period after sending the request, gateway will unsubscribe from the response topic.
valueExpression ${params} JSON-path expression, is used for creating data for sending to broker.
Doc info icon

There are 2 options for RPC request:

  1. With a response – If the configuration includes a responseTopicExpression, the gateway will attempt to subscribe to it and wait for a response.
  2. Without a response – If the configuration does not include a responseTopicExpression, the gateway will simply send the message without waiting for a response.

You can use deviceNameFilter and methodFilter to apply different mapping rules for various devices/methods. Once Gateway receives RPC request from the server to the device, it will publish the corresponding message based on requestTopicExpression and valueExpression. In case you expect a reply to the request from the device, you should also specify responseTopicExpression and responseTimeout. The Gateway will subscribe to the “response” topic and wait for a device reply until “responseTimeout” is reached (in milliseconds).

Here is an example of an RPC request (rpc-request.json) that needs to be sent from the server:

1
2
3
4
5
6
{
  "method": "echo",
  "params": {
    "message": "Hello!"
  }
}

Also, every telemetry and attribute parameter has built-in GET and SET RPC methods out of the box, so you don’t need to configure it manually. To use them, make sure you set all the required parameters (in the case of MQTT Connector, these are the following: requestTopicExpression, responseTopicExpression, responseTimeout, valueExpression). See the guide.

Workers settings

This configuration settings provides fields for configuring connector performance and message reading/formatting speed:

Select basic or advanced MQTT configuration:

image

Max number of workers is a maximal number of workers thread for converters (amount of workers changes dynamically, depending on load). Recommended amount 50-100.

Max messages queue per worker is a maximal messages count that will be in queue for each converter worker.

image

  • maxNumberOfWorkers is a maximal number of workers thread for converters (amount of workers changes dynamically, depending on load). Recommended amount 50-100;
  • maxMessageNumberPerWorker is a maximal messages count that will be in queue for each converter worker.

Configuration file

Example of MQTT Connector configuration file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
{
  "broker": {
    "name": "Default Local Broker",
    "host": "127.0.0.1",
    "port": 1883,
    "clientId": "ThingsBoard_gateway",
    "version": 5,
    "maxMessageNumberPerWorker": 10,
    "maxNumberOfWorkers": 100,
    "sendDataOnlyOnChange": false,
    "security": {
      "type": "basic",
      "username": "user",
      "password": "password"
    }
  },
  "mapping": [
    {
      "topicFilter": "sensor/data",
      "converter": {
        "type": "json",
        "deviceNameJsonExpression": "${serialNumber}",
        "deviceTypeJsonExpression": "${sensorType}",
        "sendDataOnlyOnChange": false,
        "timeout": 60000,
        "attributes": [
          {
            "type": "string",
            "key": "model",
            "value": "${sensorModel}"
          },
          {
            "type": "string",
            "key": "${sensorModel}",
            "value": "on"
          }
        ],
        "timeseries": [
          {
            "type": "double",
            "key": "temperature",
            "value": "${temp}"
          },
          {
            "type": "double",
            "key": "humidity",
            "value": "${hum}"
          },
          {
            "type": "string",
            "key": "combine",
            "value": "${hum}:${temp}"
          }
        ]
      }
    },
    {
      "topicFilter": "sensor/+/data",
      "converter": {
        "type": "json",
        "deviceNameTopicExpression": "(?<=sensor\/)(.*?)(?=\/data)",
        "deviceTypeTopicExpression": "Thermometer",
        "sendDataOnlyOnChange": false,
        "timeout": 60000,
        "attributes": [
          {
            "type": "string",
            "key": "model",
            "value": "${sensorModel}"
          }
        ],
        "timeseries": [
          {
            "type": "double",
            "key": "temperature",
            "value": "${temp}"
          },
          {
            "type": "double",
            "key": "humidity",
            "value": "${hum}"
          }
        ]
      }
    },
    {
      "topicFilter": "sensor/raw_data",
      "converter": {
        "type": "bytes",
        "deviceNameExpression": "[0:4]",
        "deviceTypeExpression": "default",
        "sendDataOnlyOnChange": false,
        "timeout": 60000,
        "attributes": [
          {
            "type": "raw",
            "key": "rawData",
            "value": "[:]"
          }
        ],
        "timeseries": [
          {
            "type": "raw",
            "key": "temp",
            "value": "[4:]"
          }
        ]
      }
    },
    {
      "topicFilter": "custom/sensors/+",
      "converter": {
        "type": "custom",
        "extension": "CustomMqttUplinkConverter",
        "cached": true,
        "extension-config": {
          "temperatureBytes": 2,
          "humidityBytes": 2,
          "batteryLevelBytes": 1
        }
      }
    }
  ],
  "connectRequests": [
    {
      "topicFilter": "sensor/connect",
      "deviceNameJsonExpression": "${serialNumber}"
    },
    {
      "topicFilter": "sensor/+/connect",
      "deviceNameTopicExpression": "(?<=sensor\/)(.*?)(?=\/connect)"
    }
  ],
  "disconnectRequests": [
    {
      "topicFilter": "sensor/disconnect",
      "deviceNameJsonExpression": "${serialNumber}"
    },
    {
      "topicFilter": "sensor/+/disconnect",
      "deviceNameTopicExpression": "(?<=sensor\/)(.*?)(?=\/disconnect)"
    }
  ],
  "attributeRequests": [
    {
      "retain": false,
      "topicFilter": "v1/devices/me/attributes/request",
      "deviceNameJsonExpression": "${serialNumber}",
      "attributeNameJsonExpression": "${versionAttribute}, ${pduAttribute}",
      "topicExpression": "devices/${deviceName}/attrs",
      "valueExpression": "${attributeKey}: ${attributeValue}"
    }
  ],
  "attributeUpdates": [
    {
      "retain": true,
      "deviceNameFilter": ".*",
      "attributeFilter": "firmwareVersion",
      "topicExpression": "sensor/${deviceName}/${attributeKey}",
      "valueExpression": "{\"${attributeKey}\":\"${attributeValue}\"}"
    }
  ],
  "serverSideRpc": [
    {
      "deviceNameFilter": ".*",
      "methodFilter": "echo",
      "requestTopicExpression": "sensor/${deviceName}/request/${methodName}/${requestId}",
      "responseTopicExpression": "sensor/${deviceName}/response/${methodName}/${requestId}",
      "responseTimeout": 10000,
      "valueExpression": "${params}"
    },
    {
      "deviceNameFilter": ".*",
      "methodFilter": "no-reply",
      "requestTopicExpression": "sensor/${deviceName}/request/${methodName}/${requestId}",
      "valueExpression": "${params}"
    }
  ]
}

Next steps

Explore guides related to main ThingsBoard features: