Introduction

Welcome to the Ubidots REST API hardware docs. Here you would reference how to send or retrieve data from your hardware devices using our supported communication protocols: HTTP, MQTT and TCP/UDP.

The purpose of this section is to help you understand what happens in the backstage when communicating with Ubidots, so you can replicate this in your firmware. For this reason, we avoid the use of examples using libraries. However, if you’d like to use one of our libraries (Python, C, and more), check out our compatible devices and API clients sections.

How Ubidots Works?

Every time a device updates a sensor value in a variable, a data-point or "dot" is created. Ubidots stores dots that come from your devices inside variables, and these stored dots have corresponding timestamps:

Each dot contains these items:

Item Description Mandatory
value A numerical value. Ubidots accepts up to 16 floating-point length numbers. YES
timestamp Unix Epoch time, in milliseconds. If not specified, then our servers will assign one upon reception. NO
context An arbitrary collection of key-value pairs. Mostly used to store the latitude and longitude coordinates of GPS devices. NO

Values

A numerical value. Ubidots accepts up to 16 floating-point length numbers.

{"value" : 34.87654974}

Timestamps

A timestamp, as best described here, is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch. Please keep in mind that when you send data to Ubidots, you must set the timestamp in milliseconds; also, if you retrieve a dot's timestamp, it will be in milliseconds.

"timestamp" : 1537453824000

The above timestamp corresponds to Thursday, September 20, 2018 2:30:24 PM.

PRO-TIP: A useful tool to convert between Unix timestamps and human-readable dates is Epoch Converter.

Context

Numerical values are not the only data type supported; you can also store string or char data types inside what we call context. The context is a key-value object that allows you to store not only numerical but also string values. An example use of the context could be:

"context" : {"status" : "on", "weather" : "sunny"}

A context is commonly used to store the latitude and longitude coordinates of your device for GPS/tracking application use cases. All Ubidots maps uses the lat and lng keys from a dot's context to extract the coordinates of your device, in that way you just need to send a single dot with the coordinates values in the variable context to plot a map instead of sending separately both latitude and longitude in two different variables. Below you can find a typical context with coordinates values:

"context" : {"lat":-6.2, "lng":75.4, "weather" : "sunny"}

Please note that you can mix both string and numerical values in the context. If your application is for geo-localization purposes, make sure that the coordinates are set in decimal degrees.

Time Series

Based on the above, we can illustrate an Ubidots time series like this:

Ubidots is an agnostic platform, this means that it does not really care what hardware device you are using, as long as you're able to interact with us through at least one of these protocols:

HTTP

HTTP is the main internet protocol for information exchange in the Internet. It also supports data encryption, which is usually called secure HTTP or HTTPs. When you use a web browser (MS Edge, Firefox, Google Chrome, etc) you are sending and receiving packages using HTTP or HTTPs. Because of this, it was not surprising to see HTTPs become a popular option for data exchange within IoT.

When a developer is to implement HTTP communication, then he should look for a RESTful Application Programming Interface, or REST API, which exposes all the endpoints required to interact with a third party application (like Ubidots). In this section, you can reference our REST API to understand how to send and retrieve data from our servers.

Note: Our goal with this section is to help you understand what’s happening behind when communicating with Ubidots, enabling you to replicate it within your own firmware. Because of this, we avoid using our custom libraries in all the examples.

HTTP requests

The following methods are specified within the HTTP standard:

HTTP Method Description
GET Used to retrieve information
POST Used to create a new element
PATCH Used to update existing elements
DELETE Used to delete existing elements

HTTP is a request/response protocol, this means that every request that you make is answered by the server. This response includes a number (response code) and a body. For example, when you make a request to retrieve a file on a webpage "(e.g. "Get me the file 'webside.html'" )", you build a GET request. If the request is correct, the server will typically return a 200 response code, along with the file requested (body).

Under the same logic, when a device sends a GET request to the Ubidots' server (i.e. requesting the last value of a variable), then the server sends back a response with the status of the request (response code), and a body, which would be the a value with its context and timestamp.

An HTTP request also needs the parameters below:

  • Host: Specifies the server you will be making HTTP requests to.

  • Path: This is typically the remaining portion of the URL that specifies the resource you want to consume, be it a variable or a device. For example, if an API endpoint is: industrial.api.ubidots.com/api/v1.6/devices/my-device then the path would be /api/v1.6/devices/my-device

  • Headers: Define the operating parameters of the HTTP request such as authentication, Content-Type, Content-Length, etc.

  • Body/payload: In the case of POST and PATCH requests, this is the data sent by your device to the server. GET requests typically do not have a body because they are meant to request data, not to send data.

