#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "broker.hivemq.com";
int port = 1883;
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
Serial.print("Connecting to ");
Serial.println(ssid);
wifiConnect();
client.setServer(mqttServer, port);
client.setCallback(callback);
}
void loop()
{
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
if (!client.connected())
{
mqttReconnect();
}
client.loop();
}
void wifiConnect() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void mqttReconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
long r = random(1000);
sprintf(clientId, "fcs-clientId-%ld", r);
if (client.connect(clientId)) {
Serial.print(clientId);
Serial.println(" connected");
client.subscribe("ESP32-sub2");
} 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: ");
String stMessage;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
stMessage += (char)message[i];
}
// if(stMessage=="off")
// {
// int adc = 4095;
// char buffer[20];
// snprintf(buffer, sizeof(buffer), "%d", adc);
// client.publish("esp32-pub",buffer);
// }
}