Skip to content
Stand with Ukraine flag

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.

Create an uplink converter that will decode incoming MQTT messages into ThingsBoard format, then configure the integration to connect to your broker.

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 string
var 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 data
var result = {
deviceName: deviceName,
deviceType: deviceType,
attributes: {
integrationName: metadata['integrationName'],
},
telemetry: {
temperature: data.temperature,
}
};
/** Helper functions 'decodeToString' and 'decodeToJson' are already built-in **/
return result;

The decoder produces:

SourceFieldOutput typeNotes
metadata.topic.split("/")[3]deviceName4th segment of the topic path (0-indexed)
hardcoded 'sensor'deviceTypeDevice profile name
data.temperaturetemperaturetelemetryFrom JSON payload
metadata.integrationNameintegrationNameattributeName 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 from data (e.g. data.deviceId) if the device name is in the payload body.
  • Different telemetry fields — add or rename fields in the telemetry object to match your payload structure.
  • Additional attributes — add more keys to the attributes object (e.g. firmware version, location).
  • Different device type — change 'sensor' to match your device profile name in ThingsBoard.

Import the uplink converter:

  1. Download the converter file for your scripting language:
  1. Go to Integrations center ⇾ Data converters.
  2. Click + Add data converter ⇾ Import converter.
  3. Drag and drop the downloaded file and click Import.
  1. Go to Integrations center ⇾ Integrations and click + Add integration.
  2. Basic settings:
    • Set Integration type to MQTT.
    • Enable integration and Allow create devices or assets are on by default.
    • Click Next.
  3. Uplink data converter:
    • Select existing — choose a previously created MQTT Uplink Converter from the list.
    • Click Next.
  4. Downlink data converter:
    • Click Skip — only needed for RPC; can be added later.
  5. Connection:
    • Set broker Host and Port (e.g. broker.hivemq.com, port 1883).
    • Select the Credentials type (e.g. Anonymous).
    • Add at least one topic filter with QoS (e.g. tb/mqtt-integration-tutorial/sensors/+/temperature, QoS 0 — 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.
    Read more about each parameter in connection settings.
  6. Click Check connection — a confirmation step appears showing Connected.
  7. Click Add to complete the integration setup.

Host and port

ParameterDefaultDescription
HostIP address or hostname of the MQTT broker (e.g. broker.hivemq.com)
Port1883Broker port: 1883 for plain MQTT, 8883 for MQTT over TLS

Credentials

ParameterDescription
Credentials typeAnonymous — 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.

FieldDescription
TopicMQTT topic filter. + matches a single level (e.g. devices/+/telemetry). # matches all sub-levels and must be the last character (e.g. devices/#)
QoS0 — at most once (fire and forget); 1 — at least once (may deliver duplicates); 2 — exactly once

Advanced settings

ParameterDefaultDescription
Protocol versionMQTT 3.1.1MQTT protocol version used for the broker connection (3.1, 3.1.1, or 5.0)
Clean sessiononWhen 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
RetainedoffWhen on, the broker caches the last downlink message per topic and delivers it immediately to any new subscriber
Client IDautoMQTT 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 message32368Maximum payload size in bytes. Messages exceeding this limit are dropped
Connection timeout (sec)10Seconds 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.

Publish a test temperature reading to the broker. Requires mosquitto-clients:

Terminal window
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.

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.

The encoder receives msg, metadata, and msgType, and must return:

  • contentTypeJSON, TEXT, or BINARY
  • data — the payload string to publish
  • metadata.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;
  1. Go to Integrations center ⇾ Integrations and open the MQTT Integration.
  2. Click Toggle edit mode.
  3. In the Downlink data converter field, click Create new.
  4. Enter a name (e.g. MQTT Downlink Converter) and paste the encoder script.
  5. Click Add, then click Apply changes.
  1. Go to Rule chains ⇾ Root Rule Chain.
  2. In the Enrichment section of the node library, find the originator fields node and drag it onto the canvas.
  3. In the originator fields node configuration, map the source fields:
    • Name ⇾ deviceName
    • Profile name ⇾ deviceType
    • Then click Add.
  4. Connect the message type switch node to the originator fields node using the Attributes Updated and Post attributes link types.
  5. In the node library, find the integration downlink node and drag it onto the canvas.
  6. In the node configuration, set a name (e.g., MQTT integration) and select your MQTT integration. Click Add.
  7. Connect the originator fields node to the integration downlink node using the Success relation.
  8. Click Apply changes.

Subscribe to the device command topic to receive downlink messages:

Terminal window
mosquitto_sub -h broker.hivemq.com -p 1883 -t "SN-001/commands"

Trigger a downlink by adding a shared attribute to the device:

  1. Go to Entities ⇾ Devices, open SN-001, and navigate to the Attributes tab.
  2. Switch to Shared attributes and click +.
  3. Enter key powerState and value on, 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:

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}"

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.topic is 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.

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.