---
# System prepended metadata

title: Lab 4 - IoT - sending data to a cloud based platform (UBIDOTS)
tags: [LAB]

---

# Lab 4 - IoT - sending data to a cloud based platform (UBIDOTS)
###### tags: `LAB`

:::info
**All the code necessary for this Lab session is available in [Poliformat/RSE: Recursos/Laboratorio/código practicas laboratorio](https://poliformat.upv.es/x/1J91ll)**, or here: https://bit.ly/codigoRSE2021

You can execute the code either in your computer or online:


In your computer:
* You need to have python3 installed, and
* `$ sudo pip3 install paho-mqtt`

Online:
* create an account in https://repl.it
* and create a new python file:
 ![](https://i.imgur.com/oW5EJIc.png)

Click here for ["the documentation of the MQTT Paho API"](https://www.eclipse.org/paho/clients/python/docs/) 
:::


In this block you will experiment about how MQTT can be used to send data to a cloud based platform. This procedure allows you to store your data in a cloud based repository and to analyze your data with software tools made available by the used platform. For these experiments we will use the [Ubidots](https://ubidots.com/) plaftorm.


## Connecting to the Ubidots platform

You will have to first create your free account in the Ubidots platform here: https://ubidots.com/stem/

Then you have to add a **Device** (select first the "Devices" section in the top on the web page):
![](https://i.imgur.com/cmCWh9I.png =x200)
choose:
![](https://i.imgur.com/M7nUX31.png =x100)

and add a name, like (**use the name that you want!!**):
![](https://i.imgur.com/Bry2Axc.png =x200)

You'll get: 
![](https://i.imgur.com/4NAGDF3.png)


Now click on the device name and you'll get to the variables creation section:
![](https://i.imgur.com/ZLZWn9F.png =x300)

click on "Add Variable" and create a "Raw" type variable. **Use the name that you want**:
![](https://i.imgur.com/TbfMs8a.png =x300)


Now you have your web system prepared to receive the data 


## Sending data to Ubidots

Now you will send data to our device **using MQTT with Python**.
Take a look first to the Ubidots MQTT API Reference: https://ubidots.com/docs/hw/?language=Python#mqtt


The name of the broker for educational users is **"things.ubidots.com"**. To interact with it, you will need a TOKEN. To get yours click on “API Credentials” under your profile tab:

![](https://i.imgur.com/StmHEVg.png)

In my case I have:

![](https://i.imgur.com/pCmKyeQ.png)

To connect to the MQTT broker you'll have to use your **``Default Token``** as the MQTT username, and `None` as password.

The **topic** you have to use is **`/v1.6/devices/{LABEL_DEVICE}`** where you have to replace your value for the **API label** `{LABEL_DEVICE}` (e.g., mydevice_pm). 

![](https://i.imgur.com/lExOClB.png =x200)


The data must be represented using JSON. The simplest format is, for example: `{"temperature":10}` 


So, for example, to send the value 25 to variable `the_variable` of device ``mydevice_pm`` the code should look like:  

```python=
...
msg_to_be_sent = '{"the_variable":25}'
client.publish("/v1.6/devices/mydevice_pm", 
                payload=msg_to_be_sent, 
                qos=0, 
                retain=False)
...
```

You'll get:

![](https://i.imgur.com/YsboDek.png)

:::danger
1.- Repite los pasos anteriores con tus datos de Ubidots (credenciales y nombre del dispositivo y variable usandos)  y utilizando el codigo del  "producer" (`sipub.py`).
El codigo tiene que enviar cada vez un numero aleatorio entre 0 y 100. Te conviene utilizar un diccionario python y luego pasarlo a JSON.

**Tienes que entregar el fichero python.**
:::

:::info

1) Para generar un numero aleatorio, puedes utilizar esta funcion: `random.randint(0, 100)`
2) Para manejar los datos JSON, Python ofrece la clase `json`. Ejemplo:
```
>>> import json
>>> d = {'sensorId': 25}
Para pasar de un diccionario a un JSON:
>>> dj = json.dumps(d)
Para pasar de JSON a un diccionario:
>>> nd = json.loads(dj)
```

:::


## Creating dashbord elements.

Ubidots allows to visualize the data in various graphical ways.

Go to the Dashboard section and add new widget associated with the variable of your device.
![](https://i.imgur.com/YDQBZ4z.png)

See the alternatives you have and how they can be configured.

:::danger
2.- Crea una dashboard a tu gusto con los datos que has enviado en el ejercicion anterior.
Haz una captura de pantalla de la dashboard resultato y adjuntala al documento a entregar.
:::

## Sending data from TTN 

:::danger
3.- Utilizando como base el codigo del fichero `lab4_ex3.py`, escribe un programa que lee los datos desde TTN, como en la sesion de laboratorio anterior, selecciona una variable (p.ej. la temperatura), y la publica en Ubidots.

Los parametros necesarios para leer datos desde TTN son: 
``` 
Broker: eu1.cloud.thethings.network
Username: lopys2ttn@ttn
Password: NNSXS.A55Z2P4YCHH2RQ7ONQVXFCX2IPMPJQLXAPKQSWQ.A5AB4GALMW623GZMJEWNIVRQSMRMZF4CHDBTTEQYRAOFKBH35G2A
Topic: v3/+/devices/#
``` 
**Tienes que entregar el codigo python desarrollado.**

:::