Ubidots accepts data as JavaScript Object Notation or JSON. JSON is a typical HTTP data type, it is a collection of name/value pairs. In various programming languages, this is treated as an object, record, struct, dictionary, hash table, keyed list, or associative array. It is also human readable and language independent. An example of a JSON data type that Ubidots accepts can be referenced below:

{"temperature": {"value":10, "timestamp": 1534881387000, "context": {"machine": "1st floor"}}}

A typical HTTP request to Ubidots should be set as below:

POST {PATH} HTTP/1.1<CR><LN>
Host: {HOST}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN>
Content-Length: {PAYLOAD_LENGTH}<CR><LN><CR><LN>
{PAYLOAD}
<CR><LN>

Where:

  • {PATH}: Path to the resource to consume
    Example: /api/v1.6/variables/ to get user's variables information.
  • {HOST}: Host URL. Example: industrial.api.ubidots.com
  • {USER_AGENT}: An optional string used to identify the type of client, be it by application type, operating system, software vendor or software version of the requesting user agent.
    Examples: ESP8266/1.0, Particle/1.2
  • {TOKEN}: Unique key that authorizes your device to ingest data inside your Ubidots account.
  • {PAYLOAD_LENGTH}: The number of characters of your payload.
    Example: The payload {"temperature": 20} will have a content-length of 19.
  • {PAYLOAD}: Data to send.
    Example: {"temperature": 20}

PRO TIP: The easy way of handle HTTP and HTTPs requests is by using cURL, a command line tool. To learn how to install cURL on Windows, MacOSX or Linux please refer to this guide.

API URLs

API access can be over HTTP or secure HTTP, HTTPs, using the following endpoints based on your Ubidots Account type.

Security Note: We strongly advise to use HTTPs to make sure your data travels encrypted, avoiding the exposure of your API token and/or sensor data.

HTTP

Ubidots Account Endpoint Port
Educational http://things.ubidots.com 80
Industrial http://industrial.api.ubidots.com 80

HTTPs

Ubidots Account Endpoint Port
Educational https://things.ubidots.com 443
Industrial https://industrial.api.ubidots.com 443

Ubidots supports SSL v1.1, TLS v1.1 and v1.2. You can download our root certificates in different formats:

  • PEM file: A certificate chain with two root certificates from our certificate authorities (CAs).
  • DER file: Same as the PEM file, with an alternative encoding.
  • CRT file: Same as the PEM file, with a different extension. Often referred to as .crt, .cert or .cer.

Fixed IPs

Ubidots also supports fixed IPs address for data ingestion, but we highly advise to our users to implement their firmware routines using the dns endpoints instead of fixed IPs, as these last ones may change in the future.

Ubidots Account ipv4 ipv6 Port
Educational 50.23.124.68 2607:f0d0:2101:39::2 80/443
Industrial 169.55.61.243 2607:f0d0:3:b::2 80/443

HTTP Authentication

Every request requires a token. A token is an unique key that authorizes your device to ingest data inside your Ubidots account.

The easiest way to get yours is clicking on "API Credentials" under your profile tab:

ubidots_token

Also, 6 hour valid tokens can be generated using your account API-KEY. If you desire to learn how to do it, please refer the Ubidots REST Software API reference.

There are two ways to send a token in a request:

  1. Send the token as parameter in the endpoint, setting it with the ?token= expression. This is the easiest one to implement but the most unsecure method to send your authentication credentials.

  2. Send the token as a request header. For this, use the X-Auth-Token header.

Security Note: While sending your token as a URL parameter can be quite comfortable in some devices, we only advise to do this for prototyping stages. For production stages, we strongly advise sending the token using the X-Auth-Token header.

GET
https://industrial.api.ubidots.com/api/

Send data

Our REST API allows you send data to the platform in two different ways:

  • Send data to a device
  • Send data to a variable

If you're looking for more advanced API capabilities, such as editing a device name, or listing all of your devices, please refer to our Ubidots Software REST API Reference.

Send data to a device

Request structure:

POST /api/v1.6/devices/{DEVICE_LABEL} HTTP/1.1<CR><LN>
Host: {Endpoint}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN>
Content-Length: {PAYLOAD_LENGTH}<CR><LN><CR><LN>
{PAYLOAD}
<CR><LN>

Expected Response:

HTTP/1.1 200 OK<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:35:06 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Cookie<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{"{VARIABLE_LABEL}": [{"status_code": 201}]}<CR><LN>
0<CR><LN>

