|
|
// Setup WiFi To own Network
|
|
|
// Send Data from ESP32 over MQTT to PC with Node-red
|
|
|
// Wokwi
|
|
|
// Setup WiFi To own Network // Send Data from ESP32 over MQTT to PC with Node-red // Wokwi
|
|
|
|
|
|
# Self-Learning Make the ESP32 an IoT-Device
|
|
|
|
|
|
**Goal**
|
|
|
The goal of this section is to send data cyclically (every 1 second) from the ESP32 to a public MQTT broker. Additionally, we aim to subscribe to the sent data packet from your PC and visualize it.
|
|
|
**Goal** The goal of this section is to send data cyclically (every 1 second) from the ESP32 to a public MQTT broker. Additionally, we aim to subscribe to the sent data packet from your PC and visualize it.
|
|
|
|
|
|
## Establishing WiFi Connection with the ESP32
|
|
|
|
|
|
There are numerous libraries available that help quickly establish a connection to your router. To develop a consistent solution during the workshop, we will use a specific library.
|
|
|
The ESP32 has a built-in WiFi antenna. Using the WiFi.h library, a WiFi connection can be established in a few steps.
|
|
|
There are numerous libraries available that help quickly establish a connection to your router. To develop a consistent solution during the workshop, we will use a specific library. The ESP32 has a built-in WiFi antenna. Using the WiFi.h library, a WiFi connection can be established in a few steps.
|
|
|
|
|
|
## Define your WiFi-Network
|
|
|
|
... | ... | @@ -42,14 +39,11 @@ void initWiFi() { |
|
|
}
|
|
|
Serial.println(WiFi.localIP());
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
> :exclamation: :books: Include this function in your code to connect your ESP with the WiFi. This function must be placed outside and above the 'setup()' function
|
|
|
|
|
|
> :books: Rufen Sie diese Funktion ``wifiConnect()`` in der ``setup()`` Ihres Programmcodes auf!
|
|
|
> For the output to work on the serial monitor, you must also call the function `Serial.begin(115200)` in the `setup()`.
|
|
|
|
|
|
> :books: Rufen Sie diese Funktion `wifiConnect()` in der `setup()` Ihres Programmcodes auf! For the output to work on the serial monitor, you must also call the function `Serial.begin(115200)` in the `setup()`.
|
|
|
|
|
|
---
|
|
|
|
... | ... | @@ -65,7 +59,9 @@ void wifiCheckConnection() { |
|
|
yield(); //
|
|
|
}
|
|
|
```
|
|
|
|
|
|
## Complete Code
|
|
|
|
|
|
```C++
|
|
|
#include <WiFi.h>
|
|
|
|
... | ... | @@ -110,19 +106,17 @@ void loop() { |
|
|
}
|
|
|
```
|
|
|
|
|
|
This is one way to set up your WiFi connection. There are several ways to make your ESP an IoT device. If your simulated ESP32 is not connecting to the WiFi, you might be facing specific circumstances while using Wokwi. The simulation environment provides you with an access point (SSID and PWD) and can only connect to the internet via this AP if your PC has internet access.
|
|
|
You can have a look into the documentation or simply replace one line of code:
|
|
|
This is one way to set up your WiFi connection. There are several ways to make your ESP an IoT device. If your simulated ESP32 is not connecting to the WiFi, you might be facing specific circumstances while using Wokwi. The simulation environment provides you with an access point (SSID and PWD) and can only connect to the internet via this AP if your PC has internet access. You can have a look into the documentation or simply replace one line of code:
|
|
|
|
|
|
```C++
|
|
|
WiFi.begin("Wokwi-GUEST", "", 6);
|
|
|
```
|
|
|
|
|
|
> Now you should have an simulated ESP32 with established Wifi-Connection.
|
|
|
|
|
|
# Communication via MQTT
|
|
|
In an industrial context, the MQTT protocol is often used for communication between entities. It allows for cleanly structured and efficiently distributed messages. If you are unfamiliar with MQTT, you can review some basics on our fundamentals page. At a minimum, you should understand the basic procedures and differences compared to, for example, REST, to comprehend the advantages of MQTT in practice.
|
|
|
// Link zum MQTT-Page
|
|
|
|
|
|
|
|
|
In an industrial context, the MQTT protocol is often used for communication between entities. It allows for cleanly structured and efficiently distributed messages. If you are unfamiliar with MQTT, you can review some basics on our fundamentals page. At a minimum, you should understand the basic procedures and differences compared to, for example, REST, to comprehend the advantages of MQTT in practice. // Link zum MQTT-Page
|
|
|
|
|
|
# JSON
|
|
|
|
... | ... | @@ -162,10 +156,194 @@ To demonstrate how quickly and easily the ESP32 can connect to WiFi, we previous |
|
|
|
|
|
## Adapting the Code
|
|
|
|
|
|
```C++
|
|
|
#include <Arduino.h>
|
|
|
#include <ArduinoJson.h>
|
|
|
#include <AsyncMqttClient.h>
|
|
|
#include "WiFi.h"
|
|
|
//-------------------------------------------------------------------------
|
|
|
//WIFI
|
|
|
//-------------------------------------------------------------------------
|
|
|
#define WIFI_SSID "Wokwi-GUEST"
|
|
|
#define WIFI_PASSWORD ""
|
|
|
TimerHandle_t wifiReconnectTimer;
|
|
|
//-------------------------------------------------------------------------
|
|
|
//MQTT
|
|
|
//-------------------------------------------------------------------------
|
|
|
#define MQTT_HOST "test.mosquitto.org"
|
|
|
#define MQTT_PORT 1883
|
|
|
const char* ID = "ThisisMyVisibleonBroker";
|
|
|
TimerHandle_t mqttReconnectTimer;
|
|
|
AsyncMqttClient mqttClient;
|
|
|
|
|
|
}
|
|
|
void connectToMqtt(){
|
|
|
mqttClient.connect();
|
|
|
}
|
|
|
|
|
|
void onMqttConnect(bool sessionPresent) {
|
|
|
Serial.println("Connected to MQTT.");
|
|
|
//uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2);
|
|
|
}
|
|
|
|
|
|
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
|
|
Serial.println("Disconnected from MQTT.");
|
|
|
|
|
|
if (WiFi.isConnected()) {
|
|
|
xTimerStart(mqttReconnectTimer, 0);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
|
|
|
Serial.println("Subscribe acknowledged.");
|
|
|
Serial.print(" packetId: ");
|
|
|
Serial.println(packetId);
|
|
|
Serial.print(" qos: ");
|
|
|
Serial.println(qos);
|
|
|
}
|
|
|
|
|
|
void onMqttUnsubscribe(uint16_t packetId) {
|
|
|
Serial.println("Unsubscribe acknowledged.");
|
|
|
Serial.print(" packetId: ");
|
|
|
Serial.println(packetId);
|
|
|
}
|
|
|
|
|
|
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
|
|
Serial.println("Publish received.");
|
|
|
Serial.print(" topic: ");
|
|
|
Serial.println(topic);
|
|
|
Serial.print(" qos: ");
|
|
|
Serial.println(properties.qos);
|
|
|
Serial.print(" dup: ");
|
|
|
Serial.println(properties.dup);
|
|
|
Serial.print(" retain: ");
|
|
|
Serial.println(properties.retain);
|
|
|
Serial.print(" len: ");
|
|
|
Serial.println(len);
|
|
|
Serial.print(" index: ");
|
|
|
Serial.println(index);
|
|
|
Serial.print(" total: ");
|
|
|
Serial.println(total);
|
|
|
}
|
|
|
|
|
|
void onMqttPublish(uint16_t packetId) {
|
|
|
Serial.println("Publish acknowledged.");
|
|
|
Serial.print(" packetId: ");
|
|
|
Serial.println(packetId);
|
|
|
}
|
|
|
void connectToWifi() {
|
|
|
Serial.println("Connecting to Wi-Fi...");
|
|
|
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
|
|
|
}
|
|
|
|
|
|
|
|
|
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;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
//-------------------------------------------------------------------------
|
|
|
//Creating JSON-Object!
|
|
|
//-------------------------------------------------------------------------
|
|
|
String set_fruitbasketMsg() {
|
|
|
// Create a JSON document
|
|
|
StaticJsonDocument<200> jsonDoc;
|
|
|
|
|
|
// Create the root object
|
|
|
JsonObject fruitBasket = jsonDoc.createNestedObject("fruitBasket");
|
|
|
|
|
|
// Add properties to the fruitBasket object
|
|
|
fruitBasket["name"] = "Victor";
|
|
|
fruitBasket["material"] = "PVC";
|
|
|
fruitBasket["emptyWeight"] = 200;
|
|
|
|
|
|
// Create the nested content object
|
|
|
JsonObject content = fruitBasket.createNestedObject("content");
|
|
|
|
|
|
// Create the nested apple object within content
|
|
|
JsonObject apple = content.createNestedObject("apple");
|
|
|
apple["weight"] = 100;
|
|
|
apple["color"] = "light green";
|
|
|
|
|
|
// Create the nested colorCodeRGB array within apple
|
|
|
JsonArray colorCodeRGB = apple.createNestedArray("colorCodeRGB");
|
|
|
colorCodeRGB.add(0);
|
|
|
colorCodeRGB.add(255);
|
|
|
colorCodeRGB.add(150);
|
|
|
|
|
|
// Add the isPoisonous property to apple
|
|
|
apple["isPoisonous"] = false;
|
|
|
|
|
|
// Convert the JSON document to a string
|
|
|
String jsonString;
|
|
|
serializeJson(jsonDoc, jsonString);
|
|
|
|
|
|
return jsonString;
|
|
|
}
|
|
|
|
|
|
void PublishMsgBasket(){
|
|
|
String msg;
|
|
|
msg = set_fruitbasketMsg();
|
|
|
String topic = "MYfancyTopic/Dummy/Data/Basket";
|
|
|
mqttClient.publish((char*)topic.c_str(),0,true,(char*)msg.c_str());
|
|
|
}
|
|
|
|
|
|
|
|
|
unsigned long previousMillis = 0;
|
|
|
const long interval = 1000; // 1 second interval
|
|
|
|
|
|
|
|
|
void setup() {
|
|
|
Serial.begin(115200);
|
|
|
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
|
|
|
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
|
|
|
|
|
|
WiFi.onEvent(WiFiEvent);
|
|
|
|
|
|
mqttClient.onConnect(onMqttConnect);
|
|
|
mqttClient.onDisconnect(onMqttDisconnect);
|
|
|
mqttClient.onSubscribe(onMqttSubscribe);
|
|
|
mqttClient.onUnsubscribe(onMqttUnsubscribe);
|
|
|
mqttClient.onMessage(onMqttMessage);
|
|
|
mqttClient.onPublish(onMqttPublish);
|
|
|
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
|
|
|
|
|
|
connectToWifi();
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
void loop(){
|
|
|
unsigned long currentMillis = millis();
|
|
|
if (currentMillis - previousMillis >= interval) {
|
|
|
previousMillis = currentMillis;
|
|
|
publishMsgBasket();
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
Now the ESP32 should send the data packet every 1000ms (1 second) to the MQTT broker via your router. To verify this, you can use sniffer tools to subscribe to the topic or even monitor the entire broker (i.e., all topics). Here, we will show you our favorite tool, which allows you to do many additional things.
|
|
|
|
|
|
### Verifying the MQTT Communication
|
|
|
|
|
|
There are various sniffer tools available that can be used to subscribe to a specific topic or even listen to all topics on the broker. We recommend using our preferred tool, Node-Red, which provides a wide range of functionalities and features for visualizing and managing your MQTT communications.
|
|
|
|
|
|
Node-Red can help you ensure that the data is being sent correctly and received as expected. It also allows you to create complex workflows and visualizations for your IoT data.
|
|
|
|
|
|
Jetzt sollte der esp32 über euren Router das Datenpaket im Zyklus von 2000ms an den MQTT-Broker senden!
|
|
|
Naja das sollten wir schon überprüfen.
|
|
|
Es gibt sogenannte SnifferTools mit denen wir das Topic abonnieren können oder auch den gesamten Broker (Sprich alle Topic) abhören können.
|
|
|
Hier zeigen wir euch aber unser Favourite Tool mit dem Ihr ganz viele zusätzliche Dinge machen könnt.
|
|
|
Make sure to explore Node-Red and other available tools to enhance your understanding and capability in handling MQTT communications effectively.
|
|
|
|
|
|
Node-Red |
|
|
\ No newline at end of file |