#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define mqttServer "mqttServer"
#define mqttPort 1883
#define mqttUser "mqttUser"
#define mqttPassword "mqttPassword"
String msg;
WiFiClient wificlient;
PubSubClient mqttClient(wificlient);
void setup() {
Serial.begin(115200);
Serial.println();
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");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
setupMQTT();
}
void loop() {
if (!mqttClient.connected()) {
reconnect();
}
mqttClient.loop();
}
void setupMQTT() {
mqttClient.setServer(mqttServer, mqttPort);
// set the callback function
mqttClient.setCallback(callback);
}
void reconnect() {
Serial.println("Connecting to MQTT Broker...");
while (!mqttClient.connected()) {
Serial.println("Reconnecting to MQTT Broker..");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (mqttClient.connect(clientId.c_str(), mqttUser, mqttPassword)) {
Serial.println("Connected.");
Serial.println(clientId);
// subscribe to topic
mqttClient.subscribe("CPE345IoT/msg");
}
}
}
void callback(char *topic, byte *payload, unsigned int length) {
String sTopic = String(topic);
Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
msg += (char)payload[i];
}
Serial.println("\n======================================");
}