The easiest way to send values to Ubidots is by specifying your Device label in the request path and making a POST request to it.

Replace the {DEVICE_LABEL} with the unique label of the desired device to send data to. If the device does not exist in your Ubidots account, it will be automatically created. Device labels can contain any alphanumerical character, without blank spaces, i.e weather-station, my-home, esp8266.

To set the variables values, just create a JSON data payload as below

Nº Variables JSON structure
One {"variable-label": VALUE}
Multiple {"variable-label-1": {"value": VALUE, "timestamp": TIMESTAMP, "context": {"key": VALUE}}, ... , "variable-label-n": {"value": VALUE, "timestamp": TIMESTAMP, "context": {"key": VALUE}}}

timestamp and context parameters are optional.

NOTE 1:: By default, the Ubidots backend will take the latitude and longitude values inside any variable labeled as "gps", "location", position or "coordinates" automatically to get your device coordinates in all of the map widgets. Alternatively, you change the default location variable.

NOTE 2: All timestamps must be in milliseconds. If you set a timestamp for a variable value, it will be stored with the date represented by it. You can easily convert dates to timestamps values here.

Examples

  • Single dot: {"temperature": 27}

  • Multiple dots: {"temperature": 27, "humidity": 55, ... ,"pressure": 78}

Including additional keys like context and timestamp

  • Single dot: {"position": {"value" : 1, "timestamp": 1514808000000, "context":{"lat":-6.2, "lng":75.4, "name" : "John"}}}

  • Multiple dots: {"temperature": {"value": 27, "timestamp": 1514808000000}, "humidity": 55, "pressure": {"value": 78, "context":{name" : "John"}}}

POST
https://industrial.api.ubidots.com/api/devices/{DEVICE_LABEL}
POST
https://things.ubidots.com/api/devices/{DEVICE_LABEL}

Send a single dot (Educational users)

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"temperature": 27}' https://things.ubidots.com/api/v1.6/devices/my-new-device
            
            

Send a single dot (Industrial users)

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"temperature": 27}' https://industrial.ubidots.com/api/v1.6/devices/my-new-device
            
            

Send a dot with coordinates

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"position": {"value" : 1, "timestamp": 1514808000000, "context":{"lat":-6.2, "lng":75.4}}}' https://industrial.ubidots.com/api/v1.6/devices/my-new-device
            
            

Send multiple dots

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"temperature": {"value": 27, "timestamp": 1514808000000}, "humidity": 55, "pressure": {"value": 78, "context":{name" : "John"}}}' https://industrial.ubidots.com/api/v1.6/devices/my-new-device
            
            

Send data to a variable

You can also send one or multiple dots to a single variable.

Request structure:

POST /api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values HTTP/1.1<CR><LN>
Host: {Endpoint}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN>
Content-Length: {PAYLOAD_LENGTH}<CR><LN><CR><LN>
{PAYLOAD}
<CR><LN>

Expected Response:

HTTP/1.1 201 Created<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:50:55 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Accept, Cookie<CR><LN>
Location: http://industrial.api.ubidots.com/api/v1.6/values/{VARIABLE_ID}<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{"url": "http://things.ubidots.com/api/v1.6/values/{VARIABLE_ID}", "value": 27.0, "timestamp": 1536101455822, "context": {}, "created_at": "2018-09-04T22:50:55.822035Z"}<CR><LN>
0<CR><LN>

In the path specified above, replace the {DEVICE_LABEL} and {VARIABLE_LABEL} keys with the unique labels of the Ubidots device and variable you wish to send data to. If the specified device and/or variable do not exist, they will be automatically created.

Examples

  • Single dot: {"value":27}

  • Single dot with context and timestamp: {"value":27, "timestamp": 1514808000000, "context":{"lat":37.773, "lng":-122.431}}

  • Multiple dots (must include the timestamp of each value): [{"value": 27, "timestamp":1514808000000}, {"value": 12, "timestamp":1514808900000}]

Send a single dot (Educational users)

POST
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values
POST
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values
curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"value": 27}' https://things.ubidots.com/api/v1.6/devices/my-new-device/my-variable/values
            
            

Send a single dot (Industrial users)

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"value": 27}' https://industrial.ubidots.com/api/v1.6/devices/my-new-device/my-variable/values
            
            

Send multiple dots

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '[{"value": 27, "timestamp":1514808000000}, {"value": 12, "timestamp":1514808900000}]' https://industrial.ubidots.com/api/v1.6/devices/my-new-device/my-variable/values
            
            

