# Lab 3 - IoT - MQTT with Python
###### 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:

Click here for ["the documentation of the MQTT Paho API"](https://www.eclipse.org/paho/clients/python/docs/)
:::
This lab aims to offer you an hands-on experience with MQTT. You will perform experiments that will allow you to learn how to "publish" data and "subscribe" to get data.
## Part 1: Basic MQTT
In this session we will use a **public broker**. There are various public brokers (also called `sandboxes`) in the Internet. For example:
* `iot.eclipse.org` (https://iot.eclipse.org/projects/sandboxes/)
* `test.mosquitto.org` (http://test.mosquitto.org/)
* `broker.hivemq.com` (https://www.hivemq.com/public-mqtt-broker/)
An extensive list is available here: https://github.com/mqtt/mqtt.github.io/wiki/public_brokers
### A simple subscriber
File: `sisub.py` cointains the code of a simple python subscriber. This code connects to a public broker and subscribes to topic `$SYS/#`.
:::danger
1.- Ejecuta este codigo y explica el resultado obtenido
Detalla la respuesta en el documento a entregar.
:::
### A simple producer
File: `sipub.py` cointains the code of a simple python producer. This code connects to a public broker and periodically publishes random values to topic `"PMtest/rndvalue"`
:::danger
2.- Ejecuta este codigo (en otro terminal) y explica el resultado obtenido.
Detalla la respuesta en el documento a entregar.
:::
:::danger
3.- Modifica `sisub.py` para poder recibir los datos enviados por `sipub.py`.
Detalla la respuesta en el documento a entregar.
:::
### Some basic tests
#### One to many communication
MQTT is very useful when we have to distribute the same piece of information to various users... but we have to be careful with topics.
For example, using the code from Question 3, set as ``topic`` for the "subscriber" the value ``Spain/Valencia/UPV`` and execute it.
Now modify the code of the "producer" so that it uses the topic ``spain/valencia/upv`` and as the message use the text that you want. Execute the "producer".
:::danger
4.- Describe lo que obtienes y por que.
Detalla la respuesta en el documento a entregar.
:::
#### Retained messages:
Normally, if a publisher publishes a message to a topic, and **no one is subscribed** to that topic the message is simply discarded by the broker. If you want your broker to remember the last published message, you'll have to use the ``retained`` option.
Only one message is retained per topic. The next message published on that topic replaces the retained message for that topic.
**Substitute the code inside the `client.loop_start()/client.loop_stop()` section of `sipub.py` with the code below:**
```python=
msg_to_be_sent = "__whatevertextyouwant__"
client.publish(THE_TOPIC,
payload=msg_to_be_sent,
qos=0,
retain=False)
```
The code will now basically send just one message and then stop.
Try now the following cases, but **remember to always execute the "subscriber" AFTER the "producer"** in all cases:
:::danger
5.- Prueba los siguentes casos:
* Publica un mensaje con la opcion de retained a "False". ¿Qué recibe el "subscriber"?
* Publica un mensaje con la opcion de retained a "True". ¿Qué recibe el "subscriber"?
* Publica varios mensajes (diferentes) con la opcion de retained a "True" antes de activar el "subscriber". ¿Qué recibe el "subscriber"?
Detalla la respuesta en el documento a entregar.
:::
Finally, how do you remove or delete a retained message? You have to publish a blank message with the retain flag set to true. ==Try it.==
:::danger
6.- Crea grupos de dos o tres miembros. Crea una aplicación de chat muy básica, donde todos los mensajes publicados de cualquiera de los miembros sean recibidos **solo por los miembros** del grupo.
> La lectura de texto desde el teclado en Python se puede hacer usando:
> `name = input("Enter text: ")`
Tienes que entregar todo el fichero con el codigo.
:::
:::danger
7.- Crea una aplicacion en python para replicar el ejemplo del [Seminario 4](https://hackmd.io/@rse2021/mqttlorawan) en el que leiamos datos desde TTN utilizando el cliente ``mqtt-explorer``. En este caso es suficiente imprimir todo el JSON que llega.
Los parametros necesarios son:
```
Broker: eu1.cloud.thethings.network
Username: lopys2ttn@ttn
Password: NNSXS.A55Z2P4YCHH2RQ7ONQVXFCX2IPMPJQLXAPKQSWQ.A5AB4GALMW623GZMJEWNIVRQSMRMZF4CHDBTTEQYRAOFKBH35G2A
Topic: v3/+/devices/#
```
Tienes que entregar el fichero con el codigo.
:::