---
# System prepended metadata

title: 'Part 4: Ubidots (HTTP request on REST API)'
tags: [PyCom, ESP32, TA Stuff ESP32, Heltec]

---

# Part 4: Ubidots (HTTP request on REST API)
###### tags: `TA Stuff ESP32` `PyCom` `Heltec` `ESP32`

This tutorial covers how to work with Ubidots Stem, the IoT platform made by Ubidots. You will learn:
+ How to register and set up a dashboard in Ubidots.
+ How to send data over **HTTP requests** to your dashboard in Ubidots and visualize it on a gauge widget.

This tutorial is based on [Ubidots documentation](https://help.ubidots.com/en/articles/1658666-connect-a-fipy-pycom-board-to-ubidots)  on connecting a FiPy Pycom Board to Ubidots over their REST API. Before we dive into the how-to-make such a connection we should get familiar with Ubidots **Terms** in the next section.

## Ubidots terms 
Each IoT cloud platform uses its terminology for different actions and It would be valuable to know them before starting working with them. So before signing up and using Ubidots read the following terms, we gathered from [**Ubidots documentation**](). 

**Devices:** A Device in Ubidots is a virtual representation of a data source or simply, an asset taking in sensor data and transmitting said data through a connection protocol to Ubidots' cloud. We need to create a device before being able to upload values.  

**Variable:** Each device in Ubidots can hold 1 to N variables, once a device is created and receiving data from your hardware, the data will be presented in its raw or calculated form as a variable, so we need to add a variable for each sensor. Ubidots support two types of variables:
+ **Raw Variable:** *A variable is any raw data within a device in Ubidots if sent directly from your development board.*
+ **Synthetic Variable:** *Synthetic variable is a variable that results from the computation of other variables within Ubidots.*

**Dashboard:** Dashboards are human-machine interfaces where data is easily visualized. Your Ubidots account will let you create as many dashboards as needed, containing widgets and data visualizations to comprehend your data at a glance.  
**Widget:** Widgets are the building blocks of the dashboards and each dashboard could hold several widgets. Every widget has a different set of configuration options. Depending on the widget, you might be able to add one or several variables. For instance, the metric widget only supports one variable, while the line chart widget supports multiple variables.

**Events:** Events are messages triggered and delivered through Email, SMS, Telegrams, Slack, Voice call,s or webhook messages based on a customized design rule created in the application.

## Setting Environment in Ubidots
In this part we show how to set up **Devices**, **Variables**, **Dashboards**,  **Widgets**, and **Events** to receive a random value and from our development board shows it on a guage and base on it trigger an alarm which is an indicator changing color. follow these steps:

+ **Step 1:** Visit [**this link**](https://ubidots.com/stem/) to register an account on Ubidots. 
+ **Step 2:** Visit [**this link**](https://stem.ubidots.com/accounts/signin/) to sign in to your control panel.
+ **Step 3:** Follow the numbered steps on the screenshots to create your first *Device* in Ubidots.

Navigate to `Device >> Devices`.
![](https://i.imgur.com/MnXZ0xX.jpg)  
<br>  

Open device create from the right by pressing on `+`
![](https://i.imgur.com/RwiHRBM.jpg) 
<br>  

Choose a `Blank Device`
![](https://i.imgur.com/tXLcQOv.jpg) 
<br>  

Choose a `Name` and click on tick mark
![](https://i.imgur.com/rJKjWgV.jpg) 
<br>  

+ **Step 4:** After we created our **Device** we can open it and create our *Variables*, for this tutorial we create two on them one called $sensor$ it indicate a random value between `0` aned `100` send by our board and the second one is $alarm$ which based on the $sensor$ value we update it (if sensor get value less than 70 we assign `0` to alarm if more than 70 we assign `1` to it) later we use this to change an indicator (like a visual alarm Green/Red). Follow these steps:

Click on `Add Variable` then choose `Raw` and at the end give it a name. (like $alarm$ and $sensor$).
![](https://i.imgur.com/1OUrI7J.jpg) 
<br>  

After we create both variables our device panel should look like this:
![](https://i.imgur.com/x0DxuuG.jpg) 
<br>  

+ **Step 5:** Now we create a *Dashboard* which is a place to keep our visual **widgets**.  Follow numbered steps:  

Click on `Data >> Dashboards` then click on the `≡`
![](https://i.imgur.com/ASFWnHc.jpg) 
<br>  

Click on `+` sign
![](https://i.imgur.com/H98k1aO.jpg) 
<br>  

Choose a `name` then `save`
![](https://i.imgur.com/5H2MfuM.jpg) 
<br>  

+ **Step 6:** After creating dashboard we open it and create two *Widgets* in it. Follow the numbered steps:

Click on `Add new widget` then on `Gauge`
![](https://i.imgur.com/tiZ3ND3.jpg) 
<br>  

Then click on `Add variables` >> `Choose your device` >> `choose sensor variable` >> click on ✔ **(We do the same for our alarm variable with Indicator Widget)**
![](https://i.imgur.com/vTBNM7P.jpg) 
<br>  

+ **Step 7:** We also create some *Events* We want our **alarm variable** being active `1` when sensor receive a value more than 70 and make the **indicator** color red and if it receive a value below 70 in inactive the alarm `0` and make the indicator color green. Follow numbered steps below:

Click on `Data` then `Events`
![](https://i.imgur.com/7L8Rby4.jpg) 
<br>  

Set the trigger conditions
![](https://i.imgur.com/ucKftst.jpg) 
<br>  

Add an action
![](https://i.imgur.com/BGKv44N.jpg) 
<br>  

Choose `Set Variable`
![](https://i.imgur.com/mRcrSqO.jpg) 
<br>  

Connect the action to a variable (alarm here) and change its value. (We need to create two action one to set alarm `ON` one to to set it `OFF`
![](https://i.imgur.com/Kf4sUy9.jpg) 
<br>  

Click on `>`
![](https://i.imgur.com/GnABDZd.jpg) 
<br>  

Then click on ✔
![](https://i.imgur.com/GEEwdb1.jpg) 
<br>  

Finally your event panel should look like this:
![](https://i.imgur.com/cha4tin.jpg) 
<br>  


:::success
The environment is set and we have the dashboard in Ubidots, before we move to the next part we need to copy three things: 1. Our device name which was `heltecboard` (all small case letters) 2. Our variable name which was `sensor`  3. Your connection *TOKEN* on `Profile >> API Credentials >> Tokens`. We need these values for our connection in development board.
:::
  
## Using Ubidots REST API to upload data
As mentioned above in this project we try to use Ubidots REST API to set a random value between 0 and 100 every 5 seconeds. In your control panel the value will be represented in a guage and based on it if it is more than 70 active an indicator and make the color red otherwise turn it back to green. You need a library for this project and can download it [**here**](https://github.com/micropython/micropython-lib/blob/master/python-ecosys/urequests/urequests.py) create a file named `urequests.py` and put the content in it. Then create `main.py` and put the following code in it and upload it to your development board.  

:::info
You need to substitute **TOKEN**, **DEVICE_LABEL**, **VARIABLE_LABEL**, **WIFI_SSID**, and **WIFI_PASS** with yours.
:::

```python=
from network import WLAN
import urequests as requests
import machine
from machine import Pin
import time

TOKEN = "Your_Ubidots_Token" #Put here your TOKEN
DEVICE_LABEL = "Your_Device_Name" # Assign the device label desire to be send
VARIABLE_LABEL = "Your_Sensor_Name"  # Assign the variable label desire to be send
WIFI_SSID = "Your_WiFi_SSID" # Assign your the SSID of your network
WIFI_PASS = "Your_WiFi_Password" # Assign your the password of your network
DELAY = 5  # Delay in seconds

# WiFi connection
wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.INT_ANT)
wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000)
while not wlan.isconnected ():
    pass
print("Connected to Wifi\n")

# Builds the json to send the request
def build_json(variable, value):
    try:
        data = {variable: {"value": value}}
        return data
    except:
        return None

# Random number generator
def random_integer(upper_bound):
    return machine.rng() % upper_bound

# Sending data to Ubidots Restful Webserice
def sendData(device, variable, value):
    try:
        url = "https://industrial.api.ubidots.com/"
        url = url + "api/v1.6/devices/" + device
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        data = build_json(variable, value)

        if data is not None:
            print(data)
            req = requests.post(url=url, headers=headers, json=data)
            return req.json()
        else:
            pass
    except:
        pass

# Your device send a random value between 0 and 100 every five second to
# Ubidots
while True:
    value = random_integer(100)
    returnValue = sendData(DEVICE_LABEL, VARIABLE_LABEL, value)
    time.sleep(DELAY)

```

Your dashboard widgets should look like this after receiving data from your board. 
![](https://i.imgur.com/8cHa2Fj.jpg) 
<br>  

![](https://i.imgur.com/ePWkeVK.jpg) 
<br>  




<style>

.markdown-body code{
    font-size: 1em !important;
}
.markdown-body .a{
    font-size: 5em !important;
}
.markdown-body pre {
    background-color: #333;
    border: 1px solid #333 !important;
    color: #dfdfdf;
    font-weight: 600;
}
.token.operator, .token.entity,
.token.url, .language-css .token.string,
.style .token.string {
    background: #000;
}
.markdown-body table {
    display: table;
    padding: 1em;
    width: 100%;
}
.markdown-body table th,
.markdown-body table td,
.markdown-body table tr {
    border: none !important;
}
.markdown-body table tr {
    background-color: transparent !important;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2) !important;
}
</style>