Retrieve data

The Ubidots REST API allows you to retrieve data from the platform data base. A typical application for data retrieval is actuators like motors or lights control.

Retrieve mutiple values from a variable

Request structure:

GET /api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values HTTP/1.1<CR><LN>
Host: {Endpoint}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN><CR><LN>

Expected Response:

HTTP/1.1 200 OK<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:35:06 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Cookie<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{"count": true, "previous": null, "results": [{PAYLOAD_WITH_VALUES}], "next": {URL_WITH_ADDITIONAL_VALUES}}<CR><LN>
0<CR><LN>

In the path specified above, replace the {DEVICELABEL} and {VARIABLE_LABEL} keys with the unique labels of the Ubidots device and variable you desired to retrieve data from. This _path returns by default the last 50 values stored of your variable. You can manage the number of dots to retrieve using the page_size parameter in your path:

/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values/?page_size=2

The path above retrieves the last 2 dots of your variable.

Ubidots API also allows you to filter the values to be retrieved by date range, number of dots, and more. If you desire to go deep into this kind of requests, please check the Ubidots Software REST API Reference.

GET
https://industrial.api.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values
GET
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/values

Get the last two values from a variable (Educational users)

curl -X GET -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" https://things.ubidots.com/api/v1.6/devices/my-device/my-variable/values/?page_size=2
            
            

Get the last two values from a variable (Industrial users)

curl -X GET -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" https://industrial.api.ubidots.com/api/v1.6/devices/my-device/my-variable/values/?page_size=2
            
            

Retrieve the last value from a variable

A typical control application in general only needs to ask for the last value of a variable, i.e, if you push a virtual switch at Ubidots, you just need to know what is the last value of the variable related with that switch to take actions on any actuators at your side.

Request structure:

GET /api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/lv HTTP/1.1<CR><LN>
Host: {Endpoint}<CR><LN>
User-Agent: {USER_AGENT}<CR><LN>
X-Auth-Token: {TOKEN}<CR><LN>
Content-Type: application/json<CR><LN><CR><LN>

Expected Response:

HTTP/1.1 200 OK<CR><LN>
Server: nginx<CR><LN>
Date: Tue, 04 Sep 2018 22:35:06 GMT<CR><LN>
Content-Type: application/json<CR><LN>
Transfer-Encoding: chunked<CR><LN>
Vary: Cookie<CR><LN>
Allow: GET, POST, HEAD, OPTIONS<CR><LN><CR><LN>
{PAYLOAD_LENGTH_IN_HEXADECIMAL}<CR><LN>
{LAST_VALUE}<CR><LN>
0<CR><LN>

In the path specified above, replace the {DEVICE_LABEL} and {VARIABLE_LABEL} keys with the unique labels of the Ubidots device and variable you desired to retrieve data from.

GET
https://industrial.api.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/lv
GET
https://things.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}/lv

Get the last value from a variable (Educational users)

curl -X GET -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" https://things.ubidots.com/api/v1.6/devices/my-device/my-variable/lv
            
            

Get the last value from a variable (Industrial users)

curl -X GET -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" https://industrial.api.ubidots.com/api/v1.6/devices/my-device/my-variable/lv
            
            

HTTP Examples

In this section, you will find different examples that show you how to handle data with Ubidots to start monitoring and controlling your IoT Devices.

At the right side, you can find each example provided in different programming languages. Please, refer to your preferred programming language by clicking the tabs located on the right upper side of the page.

Sending a geopoint

Ubidots provides multiples ways to start tracking your IoT devices, so here we are going to show you how to send coordinates to Ubidots in order to start with a GPS IoT Solution.

To learn more about the Ubidots Maps Features, please check this guide.

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"location":{"value": 1, "context":{"lat":37.773, "lng":-122.431}}}' https://industrial.api.ubidots.com/api/v1.6/devices/my-new-device
            
            

Sending a string value

The String values provide additional information to the dot which is being sent. As a basic example here, let's suppose that you are deploying a Weather Station which provides you the Weather Status as a String value. At this point, the Weather Status ought to be sent in the context of the dot.

To learn more of how to display the context of a dot in the Ubidots Dashboard, please check this guide.

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"weather":{"value": 1, "context":{"weather-status": "sunny"}}}' https://industrial.api.ubidots.com/api/v1.6/devices/my-new-device
            
            

Sending values in bulk from a datalogger

In case you desire to send information to Ubidots from a data logger which is in charge of taking samples for long periods of time, you can simply do it by managing the values registered plus the time when the value was registered.

