(Page créée avec « {{Tuto Details |Description=<translate>Know and Understand MQTT protocol. Then implement and build a project to subscribe and publish on the public server of test.mosquitt... ») |
|||
Ligne 64 : | Ligne 64 : | ||
On the other hand, we shall use the PC to view this data as a '''Subscriber.''' This will enable us to fully understand the working principle of the MQTT protocol used in IoT Communication between devices.</translate> | On the other hand, we shall use the PC to view this data as a '''Subscriber.''' This will enable us to fully understand the working principle of the MQTT protocol used in IoT Communication between devices.</translate> | ||
|Step_Picture_00=Mosquitto_MQTT_-_IoT_Platform_Series_4.png | |Step_Picture_00=Mosquitto_MQTT_-_IoT_Platform_Series_4.png | ||
+ | }} | ||
+ | {{Tuto Step | ||
+ | |Step_Title=<translate>Publisher (ESP32)</translate> | ||
+ | |Step_Content=<translate>To set up the ESP32 for MQTT, we need to install a library - <code>PubSubClient</code>. This library has functions that use variables as mentioned below to send data to the broker. | ||
+ | |||
+ | * <code>mqtt_server</code>: This variable represents the address or IP of the MQTT broker. We shall be using "test.mosquitto.org" | ||
+ | * <code>mqtt_port</code>: This variable represents the port number of the MQTT broker. In our case 1883. | ||
+ | * <code>mqtt_topic</code>: This variable represents the topic to which the publisher will send messages. For Example <code>"schoolofiot/device1".</code> Where '<nowiki/>'''schoolofiot'''<nowiki/>' is the general-most topic level. And '<nowiki/>'''device1'''' is a sub-level. | ||
+ | |||
+ | The provided code is an Arduino sketch that uses the ESP32 WiFi module and the PubSubClient library to connect to an MQTT broker and publish temperature and humidity data. Let's break down the code step by step: | ||
+ | |||
+ | '''1. Include necessary libraries:''' | ||
+ | <code>#include <WiFi.h></code> | ||
+ | <code>#include <PubSubClient.h></code> | ||
+ | This code includes the required libraries for the ESP32 WiFi module and the MQTT client functionality. | ||
+ | |||
+ | '''2. Define WiFi & MQTT Server variables:''' | ||
+ | <code>const char* ssid = "XXXXXXXXXX";</code> | ||
+ | <code>const char* password = "XXXXXXXXXX";</code> | ||
+ | <code>const char* mqtt_server = "test.mosquitto.org";</code> | ||
+ | These variables store the SSID (network name) and password for the WiFi network you want to connect to. The <code>mqtt_server</code> variable holds the IP address or hostname of the MQTT broker. | ||
+ | |||
+ | '''3. Declare global variables and objects:''' | ||
+ | <code>WiFiClient espClient;</code> | ||
+ | <code>PubSubClient client(espClient);</code> | ||
+ | <code>long lastMsg = 0;</code> | ||
+ | <code>char msg[50];</code> | ||
+ | <code>int value = 0;</code> | ||
+ | <code>float temperature = 0;</code> | ||
+ | <code>float humidity = 0;</code> | ||
+ | Here, a WiFi client object (<code>espClient</code>) and an MQTT client object (<code>client</code>) are declared. The <code>lastMsg</code> variable stores the timestamp of the last message, and the <code>msg</code> is a character array for message storage. The <code>value</code>, <code>temperature</code>, and <code>humidity</code> variables are used to hold the respective sensor values. | ||
+ | |||
+ | '''4. Setup function:''' | ||
+ | <code>void setup()</code> | ||
+ | <code>Serial.begin(115200);</code> | ||
+ | <code>setup_wifi();</code> | ||
+ | <code>client.setServer(mqtt_server, 1883);</code> | ||
+ | <code>client.setCallback(callback);</code> | ||
+ | <code>}</code> | ||
+ | The <code>setup()</code> function is called once at the start of the program. It initializes the serial communication, sets up the WiFi connection, configures the MQTT server and port, and sets the callback function to handle incoming messages. | ||
+ | |||
+ | '''5. WiFi setup function:''' | ||
+ | <code>void setup_wifi() {</code> | ||
+ | <code>// ...</code> | ||
+ | <code>}</code> | ||
+ | The <code>setup_wifi()</code> function handles the connection to the WiFi network using the provided SSID and password. It waits until the connection is established and prints the local IP address to the serial monitor. | ||
+ | |||
+ | '''6. MQTT callback function:''' | ||
+ | <code>void callback(char* topic, byte* message, unsigned int length) {</code> | ||
+ | <br /> | ||
+ | <code>// ...</code> | ||
+ | |||
+ | <code>}</code> | ||
+ | This function is called when a message is received from the MQTT broker. It prints the received message along with the corresponding topic. | ||
+ | |||
+ | '''7. MQTT reconnection function:''' | ||
+ | <code>void reconnect() {</code> | ||
+ | <code>// ...</code> | ||
+ | <code>}</code> | ||
+ | The <code>reconnect()</code> function is responsible for reconnecting to the MQTT broker if the connection is lost. It attempts to connect to the broker using a randomly generated client ID. If the connection is successful, it prints a success message. Otherwise, it waits for 5 seconds before retrying. | ||
+ | |||
+ | '''8. Main loop:''' | ||
+ | <code>void loop() {</code> | ||
+ | <code>if (!client.connected()) {</code> | ||
+ | <code>reconnect();</code> | ||
+ | <code>}</code> | ||
+ | <code>client.loop();</code> | ||
+ | <code>long now = millis();</code> | ||
+ | <code>if (now - lastMsg > 2000) {</code> | ||
+ | <code>lastMsg = now;</code> | ||
+ | <code>sendData();</code> | ||
+ | <code>}</code> | ||
+ | <code>}</code> | ||
+ | The <code>loop()</code> function is the main program loop that runs continuously after the <code>setup()</code> function. It checks if the MQTT client is connected and, if not, attempts to reconnect. It also calls the <code>client.loop()</code> function to maintain the MQTT client's internal state. Every 2 seconds, it calls the <code>sendData()</code> function to publish temperature and humidity data. | ||
+ | |||
+ | '''9. Publish sensor data function:''' | ||
+ | <code>void sendData() {</code> | ||
+ | <code>// ...</code> | ||
+ | <code>}</code> | ||
+ | The <code>sendData()</code> function is responsible for publishing temperature and humidity data to specific MQTT topics. It generates random values for temperature and humidity, converts them to strings, and publishes them along with the corresponding topic. | ||
+ | |||
+ | '''- Publish a gap message:''' | ||
+ | <code>client.publish("schoolofiot/gap", "--------------");</code> | ||
+ | This line publishes a message consisting of a series of dashes (<code>--------------</code>) to the MQTT topic "'''schoolofiot/gap'''". It is used to indicate a separation or gap between different sets of data. | ||
+ | |||
+ | '''- Read and publish temperature data:''' | ||
+ | <code>temperature = random(30, 40);</code> | ||
+ | <code>char tempString[8];</code> | ||
+ | <code>dtostrf(temperature, 1, 2, tempString);</code> | ||
+ | <code>Serial.print("Temperature: ");</code> | ||
+ | <code>Serial.println(tempString);</code> | ||
+ | <code>String tempdata = "Temperature: " + String(tempString);</code> | ||
+ | <code>client.publish("schoolofiot/temperature", tempdata.c_str());</code> | ||
+ | These lines generate a random temperature value between 30 and 40 degrees, store it in the <code>temperature</code> variable, and use<code>dtostrf()</code> function to convert decimal point data to String.<blockquote><code>dtostrf(floatValue, minStringWidth, numAfterDecimal, charBuf_to_store_string);</code></blockquote><blockquote>This function takes four parameters to convert double into an ASCII value stored inside string:</blockquote><blockquote>1. floatValue: The first parameter that takes the float value we want to convert into a string.</blockquote><blockquote>2. minStringWidth: This is the second parameter that defines the minimum field width of the output string.</blockquote><blockquote>3. numAfterDecimal: The third parameter is precision which describes the number of digits after the decimal point.</blockquote><blockquote>4. charBuffer: Final argument is where the string will be stored. This is a kind of char array having a defined size.</blockquote>The temperature value is then printed to the serial monitor and concatenated with the string "'''Temperature:''' ". The resulting string is stored in the <code>tempdata</code> variable. Finally, the <code>tempdata</code> string is published to the MQTT topic '''schoolofiot/temperature''' using the <code>client.publish()</code> function. | ||
+ | |||
+ | '''- Read and publish humidity data:''' | ||
+ | <code>humidity = random(60, 70);</code> | ||
+ | <code>char humString[8];</code> | ||
+ | <code>dtostrf(humidity, 1, 2, humString);</code> | ||
+ | <code>Serial.print("Humidity: ");</code> | ||
+ | <code>Serial.println(humString);</code> | ||
+ | <code><nowiki>''</nowiki>mString humdata = "Humidity: " + String(humString);</code> | ||
+ | <code>client.publish("schoolofiot/humidity", humdata.c_str());</code> | ||
+ | These lines generate a random humidity value between 60 and 70 percent, store it in the <code>humidity</code> variable. | ||
+ | |||
+ | Overall, the <code>sendData()</code> function generates random temperature and humidity values, converts them to strings, and publishes them to specific MQTT topics for further processing or monitoring. | ||
+ | |||
+ | '''''Final Code can be found in the Code section''''' | ||
+ | |||
+ | But to confirm this, we also need to read the data from other the side - '''Subscriber'''.</translate> | ||
+ | }} | ||
+ | {{Tuto Step | ||
+ | |Step_Title=<translate>Subscriber (Windows PC)</translate> | ||
+ | |Step_Content=<translate>To set up the Subscriber on PC, we need to install Mosquitto MQTT Applcation. This application can create a broker, publisher & subscriber - all sections | ||
+ | |||
+ | To install Mosquitto MQTT on your PC from the official website and make changes to the configuration file for listener 1883 and allow anonymous connections, you can follow these steps: | ||
+ | |||
+ | '''1. Download and''' '''Install Mosquitto:''' | ||
+ | |||
+ | * Go to the official Mosquitto website ([https://mosquitto.org/ https://mosquitto.org/)]. | ||
+ | * Navigate to the "''Downloads''" section. | ||
+ | * Choose the appropriate installer for your operating system (Windows x64 in this case) and download it | ||
+ | * Install the application in desired location. | ||
+ | |||
+ | '''2. Edit Configuration File:''' | ||
+ | |||
+ | * Open the installation directory where Mosquitto is installed. | ||
+ | * Locate the <code>mosquitto.conf</code> file (usually found in the main directory). | ||
+ | * Open <code>mosquitto.conf</code> in a text editor of your choice. Add the below 2 lines - | ||
+ | |||
+ | <code>listener 1883</code> | ||
+ | <code>allow_anonymous true</code> | ||
+ | |||
+ | * It should look somewhat like this - | ||
+ | |||
+ | * We can uncomment ad make changes in the file as well, but adding only 2 lines on the top is more simple and noticeable. | ||
+ | |||
+ | '''3. Run''' '''Mosquitto Subscriber''' | ||
+ | |||
+ | * '''We''' can run the Mosquitto broker and then subscribe to the topic we desire. But running directly the subscriber is best in our case. | ||
+ | * Open the folder/directory where the mosquitto.exe along with <code>mosquitto_sub.exe</code> is present. | ||
+ | * Run the '''''PowerShell/CMD''''' terminal from within the directory. For windows, ''open the directory > Press shift + right-mouse-button(right-click)'', and we'd see options for running a terminal like powershell. | ||
+ | |||
+ | * On the terminal, enter below command - | ||
+ | |||
+ | <code>> .\mosquitto_sub -h test.mosquitto.org -t "schoolofiot/#"</code> | ||
+ | In the above command, if you noticed, I did not subscribe to a specific topic. As per the topics we published (from ESP32), like "'''schoolofiot/gap'''", "'''schoolofiot/temperature'''" or "'''schoolofiot/humidity'''". | ||
+ | |||
+ | * The reason is, gap, temperature & humidity comes under the '''''general topic''''' of '''schoolofiot''' level. So, to access/view any data published as a sub-level of '''schoolofiot''', we can use ''''#'''<nowiki/>'. | ||
+ | * Apart from this, in case we need to subscribe to a specific topic (like temperature), we can use command like this - | ||
+ | |||
+ | <code>> .\mosquitto_sub -h test.mosquitto.org -t "schoolofiot/temperature"</code> | ||
+ | Therefore, no matter what name is put under the '''''general topic,''''' we can subscribe to it and view all of them together. | ||
+ | |||
+ | '''Hurray! 🎉''' | ||
+ | |||
+ | '''We have learned another IoT Platform - Mosquitto''' '''MQTT''' '''(By Eclipse)'''</translate> | ||
+ | |Step_Picture_00=Mosquitto_MQTT_-_IoT_Platform_Series_5.png | ||
+ | |Step_Picture_01=Mosquitto_MQTT_-_IoT_Platform_Series_6.png | ||
+ | |Step_Picture_02=Mosquitto_MQTT_-_IoT_Platform_Series_7.png | ||
}} | }} | ||
{{Notes | {{Notes | ||
Ligne 69 : | Ligne 229 : | ||
}} | }} | ||
{{PageLang | {{PageLang | ||
+ | |Language=en | ||
|SourceLanguage=none | |SourceLanguage=none | ||
|IsTranslation=0 | |IsTranslation=0 | ||
− | |||
}} | }} | ||
{{Tuto Status | {{Tuto Status | ||
|Complete=Draft | |Complete=Draft | ||
}} | }} |
Auteur Akshayan Sinha | Dernière modification 25/05/2023 par Akshayansinha
Pas encore d'image
IoT, MQTT, platform, web, mosquitto Technique
Here, there are 2 sections - Publish and Subscribe. And then there is a middleman - Broker. Let us see in depth
[EXAMPLE] When a user1 publishes an image on social media, then only the user2 subscribed to user1 can view/receive the image. Here, the user1 is the PUBLISHER, user2 is the SUBSCRIBER, and the user1's account is the BROKER.
Whenever there is a pub-sub model used as a message communication protocol, we require a broker that can transfer the information in the required device. This can be done by sending the message under correct topic.
Let us understand this -
Now that we understand how MQTT works, let us use a cloud MQTT service and send data across the internet. In this article, we'll be using Mosquitto MQTT - test.mosquitto.org
Under the Server section, we can see different ports provide feature-separated servers. These servers act like channels for sharing data over the cloud. Let us understand it first -
We shall be using 1883 port to send data and monitor. As we know, MQTT has 3 services - Publisher, Broker, and Subscriber. In this case, mosquito MQTT Cloud is already playing the role of a broker.
Now, we'd be using ESP32 Dev Board, which has a wifi chip and is able to connect to the Internet, playing the role of a Publisher for sharing its temperature and humidity data from the sensor.
On the other hand, we shall use the PC to view this data as a Subscriber. This will enable us to fully understand the working principle of the MQTT protocol used in IoT Communication between devices.
To set up the ESP32 for MQTT, we need to install a library - PubSubClient
. This library has functions that use variables as mentioned below to send data to the broker.
mqtt_server
: This variable represents the address or IP of the MQTT broker. We shall be using "test.mosquitto.org"mqtt_port
: This variable represents the port number of the MQTT broker. In our case 1883.mqtt_topic
: This variable represents the topic to which the publisher will send messages. For Example "schoolofiot/device1".
Where 'schoolofiot' is the general-most topic level. And 'device1' is a sub-level.The provided code is an Arduino sketch that uses the ESP32 WiFi module and the PubSubClient library to connect to an MQTT broker and publish temperature and humidity data. Let's break down the code step by step:
1. Include necessary libraries:
#include <WiFi.h>
#include <PubSubClient.h>
This code includes the required libraries for the ESP32 WiFi module and the MQTT client functionality.
2. Define WiFi & MQTT Server variables:
const char* ssid = "XXXXXXXXXX";
const char* password = "XXXXXXXXXX";
const char* mqtt_server = "test.mosquitto.org";
These variables store the SSID (network name) and password for the WiFi network you want to connect to. The mqtt_server
variable holds the IP address or hostname of the MQTT broker.
3. Declare global variables and objects:
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
float temperature = 0;
float humidity = 0;
Here, a WiFi client object (espClient
) and an MQTT client object (client
) are declared. The lastMsg
variable stores the timestamp of the last message, and the msg
is a character array for message storage. The value
, temperature
, and humidity
variables are used to hold the respective sensor values.
4. Setup function:
void setup()
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
The setup()
function is called once at the start of the program. It initializes the serial communication, sets up the WiFi connection, configures the MQTT server and port, and sets the callback function to handle incoming messages.
5. WiFi setup function:
void setup_wifi() {
// ...
}
The setup_wifi()
function handles the connection to the WiFi network using the provided SSID and password. It waits until the connection is established and prints the local IP address to the serial monitor.
6. MQTT callback function:
void callback(char* topic, byte* message, unsigned int length) {
// ...
}
This function is called when a message is received from the MQTT broker. It prints the received message along with the corresponding topic.
7. MQTT reconnection function:
void reconnect() {
// ...
}
The reconnect()
function is responsible for reconnecting to the MQTT broker if the connection is lost. It attempts to connect to the broker using a randomly generated client ID. If the connection is successful, it prints a success message. Otherwise, it waits for 5 seconds before retrying.
8. Main loop:
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
sendData();
}
}
The loop()
function is the main program loop that runs continuously after the setup()
function. It checks if the MQTT client is connected and, if not, attempts to reconnect. It also calls the client.loop()
function to maintain the MQTT client's internal state. Every 2 seconds, it calls the sendData()
function to publish temperature and humidity data.
9. Publish sensor data function:
void sendData() {
// ...
}
The sendData()
function is responsible for publishing temperature and humidity data to specific MQTT topics. It generates random values for temperature and humidity, converts them to strings, and publishes them along with the corresponding topic.
- Publish a gap message:
client.publish("schoolofiot/gap", "--------------");
This line publishes a message consisting of a series of dashes (--------------
) to the MQTT topic "schoolofiot/gap". It is used to indicate a separation or gap between different sets of data.
- Read and publish temperature data:
These lines generate a random temperature value between 30 and 40 degrees, store it in thetemperature = random(30, 40);
char tempString[8];
dtostrf(temperature, 1, 2, tempString);
Serial.print("Temperature: ");
Serial.println(tempString);
String tempdata = "Temperature: " + String(tempString);
client.publish("schoolofiot/temperature", tempdata.c_str());
temperature
variable, and usedtostrf()
function to convert decimal point data to String.
dtostrf(floatValue, minStringWidth, numAfterDecimal, charBuf_to_store_string);
This function takes four parameters to convert double into an ASCII value stored inside string:
1. floatValue: The first parameter that takes the float value we want to convert into a string.
2. minStringWidth: This is the second parameter that defines the minimum field width of the output string.
3. numAfterDecimal: The third parameter is precision which describes the number of digits after the decimal point.
The temperature value is then printed to the serial monitor and concatenated with the string "Temperature: ". The resulting string is stored in the4. charBuffer: Final argument is where the string will be stored. This is a kind of char array having a defined size.
tempdata
variable. Finally, the tempdata
string is published to the MQTT topic schoolofiot/temperature using the client.publish()
function.
- Read and publish humidity data:
humidity = random(60, 70);
char humString[8];
dtostrf(humidity, 1, 2, humString);
Serial.print("Humidity: ");
Serial.println(humString);
''mString humdata = "Humidity: " + String(humString);
client.publish("schoolofiot/humidity", humdata.c_str());
These lines generate a random humidity value between 60 and 70 percent, store it in the humidity
variable.
Overall, the sendData()
function generates random temperature and humidity values, converts them to strings, and publishes them to specific MQTT topics for further processing or monitoring.
Final Code can be found in the Code section
But to confirm this, we also need to read the data from other the side - Subscriber.
To set up the Subscriber on PC, we need to install Mosquitto MQTT Applcation. This application can create a broker, publisher & subscriber - all sections
To install Mosquitto MQTT on your PC from the official website and make changes to the configuration file for listener 1883 and allow anonymous connections, you can follow these steps:
1. Download and Install Mosquitto:
2. Edit Configuration File:
mosquitto.conf
file (usually found in the main directory).mosquitto.conf
in a text editor of your choice. Add the below 2 lines -listener 1883
allow_anonymous true
3. Run Mosquitto Subscriber
mosquitto_sub.exe
is present.> .\mosquitto_sub -h test.mosquitto.org -t "schoolofiot/#"
In the above command, if you noticed, I did not subscribe to a specific topic. As per the topics we published (from ESP32), like "schoolofiot/gap", "schoolofiot/temperature" or "schoolofiot/humidity".
> .\mosquitto_sub -h test.mosquitto.org -t "schoolofiot/temperature"
Therefore, no matter what name is put under the general topic, we can subscribe to it and view all of them together.
Hurray! 🎉
We have learned another IoT Platform - Mosquitto MQTT (By Eclipse)
en none 0 Draft
Vous avez entré un nom de page invalide, avec un ou plusieurs caractères suivants :
< > @ ~ : * € £ ` + = / \ | [ ] { } ; ? #