====== STM_IoT_4: Connecting to the MQTT broker and subscribing to the topic =====
In the following scenario, you will learn how to connect to the MQTT broker and subscribe to the chosen topic to receive messages.
===== Prerequisites =====
To implement this scenario, it is necessary to get familiar with the LED controlling scenario:
* [[en:iot-open:practical:hardware:sut:stm32:emb9A_1]],
and at least one of the following scenarios first:
* [[en:iot-open:practical:hardware:sut:stm32:emb5_1|]],
* [[en:iot-open:practical:hardware:sut:stm32:emb6_1|]],
* [[en:iot-open:practical:hardware:sut:stm32:emb7_1|]].
The requirement is to pass the scenarios
* [[en:iot-open:practical:hardware:sut:stm32:IoT_AT]],
* [[en:iot-open:practical:hardware:sut:stm32:IoT_1]],
* [[en:iot-open:practical:hardware:sut:stm32:IoT_2]],
* [[en:iot-open:practical:hardware:sut:stm32:IoT_3]].
To be able to connect to the WiFi network and MQTT broker.
===== Suggested Readings and Knowledge Resources =====
* [[en:iot-open:introductiontoembeddedprogramming2:cppfundamentals]],
* [[en:iot-open:hardware2:stm32|]],
* [[en:iot-open:hardware2:esp32|]],
* [[en:iot-open:practical:hardware:sut:stm32|]],
* [[en:iot-open:iotprogramming2:espressif_networking|]].
===== Hands-on Lab Scenario =====
Note - this scenario can be used in pair with [[[en:iot-open:practical:hardware:sut:stm32:iot_3|]] to build a publish-subscribe solution using two devices (sender and receiver). You need to book two devices then and develop them in parallel.
==== Task to be implemented ====
Connect to the "internal IoT" WiFI access point as presented in the scenario [[en:iot-open:practical:hardware:sut:stm32:iot_2]] — present connection status on display. Once connected to the networking layer (WiFi), connect the MQTT client to the MQTT broker and present the connection status on the display, then subscribe to the MQTT topic of your choice. Present incoming data on the chosen display or control other actuators.
MQTT clients are identified by their name, so use a unique one, e.g., the end of the IP address assigned, your unique name, etc. It is essential because if you accidentally use someone else's name, then you will mess with messages, and your MQTT client will be instantly disconnected when another one with the same name connects!
The steps below show the principles of the software operation. How to implement the full software please refer to the previous scenarios:
* [[en:iot-open:practical:hardware:sut:stm32:IoT_AT]]
* [[en:iot-open:practical:hardware:sut:stm32:IoT_1]]
* [[en:iot-open:practical:hardware:sut:stm32:iot_2]]
* [[en:iot-open:practical:hardware:sut:stm32:iot_3]]
==== Start ====
Check if you can see a full LCD in your video stream. Book a device and create a dummy Arduino file with ''void setup()...'' and ''void loop()...''.
==== Steps ====
=== Step 1 ===
The big part of the code is the same as in the previous scenario, so make a copy of it:
* [[en:iot-open:practical:hardware:sut:stm32:IoT_3]]
We will use the code template from [[en:iot-open:practical:hardware:sut:stm32:IoT_AT]] repeated for every AT command.
WiFiSerial.println("AT");
lcd.setCursor(0,0);
lcd.print("AT ");
do {
response = WiFiSerial.readStringUntil(0x0A);
lcd.setCursor(0,1);
lcd.print(response);
} while (!(response.startsWith(compOK)));
delay(1000);
=== Step 2 ===
In the firmware for the ESP32-C3 board, there are AT commands to work with the MQTT protocol. In this scenario we will use three of them:
* "AT+MQTTUSERCFG..." - to configure MQTT c
* "AT+MQTTCONN..." - to establish the connection to the broker
* "AT+MQTTSUB..." - to subscribe to the message on the topic
Below we briefly describe the commands mentioning only the parameters important to us. Please refer to the Espressif documentation((https://docs.espressif.com/projects/esp-at/en/latest/esp32c3/index.html)) for the details of commands.
If the parameter is taken within quotation marks it should be in such a form sent in a command.\\
Please refer to the MQTT description chapter for the meaning of some protocol details.
**AT+MQTTUSERCFG**
This command accepts the list of parameters:
AT+MQTTUSERCFG=,,<"client_id">,<"username">,<"password">,,,<"path">
* LinkID - currently should be 0
* scheme - 1 (MQTT over TCP)
* "client_id" - the unique ID of the MQTT client
* "username" - user to connect to the broker
* "password" - password for the user
* cert_key-ID - should be 0
* CA_ID - should be 0
* "path" - should remain empty
In our case, the command can look like this:
AT+MQTTUSERCFG=0,1,\"STM32#0001\",\"username\",\"password\",0,0,\"\"
**AT+MQTTCONN**
This command accepts the list of parameters:
AT+MQTTCONN=,<"host">,,
* LinkID - currently should be 0
* "host" - the IP address or URL of the MQTT broker
* port - the TCP port number, 1883 for most of the brokers
* reconnect - 1 for automatic reconnection (recommended in our case)
The command can look like this:
AT+MQTTCONN=0,\"192.168.1.100\",1883,1
**AT+MQTTSUB**
AT+MQTTSUB=,<"topic">,
The list of parameters:
* LinkID - currently should be 0
* "topic" - MQTT topic
* qos - mode of the quality of service, 0, 1 or 2, default 0.
The command can look like this in the example below:
AT+MQTTSUB=0,\"topic\",0
After a successful subscription, the ESP32-C3 module will send messages in the following form:
+MQTTSUBRECV:,<"topic">,,data
* LinkID - always 0
* "topic" - MQTT topic
* data_length - number of bytes of the following data packet
* data - message payload
=== Step 3 ===
Implement the MQTT configuration, connection to the broker, and subscription to the chosen topic. Use the template for the "AT" command from the first step. Ensure that your node is successfully connected and the topic subscribed.
=== Step 4 ===
Implement handling of the MQTT messages. Here we present how to control LED with messages sent with the topic "topic". If the message payload is 0 LED will be off, if it is 1 LED will be on. You can use it as the template for more advanced control of any device in the laboratory equipment.\\
Declare variables to store the strings for comparison and define LED pin.
#define LED_GREEN D3
String compend0, compend1;
String response;
Prepare string variables and set the mode of the LED pin.
compend0 = "+MQTTSUBRECV:0,\"topic\",1,0";
compend1 = "+MQTTSUBRECV:0,\"topic\",1,1";
pinMode(LED_GREEN,OUTPUT);
In the "loop();" implement periodic reads of the hardware serial port, and handle incoming messages.
response = WiFiSerial.readStringUntil(0x0A);
if (response.startsWith(compend0))
{
digitalWrite(LED_GREEN,0);
};
if (response.startsWith(compend1))
{
digitalWrite(LED_GREEN,1);
};
==== Result validation ====
You should be able to connect to the WiFi and MQTT broker (verified by the status present on the selected display) and then subscribe to the topic. After a successful subscription, you should receive messages published on the topic of your choice. Depending on whether you're fully remote or able to access our networks with an additional device, you need to implement a publisher (as present in the scenario [[[en:iot-open:practical:hardware:sut:stm32:iot_3|]]) or use MQTT Explorer (or any other application capable of connecting to our MQTT Broker) to publish messages.
Because LCD can't properly display some non-visible characters the presented code sometimes shows additional, non-letter characters. It is out of the scope of this scenario to filter these characters out. We leave the task of making visual improvements to your invention.
===== FAQ =====
**My MQTT client disconnects randomly**: The most common reason is you're using a non-unique MQTT client name. Please change it to some other (even random generated) and give it another try.\\
**Can I subscribe to more than one topic?**: Yes, you can. For every incoming message you would receive the information on the topic of this specific message, so you would be able to recognise them.\\
**How do I send messages to which I am subscribed?**: Use a software client, such as [[http://mqtt-explorer.com/| MQTT Explorer]], if you're able to access the "internal IoT" network (you're in the range of the network). If you're remote, the only way is to book another device and implement a client publishing a message with the appropriate topic, as presented in the scenario [[[en:iot-open:practical:hardware:sut:stm32:iot_3|]]. Our MQTT broker is also visible in the campus network on the wired interfaces so that you can access it, e.g. via EduVPN or from the laboratory computers. Refer to the supervisor for IP and credentials.\\
**Do I need to authorise to publish and subscribe?**: Yes, you do. The supervisor provides the user and password on demand, also presented in the Node's technical documentation.
===== Project information =====
{{:en:iot-open:logo_iot_200_px.png?200|}}\\
This Intellectual Output was implemented under the Erasmus+ KA2.\\
Project IOT-OPEN.EU Reloaded – Education-based strengthening of the European universities, companies and labour force in the global IoT market.\\
Project number: 2022-1-PL01-KA220-HED-000085090.
**__Erasmus+ Disclaimer__**\\
This project has been funded with support from the European Commission. \\
This publication reflects the views of only the author, and the Commission cannot be held responsible for any use that may be made of the information contained therein.
**__Copyright Notice__**\\
This content was created by the IOT-OPEN.EU Reloaded consortium, 2022,2024.\\
The content is Copyrighted and distributed under CC BY-NC [[https://en.wikipedia.org/wiki/Creative_Commons_license|Creative Commons Licence]], free for Non-Commercial use.