KEMBAR78
MQTT Device API Reference - ThingsBoard | PDF | Client–Server Model | Computer Data
0% found this document useful (0 votes)
35 views18 pages

MQTT Device API Reference - ThingsBoard

The MQTT Device API Reference for ThingsBoard Community Edition provides comprehensive documentation on using the MQTT protocol for IoT devices, including setup, telemetry upload, and attributes management. It covers key concepts such as MQTT basics, client library setup, and various APIs for publishing and subscribing to device data. The document also includes examples and commands for interacting with the ThingsBoard server using MQTT.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views18 pages

MQTT Device API Reference - ThingsBoard

The MQTT Device API Reference for ThingsBoard Community Edition provides comprehensive documentation on using the MQTT protocol for IoT devices, including setup, telemetry upload, and attributes management. It covers key concepts such as MQTT basics, client library setup, and various APIs for publishing and subscribing to device data. The document also includes examples and commands for interacting with the ThingsBoard server using MQTT.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Community Edition
Products Services Use Cases Customers Company


On this page

Getting
Getting started Documentation
Started Devices Library Guides Installation
Search
MQTT basics
Client libraries setup
Architecture
MQTT ConnectAPI FAQ
Key-value format
Telemetry upload API
Attributes API
Publish attribute update to the server
Request attribute values from the server
Subscribe to attribute updates from the server
JSON value support
RPC API
Server-side RPC
Client-side RPC
Claiming devices
Device provisioning
Firmware API
Protocol customization
Next steps

MQTT Device API Reference

Getting started

MQTT basics
MQTT is a lightweight publish-subscribe messaging protocol,probably making it the
most suitable for various IoT devices. You can find more information about MQTT
here.

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 1/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

ThingsBoard server nodes act as an MQTT Broker that supports QoS levels 0 (at most
once) and 1 (atEdition
Community least once) and
Products a set of configurable
Services Use Cases topics.
Customers Company


Client libraries setup
Getting Started Documentation Devices Library Guides
Search Installation
You can find a large number of MQTT client libraries on the web. Examples in this
article will be based on Mosquitto and MQTT.js. In order to set up one of those tools,
Architecture API FAQ
you can use the instructions in our Hello World guide.

MQTT Connect
In this article, we will use access token device credentials in this article and they will
be referred to later as $ACCESS_TOKEN. The application needs to send MQTT
CONNECT message with username that contains $ACCESS_TOKEN.

Possible return codes, and their reasons during the connect sequence:

0x00 Connected - Successfully connected to ThingsBoard MQTT server.

0x04 Connection Refused, bad username or password - Username is empty.

0x05 Connection Refused, not authorized - Username contains invalid


$ACCESS_TOKEN.

The alternative authentication option is to use X.509 Certificates or Basic MQTT


Credentials - combination of client id, username and password.

Now you are ready to publish telemetry data on behalf of your device. We will use
simple commands to publish data over MQTT in this example. Select your OS:

MQTT MQTT
Linux or macOS Windows

Install mqtt client for Ubuntu:

sudo apt-get install mosquitto-clients

Install cURL for macOS:

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 2/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

brew install mosquitto-clients


Community Edition
Products Services Use Cases Customers Company


Replace $THINGSBOARD_HOST_NAME and $ACCESS_TOKEN with corresponding
values.
Getting Started Documentation Devices Library Guides
Search Installation
mosquitto_pub -d -q 1 -h "$THINGSBOARD_HOST_NAME" -p "1883" -t "v1/devic

Architecture API FAQ

For example, $THINGSBOARD_HOST_NAME reference your local installation,


$ACCESS_TOKEN is ABC123:

mosquitto_pub -d -q 1 -h "localhost" -p "1883" -t "v1/devices/me/telemet

Successful output should look similar to this one:

1 Client mosqpub|xxx sending CONNECT


