/* ESP32 MQTT Basic
An example on connecting to a mqtt server
Steps:
- Go to: https://www.hivemq.com/demos/websocket-client/ and connect
- To receive messages on the web client subscribe with the topic value of the mqttTopicWeb variable
- To publish a message replace the topic with the value of the mqttTopicDevice variable, and enter a message
- In this simulation the device publishes to the same topic once it receives a message
*/
#include <WiFi.h>
#include <PubSubClient.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your MQTT broker details
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
const char* mqttTopicDevice = "wokwi/jkan/test-0/device"; // These need to be different otherwise we will be in a loop
const char* mqttTopicWeb = "wokwi/jkan/test-0/web";
char* clientId = "clientId-jk635-0";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
// Set up MQTT client
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) reconnectMQTTClient();
client.loop();
delay(10); // this speeds up the simulation
}
void reconnectMQTTClient() {
Serial.println("Connecting to MQTT cluster");
while (!client.connected()) {
if (client.connect(clientId)) {
Serial.print(clientId);
Serial.println(" connected");
client.subscribe(mqttTopicDevice);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)message[i]);
}
Serial.println();
Serial.print("Publishing on topic: ");
Serial.print(topic);
const char* reply = "Message received";
client.publish(mqttTopicWeb, reply);
}
Loading
esp32-s2-devkitm-1
esp32-s2-devkitm-1