# IoT Lab 2
###### tags: `SRM2021`
# Part A: Sending data to a cloud based platform (UBIDOTS)
:::info
**All the code necessary for this Lab session is available here [](https://www.dropbox.com/sh/dnfdlycjtupv751/AADjgCtLsdaLkE6zGjOjXQdMa?dl=0)**
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:

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):

choose:

and add a name, like (**use the name that you want!!**):

You'll get:

Now click on the device name and you'll get to the variables creation section:

click on "Add Variable" and create a "Raw" type variable. **Use the name that you want**:

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:

In my case I have:

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).

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:

:::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.

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.**
:::
# Part B: Data to Telegram Bot
In this Lab you'll have to do something similar to the previous one, but this time the data from the TTN have to be accessed using a Telegram bot. The final result should be somehting like this:

What you have to do first is create your own Bot. To generate an Access Token, you have to talk to the BotFather following a few simple steps as described here: https://core.telegram.org/bots#6-botfather
Basically, you need a Telegram account and the Telegram app installed in your smartphone or computer.
The "dialogue" will be something like this:

To program the Bot you can use, as a skeleton, the file `lab5.py`.
You can execute your Bot either in your computer or in repl.it and test it using a smartphone with Telegram.
This package is necessary to program the Bot:
```
https://github.com/python-telegram-bot/python-telegram-bot
```
If you are using your computer, than you'll have to install it using:
```
$ pip install python-telegram-bot
```
or, if you are using `repl.it`, you have to istall it from the Packages menu:

and typing in the search field `python-telegram-bot` and then on the **+** button
You should eventually get to something like this:

Fill in the places in `lab5.py` where the text `___FILL_IN_HERE___` is found with the proper values.
:::danger
4. Comprueba que el Bot funciona.
Recuerda que los parametros necesarios para leer datos desde TTN son:
```
Broker: eu1.cloud.thethings.network
Username: lopys2ttn@ttn
Password: NNSXS.A55Z2P4YCHH2RQ7ONQVXFCX2IPMPJQLXAPKQSWQ.A5AB4GALMW623GZMJEWNIVRQSMRMZF4CHDBTTEQYRAOFKBH35G2A
Topic: v3/+/devices/#
```
Entrega alguna captura de pantalla de su uso. Algo asi:

:::
:::danger
5. Modifica el Bot para que pueda devolver el valor de temperatura, humedad y luminosidad en función de la petición.
Tienes que obtener algo asi:

Entrega el fichero python.
:::