#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "bba80a9ee2ed14f0a9e48075be8f89b42.s1.eu.hivemq.cloud"; // e.g., "broker.hivemq.com"
const int mqtt_port = 8883; // default MQTT port
const char* mqtt_user = "hivemq.webclient.1730091698127"; // optional if using HiveMQ Cloud
const char* mqtt_password = "9D18AF4GzaEBcuyl.<$!"; // optional if using HiveMQ Cloud
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
// Set MQTT server and connect
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
reconnect(); // Connect to MQTT broker
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
Serial.println("connected");
client.subscribe("WeatherTest"); // Subscribe to a topic
} else {
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Publish a test message every 5 seconds
static unsigned long lastTime = 0;
if (millis() - lastTime > 5000) {
lastTime = millis();
client.publish("WeatherTest", "Hello from ESP32");
}
}