Table of Contents

STM_IoT_3: Connecting to the MQTT broker and publishing data

In the following scenario, you will learn how to connect to the MQTT broker and publish a message.

Prerequisites

To implement this scenario, it is necessary to get familiar with at least one of the following scenarios first:

The requirement is to pass the scenarios

To be able to connect to the WiFi network.

Suggested Readings and Knowledge Resources

Hands-on Lab Scenario

Note - this scenario can be used in pair with STM_IoT_4: Connecting to the MQTT broker and subscribing to the topic 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 STM_IoT_2: Connecting to the WiFi Access Point and presenting IP—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 publish an MQTT message of your choice.

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:

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 beginning of the code is the same as in the previous scenario, so make a copy of it:

We will use the code template from STM_IoT_AT: Programming of the WiFi interface with AT commands 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:

Below we briefly describe the commands mentioning only the parameters important to us. Please refer to the Espressif documentation[1] 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=<LinkID>,<scheme>,<"client_id">,<"username">,<"password">,<cert_key_ID>,<CA_ID>,<"path">

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=<LinkID>,<"host">,<port>,<reconnect>

The command can look like this:

AT+MQTTCONN=0,\"192.168.1.100\",1883,1

AT+MQTTPUB

AT+MQTTPUB=<LinkID>,<"topic">,<"data">,<qos>,<retain>

The list of parameters:

Step 3

Implement the MQTT configuration and connection to the broker. Use the template for the “AT” command from the first step. Ensure that your node is successfully connected.

Step 4

Implement publishing of the MQTT message. You can do it just once in the “setup();” function, or periodically in the “loop();”. While working periodically be sure not to send messages too often. Reasonable period is 1-5 seconds. You can send the content of the counter to observe value changes in the concurrent messages.

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 publish a message (once or periodically). Depending on whether you're fully remote or able to access our networks with an additional device, you need to implement a subscriber (as present in the scenario STM_IoT_4: Connecting to the MQTT broker and subscribing to the topic) or use MQTT Explorer (or any other application capable of connecting to our MQTT Broker) to observe messages that you publish.

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

Can I publish messages on different topics?: Certainly you can. You can publish the readings of the temperature sensor with one topic, and readings of the humidity with another. The limit of the number of different topics comes only from the available resources of the MQTT broker.
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.
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


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 Creative Commons Licence, free for Non-Commercial use.