#include <WiFi.h>
#include <WebServer.h>
//#include <HTTPClient.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH110X.h>
#include "config.h"
#include "DHTesp.h"
// Creo el objeto pantalla
Adafruit_SH1106G display = Adafruit_SH1106G(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Creo el objeto sensor de temp. y humedad
DHTesp dhtSensor;
// Creo el objeto cliente HTTP
//HTTPClient http;
TempAndHumidity data;
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
int potValue = 0;
int greenLedBrightness = 0;
String blueLedState = "off";
String relayState = "off";
String msn = "hola";
float temp = 0;
float hum = 0;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 1500ms = 1.5s)
const long timeoutTime = 1500;
// Encabezado y cola de la pagina
String headWeb = "<!DOCTYPE html>"
"<html lang='es'>"
"<head>"
"<meta charset='utf-8' />"
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>TA - TP2</title>"
"</head>";
// String tailWeb = "<script>"
// "const greenLedRange = document.getElementById('greenLedRange');"
// "const rangeValue = document.getElementById('rangeValue');"
// // Función para actualizar el valor del porcentaje
// "function actualizarPorcentaje() {"
// "const porcentaje = greenLedRange.value + '%';"
// "rangeValue.textContent = porcentaje;}"
// // Escuchar el evento input y llamar a la función de actualización
// "greenLedRange.addEventListener('input', actualizarPorcentaje);"
// // Llamar a la función inicialmente para mostrar el valor inicial
// "actualizarPorcentaje(); </script>"
// "</html>";
void setup() {
pinMode(potPin, INPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(relayPin, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(BAUDRATE);
// Connect to Wi-Fi network with SSID and password
WiFi.begin(SSID, PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi conectado");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
Serial.println("Iniciando pantalla...");
dhtSensor.setup(dhtPinout, DHTesp::DHT22);
displayInit();
delay(2000);
}
void loop() {
// On|Off relay
// buttonState = digitalRead(buttonPin);
// Si el pulsador ha sido presionado, cambiar el estado del relay
// if (buttonState != lastButtonState) {
// if (buttonState == HIGH) {
// // Cambiar el estado del relé
// relayState = !relayState;
// // Aplicar el nuevo estado al relé
// digitalWrite(relayPin, relayState);
// // Serial.println("Estado relay: HIGH");
// }
// // Guardar el último estado del pulsador
// lastButtonState = buttonState;
// delay(100);
// }
// Intensidad led verde
potValue = analogRead(potPin);
greenLedBrightness = map(potValue, 0, 4095, 0, 255);
analogWrite(greenLedPin, greenLedBrightness);
// GET temperatura y humedad
data = dhtSensor.getTempAndHumidity();
temp = data.temperature;
hum = data.humidity;
// displayUpdateAndShow(50);
WiFiClient client = server.available(); // Escucha a los clientes entrantes. Verifica si hay alguna solicitud de conexión pendiente
if (client) { // Si se conecta un nuevo cliente
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client.");
String currentLine = ""; //
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop mientras el cliente está conectado
currentTime = millis();
if (client.available()) { // si hay bytes para leer desde el cliente. Devuelve el número de bytes disponibles para lectura en el búfer de entrada del cliente
char c = client.read(); // lee un byte y lo elimina del buffer
Serial.write(c);
header += c;
if (c == '\n') { // si el byte es un caracter de salto de linea
Serial.println(currentLine);
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK"); //la solicitud HTTP se ha procesado correctamente.
client.println("Content-type:text/html"); //establece el tipo de contenido que se enviará al cliente en la respuesta. En este caso se trata de una página HTML.
client.println("Connection: close"); //la conexión entre el servidor y el cliente se cerrará después de enviar la respuesta
client.println();
// Enciende y apaga el GPIO
if (header.indexOf("GET /ledAzul/on") >= 0) {
Serial.println("LED azul on");
blueLedState = "on";
digitalWrite(LED_BUILTIN, HIGH);
} else if (header.indexOf("GET /ledAzul/off") >= 0) {
Serial.println("LED azul off");
blueLedState = "off";
digitalWrite(LED_BUILTIN, LOW);
} else if (header.indexOf("GET /relay/on") >= 0) {
Serial.println("Relay HIGH");
relayState = "on";
digitalWrite(relayPin, HIGH);
} else if (header.indexOf("GET /relay/off") >= 0) {
Serial.println("Relay LOW");
relayState = "off";
digitalWrite(relayPin, LOW);
} else if (header.indexOf("GET /mensaje") >= 0) {
Serial.println("Mostrar mensaje en display");
displayUpdateAndShow(50);
}
// Muestra la página web
client.println(headWeb);
client.println("<body><h1>Actividad N°2 – Sketch integrador con Servidor Web.</h1><hr>");
client.println("<div><h2>Datos</h2>");
client.println("<p>Valor del potenciómetro: <span id='potentiometerValue'>"+ String (potValue) +"</span></p>");
client.println("<p>Temperatura: <span id='temperature'>"+ String (temp) +"</span> °C</p>");
client.println("<p>Humedad: <span id='humidity'>"+ String (hum) +"</span>%</p>");
client.println("<p>Estado del LED azul: <span id='blueLedState'>"+blueLedState+"</span></p>");
client.println("<p>Estado del relay: <span id='relayState'>"+relayState+"</span></p>");
client.println("<p>Intensidad del LED verde: <span id='greenLedIntensity'>"+ String (greenLedBrightness)+"</span>%</p>");
client.println("</div><hr>");
client.println("<div><h2>Control</h2>");
// Muesra los botones
if (blueLedState =="off") {
client.println("<a href='/ledAzul/on'><button>Cambiar Estado LED Azul</button></a>");
} else {
client.println("<a href='/ledAzul/off'><button>Cambiar Estado LED Azul</button></a>");
}
if (relayState =="off") {
client.println("<a href='/relay/on'><button>Cambiar Estado LED Azul</button></a>");
} else {
client.println("<a href='/relay/off'><button>Cambiar Estado Relay</button></a>");
}
client.println("<hr><div><h2>Mostrar un mensaje en el display </h2>");
client.println("<textarea id='textInput' maxlength='100' cols='50' rows='5'></textarea>");
client.println("<br><a href='mensaje'><button>Mostrar mensaje</button></a></div></body>");
client.print("</html>");
//client.println(tailWeb);
// la respuesta HTTP temina con una linea en blanco
client.println();
break;
} else { // si tenemos una nueva linea limpiamos currentLine
currentLine = "";
}
} else if (c != '\r') { // si C es distinto al caracter de retorno de carro
currentLine += c; // lo agrega al final de currentLine
}
}
}
// Limpiamos la variable header
Serial.println(header);
header = "";
// Cerramos la conexión
client.stop();
}
}
const unsigned char epd_bitmap_UTN [] PROGMEM = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xf1, 0xe1, 0xe3, 0xfe, 0x1f, 0xfe, 0x10, 0x00, 0x01, 0x87, 0xff, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf1, 0xe1, 0xe3, 0xfe, 0x1f, 0xfe, 0x10, 0x00, 0x01, 0x83, 0xff, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf0, 0xe1, 0xc3, 0xfe, 0x1f, 0xfe, 0x10, 0x00, 0x01, 0x83, 0xff, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf0, 0xe1, 0x83, 0xfe, 0x1f, 0xfe, 0x1f, 0xe0, 0xff, 0x81, 0xff, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf0, 0x61, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x80, 0xff, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf8, 0x00, 0x07, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x80, 0x7f, 0x87, 0xff, 0xff, 0xff, 0xff,
0xfc, 0x00, 0x0f, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x80, 0x3f, 0x87, 0xff, 0xff, 0xff, 0xff,
0xfe, 0x00, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x80, 0x3f, 0x87, 0xff, 0xff, 0xff, 0xff,
0xff, 0x00, 0x7f, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x84, 0x1f, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf0, 0x00, 0x03, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x86, 0x0f, 0x87, 0xff, 0xff, 0xff, 0xff,
0xe0, 0x00, 0x03, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x87, 0x07, 0x87, 0xff, 0xff, 0xff, 0xff,
0xe0, 0x00, 0x03, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x87, 0x83, 0x87, 0xff, 0xff, 0xff, 0xff,
0xe0, 0x00, 0x03, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x87, 0x81, 0x87, 0xff, 0xff, 0xff, 0xff,
0xff, 0x80, 0x7f, 0xfe, 0x1f, 0xfe, 0x1f, 0xf0, 0xff, 0x87, 0xc1, 0x87, 0xff, 0xff, 0xff, 0xff,
0xff, 0x00, 0x3f, 0xfe, 0x0f, 0xfe, 0x1f, 0xf0, 0xff, 0x87, 0xe0, 0x87, 0xff, 0xff, 0xff, 0xff,
0xfe, 0x00, 0x1f, 0xff, 0x0f, 0xfc, 0x1f, 0xf0, 0xff, 0x87, 0xf0, 0x07, 0xff, 0xff, 0xff, 0xff,
0xf8, 0x00, 0x0f, 0xff, 0x0f, 0xfc, 0x3f, 0xf0, 0xff, 0x87, 0xf8, 0x07, 0xff, 0xff, 0xff, 0xff,
0xf8, 0x00, 0x07, 0xff, 0x07, 0xf8, 0x3f, 0xf0, 0xff, 0x87, 0xfc, 0x07, 0xff, 0xff, 0xff, 0xff,
0xf0, 0x61, 0x83, 0xff, 0x83, 0xf0, 0x7f, 0xf0, 0xff, 0x87, 0xfc, 0x07, 0xff, 0xff, 0xff, 0xff,
0xf0, 0xe1, 0xc3, 0xff, 0x80, 0x00, 0x7f, 0xf0, 0xff, 0x87, 0xfe, 0x07, 0xff, 0xff, 0xff, 0xff,
0xf0, 0xe1, 0xc3, 0xff, 0xc0, 0x00, 0xff, 0xf0, 0xff, 0x87, 0xff, 0x07, 0xff, 0xff, 0xff, 0xff,
0xe1, 0xe1, 0xe3, 0xff, 0xf0, 0x03, 0xff, 0xf0, 0xff, 0x87, 0xff, 0x87, 0xff, 0xff, 0xff, 0xff,
0xf1, 0xe3, 0xe3, 0xff, 0xfe, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
void displayInit() {
display.begin(0x3C, true);
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.drawBitmap(0, 0, epd_bitmap_UTN, 128, 32, SH110X_BLACK, SH110X_WHITE);
display.display();
delay(2000);
display.clearDisplay();
display.print("SSID: ");
display.println(WiFi.SSID());
display.print("ID: ");
display.println(WiFi.localIP());
display.display();
}
void displayUpdateAndShow(unsigned long interval) {
currentTime = millis();
if (currentTime - previousTime > interval)
{
previousTime = millis();
display.clearDisplay();
display.setCursor(0, 0);
// display.println("Potenciometro: " + String(potValue));
// display.setCursor(0, 12);
// display.println("T: " + String(temp, 0) + "'C" );
// display.setCursor(65, 12);
// display.println("H: " + String(hum, 0) + "%");
// display.setCursor(0, 24);
// // Formatear el estado del relé en una cadena
// char relayStatus[13]; // Reservar espacio para la cadena
// snprintf(relayStatus, sizeof(relayStatus), "Relay: %s", relayState ? "HIGH" : "LOW");
// display.println(relayStatus);
display.println(msn); //muestra el mensaje ingresado por el usuario
display.display();
}
}