curl -X POST -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -H "Content-Type: application/json" -d '{"my-sensor":[{"value": 27, "timestamp":1514808000000}, {"value": 30, "timestamp":1514808900000}, {"value": 31, "timestamp":1514809800000}, {"value": 29, "timestamp":1514810700000}, {"value": 27, "timestamp":1514768400000}]}' https://industrial.api.ubidots.com/api/v1.6/devices/my-new-device
            
            

Retrieve the last value for control

This is typically used for remote control applications. Your devices would retrieve the last value of a variable, and then act based on that value. It is also used to remotely manage your devices, like for example changing a sampling rate or performing a remote reboot.

To learn more about the control features that Ubidots offer, please check this guide.

Example Request

curl -X GET -H "X-Auth-Token: BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" "https://industrial.api.ubidots.com/api/v1.6/devices/my-new-device/control/lv"
            
            

Response codes

The Ubidots REST API uses the following response codes when you make an HTTP request, with them you can know your request status and errors if there are any:

Code Meaning
200 Ok -- Successful request.
201 Created -- Successful request + an item (device or variable) was created.
202 Accepted -- The request has been accepted for processing, but the processing has not been completed.
204 One of the fields is incorrect and the request is not saved -- Please verify it's a valid JSON string and that the fields are the ones expected by the endpoint (string, object or float).
400 Bad Request -- Error due to an invalid body in your request. Please verify it's a valid JSON string and that the fields are the ones expected by the endpoint (string, object or float).
401 Invalid API key -- Please verify your API Key.
402 Payment required -- Please verify your balance.
403 Forbidden -- This token is not valid. Please verify your token.
404 Not Found -- We couldn’t find the URL you're trying to access. This might be due to a wrong device label or ID, a wrong variable label or ID, or simply a typo in the URL of the request.
405 Method Not Allowed -- This API endpoint does not accept the method used. Check our API docs to see the allowed methods.
415 Unsupported media type -- The payload is in a format not supported by this method on the target resource.
420 You have exceeded your API limits -- To upgrade your API limits contacts the Ubidots team
423 Device does not receive data because it is disabled
429 Too many requests -- Many requests sent in a given amount of time ("rate limiting")
50* Internal Error -- We're having issues with our servers. Please check our status page.

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 from the cloud to your devices. Imagine a cloud-controlled device to open/close a door remotely. In the case of HTTP, the device would have to continuously 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 is necessary, saving battery, network bandwidth and improving the real-time experience.

In this section you will find the documentation needed to handle your devices with Ubidots over MQTT.

For a detailed explation of the Ubidots MQTT API Reference click here

Quality of Service

In MQTT, the quality of service, QoS for short, guarantees the delivery of a specific message. There are three leves of QoS:

  • 0, At most once: This level does not guarantee the message delivery, it would be labeled as best-effort server QoS.

  • 1, At least once: This level guarantees that the message is delivered at least one time to the receiver. The receiver answer with a puback packet, if this puback packet is not received the sender sends again the message.

  • 2, Exactly once: Guarantees that the message is received only once by the receptor. It is the slowest packet interchange QoS as it requires two request/response flows.

Ubidots supports QoS up to 1 (at most once).

Broker URLs

API access can be over plain MQTT or secure MQTT with TLS, using the following endpoints based on your Ubidots Account type:

Non-TLS

Ubidots Account Endpoint Port
Educational things.ubidots.com 1883
Industrial industrial.api.ubidots.com 1883

TLS

Ubidots Account Endpoint Port
Educational things.ubidots.com 8883
Industrial industrial.api.ubidots.com 8883

You can download the Ubidots PEM certificate for TLS here

Security Note: We strongly advise to use MQTT with TLS to make sure your data travels encrypted, avoiding the exposure of your API token and/or sensor data to third parties.

Fixed IPs

Ubidots also supports fixed IPs address for data ingestion, but we highly advise to our users to implement their firmware routines using the dns endpoints instead of fixed IPs, as these last ones may change in the future.

Ubidots Account ipv4 ipv6 Port
Educational 50.23.124.68 2607:f0d0:2101:39::2 80/443
Industrial 169.55.61.243 2607:f0d0:3:b::2 80/443

MQTT Authentication

To interact with the Ubidots MQTT broker you'll need a token. A token is an unique key that authorizes your device to interact with Ubidots API.

ubidots_token

To establish the connection with the MQTT broker you need to assign the username and password following the table below:

MQTT Credentials Parameter
Username Ubidots token
Password any character - not required -

Send data (Publish)

