#include <WiFi.h>
#include <PubSubClient.h>
// =================== CONFIGURACIÓN WIFI ===================
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// =================== CONFIGURACIÓN FLESPI ===================
const char* mqtt_server = "mqtt.flespi.io";
const int mqtt_port = 1883;
const char* mqtt_token = "IkQjuWiRNwmBCSVb1ctKNOk34gGyzDJp3dCtVn6wAdKn6hQyWeBpL7pHq9zGegJc";
const char* mqtt_topic = "agua/sensores";
WiFiClient espClient;
PubSubClient client(espClient);
// =================== PINES ===================
#define PIN_PRESION1 34
#define PIN_FLUJO1 32
#define PIN_HUMEDAD1 25
#define PIN_TEMPERATURA 14
#define PIN_PH 12
#define LED_ALERTA 2
#define LED_NORMAL 4
unsigned long lastReconnectAttempt = 0;
// =================== FUNCIONES ===================
void setup_wifi() {
Serial.print("📡 Conectando a WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n✅ WiFi conectado");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
}
boolean reconnect() {
String clientId = "ESP32_Agua5Sensores_" + String(random(1000, 9999));
Serial.print("🔌 Conectando a Flespi MQTT... ");
if (client.connect(clientId.c_str(), "FlespiToken", mqtt_token)) {
Serial.println("✅ Conectado");
client.subscribe(mqtt_topic);
}
return client.connected();
}
// =================== SETUP ===================
void setup() {
Serial.begin(115200);
delay(200);
pinMode(LED_ALERTA, OUTPUT);
pinMode(LED_NORMAL, OUTPUT);
digitalWrite(LED_ALERTA, LOW);
digitalWrite(LED_NORMAL, HIGH);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
// Ajustes finos de conexión
client.setKeepAlive(120); // envía ping cada 2 min
client.setSocketTimeout(180); // 3 minutos de tolerancia
randomSeed(micros());
lastReconnectAttempt = 0;
}
// =================== LOOP ===================
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
unsigned long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
client.loop();
// Leer sensores
int presion1 = analogRead(PIN_PRESION1);
int flujo1 = analogRead(PIN_FLUJO1);
int humedad1 = analogRead(PIN_HUMEDAD1);
int temperatura = analogRead(PIN_TEMPERATURA);
int ph = analogRead(PIN_PH);
// Crear JSON
char payload[150];
snprintf(payload, sizeof(payload),
"{\"presion1\":%d,\"flujo1\":%d,\"humedad1\":%d,\"temperatura\":%d,\"ph\":%d}",
presion1, flujo1, humedad1, temperatura, ph);
// Enviar
bool ok = client.publish(mqtt_topic, payload);
if (ok) {
Serial.println("📤 Datos enviados a Flespi:");
Serial.println(payload);
digitalWrite(LED_NORMAL, !digitalRead(LED_NORMAL));
} else {
Serial.println("⚠️ Error publicando en MQTT");
digitalWrite(LED_ALERTA, HIGH);
}
delay(5000);
}
}