#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define WIFI_CHANNEL 6
#define ledA 12
#define ledB 14
#define ledC 25
const char *MQTT_BROKER_ADRESS = "mqtt.eclipseprojects.io";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "PabloRomero_sub_test";
WiFiClient espClient;
PubSubClient mqttClient(espClient);
String payload;
String content = "";
void ConnectWiFi()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void InitMqtt()
{
mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
SuscribeMqtt_BA();
SuscribeMqtt_BB();
SuscribeMqtt_BC();
mqttClient.setCallback(OnMqttReceived);
}
void ConnectMqtt()
{
while (!mqttClient.connected())
{
Serial.print("Starting MQTT connection...");
if (mqttClient.connect(MQTT_CLIENT_NAME))
{
Serial.println("Client connected!");
SuscribeMqtt_BA();
SuscribeMqtt_BB();
SuscribeMqtt_BC();
}
else
{
Serial.print("Failed MQTT connection, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void HandleMqtt()
{
if (!mqttClient.connected())
{
ConnectMqtt();
}
mqttClient.loop();
}
void SuscribeMqtt_BA()
{
mqttClient.subscribe("PabloRomero/Boton A"); //topic del boton A
}
void SuscribeMqtt_BB()
{
mqttClient.subscribe("PabloRomero/Boton B"); //topic del boton B
}
void SuscribeMqtt_BC()
{
mqttClient.subscribe("PabloRomero/Boton C"); //topic del boton C
}
//este es el unico que uso, que se ejecuta siempre en cualquier callback
void OnMqttReceived(char *topic, byte *payload, unsigned int length)
{
content = "";
for (size_t i = 0; i < length; i++)
{
content.concat((char)payload[i]);
}
if (String(topic) == "PabloRomero/Boton A")
{
if (content == "1")
{
digitalWrite(ledA, HIGH); // Enciende LED A
}
else if (content == "0")
{
digitalWrite(ledA, LOW); // Apaga LED A
}
}
else if (String(topic) == "PabloRomero/Boton B")
{
if (content == "1")
{
digitalWrite(ledB, HIGH); // Enciende LED B
}
else if (content == "0")
{
digitalWrite(ledB, LOW); // Apaga LED B
}
}
else if (String(topic) == "PabloRomero/Boton C")
{
if (content == "1")
{
digitalWrite(ledC, HIGH); // Enciende LED C
}
else if (content == "0")
{
digitalWrite(ledC, LOW); // Apaga LED C
}
}
}
void setup(void)
{
Serial.begin(115200);
pinMode(ledA, OUTPUT);
pinMode(ledB, OUTPUT);
pinMode(ledC, OUTPUT);
ConnectWiFi();
InitMqtt();
SuscribeMqtt_BA();
SuscribeMqtt_BB();
SuscribeMqtt_BC();
}
void loop()
{
HandleMqtt();
delay(10);
}