#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
// ====== Configuración WiFi ======
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ====== Configuración MQTT ======
const char* mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883;
const char* topicData = "fitotron/data";
WiFiClient espClient;
PubSubClient client(espClient);
// ====== LED de estado ======
const int statusLedPin = 2;
// ====== Variables de sensores simulados ======
float temp = 25.0;
float hum = 60.0;
float co2 = 400.0;
float ph = 6.5;
float ec = 1.2;
float light = 300.0;
float waterLevel = 50.0;
float par = 200.0;
// ====== Función conexión WiFi ======
void setupWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi conectado, IP: " + WiFi.localIP().toString());
digitalWrite(statusLedPin, HIGH);
}
// ====== Reconexión MQTT ======
void reconnectMQTT() {
while (!client.connected()) {
String clientId = "ESP32-Fitotron-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("MQTT conectado");
} else {
delay(2000);
}
}
}
// ====== Simulación de sensores ======
float generateRandomValue(float current, float minV, float maxV, float variation) {
float newValue = current + random(-variation * 100, variation * 100) / 100.0;
if (newValue < minV) newValue = minV;
if (newValue > maxV) newValue = maxV;
return newValue;
}
// ====== Publicar datos ======
void publishSensorData(void * parameter) {
for (;;) {
if (!client.connected()) reconnectMQTT();
client.loop();
// Simular sensores
temp = generateRandomValue(temp, 15, 35, 0.5);
hum = generateRandomValue(hum, 30, 90, 1.0);
co2 = generateRandomValue(co2, 300, 2000, 50);
ph = generateRandomValue(ph, 5.5, 7.5, 0.1);
ec = generateRandomValue(ec, 0.5, 3.0, 0.1);
light = generateRandomValue(light, 100, 1000, 20);
waterLevel = generateRandomValue(waterLevel, 0, 100, 2);
par = generateRandomValue(par, 50, 500, 10);
// Crear JSON
StaticJsonDocument<256> doc;
doc["temp"] = temp;
doc["hum"] = hum;
doc["co2"] = co2;
doc["ph"] = ph;
doc["ec"] = ec;
doc["light"] = light;
doc["waterLevel"] = waterLevel;
doc["par"] = par;
char buffer[256];
serializeJson(doc, buffer);
client.publish(topicData, buffer);
Serial.println("MQTT >> " + String(buffer));
vTaskDelay(2000 / portTICK_PERIOD_MS); // cada 2s
}
}
// ====== Setup ======
void setup() {
Serial.begin(115200);
pinMode(statusLedPin, OUTPUT);
setupWiFi();
client.setServer(mqtt_server, mqtt_port);
// Crear tarea para publicar sensores
xTaskCreatePinnedToCore(
publishSensorData, // función
"TaskPublish", // nombre
4096, // stack
NULL, // parámetro
1, // prioridad
NULL, // handle
1 // core
);
}
void loop() {
// Nada, todo lo maneja FreeRTOS
}