MQTT With NODE - RED - Version Finale
MQTT With NODE - RED - Version Finale
MQTT With NODE - RED - Version Finale
Eclipse Mosquitto is an open source message broker that implements the MQTT
protocol versions 5.0, 3.1.1 and 3.1.
Mosquitto is lightweight and is suitable for use on all devices from low power single
board computers to full servers.
The MQTT protocol provides a lightweight method of carrying out messaging using
a publish/subscribe model. This makes it suitable for IoT messaging such as with low
power sensors or mobile devices such as phones, embedded computers or
microcontrollers.
The Mosquitto project also provides a C library for implementing MQTT clients, and
the very popular mosquitto_pub and mosquitto_sub command line MQTT clients.
IoT 3
MQTT Communication Protocol–Node-RED
We propose to use locally the mosquitto broker to test the following flow:
The sensor publish the topic temperatuyre. A distant equpment must subscribe to
get this information.
The broker is then waiting for information from the sensor in order to
publish them
- Now, we have to simulate the sensor behavior using a new prompt
command. Change directory to the mosquito destination folder and check
the mosquito appropriate command to publish the temperature values
(mosquito_pub):
IoT 3
MQTT Communication Protocol–Node-RED
- Run the following command to publish the value 16°C for the temperature
using the localhost server.
The broker receives the message and it can publish this information to the
subscribers. At this time, we have no subscribers yet.
IoT 3
MQTT Communication Protocol–Node-RED
At this stage, the subscriber doesn’t get the temperature value. It is normal, because
the default QoS is set to QoS0 and the broker did not save the temperature value to
publish it to the subscriber. So, if we run again the publish command, we will get the
result on the subscriber window.
- Try to publish different temperature values and see the obtained results.
- Try to reproduce this example with 2 or more sensors and 2 or more
remote equipments.
IoT 3
MQTT Communication Protocol–Node-RED
Note: The remote equipment can subscribe to both temperature and pressure topics.
In this configuration, the remote equipment will be the node-RED application which
is subscribed to the topics temperature and pressure. The Dashboard, within node-
RED application, enables us to see results in a very illustrative way.
IoT 3
MQTT Communication Protocol–Node-RED
mqtt Node:
IoT 3
MQTT Communication Protocol–Node-RED
- Try to publish a temperature value and see results in the debug window.
IoT 3
MQTT Communication Protocol–Node-RED
- Create the following flow. Deploy, Inject Input and see results in the
subscriber command prompt
- Reproduce the following flow. Deploy, change humidity values from the
dashboard and see results in the subscriber command prompt
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
Hardware Environment:
- ESP32
- Temperature and Humidity Sensor DHT11
- PC
Software Environment:
- Arduino IDE
- Node-RED Application
Prerequisites:
Note: if you already have the ESP8266 boards URL, you can separate the URLs
with a comma as follows:
IoT 3
MQTT Communication Protocol–Node-RED
- Testing the installation: Plug the ESP32 board to your computer. With your
Arduino IDE open, follow these steps:
Select your Board in Tools > Board menu
Check the ESP board presence
Select the Tools >Port (if you don’t see the COM Port in your
Arduino IDE, you need to install the USB to UART Bridge VCP
Drivers from this site :
https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers
Open the following example under File>Examples>WiFi
(ESP32)>WiFiScan
A new sketch opens in your Arduino IDE
Press the Upload button in the Arduino IDE. Wait a few seconds
while the code compiles and uploads to your board.
If everything went as expected, you should see a “Done uploading.”
message.
Note:If you try to upload a new sketch to your ESP32 and you get this error
message “A fatal error occurred: Failed to connect to ESP32: Timed out…
Connecting…“. It means that your ESP32 is not in flashing/uploading mode.
Having the right board name and COM port selected, follow these steps:
IoT 3
MQTT Communication Protocol–Node-RED
• MQTT Library :
To use MQTT with the ESP, you also need the Async TCP library.
- Click here to download the Async TCP library
https://github.com/me-no-dev/AsyncTCP
You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get AsyncTCP-master folder
- Rename your folder from AsyncTCP-master to AsyncTCP
- Move the AsyncTCP folder to your Arduino IDE installation libraries
folder
- Finally, re-open your Arduino IDE
Alternatively, you can go to Sketch >Include Library>Add . ZIP library and select
the library you’ve just downloaded.
IoT 3
MQTT Communication Protocol–Node-RED
- Open your Arduino IDE and go to Sketch > Include Library > Manage
Libraries. The Library Manager should open.
- Search for “DHT11” on the Search box and install the DHT library from
Adafruit
- After installing the libraries, restart your Arduino IDE.
Schematic diagram
- Wire the sensor to the ESP32 as shown in the following schematic diagram
with the data pin connected to GPIO4. However, you can use any other
suitable digital pin.
- Connect a 4.7 KΩ pull-up Resistor between Data Pin and VIN (or 3.3V) of
ESP32.
This step is necessary to attribute the PC’IP to the broker Mosquito which is running
locally.
Note: To find the local IP address of your PC, open a prompt command and run
directly the following command ** ipconfig, you will find the address in the line
« Adresse IPv4 »
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
- Click on Next
- Type 1883 in the “Ports locaux spécifiques” field
IoT 3
MQTT Communication Protocol–Node-RED
- Click on Next
- Keep defaut configurations
- Click on Next
- Keep defaut configurations
IoT 3
MQTT Communication Protocol–Node-RED
- Click on Next
- Edit the name as follows:
- Click on Finish
- Check the presence of a mosquitto flow in “Règles de traffic entrant”
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
Copy the following code to your Arduino IDE. To make it work for you, you need
to insert your network credentials as well as the MQTT broker details.
Define the GPIO that the DHT sensor data pin is connected
to. In our case, it is connected to GPIO4
The temp and hum variables will hold the temperature and
humidity values from the DHT22 sensor.
IoT 3
MQTT Communication Protocol–Node-RED
Basically, all these functions that we’ve just mentioned are callback functions. So, they are executed asynchronously.
IoT 3
MQTT Communication Protocol–Node-RED
The lines create timers that will allow both the MQTT
broker and Wi-Fi connection to reconnect, in case the
connection is lost.
--
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
#include "DHT.h"
#include <WiFi.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMqttClient.h>
#define WIFI_SSID "TOPNET_8F98"
#define WIFI_PASSWORD "xdfqduc4fu"
// Raspberry Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, 15)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "localhost"
#define MQTT_PORT 1883
// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp32/dht/temperature"
#define MQTT_PUB_HUM "esp32/dht/humidity"
// Digital pin connected to the DHT sensor
#define DHTPIN 4
// Uncomment whatever DHT sensor type you're using
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Variables to hold sensor readings
float temp;
float hum;
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings
void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting
to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3
MQTT Communication Protocol–Node-RED
if (isnan(temp) || isnan(hum)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Publish an MQTT message on topic esp32/dht/temperature
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true,
String(temp).c_str());
Serial.printf("Publishing on topic %s at QoS 0, packetId: %i", MQTT_PUB_TEMP,
packetIdPub1);
Serial.printf("Message: %.2f \n", temp);
// Publish an MQTT message on topic esp32/dht/humidity
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
Serial.printf("Publishing on topic %s at QoS 0, packetId %i: ", MQTT_PUB_HUM,
packetIdPub2);
Serial.printf("Message: %.2f \n", hum);
}
}
- Open the Serial Monitor at a baud rate of 115200 and you’ll see that the ESP32
starts publishing messages on the topics we’ve defined previously.
IoT 3
MQTT Communication Protocol–Node-RED
The Server field refers to the MQTT broker. In our case, the MQTT broker is
installedin our local PC, so it is set to localhost:1883. If you’re using a Cloud MQTT
broker, you should change that field.
- Insert the topic you want to be subscribed to and the QoS. This previous
MQTT node is subscribed to the esp32/dht/temperaturetopic.
- Click on the other MQTT in node and edit its properties with the same
server, but for the other topic: esp32/dht/humidity.
- Click on the gauge nodes and edit its properties for each reading. The
following node is set for the temperature readings. Edit the other chart
node for the humidity readings
IoT 3
MQTT Communication Protocol–Node-RED
IoT 3