# IoT Lab 1 ###### tags: `SRM2021` # Block 1: MQTT using a web client For the first experiments you will use an MQTT client that can be used in any OS, it's called MQTT-explorer: ![](https://i.imgur.com/F8IPtvN.png) You have to install it from here: http://mqtt-explorer.com ## Connecting to a public broker There are various public MQTT brokers, for example: * broker.hivemq.com * broker.mqttdashboard.com * test.mosquitto.org In this exercise we will use the one offered by HiveMQ (broker.hivemq.com). Fill in the data as indicated below: ![MQTT client](https://i.imgur.com/BJWDHby.png) Then click on ```ADVANCED```, and add a topic: ![](https://i.imgur.com/DSLEVh0.png) if you want you can assign your own client ID. Now click on ```BACK```, and then on ```CONNECT```. You will start seeing something like this: ![](https://i.imgur.com/vKfrVBA.png) ## Some basic exercises Let's start with an easy one. Click on the ```DISCONNECT``` button. Now add a subscription to the topic ``Spain/Valencia/UPV``, then CONNECT once again. Now, (1) write the same **identical** text for the topic (i.e., ``Spain/Valencia/UPV``) **in the ``topic`` field of the Publish section**, select the ```raw``` option and write a text in the box below. **The text can be whatever you want** (e.g., ``Ciao!!``). When you are done click on the ``Publish`` button. You'll get something like the image below... **plus all the messages written by all the other clients.** With just one publish action you actually reached various devices!! ![](https://i.imgur.com/dmbXMOB.png) :::danger 1. Pruebas rápidas: a. ¿Qué pasa si escribes ``spain/valencia/upv`` en su lugar? b. ¿Cómo construirías una aplicación de mensajería? Detalla la respuesta en el documento a entregar. ::: ## Simple data collection using MQTT You will now read the values of two LoRaWAN sensors that are periodically sending their data to the TTN Network Server from the GRC lab. ![](https://i.imgur.com/4zEsurt.jpg =300x) You have to use the MQTT Explore with the following parameters: ``` Broker: eu1.cloud.thethings.network:1883 Username: lopys2ttn@ttn Password: NNSXS.A55Z2P4YCHH2RQ7ONQVXFCX2IPMPJQLXAPKQSWQ.A5AB4GALMW623GZMJEWNIVRQSMRMZF4CHDBTTEQYRAOFKBH35G2A Topic: v3/+/devices/# ``` ![](https://i.imgur.com/UOu3nfX.png) :::danger 2. Detalla en el documento a entregar alguno de los topics completos de los mensajes que has recibido ::: # Block 2: MQTT with python :::info **All the code necessary for this Lab session is available here [![](https://i.imgur.com/8f3a7R2.png =100x)](https://www.dropbox.com/sh/dnfdlycjtupv751/AADjgCtLsdaLkE6zGjOjXQdMa?dl=0)** You can execute the code either in your computer or online: * online. Create an account in https://repl.it ![](https://i.imgur.com/oW5EJIc.png) * in your computer. You must have python3 installed and the `paho-mqtt` library: ``` $ sudo pip3 install paho-mqtt ``` The documentation of the MQTT Paho API is here: https://www.eclipse.org/paho/clients/python/docs/ ::: ## 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 3.- 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 4.- Ejecuta este codigo (en otro terminal) y explica el resultado obtenido. Detalla la respuesta en el documento a entregar. ::: :::danger 5.- 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 Questions 3 and 4, 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 6.- 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 7.- 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 8.- 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 9.- Repite el ejemplo anterior en el que, utilizando el cliente http://mqtt-explorer.com leiamos datos desde TTN. 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. :::