#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
#define BOTONA_PIN 25
#define BOTONB_PIN 26
#define BOTONC_PIN 27
// constantes del MQTT
// direccion broker, puerto, y nombre cliente
const char *MQTT_BROKER_ADRESS = "mqtt.eclipseprojects.io";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "PUB_ALEJANDRORP";
// instanciar objetos
WiFiClient espClient;
PubSubClient mqttClient(espClient);
String payload;
String content = "";
volatile bool aPulsado = false;
volatile bool bPulsado = false;
volatile bool cPulsado = false;
void IRAM_ATTR botonA()
{
aPulsado = true;
}
void IRAM_ATTR botonB()
{
bPulsado = true;
}
void IRAM_ATTR botonC()
{
cPulsado = true;
}
void ConnectWiFi()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
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);
}
void ConnectMqtt()
{
while (!mqttClient.connected())
{
Serial.print("Starting MQTT connection...");
if (mqttClient.connect(MQTT_CLIENT_NAME))
{
Serial.print("Client connected");
}
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 PublishMqtt(int data, int caso)
{
payload = "";
payload = String(data);
switch (caso)
{
case 0:
mqttClient.publish("ALEJANDRORP/A", (char *)payload.c_str());
break;
case 1:
mqttClient.publish("ALEJANDRORP/B", (char *)payload.c_str());
break;
case 2:
mqttClient.publish("ALEJANDRORP/C", (char *)payload.c_str());
break;
}
}
void setup(void)
{
Serial.begin(115200);
pinMode(BOTONA_PIN, INPUT_PULLUP);
pinMode(BOTONB_PIN, INPUT_PULLUP);
pinMode(BOTONC_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BOTONA_PIN), &botonA, RISING);
attachInterrupt(digitalPinToInterrupt(BOTONB_PIN), &botonB, RISING);
attachInterrupt(digitalPinToInterrupt(BOTONC_PIN), &botonC, RISING);
ConnectWiFi();
InitMqtt();
}
void loop()
{
HandleMqtt();
if (aPulsado)
{
PublishMqtt(0, 0);
aPulsado = false;
}
if (bPulsado)
{
PublishMqtt(1, 1);
bPulsado = false;
}
if (cPulsado)
{
PublishMqtt(2, 2);
cPulsado = false;
}
delay(100);
}