//Incluimos las librerias
#include <WiFi.h>
#include <PubSubClient.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> //Javascript object notation
#include "DHTesp.h"
//URL / ruta a conectar
const char* apiEndpoint = "https://automatic-dollop-gww46wq6jwfv5pq-5000.app.github.dev/sensor_data";
//coneccion a la red
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Broker // IP Raspberry Pi// COMPUTADORA
const char *broker = "broker.mqtt-dashboard.com";
int puerto = 1883;
const char *id_cliente = "control_led_TuNombre";//Escribe tu nombre. #el identificador tiene que ser único
//Decaramos el variable que almacena el pin a conectar el DHT11
int pinDHT = 15;
const char *topico1 = ""; //topico al que me suscribo
const char *topico2 = ""; //topico en el que voy a publicar
long now = millis();
//Instanciamos el DHT
DHTesp dht;
void setup_wifi();
void procesar_mensajes(char *topic, byte *mensaje, unsigned int longitud);
void publicar();
//conexion a internet
WiFiClient BoardESP32;
PubSubClient client_mqtt(BoardESP32);
//funcion wifi
void setupWifi(){
Serial.begin(115200);
Serial.print("Connecting to WiFi");
//funcion wifi que se conecta a la red (inicializa la red)
WiFi.begin(ssid, password);
//condicion cuando se esta conectando
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.print(" Connected: ");
//extrae su ip
Serial.println(WiFi.localIP());
}
//primera funcion que se realiza
void setup() {
//puerto serial que va a imprimir todo lo que le indiquemos
Serial.begin(115200);
//Inicializamos el dht
dht.setup(pinDHT, DHTesp::DHT22);
//invocar la funcion wifi
setupWifi();
//Conexion al broker
client_mqtt.setServer(broker, puerto);
if (client_mqtt.connect(id_cliente)) {
Serial.println("Connected to MQTT Broker!");
}
else {
Serial.println("Connected to MQTT failed...");
}
if (client_mqtt.connect(id_cliente)) {
Serial.print("Conectado con broker ");
Serial.println(broker);
}
else {
Serial.print("No se pudo conectar con broker");
}
//Activar la rutina para recibir mensajes
client_mqtt.setCallback(procesar_mensajes);
//Suscribirse a un tópico
if (client_mqtt.subscribe(topico1)) {
Serial.printf("Suscrito a topico %s\n", topico1);
}
}
//envio de datos
void sendData(float temperature, float humidity){
Serial.print("Sending data to API: ");
// Set up HTTP connection with the API endpoint
HTTPClient http;
http.begin(apiEndpoint);
//avisar que es lo que se va a llegar (tipos de datos) de los endpoints
http.addHeader("Content-Type", "application/json");
// Create a JSON document using the ArduinoJson library
StaticJsonDocument<200> doc;
// Add the data to the JSON document
doc["temperature"] = temperature;
doc["humidity"] = humidity;
// Add the current date and time to the JSON document. This will change to a date from the proper sensor in the future
//doc["date_time"] = "2021-01-01 00:00:00";
// Serialize the JSON document to a string
String json;
serializeJson(doc, json);
// Send the POST request to the API endpoint
int httpResponseCode = http.POST(json);
if (httpResponseCode > 0){
// Print the response from the server
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String responseString = http.getString();
Serial.println("Received response: " + responseString);
} else{
// Print the error code
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
void publicar()
{
int EdoSensor=23;
char EdoSensorString [5];
itoa(EdoSensor,EdoSensorString,10);
client_mqtt.publish(topico2, EdoSensorString);
}
void procesar_mensajes(char *topic, byte *mensaje, unsigned int longitud) {
char mensaje_local[100] = {0};
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Mensaje recibido: ");
for (int i = 0; i < longitud; i++) {
Serial.write(mensaje[i]);
mensaje_local[i] = mensaje[i];
}
Serial.println();
int DatoRecibido = strtol(mensaje_local, 0, 10);
Serial.print("Dato recibido tipo long: ");
Serial.println(DatoRecibido);
}
void loop() {
//Obtenemos el arreglo de datos (humedad y temperatura)
TempAndHumidity data = dht.getTempAndHumidity();
//Mostramos los datos de la temperatura y humedad
//string funciona para que pueda convertir los datos flotantes a un dato de texto para que pueda ser visualizado
lcd.setCursor(0, 0);
lcd.print(String(data.temperature, 2) + "°C");
lcd.setCursor(0, 2);
lcd.print(String(data.humidity, 1) + "%");
Serial.println("Temperatura: " + String(data.temperature, 2) + "°C");
Serial.println("Humedad: " + String(data.humidity, 1) + "%");
Serial.println("---");
delay(1000);
sendData(data.temperature, data.humidity);
publicar();
now = millis();
//Esta funcion se debe llamar para mantener activa la conexion con el broker
client_mqtt.loop();
}