MQTT Integration
MQTT Integration connects ThingsBoard Edge to an external MQTT broker as an MQTT client. It subscribes to topics, converts incoming payloads into telemetry and attributes, and can publish downlink messages to devices through the same broker.
Prerequisites
Section titled “Prerequisites”- A ThingsBoard server with tenant administrator access. The templates are created there.
- A ThingsBoard Edge instance connected to the server.
- An MQTT broker that the Edge can reach by DNS name or static IP address. This guide uses
broker.hivemq.comon port 1883. - The
mosquitto_pubandmosquitto_subclients installed locally.
The example sensor SN-001 publishes temperature readings to tb-edge/mqtt-integration-tutorial/sensors/SN-001/temperature as {"value":25.1} and subscribes to tb-edge/mqtt-integration-tutorial/sensors/SN-001/rx for commands.
Create converter templates
Section titled “Create converter templates”Converter templates are created on the server. The uplink converter decodes the MQTT payload into telemetry and attributes and takes the device name from the topic (segment index 3). The downlink converter encodes messages from the rule engine and sets the target topic from the device name in the message metadata.
Uplink converter
Section titled “Uplink converter”-
On the server, go to Edge management > Templates and open the Converter tab. Click Add data converter and select Create new converter.
-
Set Converter type to Uplink, select MQTT as the Integration type, and enter the name
MQTT uplink converter. -
In Main decoding configuration, select TBEL or JS, paste the matching script, and click Add.
/** Decoder **/// decode payload to stringvar payloadStr = decodeToString(payload);var data = JSON.parse(payloadStr);var deviceName = metadata.topic.split("/")[3];var deviceType = 'sensor';// Result object with device attributes/telemetry datavar result = {deviceName: deviceName,deviceType: deviceType,attributes: {integrationName: metadata['integrationName'],},telemetry: {temperature: data.value,}};/** 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';// Result object with device attributes/telemetry datavar result = {deviceName: deviceName,deviceType: deviceType,attributes: {integrationName: metadata['integrationName'],},telemetry: {temperature: data.value,}};/** Helper functions **/function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}function decodeToJson(payload) {var str = decodeToString(payload);return JSON.parse(str);}return result;
Downlink converter
Section titled “Downlink converter”-
On the Converter tab, click Add data converter and select Create new converter.
-
Set Converter type to Downlink, select MQTT as the Integration type, and enter the name
MQTT downlink converter. -
In Main encoding configuration, select TBEL or JS, paste the matching script, and click Add.
/** Encoder **/// Result object with encoded downlink payloadvar result = {// downlink data content type: JSON, TEXT or BINARY (base64 format)contentType: "JSON",// downlink datadata: JSON.stringify(msg),// Optional metadata object presented in key/value formatmetadata: {topic: 'tb-edge/mqtt-integration-tutorial/sensors/' + metadata['originatorName'] + '/rx'}};return result;/** Encoder **/// Result object with encoded downlink payloadvar result = {// downlink data content type: JSON, TEXT or BINARY (base64 format)contentType: "JSON",// downlink datadata: JSON.stringify(msg),// Optional metadata object presented in key/value formatmetadata: {topic: 'tb-edge/mqtt-integration-tutorial/sensors/' + metadata['originatorName'] + '/rx'}};return result;
Create integration template
Section titled “Create integration template”-
On the server, go to Edge management > Templates, open the Integration tab, and click Add integration.
-
On the Basic settings step, select MQTT as the Integration type. Keep the name
MQTT integrationor enter your own. Click Next. -
On the Uplink data converter step, select Select existing, choose
MQTT uplink converter, and click Next. -
On the Downlink data converter step, select Select existing, choose
MQTT downlink converter, and click Next. -
On the Connection step, configure the broker connection:
Field Value Host ${{brokerIp}}. The placeholder is replaced by thebrokerIpserver attribute of each Edge.Port 1883Credentials type Anonymous Topic filters Replace the default #withtb-edge/mqtt-integration-tutorial/sensors/+/temperature. Keep QoS at 0 - At most once. -
Expand Advanced settings, turn off Clean session, and keep Downlink topic pattern at its default
${topic}. The integration then publishes downlinks to the topic set by the downlink converter inmetadata.topic. Click Add.
The ${{brokerIp}} placeholder lets you assign one template to several Edges that use different brokers. See Configuration placeholders.
Assign the integration to the Edge
Section titled “Assign the integration to the Edge”Add the brokerIp attribute first. Without it, the assignment dialog warns Edge has missing attribute(s) and the Edge receives the literal placeholder.
-
On the server, go to Edge management > Edges and click the Edge. On the Attributes tab, with the Server attributes scope selected, click +. Enter
brokerIpas the key andbroker.hivemq.comas the value. Click Add. -
On the Details tab, click Manage integrations, then Assign to edge (+). Select
MQTT integrationand click Assign. -
Log in to the Edge and go to Integrations > Integrations. Open the integration. Host shows
broker.hivemq.cominstead of the placeholder.
Send an uplink message
Section titled “Send an uplink message”-
Publish a test message with
mosquitto_pub. This simulates the sensor sending a temperature reading:Terminal window mosquitto_pub -h broker.hivemq.com -p 1883 \-t "tb-edge/mqtt-integration-tutorial/sensors/SN-001/temperature" \-m '{"value":25.2}' -
On the Edge, go to Integrations > Integrations, open the MQTT integration, and select the Events tab. An Uplink event with status OK appears. Click the three dots in the Message column to see the topic and payload.
-
The device SN-001 is created automatically. On the Edge, go to Devices & assets > Devices, open it, and select the Latest telemetry tab. The
temperaturekey shows25.2. -
To see how the converter processed the message, go to Integrations > Data converters, open
MQTT uplink converter, and select the Events tab. The In column shows the raw payload, the Out column the decoded telemetry.
Configure the rule chain for downlinks
Section titled “Configure the rule chain for downlinks”To send messages from the rule engine to the integration, add two nodes to the root rule chain of the Edge: originator fields, which puts the device name into the message metadata, and integration downlink, which passes the message to the integration. The downlink converter uses originatorName from the metadata to build the topic.
-
On the Edge, go to Data processing > Rule chains and open Edge Root Rule Chain.
-
In the node search field, type
originator fieldsand drag the originator fields node onto the canvas. Name itadd name & type. Keep the default Originator fields mapping (Name tooriginatorName, Profile name tooriginatorType) and keep Add mapped originator fields to at Metadata. Click Add. -
Search for
integration downlinkand drag the integration downlink node onto the canvas. Name itpush to integration, selectMQTT integrationin the Integration field, and click Add. -
Connect the nodes:
- message type switch to originator fields with the Attributes Updated and Post attributes labels.
- originator fields to integration downlink with the Success label.
-
Click the checkmark icon (Apply changes) to save the rule chain.
Send a downlink message
Section titled “Send a downlink message”-
In a terminal, subscribe to the command topic of the device and keep the window open:
Terminal window mosquitto_sub -h broker.hivemq.com -p 1883 \-t "tb-edge/mqtt-integration-tutorial/sensors/+/rx" -
On the Edge, go to Devices & assets > Devices, open SN-001, and select the Attributes tab. Select the Shared attributes scope, click +, enter the key
firmwareand the valuev1.0, and click Add. -
The subscriber terminal receives the downlink message:
{"firmware":"v1.0"} -
On the Edge, open the Events tab of the integration. A Downlink event with status OK appears. Its message contains the target topic
tb-edge/mqtt-integration-tutorial/sensors/SN-001/rxand the payload. -
To see the encoded message, go to Integrations > Data converters, open
MQTT downlink converter, and select the Events tab. The In column shows the message from the rule engine, includingoriginatorNamein the metadata. The Out column shows the message sent to the device.
Was this helpful?