To send data, set the unique Device label in the topic path.

Ubidots accepts MQTT data JavaScript Object Notation or JSON. JSON is a collection of name/value pairs in various programming languages, this is treated as an object, record, struct, dictionary, hash table, keyed list, or associative array. It is also human readable and language independent. An example of a JSON data type that Ubidots accepts can be referenced below:

{"temperature": {"value":10, "timestamp": 1534881387000, "context": {"machine": "1st floor"}}}

The keys context and timestamp are optional.

NOTE 1:: The Ubidots backend will take the latitude and longitude values inside any variable labeled as "gps", "location", position or "coordinates" automatically to get your device coordinates in all of the map widgets. You may change the default location variable from Ubidots web user interface.

NOTE 2: All timestamps must be in milliseconds. If you set a timestamp for a variable value, it will be stored with the date represented by it. You can easily convert dates to timestamps values here.

If you wish to send more than one value, then you need to separate them using commas. Below you can reference a typical structure for MQTT payloads:

Variables JSON structure
One {"VARIABLE-LABEL": {"value":VALUE, "timestamp": TIMESTAMP, "context":{"KEY":VALUE}}}
Multiple {"VARIABLE-LABEL_1": {"value":VALUE, "context":{"KEY":VALUE}}, ... , "VARIABLE-LABEL_n": {"value":VALUE, "context":{"KEY": VALUE}}}

keys context and timestamp are optional.

Examples

Note: All the bash examples from this section makes use of the Eclipse Mosquitto library, if you wish to test them please install it using the official instructions

  • Single dot: {"temperature": 27}

  • Multiple dots: {"temperature": 27, "humidity": 55, ... ,"pressure": 78}

Including additional keys like context and timestamp

  • Single dot: {"position": {"value" : 1, "timestamp": 1514808000000, "context":{"lat":-6.2, "lng":75.4, "name" : "John"}}}
  • Multiple dots:{"temperature": {"value": 27, "timestamp": 1514808000000}, "humidity": 55, "pressure": {"value": 78, "context":{name" : "John"}}}
PUB
/v1.6/devices/{DEVICE_LABEL}/

Send a single dot (Educational users)

mosquitto_pub -h "things.api.ubidots.com" -t "/v1.6/devices/weather-station" -u "p4uuT2O25AJwv7ncADLoVhQfImwRQW" -p 1883 -q 1 -m '{"temperature": 27}'
            
            

Send a single dot (Industrial users)

mosquitto_pub -h "industrial.api.ubidots.com" -t "/v1.6/devices/weather-station" -u "BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -p 1883 -q 1 -m '{"temperature": 27}'
            
            

Send a dot with coordinates

mosquitto_pub -h "industrial.api.ubidots.com" -t "/v1.6/devices/weather-station" -u "BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -p 1883 -q 1 -m '{"position": {"value" : 1, "timestamp": 1514808000000, "context":{"lat":-6.2, "lng":75.4}}}' 
            
            

Send multiple dots

mosquitto_pub -h "industrial.api.ubidots.com" -t "/v1.6/devices/weather-station" -u "BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -p 1883 -q 1 -m '{"temperature": {"value": 27, "timestamp": 1514808000000}, "humidity": 55, "pressure": {"value": 78, "context":{name" : "John"}}}'
            
            

Retrieve data (Subscribe)

Similar to the GET function in HTTP, subscribe is the method to obtain values with a huge difference: you do not have to be continuously ask the server for each value in your custom script. For example, if a variable's value changes, Ubidots will automatically update you (the user) of any changes. Thus saving data requests and processing time for your device and overall project functionality and expenses. Because of this, MQTT is a communication protocol adviced to implement firmware routines to control actuators.

Retrieve the last value of a variable

Replace the {DEVICE_LABEL} and {VARIABLE_LABEL} with the unique label of the device and the variable to subscribe for retrieving values update. If the specified Device or Variable do not exist, you will not able to establish the subscription with it.

SUB
/v1.6/devices/{DEVICE_LABEL}/{LABEL_VARIABLE}/lv

Subscribe to a variable (Educational users)

mosquitto_sub -h "things.ubidots.com" -t "/v1.6/devices/weather-station/temperature/lv" -u "p4uuT2O25AJwv7ncADLoVhQfImwRQW" -p 1883 -q 1
            
            

Subscribe to a variable (Industrial users)

mosquitto_sub -h "industrial.api.ubidots.com" -t "/v1.6/devices/weather-station/temperature/lv" -u "BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB" -p 1883 -q 1
            
            

