#include <WiFi.h>
#include "cloud_config.h"
#if TB_USE_TLS
#include <WiFiClientSecure.h>
#else
#include <WiFiClient.h>
#endif
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DHT.h>
#include <ESP32Servo.h>
// Proyecto Final IoT - Invernadero inteligente
// Telemetria MQTT directa a ThingsBoard Cloud + RPC para telecontrol.
// La escritura a InfluxDB se realiza desde la Rule Chain de ThingsBoard.
#define DHT_PIN 15
#define DHT_TYPE DHT22
#define LDR_PIN 34
#define LED_PIN 12
#define SERVO_PIN 13
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
#if TB_USE_TLS
const uint16_t TB_MQTT_PORT = 8883;
#else
const uint16_t TB_MQTT_PORT = 1883;
#endif
const char* TB_TELEMETRY_TOPIC = "v1/devices/me/telemetry";
const char* TB_RPC_TOPIC = "v1/devices/me/rpc/request/+";
#if TB_USE_TLS
WiFiClientSecure networkClient;
#else
WiFiClient networkClient;
#endif
PubSubClient mqtt(networkClient);
DHT dht(DHT_PIN, DHT_TYPE);
Servo ventServo;
unsigned long lastPublish = 0;
const unsigned long PUBLISH_INTERVAL_MS = 5000;
int servoAngle = 90;
bool ledOn = false;
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 6);
Serial.print("Conectando a WiFi Wokwi-GUEST");
const unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < 30000) {
delay(400);
Serial.print(".");
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
Serial.print("WiFi conectado. IP: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("No fue posible conectar a WiFi. Se reintentara.");
}
}
void applyLed(bool value) {
ledOn = value;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
void applyServo(int angle) {
servoAngle = constrain(angle, 0, 180);
ventServo.write(servoAngle);
}
void sendRpcResponse(const String& requestId, bool success, const char* message) {
if (requestId.length() == 0 || !mqtt.connected()) return;
JsonDocument response;
response["success"] = success;
response["message"] = message;
response["led_on"] = ledOn;
response["servo_angle"] = servoAngle;
char payload[192];
size_t length = serializeJson(response, payload, sizeof(payload));
String responseTopic = String("v1/devices/me/rpc/response/") + requestId;
mqtt.publish(responseTopic.c_str(), payload, length);
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String topicText(topic);
String requestId = topicText.substring(topicText.lastIndexOf('/') + 1);
String body;
body.reserve(length + 1);
for (unsigned int i = 0; i < length; i++) body += (char)payload[i];
Serial.printf("RPC recibido [%s]: %s\n", topic, body.c_str());
JsonDocument command;
DeserializationError error = deserializeJson(command, body);
if (error) {
Serial.printf("JSON RPC invalido: %s\n", error.c_str());
sendRpcResponse(requestId, false, "JSON invalido");
return;
}
const char* method = command["method"] | "";
JsonVariantConst params = command["params"];
bool success = false;
if (strcmp(method, "setLed") == 0) {
// ThingsBoard Command Button can send a primitive Boolean (true/false)
// or a JSON object such as {"value": true}. Accept both formats.
if (params.is<bool>()) {
applyLed(params.as<bool>());
success = true;
} else if (params["value"].is<bool>()) {
applyLed(params["value"].as<bool>());
success = true;
} else {
Serial.println("Parametro LED invalido. Use Boolean True/False o JSON {\"value\":true/false}.");
}
} else if (strcmp(method, "setServo") == 0) {
// Accept either a numeric angle or a JSON object {"angle": 90}.
if (params.is<int>()) {
applyServo(params.as<int>());
success = true;
} else if (params["angle"].is<int>()) {
applyServo(params["angle"].as<int>());
success = true;
} else {
Serial.println("Parametro servo invalido. Use un entero 0-180 o JSON {\"angle\":90}.");
}
} else if (strcmp(method, "setActuators") == 0) {
bool changed = false;
if (params["led"].is<bool>()) {
applyLed(params["led"].as<bool>());
changed = true;
}
if (params["servo_angle"].is<int>()) {
applyServo(params["servo_angle"].as<int>());
changed = true;
}
success = changed;
}
if (success) {
Serial.printf("Actuadores actualizados: LED=%s, servo=%d grados\n",
ledOn ? "ON" : "OFF", servoAngle);
sendRpcResponse(requestId, true, "Comando ejecutado");
} else {
Serial.printf("Metodo RPC no reconocido o parametros invalidos: %s\n", method);
sendRpcResponse(requestId, false, "Metodo o parametros no validos");
}
}
bool connectThingsBoard() {
if (mqtt.connected()) return true;
mqtt.setServer(TB_MQTT_HOST, TB_MQTT_PORT);
mqtt.setCallback(mqttCallback);
mqtt.setKeepAlive(45);
mqtt.setSocketTimeout(10);
mqtt.setBufferSize(512);
String clientId = String("wokwi-greenhouse-") + String((uint32_t)ESP.getEfuseMac(), HEX);
Serial.printf("Conectando a ThingsBoard Cloud: %s:%u ...\n", TB_MQTT_HOST, TB_MQTT_PORT);
// Access Token del dispositivo como usuario MQTT; password vacio.
if (mqtt.connect(clientId.c_str(), TB_ACCESS_TOKEN, nullptr)) {
Serial.println("MQTT ThingsBoard conectado.");
if (mqtt.subscribe(TB_RPC_TOPIC, 1)) {
Serial.printf("Suscrito a comandos RPC: %s\n", TB_RPC_TOPIC);
} else {
Serial.println("No se pudo suscribir al canal RPC.");
}
return true;
}
Serial.printf("Conexion MQTT fallida. Estado PubSubClient=%d\n", mqtt.state());
return false;
}
float readIlluminationLux(int raw) {
// Estimacion aproximada para el LDR de Wokwi (RL10=50 kOhm, gamma=0.7).
const float GAMMA = 0.7f;
const float RL10 = 50.0f;
const float voltage = (raw / 4095.0f) * 3.3f;
if (voltage >= 3.29f) return 0.0f;
if (voltage <= 0.001f) return 100000.0f;
const float resistance = 10000.0f * voltage / (3.3f - voltage);
float lux = pow((RL10 * 1000.0f * pow(10.0f, GAMMA)) / resistance, 1.0f / GAMMA);
if (!isfinite(lux)) lux = 100000.0f;
return constrain(lux, 0.0f, 100000.0f);
}
void publishTelemetry() {
if (!mqtt.connected()) return;
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
int ldrRaw = analogRead(LDR_PIN);
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Lectura DHT22 no valida; se omite el envio.");
return;
}
float illuminationLux = readIlluminationLux(ldrRaw);
JsonDocument telemetry;
telemetry["temperature_c"] = temperature;
telemetry["humidity_pct"] = humidity;
telemetry["illumination_lux"] = illuminationLux;
telemetry["ldr_raw"] = ldrRaw;
telemetry["led_on"] = ledOn;
telemetry["servo_angle"] = servoAngle;
telemetry["uptime_s"] = millis() / 1000;
char payload[320];
size_t length = serializeJson(telemetry, payload, sizeof(payload));
bool sent = mqtt.publish(TB_TELEMETRY_TOPIC, payload, length);
Serial.printf("Telemetria %s: %s\n", sent ? "ENVIADA" : "FALLIDA", payload);
}
void setup() {
Serial.begin(115200);
delay(250);
pinMode(LED_PIN, OUTPUT);
applyLed(false);
analogReadResolution(12);
dht.begin();
ventServo.setPeriodHertz(50);
ventServo.attach(SERVO_PIN, 500, 2400);
applyServo(90);
if (String(TB_ACCESS_TOKEN).length() < 10 || String(TB_ACCESS_TOKEN).startsWith("PEGA_")) {
Serial.println("ERROR: configura TB_ACCESS_TOKEN en cloud_config.h.");
while (true) delay(1000);
}
#if TB_USE_TLS
if (String(TB_ROOT_CA).length() < 500 || String(TB_ROOT_CA).indexOf("PEGAR") >= 0) {
Serial.println("ERROR: TLS esta activado, pero falta el certificado CA en cloud_config.h.");
while (true) delay(1000);
}
networkClient.setCACert(TB_ROOT_CA);
#else
Serial.println("AVISO: MQTT sin TLS (puerto 1883). Usa solo un token temporal de demostracion.");
#endif
connectWiFi();
mqtt.setServer(TB_MQTT_HOST, TB_MQTT_PORT);
mqtt.setCallback(mqttCallback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
delay(100);
return;
}
if (!mqtt.connected()) {
connectThingsBoard();
delay(100);
return;
}
mqtt.loop();
unsigned long now = millis();
if (now - lastPublish >= PUBLISH_INTERVAL_MS) {
lastPublish = now;
publishTelemetry();
}
}