>

MQTT API Reference

What is MQTT?

MQTT is an “Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium (Source: MQTT.org).

MQTT is specially useful to push data to your devices. Imagine a cloud-controlled device to open/close a door remotely. In the case of HTTP, the device would have to continously make GET requests to the Ubidots server to see if there’s a change in a variable, say “Door Control Variable”, and then take an action depending on the last reading. This takes a lot of requests and it’s not entirely a real-time interaction since it depends of the polling frequency. With MQTT, the device can “listen” to the cloud and only get notified when there’s a change in the variable. This way, the connection between the device and the cloud is left open but data only travels when necessary, saving battery, network bandwith and improving the real-time experience.

To interact with an MQTT broker you’ll need an MQTT client. Here’s a quick list of MQTT clients and resources:

  • 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 connectoin, since it appears not to allow blank passwords.

  • MQTT Inspector: A general MQTT testing app for iOS (iPhone and iPad).

Authentication

NodeJS MQTT authentication example


var mqtt = require("mqtt");
var client  = mqtt.connect('mqtt://things.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});

Our MQTT broker is available at the following URLs:

For Educational users::

things.ubidots.com port: 1883

For Business users::

industrial.api.ubidots.com port: 1883

To interact with it, you will need a TOKEN. The easiest way to get yours is clicking on “API Credentials” under your profile tab:

To connect to our MQTT broker, use your Ubidots TOKEN as the MQTT username, and leave the password field empty.

MQTT Credentials Ubidots
username –> 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.

Publish

Publish values to a Device

NodeJS publish value of several variables example


var mqtt = require("mqtt");
var client  = mqtt.connect('mqtt://things.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});
var variablesPublish = {"temperature": 24.5, "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);
    });

To send values to several variables to the broker you have to send a PUBLISH message with the topic:

/v1.6/devices/{LABEL_DEVICE}

to the url:

mqtt://things.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}

Accepted values for “value”, “timestamp” and “context” keys are:

value
required
Float or integer number.
Example: "value": "35.8" or "value": 35.8
context A JSON object with optional meta data as “key”:“value” pairs.
Example: "context": {"lat": 6.1, "lng": -35.1, "status": "driving"}
timestamp Optional timestamp in milliseconds, according to the POSIX standard.
Example: "timestamp":1376056359000

Publish values to one variable

NodeJS publish example


var mqtt = require("mqtt");
var client  = mqtt.connect('mqtt://things.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});
client.publish("/v1.6/devices/label_ds/label_var",
'{"value": 24.5}', {'qos':1, 'retain':false},
function(err, response){
  console.log(response);
});

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_DEVICE}/{LABEL_VARIABLE}

to the url:

mqtt://things.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}]

Accepted values for “value”, “timestamp” and “context” keys are:

value
required
Float or integer number.
Example: "value": "35.8" or "value": 35.8
context A JSON object with optional meta data as “key”:“value” pairs.
Example: "context": {"lat": 6.1, "lng": -35.1, "status": "driving"}
timestamp Optional timestamp in milliseconds, according to the POSIX standard.
Example: "timestamp":1376056359000

Publish values with Retained Messages

NodeJS publish example with Retained Message

var mqtt = require("mqtt");
var client  = mqtt.connect('mqtt://things.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});
client.publish("/v1.6/devices/label_ds/label_var",
'{"value": 24.5}', {'qos':1, 'retain':true},
function(err, response){
  console.log(response);
});

If a MQTT message has set the retained flag to true, the broker will be in charge of storing the last received message and the corresponding QoS for that topic. If a new client subscribes to a topic with a retained value, it will receive a message right after subscribing with the topic’s retained value. Also, it is important to metiond that for each topic only one retained message will be stored by the broker.

Retained messages are useful for control purposes in order to make available for your device the last stored value in an Ubidots variable.

IMPORTANT NOTE: Ubidots broker take all the messages as retained, even if you do not set to true the retained flag.

Subscribe

Subscribe to a variable

NodeJS subscription to a variable


var mqtt = require("mqtt");
var client  = mqtt.connect('mqtt://things.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});
client.subscribe({"/v1.6/devices/label_ds/label_var": 1}, function(err, granted) {
  console.log(granted);
});
client.on('message', function(topic, message, packet) {
    //here you can process updates from the broker
});

Server Response

{"timestamp": 1526081983987, "context": {}, "value": 24.5, "id": "5af629c0bbddbd0ebd4a1e0d"}

NodeJS subscription to the last value of a variable


var mqtt = require("mqtt");
var client  = mqtt.connect('mqtt://things.ubidots.com', {username:'c74qFmzI7ikTmZ3dFvF3e2hPEmCfu5', password:""});
client.subscribe({"/v1.6/devices/label_ds/label_var/lv": 1}, function(err, granted) {
  console.log(granted);
});
client.on('message', function(topic, message, packet) {
    //here you can process updates from the broker
});

Server Response

24.5

Once the MQTT client is successfully authenticated you should be able to subscribe to a variable so you can get notified when the variables receives data.

It’s important to metion that Ubidots broker take all the messages as retained, so once you subscribe to a topic you will get a new message with the last value received in the variable to which you have just subscribed. For example, if the client N°1 publishes message to /v1.6/devices/label_ds/label_var and the client N°2 subscribes to /v1.6/devices/label_ds/#, then the client N°2 will receive the retained message sent by client N°1 directly after subscribing and also any message received in the variables of the subscribed topic.

From the last example, the subscribed topic does not match but it will also receive a retained message as the subscribe action included a wildcard, which allows you to subscribe to updates of the whole device, if you wish to refer about wildcards, please go to the next section. Also, the subscribing client can identify if a received message was a retained message or not, because the broker sends out retained messages with the retained flag still set to true so the client can then decide on how to process the message.

To subscribe to a variable, send a SUBSCRIBE message to the url:

mqtt://things.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.

/v1.6/devices/{LABEL_DEVICE}/{LABEL_VARIABLE}: This will return a JSON document with the structure of the right.

/v1.6/devices/{LABEL_DEVICE}/+/lv: This will return the last value of all the variables available in the device assigned.

/v1.6/devices/{LABEL_DEVICE}/#: This will return a JSON document of all the variables available in the device assigned with the structure of the right.

/v1.6/devices/#: This will return every message sent over the MQTT broker at your entire Ubidots account (all the devices created).

JSON structure

{
    "value": value,
    "timestamp": timestamp,
    "context": context,
    "id": id_value
}

where value is a float, context a JSON document, timestamp is the number of milliseconds since 01-01-1970 00:00:00.000 UTC, and id the unique id of the value.

In the response the QOS parameter will be 1 if the subscription was successful, otherwise it will be something like 128 or 0 which means the broker will not send updates for the specified topic.



GET STARTED
Join thousands of fellow IoT developers using Ubidots to build production-ready IoT solutions.

Sign up for free