#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <ESP32Servo.h>
#include <math.h>
#include <time.h>
#include "certs.h"
// =====================================================
// CONFIGURACION FIREBASE
// =====================================================
const char* DATABASE_URL =
"https://gestion-inteligente-residuos-default-rtdb.firebaseio.com";
String idToken = "";
unsigned long tokenCreatedAt = 0;
const unsigned long TOKEN_LIFETIME = 3300000;
// =====================================================
// CONFIGURACION CLOUDFLARE
// =====================================================
const char* WORKER_URL =
"https://gestion-inteligente-residuos.camiloggiraldo1.workers.dev";
// Cambiar a true cuando se quiera probar Cloudflare.
const bool PROBAR_CLOUDFLARE = false;
bool pruebaCloudflareRealizada = false;
// =====================================================
// CONFIGURACION WIFI
// =====================================================
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const unsigned long WIFI_RETRY_INTERVAL = 15000;
unsigned long lastWiFiAttempt = 0;
bool clockStarted = false;
bool wifiWasConnected = false;
// =====================================================
// CONFIGURACION DE SENSORES
// =====================================================
const int TRIG_A = 16;
const int ECHO_A = 34;
const int TRIG_B = 17;
const int ECHO_B = 35;
const int TRIG_C = 18;
const int ECHO_C = 32;
const int PIN_SERVO = 25;
// =====================================================
// CALIBRACION
// =====================================================
const float DISTANCIA_VACIO = 30.0;
const float DISTANCIA_LLENO = 3.0;
const float UMBRAL_RECOLECCION = 75.0;
// =====================================================
// TEMPORIZACION
// =====================================================
const unsigned long INTERVALO = 5000;
unsigned long lastCycle = 0;
unsigned long lastSensorRead = 0;
int sensorIndex = 0;
bool measuring = false;
// =====================================================
// SERVOMOTOR Y MONITOR SERIAL
// =====================================================
Servo servoTapa;
const int SERVO_CERRADO = 0;
const int SERVO_ABIERTO = 90;
String serialBuffer = "";
bool descartarComando = false;
// =====================================================
// ESTRUCTURA DE CONTENEDORES
// =====================================================
struct Contenedor {
char nombre;
int trigPin;
int echoPin;
float distancia;
float nivel;
bool critico;
bool valido;
float x;
float y;
};
Contenedor contenedores[3] = {
{'A', TRIG_A, ECHO_A, 0, 0, false, false, 2, 1},
{'B', TRIG_B, ECHO_B, 0, 0, false, false, 5, 2},
{'C', TRIG_C, ECHO_C, 0, 0, false, false, 4, 5}
};
// =====================================================
// DECLARACION DE FUNCIONES
// =====================================================
void gestionarWiFi();
void gestionarMediciones();
float medirDistancia(int trigPin, int echoPin);
float calcularNivel(float distancia);
void leerContenedor(Contenedor &c);
const char* obtenerEstado(float nivel);
void mostrarContenedores();
float distanciaEntrePuntos(
float x1,
float y1,
float x2,
float y2
);
void generarRuta();
void enviarFirebase();
void controlarServoSerial();
void procesarComando(String comando);
void probarCloudflare();
// =====================================================
// SETUP
// =====================================================
void setup() {
Serial.setRxBufferSize(4096);
Serial.begin(115200);
Serial.setTimeout(1000);
serialBuffer.reserve(4096);
Serial.println();
Serial.println("==============================");
Serial.println(" SISTEMA INTELIGENTE IoT");
Serial.println("==============================");
// Configuracion de sensores
for (int i = 0; i < 3; i++) {
pinMode(contenedores[i].trigPin, OUTPUT);
pinMode(contenedores[i].echoPin, INPUT);
digitalWrite(contenedores[i].trigPin, LOW);
}
// Configuracion del servomotor
servoTapa.setPeriodHertz(50);
servoTapa.attach(PIN_SERVO, 500, 2400);
servoTapa.write(SERVO_CERRADO);
// Configuracion WiFi
WiFi.mode(WIFI_STA);
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD,
6
);
lastWiFiAttempt = millis();
Serial.println("Conectando a Wokwi-GUEST...");
Serial.println();
Serial.println("COMANDOS DISPONIBLES:");
Serial.println("A: Abrir tapa");
Serial.println("C: Cerrar tapa");
Serial.println("TOKEN <token>: Autenticar Firebase");
}
// =====================================================
// LOOP PRINCIPAL
// =====================================================
void loop() {
gestionarWiFi();
controlarServoSerial();
gestionarMediciones();
// Prueba opcional de Cloudflare
if (
PROBAR_CLOUDFLARE &&
!pruebaCloudflareRealizada &&
WiFi.status() == WL_CONNECTED &&
time(nullptr) >= 1700000000
) {
pruebaCloudflareRealizada = true;
probarCloudflare();
}
delay(1);
}
// =====================================================
// GESTIONAR CONEXION WIFI
// =====================================================
void gestionarWiFi() {
if (WiFi.status() == WL_CONNECTED) {
if (!wifiWasConnected) {
wifiWasConnected = true;
Serial.println();
Serial.println("WiFi conectado correctamente.");
Serial.print("Direccion IP: ");
Serial.println(WiFi.localIP());
}
if (!clockStarted) {
clockStarted = true;
// Sincronizar reloj para HTTPS
configTime(
0,
0,
"pool.ntp.org",
"time.google.com"
);
Serial.println("Sincronizando reloj...");
Serial.println();
Serial.println("Esperando token de Firebase.");
Serial.println(
"Pegue el comando TOKEN en el monitor serial."
);
}
return;
}
if (wifiWasConnected) {
wifiWasConnected = false;
Serial.println("Se perdio la conexion WiFi.");
}
// Intentar reconexion cada 15 segundos
if (
millis() - lastWiFiAttempt >= WIFI_RETRY_INTERVAL
) {
lastWiFiAttempt = millis();
Serial.print("Estado WiFi: ");
Serial.println((int) WiFi.status());
Serial.println("Intentando reconectar WiFi...");
WiFi.disconnect();
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD,
6
);
}
}
// =====================================================
// GESTIONAR CICLO DE MEDICIONES
// =====================================================
void gestionarMediciones() {
unsigned long ahora = millis();
if (!measuring) {
if (ahora - lastCycle < INTERVALO) {
return;
}
lastCycle = ahora;
sensorIndex = 0;
measuring = true;
lastSensorRead = ahora;
return;
}
// Separar lecturas para evitar interferencias
if (ahora - lastSensorRead < 70) {
return;
}
lastSensorRead = ahora;
leerContenedor(contenedores[sensorIndex]);
sensorIndex++;
if (sensorIndex >= 3) {
measuring = false;
mostrarContenedores();
generarRuta();
enviarFirebase();
}
}
// =====================================================
// MEDIR DISTANCIA
// =====================================================
float medirDistancia(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
unsigned long duracion =
pulseIn(echoPin, HIGH, 30000);
if (duracion == 0) {
return NAN;
}
float distancia =
duracion * 0.0343 / 2.0;
if (distancia < 2 || distancia > 400) {
return NAN;
}
return distancia;
}
// =====================================================
// CALCULAR NIVEL DE LLENADO
// =====================================================
float calcularNivel(float distancia) {
float nivel =
(
(DISTANCIA_VACIO - distancia) /
(DISTANCIA_VACIO - DISTANCIA_LLENO)
)
* 100.0;
return constrain(nivel, 0.0f, 100.0f);
}
// =====================================================
// LEER CONTENEDOR
// =====================================================
void leerContenedor(Contenedor &c) {
float distancia =
medirDistancia(c.trigPin, c.echoPin);
if (isnan(distancia)) {
c.valido = false;
c.critico = false;
Serial.print("Error de medicion: ");
Serial.println(c.nombre);
return;
}
c.valido = true;
c.distancia = distancia;
c.nivel = calcularNivel(distancia);
c.critico =
c.nivel >= UMBRAL_RECOLECCION;
}
// =====================================================
// CLASIFICAR NIVEL
// =====================================================
const char* obtenerEstado(float nivel) {
if (nivel < 50) {
return "BAJO";
}
if (nivel < 75) {
return "MEDIO";
}
return "CRITICO";
}
// =====================================================
// MOSTRAR CONTENEDORES
// =====================================================
void mostrarContenedores() {
Serial.println();
Serial.println("==============================");
Serial.println(" NUEVA MEDICION");
Serial.println("==============================");
for (int i = 0; i < 3; i++) {
Contenedor &c = contenedores[i];
Serial.print("Contenedor ");
Serial.println(c.nombre);
if (!c.valido) {
Serial.println(" Medicion invalida");
continue;
}
Serial.print(" Distancia: ");
Serial.print(c.distancia, 2);
Serial.println(" cm");
Serial.print(" Nivel: ");
Serial.print(c.nivel, 2);
Serial.println(" %");
Serial.print(" Estado: ");
Serial.println(obtenerEstado(c.nivel));
Serial.println();
}
}
// =====================================================
// DISTANCIA EUCLIDIANA
// =====================================================
float distanciaEntrePuntos(
float x1,
float y1,
float x2,
float y2
) {
return sqrt(
pow(x2 - x1, 2) +
pow(y2 - y1, 2)
);
}
// =====================================================
// GENERAR RUTA - VECINO MAS CERCANO
// =====================================================
void generarRuta() {
bool visitado[3] = {
false,
false,
false
};
float actualX = 0;
float actualY = 0;
int cantidadCriticos = 0;
for (int i = 0; i < 3; i++) {
if (!contenedores[i].valido) {
Serial.println(
"Ruta no calculada: medicion invalida."
);
return;
}
if (contenedores[i].critico) {
cantidadCriticos++;
}
}
if (cantidadCriticos == 0) {
Serial.println("No se requiere recoleccion.");
return;
}
Serial.print("Ruta recomendada: BASE");
for (int paso = 0; paso < cantidadCriticos; paso++) {
int mejorIndice = -1;
float mejorDistancia = INFINITY;
for (int i = 0; i < 3; i++) {
if (
contenedores[i].critico &&
!visitado[i]
) {
float distancia = distanciaEntrePuntos(
actualX,
actualY,
contenedores[i].x,
contenedores[i].y
);
if (distancia < mejorDistancia) {
mejorDistancia = distancia;
mejorIndice = i;
}
}
}
if (mejorIndice == -1) {
break;
}
visitado[mejorIndice] = true;
Serial.print(" -> ");
Serial.print(contenedores[mejorIndice].nombre);
actualX = contenedores[mejorIndice].x;
actualY = contenedores[mejorIndice].y;
}
Serial.println(" -> BASE");
}
// =====================================================
// ENVIAR MEDICIONES A FIREBASE
// =====================================================
void enviarFirebase() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi no disponible.");
return;
}
if (idToken.isEmpty()) {
Serial.println("Firebase: esperando token.");
return;
}
if (millis() - tokenCreatedAt >= TOKEN_LIFETIME) {
idToken = "";
Serial.println("Se requiere un nuevo token.");
return;
}
if (time(nullptr) < 1700000000) {
Serial.println("Esperando sincronizacion del reloj.");
return;
}
// Validar todas las mediciones
for (int i = 0; i < 3; i++) {
if (!contenedores[i].valido) {
Serial.println(
"Envio omitido: medicion invalida."
);
return;
}
}
// Construir objeto JSON
JsonDocument doc;
for (int i = 0; i < 3; i++) {
Contenedor &c = contenedores[i];
char id[2] = {c.nombre, '\0'};
JsonObject item =
doc[id].to<JsonObject>();
item["nivel"] =
roundf(c.nivel * 100.0f) / 100.0f;
item["distancia"] =
roundf(c.distancia * 100.0f) / 100.0f;
}
String json;
serializeJson(doc, json);
// Conexion HTTPS segura
WiFiClientSecure client;
client.setCACert(GOOGLE_ROOT_CA);
client.setHandshakeTimeout(20);
HTTPClient http;
String base = DATABASE_URL;
if (base.endsWith("/")) {
base.remove(base.length() - 1);
}
String url =
base +
"/sistema-residuos/contenedores.json?auth=" +
idToken;
if (!http.begin(client, url)) {
Serial.println("No se pudo iniciar HTTPS.");
return;
}
http.setConnectTimeout(15000);
http.setTimeout(15000);
http.addHeader(
"Content-Type",
"application/json"
);
Serial.println();
Serial.println("Enviando mediciones a Firebase...");
int httpCode = http.PUT(json);
Serial.print("Codigo HTTP: ");
Serial.println(httpCode);
// Errores de conexion
if (httpCode < 0) {
Serial.print("Detalle HTTP: ");
Serial.println(
HTTPClient::errorToString(httpCode)
);
char tlsError[256] = {0};
int tlsCode = client.lastError(
tlsError,
sizeof(tlsError)
);
Serial.print("Codigo TLS: ");
Serial.println(tlsCode);
Serial.print("Detalle TLS: ");
Serial.println(tlsError);
http.end();
return;
}
String respuesta = http.getString();
// Envio exitoso
if (httpCode == 200) {
Serial.println(
"Datos enviados correctamente a Firebase."
);
Serial.println(json);
} else {
Serial.println("Error enviando datos.");
Serial.print("Respuesta de Firebase: ");
Serial.println(respuesta);
if (httpCode == 401) {
Serial.println("Autorizacion rechazada.");
Serial.println(
"Verifique el token y los permisos."
);
idToken = "";
}
}
http.end();
}
// =====================================================
// CONTROL SERIAL
// =====================================================
void controlarServoSerial() {
while (Serial.available() > 0) {
char caracter = Serial.read();
if (caracter == '\r') {
continue;
}
if (caracter == '\n') {
if (!descartarComando) {
serialBuffer.trim();
if (serialBuffer.length() > 0) {
procesarComando(serialBuffer);
}
}
serialBuffer = "";
descartarComando = false;
} else {
if (descartarComando) {
continue;
}
if (serialBuffer.length() < 4096) {
serialBuffer += caracter;
} else {
serialBuffer = "";
descartarComando = true;
Serial.println(
"Comando serial demasiado largo."
);
}
}
}
}
// =====================================================
// PROCESAR COMANDOS
// =====================================================
void procesarComando(String comando) {
comando.trim();
// Recibir token de Firebase
if (comando.startsWith("TOKEN ")) {
String tokenRecibido =
comando.substring(6);
tokenRecibido.trim();
int primerPunto =
tokenRecibido.indexOf('.');
int segundoPunto =
tokenRecibido.indexOf('.', primerPunto + 1);
if (
tokenRecibido.length() < 100 ||
primerPunto <= 0 ||
segundoPunto <= primerPunto + 1 ||
segundoPunto >= tokenRecibido.length() - 1 ||
tokenRecibido.indexOf('.', segundoPunto + 1) >= 0 ||
tokenRecibido.indexOf(' ') >= 0
) {
Serial.println("Formato de token invalido.");
return;
}
idToken = tokenRecibido;
tokenCreatedAt = millis();
Serial.println();
Serial.println("==============================");
Serial.println(" TOKEN DE FIREBASE RECIBIDO");
Serial.println("==============================");
Serial.println("Esperando siguiente medicion.");
return;
}
// Abrir servomotor
if (comando.equalsIgnoreCase("A")) {
servoTapa.write(SERVO_ABIERTO);
Serial.println("Servo: ABIERTO");
return;
}
// Cerrar servomotor
if (comando.equalsIgnoreCase("C")) {
servoTapa.write(SERVO_CERRADO);
Serial.println("Servo: CERRADO");
return;
}
Serial.println("Comando no reconocido.");
}
// =====================================================
// PROBAR CONEXION CON CLOUDFLARE
// =====================================================
void probarCloudflare() {
WiFiClientSecure client;
client.setCACert(GOOGLE_ROOT_CA);
client.setHandshakeTimeout(20);
HTTPClient http;
Serial.println();
Serial.println("==============================");
Serial.println(" PRUEBA CON CLOUDFLARE");
Serial.println("==============================");
if (!http.begin(client, WORKER_URL)) {
Serial.println("No se pudo iniciar HTTPS.");
return;
}
http.setConnectTimeout(15000);
http.setTimeout(15000);
int httpCode = http.GET();
Serial.print("Codigo HTTP: ");
Serial.println(httpCode);
if (httpCode > 0) {
String respuesta = http.getString();
Serial.print("Respuesta: ");
Serial.println(respuesta);
} else {
Serial.print("Detalle HTTP: ");
Serial.println(
HTTPClient::errorToString(httpCode)
);
char error[256] = {0};
int codigo = client.lastError(
error,
sizeof(error)
);
Serial.print("Codigo TLS: ");
Serial.println(codigo);
Serial.print("Detalle TLS: ");
Serial.println(error);
}
http.end();
Serial.println("==============================");
}