#include <WiFi.h>
#include <PubSubClient.h>
#define LED1 12 // LED para el usuario 1
#define LED2 4 // LED para el usuario 2
#define LED3 5 // LED para el usuario 3
#define LED4 14 // LED para el usuario 4
#define LED5 32 // LED para el usuario 5
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const char* mqtt_server = "broker.hivemq.com";
const char* channelTopic = "IoTLabMQTT63";
const char* responseTopic = "IoTLabMQTT63/response"; // Tema para respuestas
WiFiClient espClient;
PubSubClient client(espClient);
// Lista de IDs para los usuarios
const String userClientIDs[5] = {"client1", "client2", "client3", "client4", "client5"};
int userLEDs[5] = {LED1, LED2, LED3, LED4, LED5};
void setup_wifi() {
delay(100);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Conectado al WiFi");
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
for (unsigned int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Mensaje recibido en el tema ");
Serial.print(topic);
Serial.print(": ");
Serial.println(message);
// Determinar el client ID que envió el mensaje
String clientID = clientIDfromPayload(payload, length);
// Identificar el LED correspondiente al client ID
for (int i = 0; i < 5; i++) {
if (clientID == userClientIDs[i]) {
digitalWrite(userLEDs[i], HIGH); // Enciende el LED
delay(1000); // Espera un segundo
digitalWrite(userLEDs[i], LOW); // Apaga el LED
// Publicar un mensaje de respuesta al broker con el estado del LED
String responseMessage = "LED de " + userClientIDs[i] + " encendido y apagado.";
client.publish(responseTopic, responseMessage.c_str()); // Publica en el tema de respuesta
break;
}
}
}
String clientIDfromPayload(byte* payload, unsigned int length) {
// Extrae el client ID del payload si está presente; en este caso, asumimos que el mensaje contiene solo el texto.
String clientID = "";
for (unsigned int i = 0; i < length; i++) {
clientID += (char)payload[i];
}
return clientID;
}
void reconnect() {
while (!client.connected()) {
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
client.subscribe(channelTopic);
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}