1. What is MQTT?
MQTT is specially useful to push data to your devices. Imagine an IoT application that needs to send downlink messages to thousands of devices. In the case of HTTP, each device would have to continuously make GET requests to the server to see if there’s new data available for them. That would mean thousands of unnecessary requests per second, and it’s not entirely a real-time interaction since it depends of the polling frequency.
With MQTT, the devices can subscribe or “listen” to the cloud and only get notified when there’s new data for them. This way, the connection between the device and the cloud is left open but data only travels when necessary, saving battery, network bandwidth, and improving the real-time experience.
To interact with an MQTT broker, your device, gateway, or application has to support this protocol. Read the instructions from the manufacturer to make sure it's supported.
A good way to learn about MQTT and the supported payloads is to tinker with existing clients or libraries, such as:
Paho: The Eclipse Paho project provides open-source MQTT clients for C/C++, Python, Java, Javascript, Go and C#.
MQTT.fx: A JavaFX based MQTT client.
MQTT Lens: A Google Chrome extension that connects to an MQTT broker and is able to publish and subscribe to MQTT topics. If you’re using this tool to test Ubidots MQTT API, then enter any random text in its password field of the connection, since it appears to not allow blank passwords.
MQTT Inspector: A general MQTT testing app for iOS (iPhone and iPad).
2. General Features
Here are the general features of Ubidots' MQTT broker. To learn more, read our MQTT technical documentation.
Feature | Description | Supported |
TLS Authentication | Encrypted communication using PEM keys. | YES |
Quality of Service (QoS) |
| YES, only up to QoS=1*.
*If you require QoS = 2, please get in touch with us in order to deploy a dedicated MQTT broker for you. |
Last Will Testament (LWT) | Messages that are sent by the broker once the connection with the client has been interrupted (when the client has gone offline). | NO*
*If you require LWT, please get in touch with us in order to deploy a dedicated MQTT broker for you. |
Persistent sessions | Persistent sessions are a way of having the broker save relevant information about the client in case the connection is lost. Once the connection is back up, the broker will have the connection information immediately. | NO*
(Setting the cleanSession flag to false won't make effect). Once the connection has been lost, the client must establish the connection settings again.
*If you require persistent sessions, please get in touch with us in order to deploy a dedicated MQTT broker for you. |
Inactive clients | Connection from MQTT clients that don't receive any packets. | The connection of inactive clients subscribed to the broker will be closed after 90 minutes.
*If you require longer sessions, please get in touch with us in order to deploy a dedicated MQTT broker for you. |
Fixed IP address | The IP address of the broker, which is useful when the client's firmware does not have DNS resolving capabilities. | See the current IP address of the broker here.
We highly advise implementing DNS routines instead of fixed IPs, as these may change in the future*.
*If you require a fixed IP, please get in touch with us in order to deploy a dedicated MQTT broker for you. |
3. Authentication
Our MQTT broker is available at the following URL:
industrial.api.ubidots.com
Port: 1883
To interact with it, you will need a token. The easiest way to get yours is by clicking on "API credentials", found under the account drop-down button in your Ubidots account.
To connect to our MQTT broker, use your Ubidots token as the MQTT username, and leave the password field empty.
Username → Ubidots token.
Password → Leave blank.
If the connection is successful, you should be able to publish and subscribe to MQTT topics, otherwise the broker will return an error and disconnect the client.
4. Publish
To send values to several variables you have to send a PUBLISH message with the topic:
/v1.6/devices/{LABEL_DEVICE}
To this URL:
mqtt://industrial.api.ubidots.com
The payload should be a JSON dictionary where every key corresponds to the unique label of each variable, and every value can be any of the following:
A float or integer number. For example:
{"temperature": 10, "humidity": 50}
A JSON object containing the "value", "timestamp" and "context" of the data point. For example:
{"temperature": {"value":10, "timestamp": 1464661369000, "context":{"lat":-6.2, "lng":75.4, "my-key":"hello there"}}, "humidity": 50}
A list of JSON objects, each one containing the “value” key, and optionally the “timestamp” and “context” of the data point. For example:
{"temperature":[{"value": 10, "timestamp":1464661369000}, {"value": 12, "timestamp":1464661369999}], "humidity": 50}
4.1. Publish values to one variable
Once the MQTT client is successfully authenticated you should be able to publish values to the broker. To send a value to the broker you have to send a PUBLISH message with the topic:
/v1.6/devices/{LABEL_OF_DEVICE}/{LABEL_OF_VARIABLE}
To this URL:
mqtt://industrial.api.ubidots.com
The body of the POST request can be either:
A JSON object containing the "value" key, and optionally the "timestamp" and "context" of the data point. For example:
{"value":10}
Or
{"value":10, "timestamp": 1464661369000, "context":{"lat":-6.2, "lng":75.4}}
A list of JSON objects, each one containing the "value" key, and optionally the "timestamp" and "context" of the data point:
[{"value": 10, "timestamp":1464661369000}, {"value": 12, "timestamp":1464661369999}]
5. Subscribe
5.1. Subscribe to a variable
Once the MQTT client is successfully authenticated, you should be able to subscribe to a variable so you can get notified when it receives data.
To subscribe to a variable, send a SUBSCRIBE message to this URL:
mqtt://industrial.api.ubidots.com
With the topic:
/v1.6/devices/{LABEL_DEVICE}/{LABEL_VARIABLE}/lv
This will return the last value of the variable as a single float value. This makes it easier to parse in microcontrollers.
NOTE: The subscription topic must be all in lowercase.
Alternatively, you can use this topic:
/v1.6/devices/{LABEL_DEVICE}/{LABEL_VARIABLE}
This will return a JSON document with the following structure:
{ "value": value, "timestamp": timestamp, "context": context, "id": id_value}
NOTE: The subscription topic must be all in lowercase.
6. Examples
6.1. Node.js MQTT authentication example
var mqtt = require("mqtt");var client = mqtt.connect('mqtt://industrial.api.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});
6.2. Node.js: Publish data to a Device
var mqtt = require("mqtt");var client = mqtt.connect('mqtt://industrial.api.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});var variablesPublish = {"temperature": 10, "luminosity": {"value":10}, "wind_speed": [{"value": 11, "timestamp":10000}, {"value": 12, "timestamp":13000}]};var json = JSON.stringify(variablesPublish);client.publish("/v1.6/devices/label_ds", json, {'qos': 1, 'retain': false}, function (error, response) { console.log(response); });
6.3. Node.js: Publish data to a single variable
var mqtt = require("mqtt");var client = mqtt.connect('mqtt://industrial.api.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});client.publish("/v1.6/devices/label_ds/label_var",'{"value": 10.3}', {'qos':1, 'retain':false},function(err, response){ console.log(response);});
6.4. Node.js: Subscription to a variable
var mqtt = require("mqtt");var client = mqtt.connect('mqtt://industrial.api.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});client.subscribe({"/v1.6/devices/label_ds/variable_label": 1}, function(err, granted) { console.log(granted);});client.on('message', function(topic, message, packet) { //here you can process updates from the broker});
6.5. Node.js: Subscription to the last value of a variable
var mqtt = require("mqtt");var client = mqtt.connect('mqtt://industrial.api.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});client.subscribe({"/v1.6/devices/label_ds/variable_label/lv": 1}, function(err, granted) { console.log(granted);});client.on('message', function(topic, message, packet) { //here you can process updates from the broker});