2 Client mosqpub|xxx received CONNACK
3 Client mosqpub|xxx sending PUBLISH (d0, q1, r0, m1, 'v1/devices/me/t
4 Client mosqpub|xxx received PUBACK (Mid: 1)
5 Client mosqpub|xxx sending DISCONNECT

Note: Since ThingsBoard 3.2, you are able to use basic MQTT credentials
(combination of client id, username and password) and customize topic
names and payload type using Device Profile. See more info here.

Key-value format
By default, ThingsBoard supports key-value content in JSON. Key is always a string,
while value can be either string, boolean, double, long or JSON. For example:

1 {
2 "stringKey":"value1",

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 3/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

3 "booleanKey":true,
Community
4 Edition
Products
"doubleKey":42.0, Services Use Cases Customers Company


5 "longKey":73,
6 "jsonKey": {
Getting Started Documentation Devices Library Guides
Search Installation
7 "someNumber": 42,
8 "someArray": [1,2,3],
Architecture API FAQ
9 "someNestedObject": {"key": "value"}
10 }
11 }

However, it is also possible to send data via Protocol Buffers. Please refer to the MQTT
transport type configuration section in device profile article for more details.

Using custom binary format or some serialization framework is also possible. See
protocol customization for more details.

Telemetry upload API


In order to publish telemetry data to ThingsBoard server node, send PUBLISH
message to the following topic:

v1/devices/me/telemetry

The simplest supported data formats are:

{"key1":"value1", "key2":"value2"}

or

[{"key1":"value1"}, {"key2":"value2"}]

Please note that in this case, the server-side timestamp will be assigned to
uploaded data!

In case your device is able to get the client-side timestamp, you can use following
format:
https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 4/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

{"ts":1451649600512, "values":{"key1":"value1", "key2":"value2"}}


Community Edition
Products Services Use Cases Customers Company


Where 1451649600512 is a unix timestamp with milliseconds precision. For example,
Getting
the valueStarted Documentation
‘1451649600512’ Devices
corresponds to ‘Fri, 01 JanLibrary
2016Search Guides
12:00:00.512 GMT’ Installation

Architecture API
Below are the examples FAQ
of commands for publishing different types of telemetry
data.

Don’t forget to replace demo.thingsboard.io with your host and $ACCESS_TOKEN with
your device’s access token. In this example, the hostname references live demo
server.

Example 1. Publish data as an object without timestamp (server-side timestamp will


be used).

Execute the command:

Mosquitto MQTT.js

mosquitto_pub -d -q 1 -h "demo.thingsboard.io" -t "v1/devices/me/telemetry"

Telemetry data:

{"temperature":42}

Example 2. Publish data as an object without timestamp (server-side timestamp will


be used) using data from telemetry-data-as-object.json file.

Execute the command:

Mosquitto MQTT.js

mosquitto_pub -d -q 1 -h "demo.thingsboard.io" -t "v1/devices/me/telemetry"

The content of the JSON file:

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 5/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

1 {
Community Edition
Products Services Use Cases Customers Company


2 "stringKey": "value1",
3 "booleanKey": true,
Getting
4 Started Documentation
"doubleKey": 42.0, Devices Library Guides
Search Installation
5 "longKey": 73,
6 "jsonKey":
Architecture API { FAQ
7 "someNumber": 42,
8 "someArray": [1,2,3],
9 "someNestedObject": {"key": "value"}
10 }
11 }

Example 3. Publish data as an array of objects without timestamp (server-side


timestamp will be used) using data from telemetry-data-as-array.json file.

Execute the command:

Mosquitto MQTT.js

mosquitto_pub -d -q 1 -h "demo.thingsboard.io" -t "v1/devices/me/telemetry"

The content of the JSON file:

[{"key1":"value1"}, {"key2":true}]

Example 4. Publish data as an object with timestamp (telemetry timestamp will be


used) using data from telemetry-data-with-ts.json file.

Execute the command:

Mosquitto MQTT.js

mosquitto_pub -d -q 1 -h "demo.thingsboard.io" -t "v1/devices/me/telemetry"

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 6/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

The content of the JSON file:


Community Edition
Products Services Use Cases Customers Company


1 {
2 "ts": 1451649600512,
Getting
3 Started
"values": Documentation
{ Devices Library Guides
Search Installation
4 "stringKey": "value1",
Architecture
5 API FAQtrue,
"booleanKey":
6 "doubleKey": 42.0,
7 "longKey": 73,
8 "jsonKey": {
9 "someNumber": 42,
10 "someArray": [1, 2, 3],
11 "someNestedObject": {
12 "key": "value"
13 }
14 }
15 }
16 }

Attributes API
ThingsBoard attributes API allows devices to

Upload client-side device attributes to the server.

Request client-side and shared device attributes from the server.

Subscribe to shared device attributes from the server.

Publish attribute update to the server


In order to publish client-side device attributes to ThingsBoard server node, send
PUBLISH message to the following topic:

v1/devices/me/attributes

Below are the examples of how to publish client-side device attributes.

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 7/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Don’t forget to replace demo.thingsboard.io with your host and $ACCESS_TOKEN with
your device’s access
Community token. In this
Edition
Products example,Use
Services the hostname
Cases references
Customers live demo
Company


server.

Example 1. Publish client-side attributes update.


Getting Started Documentation Devices Library Guides
Search Installation
Telemetry data:

Architecture
{"attribute1":API FAQ "attribute2": true}
"value1",

Execute the command:

mosquitto_pub -d -h "demo.thingsboard.io" -t "v1/devices/me/attributes" -u "

Example 2. Publish client-side attributes update using data from new-attributes-


values.json file.

The content of the “new-attributes-values.json” file:

1 {
2 "attribute1": "value1",
3 "attribute2": true,
4 "attribute3": 42.0,
5 "attribute4": 73,
6 "attribute5": {
7 "someNumber": 42,
8 "someArray": [1,2,3],
9 "someNestedObject": {"key": "value"}
10 }
11 }

Execute the command:

Mosquitto MQTT.js

mosquitto_pub -d -h "demo.thingsboard.io" -t "v1/devices/me/attributes" -u

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 8/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Community Edition
Products Services Use Cases Customers Company


Request attribute values from the server
Getting Started Documentation Search Devices Library Guides Installation
In order to request client-side or shared device attributes to ThingsBoard server
node, send PUBLISH message to the following topic:
Architecture API FAQ
v1/devices/me/attributes/request/$request_id

where $request_id is your integer request identifier. Before sending PUBLISH


message with the request, client needs to subscribe to

v1/devices/me/attributes/response/+

The following example is written in javascript and is based on mqtt.js. Pure


command-line examples are not available because subscribe and publish need to
happen in the same mqtt session.

Save the “mqtt-js-attributes-request.js” file to your PC. Don’t forget to replace the
hostname “demo.thingsboard.io” to your host. In this example, the hostname
references live demo server.

The content of the "mqtt-js-attributes-request.js" file:

1 var mqtt = require('mqtt')


2 var client = mqtt.connect('mqtt://demo.thingsboard.io',{
3 username: process.env.TOKEN
4 })
5
6 client.on('connect', function () {
7 console.log('connected')
8 client.subscribe('v1/devices/me/attributes/response/+')
9 client.publish('v1/devices/me/attributes/request/1', '{"clientKe
10 })
11
12 client.on('message', function (topic, message) {

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 9/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

13 console.log('response.topic: ' + topic)


Community
14 Edition
Products Services
console.log('response.body: Use
' + Cases Customers
message.toString()) Company


15 client.end()
16 })
Getting Started Documentation Devices Library Guides
Search Installation

Execute the command. Don’t forget to replace $ACCESS_TOKEN with your device’s
Architecture API FAQ
access token.

1 export TOKEN=$ACCESS_TOKEN
2 node mqtt-js-attributes-request.js

Result:

{"client":{"attribute1":"value1","attribute2":true}}

Please note, the intersection of client-side and shared device attribute keys is
a bad practice! However, it is still possible to have same keys for client,
shared or even server-side attributes.

Subscribe to attribute updates from the server


In order to subscribe to shared device attribute changes, send SUBSCRIBE message
to the following topic:

v1/devices/me/attributes

When a shared attribute is changed by one of the server-side components (such as


the REST API or the Rule Chain), the client will receive the following update:

{"key1":"value1"}

For the following example, don’t forget to replace demo.thingsboard.io with your host
and $ACCESS_TOKEN with your device’s access token. In this example, the hostname
references live demo server.

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 10/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Execute the command:


Community Edition
Products Services Use Cases Customers Company


Mosquitto MQTT.js

Getting Started Documentation Search Devices Library Guides Installation


mosquitto_sub -d -h "demo.thingsboard.io" -t "v1/devices/me/attributes" -u

Architecture API FAQ

JSON value support


We have added support of JSON data structures to telemetry and attributes API to
simplify work with device configuration. JSON support allows you to both upload from
the device, and push nested objects to the device. You can store one configuration
JSON as a shared attribute and push it to the device. You can also process the JSON
data in the rule engine and raise alarms, etc.

Therefore, this improvement minimizes the number of Database operations when


ThingsBoard stores the data. For example, “temperature” and “humidity” would be
stored as separate rows in SQL or NoSQL databases in order to efficiently aggregate
this data for visualization. Since there is no need to aggregate JSON data, we can
store all the content as one row instead of separate rows for each configuration item.
In some of our environments, it is possible to decrease the number of database
operations more than 10 times by aggregating multiple parameters within one JSON.

Learn more about JSON value support with the video.

RPC API

Server-side RPC
In order to subscribe to RPC commands from the server, send SUBSCRIBE message to
the following topic:

v1/devices/me/rpc/request/+

Once subscribed, the client will receive individual commands as a PUBLISH message
to the corresponding topic:

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 11/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

v1/devices/me/rpc/request/$request_id
Community Edition
Products Services Use Cases Customers Company


where $request_id is an integer request identifier.
Getting Started Documentation Devices Library Guides
Search Installation
The client should publish the response to the following topic:

Architecture API FAQ


v1/devices/me/rpc/response/$request_id

The following example is written in javascript and is based on mqtt.js. Pure


command-line examples are not available because subscribe and publish need to
happen in the same mqtt session.

Save the “mqtt-js-rpc-from-server.js” file to your PC. Don’t forget to replace the
hostname “demo.thingsboard.io” with your host. In this example, the hostname
references live demo server.

The content of the "mqtt-js-rpc-from-server.js" file

1 var mqtt = require('mqtt');


2 var client = mqtt.connect('mqtt://demo.thingsboard.io',{
3 username: process.env.TOKEN
4 });
5
6 client.on('connect', function () {
7 console.log('connected');
8 client.subscribe('v1/devices/me/rpc/request/+')
9 });
10
11 client.on('message', function (topic, message) {
12 console.log('request.topic: ' + topic);
13 console.log('request.body: ' + message.toString());
14 var requestId = topic.slice('v1/devices/me/rpc/request/'.length);
15 //client acts as an echo service
16 client.publish('v1/devices/me/rpc/response/' + requestId, message)
17 });

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 12/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Now, follow these steps:


Community Edition
Products Services Use Cases Customers Company


Use RPC debug terminal widget in your ThingsBoard instance;

Execute
Getting the command
Started to subscribe toDevices
Documentation RPC commands
Library from
Search the serverInstallation
Guides using the
command below. Don’t forget to replace $ACCESS_TOKEN with your device’s access
token.
Architecture API FAQ
1 export TOKEN=$ACCESS_TOKEN
2 node mqtt-js-rpc-from-server.js

Send an RPC request “connect” to the device using RPC debug terminal widget;

You should receive a response from the device.

In case your MQTT device is a gateway, ThingsBoard will send a server-side RPC
(notification) about changes on provisioned device entities.
Your MQTT gateway device will receive a service RPC about removal or renaming of
device to properly resolve such events.

Client-side RPC
In order to send RPC commands to server, send PUBLISH message to the following
topic:

v1/devices/me/rpc/request/$request_id

where $request_id is an integer request identifier. The response from server will be
published to the following topic:
https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 13/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

v1/devices/me/rpc/response/$request_id
Community Edition
Products Services Use Cases Customers Company


The following example is written in javascript and is based on mqtt.js. Pure
Getting Started
command-line Documentation
examples Devices
are not available because Library Guides
Search
subscribe Installation
and publish need to
happen in the same mqtt session.

Architecture API FAQ


Save the “mqtt-js-rpc-from-client.js” file to your PC. Don’t forget to replace the
hostname “demo.thingsboard.io” to your host. In this example, the hostname
references live demo server.

The content of the "mqtt-js-rpc-from-client.js" file

1 var mqtt = require('mqtt');


2 var client = mqtt.connect('mqtt://demo.thingsboard.io', {
3 username: process.env.TOKEN
4 });
5
6 client.on('connect', function () {
7 console.log('connected');
8 client.subscribe('v1/devices/me/rpc/response/+');
9 var requestId = 1;
10 var request = {
11 "method": "getCurrentTime",
12 "params": {}
13 };
14 client.publish('v1/devices/me/rpc/request/' + requestId, JSON.stri
15 });
16
17 client.on('message', function (topic, message) {
18 console.log('response.topic: ' + topic);
19 console.log('response.body: ' + message.toString());
20 });

Now, follow these steps:

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 14/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Add two nodes to the Rule Chain: “script” and “rpc call reply”;
Community
In the scriptEdition
Products
node enter theServices
function: Use Cases Customers Company


return {msg: {time:String(new Date())}, metadata: metadata, msgType: msgType
Getting Started Documentation Devices Library Guides
Search Installation

Architecture API FAQ


Send request to the server. Don’t forget to replace $ACCESS_TOKEN with your
device’s access token.

1 export TOKEN=$ACCESS_TOKEN
2 node mqtt-js-rpc-from-client.js

You should receive a response from the server.

Claiming devices
Please see the corresponding article to get more information about the Claiming
devices feature.

In order to initiate claiming device, send PUBLISH message to the following topic:

v1/devices/me/claim

The supported data format is:

{"secretKey":"value", "durationMs":60000}

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 15/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Please note that the above fields are optional. In case the secretKey is not
Community Edition
Products Services Use Cases Customers Company


specified, the empty string as a default value is used. In case the durationMs
is not specified, the system parameter device.claim.duration is used (in the
file /etc/thingsboard/conf/thingsboard.yml).
Getting Started Documentation Devices Library Guides
Search Installation

Architecture
API FAQ
Device provisioning
Please see the corresponding article to get more information about the Device
provisioning feature.

In order to initiate device provisioning, send Provisioning request to the following


topic:

/provision

Also, you should set username or clientId to provision.

The supported data format is:

1 {
2 "deviceName": "DEVICE_NAME",
3 "provisionDeviceKey": "u7piawkboq8v32dmcmpp",
4 "provisionDeviceSecret": "jpmwdn8ptlswmf4m29bw"
5 }

Firmware API
When ThingsBoard initiates an MQTT device firmware update, it sets the fw_title,
fw_version, fw_checksum, fw_checksum_algorithm shared attributes. To receive the
shared attribute updates, the device has to subscribe to

v1/devices/me/attributes/response/+

Where

+ is the Wildcard character.

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 16/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

When the MQTT device receives updates for fw_title and fw_version shared
attributes,
Community it has to send PUBLISH
Edition
Products message to
Services Use Cases Customers Company


v2/fw/request/${requestId}/chunk/${chunkIndex}
Getting Started Documentation Devices Library Guides
Search Installation

Where
Architecture API FAQ
${requestId} - number corresponding to the number of firmware updates. The
${requestId} has to be different for each firmware update.
${chunkIndex} - number corresponding to the index of firmware chunks. The
${chunkID} are counted from 0. The device must increment the chunk index for each
request until the received chunk size is zero.
And the MQTT payload should be the size of the firmware chunk in bytes.

For each new firmware update, you need to change the request ID and subscribe to

v2/fw/response/+/chunk/+

Where

+ is the Wildcard character.

Protocol customization
MQTT transport can be fully customized for specific use-case by changing the
corresponding module.

Next steps
Getting started guides - These guides provide quick overview of main
ThingsBoard features. Designed to be completed in 15-30 minutes.

Data visualization - These guides contain instructions on how to configure


complex ThingsBoard dashboards.

Data processing & actions - Learn how to use ThingsBoard Rule Engine.

IoT Data analytics - Learn how to use rule engine to perform basic analytics
tasks.

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 17/18
7/23/24, 11:53 PM MQTT Device API Reference | ThingsBoard Community Edition

Hardware samples - Learn how to connect various hardware platforms to


ThingsBoard.
Community Edition
Products Services Use Cases Customers Company


Advanced features - Learn about advanced ThingsBoard features.

Contribution
Getting StartedandDocumentation
Development - Learn about contribution
Devices Library
Search and development
Guides in
Installation
ThingsBoard.

Architecture API FAQ

Get Use Contact


Documentation Blog Services
Started cases us

© 2024 The ThingsBoard Authors

https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server 18/18

You might also like