MQTT Examples

In this section, you will find different examples that show you how use MQTT to implement several IoT applications.

At the right side, you can find each example provided in different programming languages. Please, refer to your preferred programming language by clicking the tabs located on the right upper side of the page.

GPS Tracker

Ubidots provides multiples ways to start tracking your IoT devices, so here we are going to show you how to send coordinates to Ubidots in order to start with a GPS IoT Solution.

To learn more about the Ubidots Maps Features, please check this guide.

mosquitto_pub -p 1883 -h industrial.api.ubidots.com -t "/v1.6/devices/my-new-device" -u 'BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB' -m '{"location":{"value": 1, "context":{"lat":37.773, "lng":-122.431}}}' -d -q 1
            
            

Weather description

The String values provide additional information to the dot which is being sent. As a basic example here, let's suppose that you are deploying a Weather Station which provides you the Weather Status as a String value. At this point, the Weather Status ought to be sent in the context of the dot.

To learn more of how to display the context of a dot in the Ubidots Dashboard, please check this guide.

 mosquitto_pub -p 1883 -h industrial.api.ubidots.com -t "/v1.6/devices/my-new-device" -u 'BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB' -m '{"weather":{"value": 1, "context":{"weather-status": "sunny"}}}' -d -q 1
            
            

Retrieve the last value for control

This is the perfect solution for you in case your desire to control remotely the garage doors, home lights, alarm system, or any asset you desire.

To learn more about the control features that Ubidots offer, please check this guide.

Example Request

mosquitto_sub -p 1883 -h industrial.api.ubidots.com -t "/v1.6/devices/my-new-device/control/lv" -u 'BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB' -d -q 1
            
            

TCP / UDP

The Transmision Control Protocol, TCP, is one of the most popular data transport protocols, so much it is supported by default in most hardware devices. Its main advantage comes in the packet size, usually lower than packets sent using HTTP (which in fact, uses TCP as transport layer). TCP is "connection oriented", which means it implements confirmation methods to guarantee that data is received by the destinatary.

The User Datagram Protocol, UDP, is also a very popular protocol that, unlike TCP, it is "connectionless". This means it does not implements any confirmation method to guarantee that data is received by the destinatary. This can be an advantage in applications where simplicity and speed are more important than reliability.

TCP and UDP are similar in the sense that they share the structure of endpoint + port.

TCP Authentication

Ubidots offers TCP/UDP communication on the PORT 9012 pointing to the following URLs. Please choose the right one based on your Ubidots License:

Ubidots Account URL
Educational things.ubidots.com
Industrial industrial.api.ubidots.com

To send data to Ubidots using TCP or UDP broker you need your Ubidots TOKEN. The easiest way to get it is by clicking on "API Credentials" under your profile tab:

ubidots_token

Send Data

Structure

Ubidots created a pre-defined structure to understand the content of your TCP/UDP packets. If you wish to implement a custom structure, please get in touch with our support channel.

{USER_AGENT}|POST|{TOKEN}|{DEVICE_LABEL}:{DEVICE_NAME}@{GLOBAL_TIMESTAMP}=>{VARIABLE_LABEL}:{VALUE}${CONTEXT_KEY_1}={CONTEXT_VALUE}${CONTEXT_KEY_2}={CONTEXT_VALUE}@{VARIABLE_TIMESTAMP}|end

Where:

  • {USER_AGENT}: Mandatory. Contains a characteristic string that allows to identify the application type, operating system, software vendor or software version of the requesting software user agent. Examples: ESP8266/1.0, Particle/1.2

  • {DEVICE_LABEL}: Mandatory. The device label to publish values. If it does not exist, Ubidots will create it. Blank spaces are not allowed.
    Examples: Weather-station, living-room

  • {DEVICE_Name}: Optional. The device name to publish values. If not set, the device name will be set using the device label. This parameter is useful when you have as device label your device MAC and you wish to show to final users a friendly name. Blank spaces are not allowed.
    Examples: Street-42-weather-station, living-room-floor-1

  • {GLOBAL_TIMESTAMP}: Optional. Unix time stamp. If set, any variable value without timestamp will use this one to store values. Must be in milliseconds.If not set, Ubidots will add it automatically with the actual timestamp in UTC.
    Examples: 1534282544356

  • {VARIABLE_LABEL}: Mandatory. The variable label that will store the dot. If it does not exist, Ubidots will create it.
    Examples: temperature, wind-speed

  • {VALUE}: Mandatory. Dot value. You can use a dot to set float numbers.
    Examples: 1.0005, 2

  • {CONTEXT_KEY}: Optional. If set, you must specify a context value. You can add as many context key as you wish splitting them with a '$' char.
    Examples: lat, lng, name, surname.

  • {CONTEXT_VALUE}: Optional. The context key value.
    Examples (based on keys above): -6.2, 75.4, "John", "Smith"

  • {VARIABLE_TIMESTAMP}: Optional. Unix time stamp. If set, the variable will use this one to store dots. This parameter has precedence among the global timestamp. Must be in milliseconds.If not set, Ubidots will add it automatically with the actual timestamp in UTC.
    Examples: 1534282544356

