// To view the data:
// 1. Go to http://www.hivemq.com/demos/websocket-client/
// 2. Click "Connect"
// 3. Under Subscriptions, click "Add New Topic Subscription"
// 4. In the Topic field, type "esp32/test" then click "Subscribe"
#include <WiFi.h>
#include <PubSubClient.h>
const char *mqtt_broker = "broker.mqttdashboard.com";
const char *topic = "esp32/test";
const char *mqtt_username = "";
const char *mqtt_password = "";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600);
Serial.println("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println();
Serial.println("Connected!");
client.setServer(mqtt_broker, mqtt_port);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s is connecting to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public hivemq broker connected!");
} else {
Serial.printf("Failed with state %s\n", client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "Hello");
client.subscribe(topic);
}
// void callback(char *topic, byte *payload, unsigned int length) {
// Serial.print("Message arrived in topic: ");
// Serial.println(topic);
// Serial.print("Message:");
// for (int i = 0; i < length; i++) {
// Serial.print((char) payload[i]);
// }
// Serial.println();
// Serial.println("-----------------------");
// }
void loop() {
// delay(100); // TODO: Build something amazing!
client.loop();
}