MQTT Integration
MQTT Integration connects ThingsBoard to an external MQTT broker: it subscribes to topics, decodes device payloads via an uplink converter, and pushes telemetry and attributes to the platform. In the reverse direction, it encodes Rule Engine messages via a downlink converter and publishes them back to the broker.
ThingsBoard integration setup
Section titled “ThingsBoard integration setup”Create an uplink converter that will decode incoming MQTT messages into ThingsBoard format, then configure the integration to connect to your broker.
Create an uplink converter
Section titled “Create an uplink converter”The MQTT integration uses a generic uplink converter. The decoder parses the JSON payload and extracts the device name from metadata.topic.
The decoder function used in this tutorial:
/** Decoder **/
// decode payload to stringvar payloadStr = decodeToString(payload);var data = JSON.parse(payloadStr);
var deviceName = metadata.topic.split("/")[3];var deviceType = 'sensor'; // hardcoded device profile
// Result object with device attributes/telemetry datavar result = { deviceName: deviceName, deviceType: deviceType, attributes: { integrationName: metadata['integrationName'], }, telemetry: { temperature: data.temperature, }};
/** Helper functions 'decodeToString' and 'decodeToJson' are already built-in **/
return result;/** Decoder **/
// decode payload to stringvar payloadStr = decodeToString(payload);var data = JSON.parse(payloadStr);
var deviceName = metadata.topic.split("/")[3];var deviceType = 'sensor'; // hardcoded device profile
// Result object with device attributes/telemetry datavar result = { deviceName: deviceName, deviceType: deviceType, attributes: { integrationName: metadata['integrationName'], }, telemetry: { temperature: data.temperature, }};
/** Helper functions **/
function decodeToString(payload) { return String.fromCharCode.apply(String, payload);}
function decodeToJson(payload) { // convert payload to string. var str = decodeToString(payload);
// parse string to JSON var data = JSON.parse(str); return data;}
return result;The decoder produces:
| Source | Field | Output type | Notes |
|---|---|---|---|
metadata.topic.split("/")[3] | deviceName | — | 4th segment of the topic path (0-indexed) |
hardcoded 'sensor' | deviceType | — | Device profile name |
data.temperature | temperature | telemetry | From JSON payload |
metadata.integrationName | integrationName | attribute | Name of the integration |
For topic tb/mqtt-integration/sensors/SN-001/temperature and payload {"temperature": 25.7}, the decoder produces:
{ "deviceName": "SN-001", "deviceType": "sensor", "attributes": { "integrationName": "MQTT Integration" }, "telemetry": { "temperature": 25.7 }}To adapt this converter to your device:
- Different topic structure — change the index in
metadata.topic.split("/")[3]to match the position of the device identifier in your topic path. - Device name from payload — replace
metadata.topic.split("/")[3]with a field fromdata(e.g.data.deviceId) if the device name is in the payload body. - Different telemetry fields — add or rename fields in the
telemetryobject to match your payload structure. - Additional attributes — add more keys to the
attributesobject (e.g. firmware version, location). - Different device type — change
'sensor'to match your device profile name in ThingsBoard.
Import the uplink converter:
- Download the converter file for your scripting language:
- Go to Integrations center ⇾ Data converters.
- Click + Add data converter ⇾ Import converter.
- Drag and drop the downloaded file and click Import.
Create the integration
Section titled “Create the integration”- Go to Integrations center ⇾ Integrations and click + Add integration.
- Basic settings:
- Set Integration type to MQTT.
- Enable integration and Allow create devices or assets are on by default.
- Click Next.
- Uplink data converter:
- Select existing — choose a previously created
MQTT Uplink Converterfrom the list. - Click Next.
- Select existing — choose a previously created
- Downlink data converter:
- Click Skip — only needed for RPC; can be added later.
- Connection:
- Set broker Host and Port (e.g.
broker.hivemq.com, port1883). - Select the Credentials type (e.g. Anonymous).
- Add at least one topic filter with QoS (e.g.
tb/mqtt-integration-tutorial/sensors/+/temperature, QoS0 — At most once). Click Add topic filter to subscribe to additional topics. - Expand Advanced settings and uncheck Clean session to persist broker-side subscriptions and queued QoS 1/2 messages across reconnects.
- Set broker Host and Port (e.g.
- Click Check connection — a confirmation step appears showing Connected.
- Click Add to complete the integration setup.
Connection settings
Section titled “Connection settings”Host and port
| Parameter | Default | Description |
|---|---|---|
| Host | — | IP address or hostname of the MQTT broker (e.g. broker.hivemq.com) |
| Port | 1883 | Broker port: 1883 for plain MQTT, 8883 for MQTT over TLS |
Credentials
| Parameter | Description |
|---|---|
| Credentials type | Anonymous — no authentication; Basic — username and password; PEM — TLS client certificate |
Enable SSL
Encrypts the connection using TLS. Required when using PEM credentials; optional with Anonymous or Basic.
Topic filters
Defines which MQTT topics ThingsBoard subscribes to for uplink messages. Multiple filters can be added.
| Field | Description |
|---|---|
| Topic | MQTT topic filter. + matches a single level (e.g. devices/+/telemetry). # matches all sub-levels and must be the last character (e.g. devices/#) |
| QoS | 0 — at most once (fire and forget); 1 — at least once (may deliver duplicates); 2 — exactly once |
Advanced settings
| Parameter | Default | Description |
|---|---|---|
| Protocol version | MQTT 3.1.1 | MQTT protocol version used for the broker connection (3.1, 3.1.1, or 5.0) |
| Clean session | on | When off, the broker retains session state (subscriptions and queued QoS 1/2 messages) for this Client ID across reconnects. When on, each connection starts fresh and offline messages are discarded |
| Retained | off | When on, the broker caches the last downlink message per topic and delivers it immediately to any new subscriber |
| Client ID | auto | MQTT client identifier sent to the broker. Leave empty for auto-generated. Must be unique per connection — most brokers reject duplicate Client IDs |
| Max bytes in message | 32368 | Maximum payload size in bytes. Messages exceeding this limit are dropped |
| Connection timeout (sec) | 10 | Seconds ThingsBoard waits for a broker response before marking the connection as failed |
| Downlink topic pattern | ${topic} | MQTT topic used for publishing downlink messages. The default ${topic} reads the topic from metadata.topic in the downlink converter output. Can be set to a fixed topic string |
Execute remotely
When enabled, ThingsBoard generates an Integration key and Integration secret that allow external services to call the Integration API — for example, to push messages into this integration from an external system.
Test uplink
Section titled “Test uplink”Publish a test temperature reading to the broker. Requires mosquitto-clients:
mosquitto_pub -h broker.hivemq.com -p 1883 -t "tb/mqtt-integration-tutorial/sensors/SN-001/temperature" -m '{"temperature":25.1}'Go to Entities ⇾ Devices — device SN-001 is provisioned automatically on the first uplink. Open it and check the Latest Telemetry tab to confirm temperature = 25.1.
Inspect event logs
To trace the message through the integration, go to Integrations center ⇾ Integrations, click MQTT integration, open the Events tab, and set Event type to Debug. Click … in the Message column to see the raw MQTT topic and payload received by the integration.
To inspect converter processing, go to Integrations center ⇾ Data converters, click the uplink converter, and open its Events tab. In shows the raw payload, Out shows the decoded result (device name, type, attributes, telemetry), and Metadata contains the MQTT topic and integration name.
Configure and test downlink
Section titled “Configure and test downlink”A downlink converter is required only when the integration sends commands to devices (RPCs, attribute updates). If you only ingest data into ThingsBoard, skip this section.
Add a downlink converter
Section titled “Add a downlink converter”The encoder receives msg, metadata, and msgType, and must return:
contentType—JSON,TEXT, orBINARYdata— the payload string to publishmetadata.topic— when the integration’s Downlink topic pattern is${topic}, the integration publishes to this topic
For RPC commands, msg.method and msg.params are available. msg.params is always a string — use parseFloat(msg.params) or JSON.parse(msg.params) when a numeric or structured value is needed. See the Downlink data converter reference for the full encoder API.
The encoder function used in this tutorial:
/** Encoder **/// Publish the ThingsBoard message as JSON to the device command topic.// metadata.topic is read by the integration when Downlink topic pattern is ${topic}.
var result = { contentType: "JSON", data: JSON.stringify(msg), metadata: { topic: metadata['deviceName'] + '/commands' }};
return result;/** Encoder **/// Publish the ThingsBoard message as JSON to the device command topic.// metadata.topic is read by the integration when Downlink topic pattern is ${topic}.
var result = { contentType: "JSON", data: JSON.stringify(msg), metadata: { topic: metadata['deviceName'] + '/commands' }};
return result;- Go to Integrations center ⇾ Integrations and open the MQTT Integration.
- Click Toggle edit mode.
- In the Downlink data converter field, click Create new.
- Enter a name (e.g.
MQTT Downlink Converter) and paste the encoder script. - Click Add, then click Apply changes.
Configure the Root Rule Chain
Section titled “Configure the Root Rule Chain”- Go to Rule chains ⇾ Root Rule Chain.
- In the Enrichment section of the node library, find the originator fields node and drag it onto the canvas.
- In the originator fields node configuration, map the source fields:
- Name ⇾ deviceName
- Profile name ⇾ deviceType
- Then click Add.
- Connect the message type switch node to the originator fields node using the Attributes Updated and Post attributes link types.
- In the node library, find the integration downlink node and drag it onto the canvas.
- In the node configuration, set a name (e.g., MQTT integration) and select your MQTT integration. Click Add.
- Connect the originator fields node to the integration downlink node using the Success relation.
- Click Apply changes.
Test the downlink
Section titled “Test the downlink”Subscribe to the device command topic to receive downlink messages:
mosquitto_sub -h broker.hivemq.com -p 1883 -t "SN-001/commands"Trigger a downlink by adding a shared attribute to the device:
- Go to Entities ⇾ Devices, open SN-001, and navigate to the Attributes tab.
- Switch to Shared attributes and click +.
- Enter key
powerStateand valueon, then click Add.
The Rule Engine routes the attribute update to the integration downlink node, which passes it to the encoder. The terminal receiving on SN-001/commands will print the downlink payload:
{"powerState":"on"}The sent and received data can be viewed in the downlink converter’s Events tab — the In block shows the input data, the Out block shows the encoded message sent to the device, and Metadata shows the request headers:
Message retransmission
Section titled “Message retransmission”ThingsBoard retransmits unacknowledged MQTT packets — PUBLISH (QoS 1/2), SUBSCRIBE, UNSUBSCRIBE, and PUBREL — using exponential backoff: the delay doubles with each attempt, and a jitter factor adds random variance to prevent synchronized retries.
Example: 3 attempts, 5,000 ms initial delay, jitter factor 0.15 → retries at approximately 5,000 ms, 10,000 ms, and 20,000 ms (each ±15%). If the final attempt goes unacknowledged, the message is dropped and the Rule Engine routes it via the Failure chain.
Configure retransmission parameters globally using environment variables — these settings apply to all MQTT clients on the platform. For configuration instructions, see How to change configuration. After making changes, restart the ThingsBoard service.mqtt: client: retransmission: max_attempts: "${TB_MQTT_CLIENT_RETRANSMISSION_MAX_ATTEMPTS:3}" initial_delay_millis: "${TB_MQTT_CLIENT_RETRANSMISSION_INITIAL_DELAY_MILLIS:5000}" jitter_factor: "${TB_MQTT_CLIENT_RETRANSMISSION_JITTER_FACTOR:0.15}"Troubleshooting
Section titled “Troubleshooting”Integration cannot connect to the broker
- Verify the host and port are correct and the broker is reachable from the ThingsBoard server.
- ThingsBoard Cloud instances cannot connect to brokers on private networks — use a Remote Integration instead.
- Uncheck Clean session in Advanced settings if the broker drops the connection unexpectedly.
No messages received
- Check that the topic filter exactly matches the published topic pattern, including wildcard levels.
- Use the integration Events tab to verify whether messages arrive and how the converter processes them.
Downlink not delivered to device
- Verify that
metadata.topicis set in the downlink converter output. - Confirm the Integration Downlink node is connected to the Message Type Switch node via the correct relation type — Attributes Updated for attribute changes, RPC Request to Device for RPC commands.
- Check that the MQTT Integration has a downlink converter assigned.
Cannot identify what went wrong
- Enable Debug mode on the integration — it captures all raw input/output events and makes them visible on the Events tab. Starting from ThingsBoard 3.9, the full set of debug events is stored only during the first 1 hour; afterward, only error events are retained. Disable debug mode once the issue is identified.
Examples
Section titled “Examples”The following guides walk through complete end-to-end scenarios using the MQTT Integration, covering both uplink telemetry ingestion and downlink RPC commands:
- MQTT two-way RPC — send an RPC command from ThingsBoard to a device over MQTT and receive the response back.
- MQTT one-way RPC — send a one-way RPC command from ThingsBoard to a device over MQTT with no response expected.