Server Response

Ubidots will answer 'Ok' if the request is correct. If multiple values are sent, 'Ok' strings (one per variable in the request) splitted by pipelines '|' will be returned. If there is an error with the request, Ubidots will return 'ERROR'

Examples

Send a single dot to a device with name green-truck and device label 5b7356ccbbddbd594df54555 stored inside the variable speed:

ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|5b7356ccbbddbd594df54555:green-truck=>speed:2|end

Send a single dot to a device named as green-truck with device label 5b7356ccbbddbd594df54555 stored inside the variable speed at 2017/12/31 8:00 UTC:

ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|5b7356ccbbddbd594df54555:green-truck=>speed:2@1514707200000|end

Send a single dot to a device labeled as green-truck with api label 5b7356ccbbddbd594df54555 stored inside the variable speed at 2017/12/31 8:00 UTC with latitude, longitude and other keys inside its context:

ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|5b7356ccbbddbd594df54555:green-truck=>speed:2$lat=-6.2$lng=75.4$name=John$surname=Smith@1514707200000|end

Send multiple values

ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|weather-station=>temperature:20,humidity:35|end

Send a single dot (Educational users)

echo -n "ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|5b7356ccbbddbd594df54555:green-truck=>speed:2|end" | telnet things.ubidots.com 9012
            
            

Send a single dot (Industrial users)

echo -n "ESP8266/1.0|POST|BBFF-kiFdJvtV3OWTY56M0rKluUGm71lzzn6kboWpbWpfhJFah7fL6p1kcks|green-truck:5b7356ccbbddbd594df54555=>speed:2|end" | telnet industrial.api.ubidots.com 9012
            
            

Send multiple dots (Educational users)

echo -n "ESP8266/1.0|POST|p4uuT2O25AJwv7ncADLoVhQfImwRQW|weather-station=>temperature:20,humidity:35|end" | telnet things.ubidots.com 9012
            
            

Send multiple dots (Industrial users)

echo -n "ESP8266/1.0|POST|BBFF-kiFdJvtV3OWTY56M0rKluUGm71lzzn6kboWpbWpfhJFah7fL6p1kcks|weather-station=>temperature:20,humidity:35|end" | telnet industrial.api.ubidots.com 9012
            
            

Retrieve Data

Structure

Ubidots TCP/UDP supports the payload request structure below for retrieving dots values

{USER_AGENT}|LV|{TOKEN}|{DEVICE_LABEL}:{VARIABLE_LABEL}|end

where:

  • {USER_AGENT}: Mandatory. Contains a characteristic string that allows to identify the application type, operating system, software vendor or software version of the requesting software user agent. Examples: ESP8266/1.0, Particle/1.2

  • {DEVICE_LABEL}: Mandatory. The device label to publish values. If it does not exist, Ubidots will create it. Blank spaces are not allowed.
    Examples: Weather-station, living-room

  • {VARIABLE_LABEL}: Mandatory. The variable label that will store the dot. If it does not exist, Ubidots will create it.
    Examples: temperature, wind-speed

Server Response

Ubidots will answer with the last value of the variable requested. If there is an error with the request, Ubidots will return 'ERROR'

Examples

Get the last value from the variable speed inside a device labeled with api label green-truck:

ESP8266/1.0|LV|p4uuT2O25AJwv7ncADLoVhQfImwRQW|green-truck:speed|end

Get last variable value (Educational users)

echo -n "ESP8266/1.0|LV|p4uuT2O25AJwv7ncADLoVhQfImwRQW|green-truck:speed|end" | telnet things.ubidots.com 9012
            
            

Get last variable value (Industrial users)

echo -n "ESP8266/1.0|LV|BBFF-kiFdJvtV3OWTY56M0rKluUGm71lzzn6kboWpbWpfhJFah7fL6p1kcks|green-truck:speed|end" | telnet industrial.api.ubidots.com 9012
            
            
Show examples in:
Ubidots API docs [hardware engineers]