Azure Service Bus Integration
Azure Service Bus Integration receives messages from a topic subscription in Azure Service Bus. An uplink data converter transforms each message into device or asset data, including telemetry and attributes. ThingsBoard can also publish downlink messages to a separate Service Bus topic.
Use Azure Service Bus Integration when:
- Your applications or IoT platforms already publish device data to a Service Bus topic.
- Several consumers must read the same data: each topic subscription receives its own copy of every message.
- Backend services must receive commands or data from ThingsBoard through a Service Bus topic.
Architecture
Section titled “Architecture”- Receive data. A producer sends a message to the uplink topic. The integration receives it from its subscription on that topic.
- Decode the payload. The uplink converter identifies the target device or asset from the payload or the message’s custom properties, and extracts attributes and telemetry.
- Process the message. ThingsBoard processes the converted data through the Rule Engine. If Allow create devices or assets is enabled, ThingsBoard can create an entity that does not exist yet.
- Send downlink data (optional). The Rule Engine passes a message to the integration. The downlink converter encodes it, and the integration publishes it to the downlink topic.
Prerequisites
Section titled “Prerequisites”- Access to ThingsBoard or ThingsBoard Cloud with integrations enabled for your tenant.
- Permission to create integrations and data converters, and to edit rule chains for downlink.
- An Azure account with an active subscription and permission to create a Service Bus namespace on the Standard or Premium tier. The Basic tier does not support topics.
- Outbound TCP port
5671(AMQP) open from the ThingsBoard server (or the remote integration host) to*.servicebus.windows.net.
Configure Azure Service Bus
Section titled “Configure Azure Service Bus”Create a namespace, a topic with a subscription for ThingsBoard, and a policy that ThingsBoard uses to read the messages. For details, see Create Service Bus topics and subscriptions.
Create a Namespace
Section titled “Create a Namespace”- In the Azure portal, search for Service Bus, open it, and click + Create.
- On the Basics tab, select or create a Resource group, for example
tb-integrations, enter a globally unique Namespace name, for exampletb-servicebus-01, and choose a Location. - Set Pricing tier to Standard or Premium. The Basic tier does not support topics.
- Click Review + create, then Create.
- When the deployment finishes, click Go to resource.
Create a Topic and a Subscription
Section titled “Create a Topic and a Subscription”The integration reads messages from a subscription on a topic, not from a queue. Each subscription receives its own copy of every message sent to the topic, so give ThingsBoard a subscription that no other application reads.
- In the namespace, go to Entities ⇾ Topics and click + Topic.
- Enter a Name, for example
tb-uplink, keep the other settings, and click Create. - Open the topic, go to Entities ⇾ Subscriptions, and click + Subscription.
- Enter a Name, for example
thingsboard, keep Max delivery count10and the other settings, and click Create.
Downlink uses a second topic. You create it in Configure Downlink.
Copy the Connection String
Section titled “Copy the Connection String”ThingsBoard needs only Listen permission to receive messages. Create a separate policy for it, so the key does not allow sending or managing the namespace.
- In the namespace, go to Settings ⇾ Shared access policies and click + Add.
- Enter a Policy name, for example
tb-listen, select Listen, and click Create. - Open the policy and copy the Primary connection string. It has the form
Endpoint=sb://tb-servicebus-01.servicebus.windows.net/;SharedAccessKeyName=tb-listen;SharedAccessKey=<key>.
You now have the values for the integration:
| Value | Example | Source |
|---|---|---|
| Connection string | Endpoint=sb://tb-servicebus-01.servicebus.windows.net/;SharedAccessKeyName=tb-listen;SharedAccessKey=… |
Primary connection string of the policy |
| Topic name | tb-uplink |
The topic |
| Subscription name | thingsboard |
The subscription on the topic |
Set Up Azure Service Bus Integration
Section titled “Set Up Azure Service Bus Integration”Create the uplink converter, assign it to a new Azure Service Bus integration, and send a test message.
Create the Uplink Data Converter
Section titled “Create the Uplink Data Converter”The uplink converter receives each message body as a byte array, finds the target device, and returns its telemetry and attributes. For converter types and the full decoder reference, see Uplink data converter.
-
Go to Integrations ⇾ Data converters and click + Add data converter ⇾ Create new converter.
-
Converter type — keep Uplink.
-
Integration type — select Azure Service Bus.
-
Name — enter a name, for example
Azure Service Bus Uplink Converter. -
Main decoding configuration — the editor opens with the default Azure Service Bus template, which is the decoder below. Keep it, or adapt it to your payload. The editor opens in TBEL; use the TBEL / JS toggle to switch to JavaScript.
/** Decoder **/// Decode the incoming payload to a JSON object.var data = decodeToJson(payload);// The device name comes from deviceId in the payload.// Otherwise, it comes from the custom message property deviceId (sysProp:deviceId).// Reject the message if neither is present.var deviceName = data.deviceId != null ? data.deviceId.toString().trim() : "";var propertyId = metadata["sysProp:deviceId"];if (deviceName.isEmpty() && propertyId != null) {deviceName = propertyId.trim();}if (deviceName.isEmpty()) {raiseError("Payload has no deviceId and the message has no deviceId property");}// The device profile comes from deviceType. If it is missing or empty, the "default" profile is used.var deviceType = data.deviceType != null ? data.deviceType.toString().trim() : "";if (deviceType.isEmpty()) {deviceType = "default";}// Use the timestamp if provided; otherwise, use the current server time.// An invalid timestamp rejects the message.var ts = data.timestamp != null && !data.timestamp.toString().trim().isEmpty() ? new Date(data.timestamp).getTime() : Date.now();// Static device properties become attributes.var attributes = {};if (data.location != null) {attributes.latitude = data.location.latitude;attributes.longitude = data.location.longitude;attributes.altitude = data.location.altitude;}if (data.metadata != null) {attributes.version = data.metadata.version;attributes.manufacturer = data.metadata.manufacturer;}// All other top-level fields (temperature, pressure, status, humidity, ...) become telemetry as they are.var handled = ["deviceId", "deviceType", "timestamp", "location", "metadata", "vibration", "alarms"];var telemetry = {};foreach (key : data.keySet()) {if (!handled.contains(key)) {telemetry[key] = data[key];}}if (data.alarms != null) {telemetry.receivedAlarms = data.alarms;}if (data.vibration != null) {telemetry.vibrationX = data.vibration.x;telemetry.vibrationY = data.vibration.y;telemetry.vibrationZ = data.vibration.z;}if (data.metadata != null) {telemetry.batteryLevel = data.metadata.batteryLevel;telemetry.batteryStatus = data.metadata.batteryStatus;}// Return the converted uplink message.return {deviceName: deviceName,deviceType: deviceType,attributes: attributes,telemetry: {ts: ts,values: telemetry}};/** Decoder **/// Decode the incoming payload to a JSON object.var data = decodeToJson(payload);// The device name comes from deviceId in the payload.// Otherwise, it comes from the custom message property deviceId (sysProp:deviceId).// Reject the message if neither is present.var deviceName = data.deviceId != null ? String(data.deviceId).trim() : "";var propertyId = metadata["sysProp:deviceId"];if (!deviceName && propertyId) {deviceName = String(propertyId).trim();}if (!deviceName) {throw new Error("Payload has no deviceId and the message has no deviceId property");}// The device profile comes from deviceType. If it is missing or empty, the "default" profile is used.var deviceType = data.deviceType != null ? String(data.deviceType).trim() : "";if (!deviceType) {deviceType = "default";}// Use the timestamp if provided; otherwise, use the current server time.// An invalid timestamp rejects the message.var ts = data.timestamp != null && String(data.timestamp).trim() !== "" ? new Date(data.timestamp).getTime() : Date.now();if (isNaN(ts)) {throw new Error("Invalid timestamp: " + data.timestamp);}// Static device properties become attributes.var attributes = {};if (data.location != null) {attributes.latitude = data.location.latitude;attributes.longitude = data.location.longitude;attributes.altitude = data.location.altitude;}if (data.metadata != null) {attributes.version = data.metadata.version;attributes.manufacturer = data.metadata.manufacturer;}// All other top-level fields (temperature, pressure, status, humidity, ...) become telemetry as they are.var handled = ["deviceId", "deviceType", "timestamp", "location", "metadata", "vibration", "alarms"];var telemetry = {};for (var key in data) {if (handled.indexOf(key) < 0) {telemetry[key] = data[key];}}if (data.alarms != null) {telemetry.receivedAlarms = data.alarms;}if (data.vibration != null) {telemetry.vibrationX = data.vibration.x;telemetry.vibrationY = data.vibration.y;telemetry.vibrationZ = data.vibration.z;}if (data.metadata != null) {telemetry.batteryLevel = data.metadata.batteryLevel;telemetry.batteryStatus = data.metadata.batteryStatus;}var result = {deviceName: deviceName,deviceType: deviceType,attributes: attributes,telemetry: {ts: ts,values: telemetry}};/** Helper functions **/// Convert the byte array to a string.function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}// Convert the byte array to a JSON object.function decodeToJson(payload) {return JSON.parse(decodeToString(payload));}// Return the converted uplink message.return result;The decoder:
- takes the device name from
deviceIdin the payload, or from the custom message propertydeviceId, and rejects the message if both are missing; - takes the device profile from
deviceType, or usesdefault; - uses
timestampas the time of the data, or the server time if the payload has notimestamp; - stores
locationandmetadata.version/metadata.manufactureras attributes, and all other fields as telemetry.
To adapt:
- Device name in another field — replace
data.deviceId, for example withdata.serialNumber. - Fields that are not telemetry — add them to
handled, then map them yourself. - Update-only keys — for Azure Service Bus, ThingsBoard pre-fills the Update only keys list in Advanced decoding parameters with
manufacturer,receivedAlarms,status,batteryLevel,batteryStatus, andversion. These keys are stored only when their value changes. Edit the list to match your keys.
- takes the device name from
-
Click Test decoder function and check the result (see Test the Decoder).
-
Click Add.
Decoder Inputs
The decoder signature is function decoder(payload, metadata): object | object[].
| Variable | Type | Content |
|---|---|---|
payload |
byte array | The message body. |
metadata |
{[key: string]: string} |
integrationName, the key–value pairs from the integration’s Metadata field, and each custom property of the message as sysProp:<name>, for example sysProp:site. Broker properties such as Label/Subject or Message ID are not passed. |
Built-in helpers:
| Function | Result |
|---|---|
decodeToJson(payload) |
Parses the bytes as JSON and returns an object. |
decodeToString(payload) |
Converts the bytes to a UTF-8 string. |
For field renaming, nested values, and non-JSON payloads, see Common scripting patterns.
Test the Decoder
Click Test decoder function below the editor. Metadata holds integrationName, and Payload already holds a sample message, the same one that you send in Test Uplink:
{"deviceId": "sb-sensor-01", "temperature": 24.6, "humidity": 51}Click Test. The Output panel shows:
{ "deviceName": "sb-sensor-01", "deviceType": "default", "attributes": {}, "telemetry": { "ts": 1795099761202, "values": { "temperature": 24.6, "humidity": 51 } }}The payload has no timestamp, so ts is the time of the test, in milliseconds, and differs in your output. Neither temperature nor humidity is named in the decoder: like every other top-level field that is not in handled, they become telemetry as they are.
Check that deviceName is set and telemetry holds the expected keys. If the output is empty or shows an error, fix the decoder and test again.
Create the Integration
Section titled “Create the Integration”- Go to Integrations ⇾ Integrations and click + Add integration.
- Basic settings:
- Integration type — select Azure Service Bus.
- Name — keep the default
Azure Service Bus integrationor enter your own. - Enable integration and Allow create devices or assets — keep both on, so the device is created on its first uplink.
- Click Next.
- Uplink data converter:
- Click Select existing and choose
Azure Service Bus Uplink Converter. - Click Next.
- Click Select existing and choose
- Downlink data converter:
- Click Skip. Add a downlink converter later if you need to publish to Service Bus.
- Connection:
- Connection string — paste the Primary connection string of
tb-listen. - Topic name — enter
tb-uplink. - Subscription name — enter
thingsboard. - See Connection Settings for details.
- Connection string — paste the Primary connection string of
- Click Add.
Connection Settings
Section titled “Connection Settings”| Parameter | Description |
|---|---|
| Connection string | Connection string of a policy with Listen permission. Required. |
| Topic name | Topic the integration receives from. Required. |
| Subscription name | Subscription on that topic. Required. |
| Downlink connection string | Connection string of a policy with Send permission. Shown and required only when a downlink converter is assigned. |
| Downlink topic name | Topic the integration publishes downlinks to. Shown and required only when a downlink converter is assigned. |
| Execute remotely | Runs the integration as a separate process outside the ThingsBoard cluster, for example in a network with access to Azure. ThingsBoard generates an Integration key and Integration secret for it. See Remote Integration. |
Advanced settings
| Parameter | Description |
|---|---|
| Description | Free-text description. |
| Metadata | Key–value pairs added to the metadata of every message from this integration. |
Check connection reads only the connection string and does not connect to Service Bus. It shows Connection established. even for a wrong key or a topic that does not exist, so check the names and the key against the Azure portal.
If the converter fails on a message, the integration still removes the message from the subscription, and the message is lost. Check Error events of the converter to catch such messages.
Test Uplink
Section titled “Test Uplink”Send a message to tb-uplink, then confirm that ThingsBoard decoded it and created the device.
Send a Test Uplink
Section titled “Send a Test Uplink”-
In the namespace, go to Entities ⇾ Topics and open
tb-uplink. -
Click Service Bus Explorer in the topic menu, then click Send messages.
-
Set Content type to
application/json. -
Paste the payload into Message Body:
{"deviceId": "sb-sensor-01", "temperature": 24.6, "humidity": 51} -
Click Send.
The payload has no timestamp, so the decoder uses the server time.
To add a custom property, expand Custom Properties in the Send messages panel. The decoder receives it as sysProp:<name>.
Verify the Result
Section titled “Verify the Result”- Integration events — go to Integrations ⇾ Integrations, open the integration, and click the Events tab. The uplink appears with status OK. Click
⋅⋅⋅in the Message column to seesystemProperties(the custom properties of the message) andpayload. - Converter events — open
Azure Service Bus Uplink Converterin Integrations ⇾ Data converters and click the Events tab. In shows the received payload, Out shows the decoded result, and Metadata showsintegrationNameand anysysProp:values. - Device — go to Devices & assets ⇾ Devices. The integration has created sb-sensor-01 with the
defaultprofile. Open it and check the Latest telemetry tab fortemperature24.6andhumidity51.
Configure Downlink
Section titled “Configure Downlink”ThingsBoard publishes a downlink when the Rule Engine routes a message to the integration — for example, after a shared attribute update. The integration sends it to the Downlink topic name. Every subscription on that topic receives a copy, and your backend reads it from its subscription.
Each downlink message carries:
- Body — the encoder’s
data. - contentType — the encoder’s
contentType:JSON,TEXT, orBINARY. - to — the encoder’s
metadata.deviceId. - Custom properties — every key of the encoder’s
metadata.
The downlink converter turns a Rule Engine message into the published message. For the full encoder reference, see Downlink data converter.
Create the Downlink Topic
Section titled “Create the Downlink Topic”A message sent to a topic without subscriptions is discarded, so the downlink topic needs a subscription for its consumer before ThingsBoard publishes to it.
- In the namespace, go to Entities ⇾ Topics, click + Topic, enter
tb-downlink, and click Create. - Open
tb-downlink, go to Entities ⇾ Subscriptions, click + Subscription, enterdevice-commands, keep Max delivery count10, and click Create. Your backend reads the downlinks from this subscription. - In the namespace, go to Settings ⇾ Shared access policies, click + Add, enter
tb-send, select Send, and click Create. - Open
tb-sendand copy the Primary connection string.
Create and Assign the Downlink Converter
Section titled “Create and Assign the Downlink Converter”The encoder must set metadata.deviceId. Without it, the integration skips the message without an error.
- Open the integration in Integrations ⇾ Integrations and click Toggle edit mode (pencil icon).
- In the Downlink data converter field, click Create new. The Downlink converter type and Azure Service Bus integration type are preselected.
- Enter a name, for example
Azure Service Bus Downlink Converter. - Click the debug button next to the name, select All messages, and click Apply. A converter created here records only failures, so without this its Events tab shows only errors.
- Main encoding configuration opens with the default Azure Service Bus encoder, which is the encoder below. Keep it, or adapt it.
- Click Add.
- Below Subscription name, fill in the fields that appear once the downlink converter is assigned:
- Downlink connection string — the Primary connection string of
tb-send. - Downlink topic name — enter
tb-downlink.
- Downlink connection string — the Primary connection string of
- Click Apply changes.
/** Encoder **/
// Publish the ThingsBoard message as JSON to the downlink topic.// metadata.deviceId becomes the To property and the custom property deviceId of the message;// the integration skips messages without it. This template uses the ThingsBoard device name.// Add it to the message metadata with the "originator fields" rule node (Name -> deviceName).var deviceId = metadata.deviceName != null ? metadata.deviceName.trim() : null;if (deviceId == null || deviceId.isEmpty()) { raiseError("Message metadata has no deviceName");}
var result = { // Payload content type: JSON, TEXT, or BINARY (Base64). contentType: "JSON", data: JSON.stringify(msg), metadata: { deviceId: deviceId }};
return result;/** Encoder **/
// Publish the ThingsBoard message as JSON to the downlink topic.// metadata.deviceId becomes the To property and the custom property deviceId of the message;// the integration skips messages without it. This template uses the ThingsBoard device name.// Add it to the message metadata with the "originator fields" rule node (Name -> deviceName).var deviceId = typeof metadata.deviceName === "string" ? metadata.deviceName.trim() : "";if (!deviceId) { throw new Error("Message metadata has no deviceName");}
var result = { // Payload content type: JSON, TEXT, or BINARY (Base64). contentType: "JSON", data: JSON.stringify(msg), metadata: { deviceId: deviceId }};
return result;To check the encoder, click Test encoder function. Message type (ATTRIBUTES_UPDATED), Message ({"temperatureUploadFrequency": 60}), and deviceName sb-sensor-01 in Metadata are already filled in. Click Test. The Output shows:
{ "contentType": "JSON", "data": "{\"temperatureUploadFrequency\":60}", "metadata": { "deviceId": "sb-sensor-01" }}To adapt:
- Another envelope — build
datain the structure your consumer expects, for example{ "device": deviceId, "config": msg }. - Routing properties — add keys to
metadata, for exampletype: "config". Subscription filter rules on the downlink topic can route on these custom properties. - Other message types — branch on
msgType, for example to handleRPC_CALL_FROM_SERVER_TO_DEVICEwithmsg.methodandmsg.params. See Rule Engine message types.
Configure the Root Rule Chain
Section titled “Configure the Root Rule Chain”The encoder reads deviceName from the message metadata, so the rule chain first adds the device name.
- Go to Data processing ⇾ Rule chains and open the Root Rule Chain.
- From the Enrichment section, drag an originator fields node onto the canvas.
- Enter a Name, for example
Add device name, and map the source fields:- Name ⇾ deviceName
- Add mapped originator fields to ⇾ Metadata
- Click Add.
- Connect the message type switch node to the originator fields node with the Attributes Updated relation.
- From the Action section, drag an integration downlink node onto the canvas.
- Enter a Name, for example
Downlink to Azure Service Bus, selectAzure Service Bus integration, and click Add. - Connect the originator fields node to the integration downlink node with the Success relation.
- Click Apply changes.
Test Downlink
Section titled “Test Downlink”- Go to Devices & assets ⇾ Devices, select sb-sensor-01, and open the Attributes tab.
- Select Shared attributes and click +.
- Set Key to
temperatureUploadFrequency, Type to Integer, Value to60, and click Add. ThingsBoard publishes the downlink.
Verify the Downlink
Section titled “Verify the Downlink”- Integration events — the integration’s Events tab shows a Downlink event with
deviceIdsb-sensor-01,payload{"temperatureUploadFrequency":60}, andproperties. - Service Bus Explorer — open
tb-downlink, click Service Bus Explorer, select the subscriptiondevice-commands, and click Peek from start. Select the message: Message Body shows{"temperatureUploadFrequency":60}; Message Properties shows contentTypeJSON, tosb-sensor-01, and the custom propertydeviceIdsb-sensor-01.
Peek from start leaves the message in the subscription.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Cause | Fix |
|---|---|---|
| Check connection shows Connection established., but no uplinks arrive | Check connection does not connect to Service Bus. The namespace, topic, subscription, or key is wrong, or the policy lacks Listen. | Compare the names with the Azure portal. Copy the connection string again from a policy with Listen. |
| Uplinks stop, the integration shows no errors | The key of the policy was regenerated, or the topic or subscription was deleted. ThingsBoard writes the error only to the server log, for example 401 InvalidSignature. |
After a key change, copy the new connection string to the integration and click Apply changes; the messages that waited in the subscription arrive. If the topic or subscription was deleted, create it again; messages sent while it was missing are not delivered. |
| Same, from a private network | Outbound port 5671 is blocked. |
Open TCP 5671 to *.servicebus.windows.net, or use a Remote Integration. |
| Messages go to another consumer | Another application reads the same subscription. | Create a dedicated subscription for ThingsBoard. |
| Topics are not available | The namespace is on the Basic tier. | Use the Standard or Premium tier. |
| Uplink event with status ERROR | The converter failed on the message. The message is removed from the subscription and lost. | Check Error in the converter events, fix the decoder, and send the message again. |
| Device not created | deviceName is empty, or Allow create devices or assets is off. |
Check Out in the converter events and the integration settings. |
| Downlink: ATTRIBUTES_UPDATED is OK, but no Downlink event and nothing in the downlink subscription | The encoder does not set metadata.deviceId, so the integration skips the message. |
Check Out in the downlink converter events for deviceId. Use the encoder from this guide. |
| No downlink events at all | The rule chain does not reach the integration downlink node. | Check the Root Rule Chain wiring. |
| Downlink event with status ERROR | The encoder found no deviceName in the message metadata, or the Downlink connection string, Downlink topic name, or Send permission is wrong. |
Read the error text in the event. Check the originator fields node in the Root Rule Chain, and compare the downlink settings with tb-send and tb-downlink in the Azure portal. |
| Downlink event is OK, nothing in the downlink subscription | The downlink topic had no subscription when the message arrived, or a subscription filter rejected it. | Create the subscription before you trigger the downlink. Check its filter rules. |
To read debug events, open the integration or converter, click Events, and select an event: In is the received data, Out is the converter result, and Error holds the error text.
See Also
Section titled “See Also”- Integrations overview — how integrations, converters, uplinks, and downlinks fit together.
- Uplink data converter — decoder inputs, output format, and scripting patterns.
- Downlink data converter — encoder reference.
- Remote Integration — run the integration outside the ThingsBoard cluster.
- TBEL — built-in functions and syntax for converter scripts.
- Service Bus queues, topics, and subscriptions — messaging model and subscription filters.
- Service Bus Explorer — send, peek, and receive messages in the Azure portal.
Was this helpful?