I have a ESP32 with a web server. In the page where I show the sensor readings and the state of the system, right now the readings are showing themselves well. The problem comes when I want to show the state of the system.
Right now I'm testing the behavior only with the /encender page. The state of the system is sent in a JSON file to only update the elements that contains the system state. Instead of update those html elements, the page disappears and the web explorer shows me an error of empty response.
Here follows my actual code related to my problem:
Code related to the /encender page (an element) in backend.cpp:
server.on("/encender", HTTP_GET,[](AsyncWebServerRequest *request){
digitalWrite(ledPinSistemaApagado,LOW);
digitalWrite(ledPinSistemaEncendido,HIGH);
if(ultimaPaginaCargada == "/encender");
{
Serial.println("No se envía la página /encender, solo se actualizará el estado del sistema.");
request->send(200);
return;
}
ultimaPaginaCargada = "/encender";
cuentaAcceso = true;
request->send(SPIFFS,"/index.html", String(), false, Procesador);
});
The code in backend.cpp related to the update of the state of the function is like follows:
server.on("/data-estado", HTTP_GET, [](AsyncWebServerRequest *request){
if(!request->authenticate(usuarioHTTP, claveHTTP) && !cuentaAcceso) {
return request->requestAuthentication("Ingreso al Sistema");
};
Serial.println("Enviando la data de estado.");
sistemaEstado["estado-sistema"] = ledEstado;
sistemaEstado["modo-sistema"] = modoSistema;
String json = "";
serializeJsonPretty(sistemaEstado, json);
Serial.println(json);
ultimaPaginaCargada = "/data-estado";
cuentaAcceso = true;
request->send(200, "application/json", json);
json = String();
Serial.println("Enviada la data de estado.");
});
Right now the above piece of code, if the variable ùltimaPaginaCargada is "/encender", it means that the page /encender was previously loaded, so it only sends "200" to the web explorer. On the contrary, the "/encender" wasn't previously loaded and that page is sent.
Following is the code on my app.js:
function Actualiza_Estado() {
console.log("Entrando a Actualiza_Estado().");
var xxhr = new XMLHttpRequest();
if(this.readyState == 4 && this.status == 200)
{
console.log("Analizando los componentes reibidos en Actualiza_Estado()");
var estadoWeb = JSON.parse(this.responseText);
console.log(estadoWeb);
var estadoEnc = document.getElementById("estado-sistema");
estadoEnc.innerHTML = "<p>Estado Sistema: " + "<strong>" + `${estadoWeb.estado-sistema}` + "</strong>";
var modoEnc = document.getElementById("modo-sistema");
modoEnc.innerHTML = "<p>Modo Sistema: " + "<strong>" + `${modoEnc.modo-sistema}` + "</strong>";
console.log("Enviados los componentes a actualizar a la pantalla");
}
else
{
console.log("Contenido no cargado en Actualiza_Estado()");
}
xxhr.open("HTTP_GET", "/data-estado", true);
xxhr.send();
console.log("Solicitada la actualización del estado del sistema");
};
// Funciones para mostrar el nivel del tanque en la página de visualización.
function Lee_Nivel_Tanque() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200)
{
var volTanqueWeb = JSON.parse(this.responseText);
console.log(volTanqueWeb);
var volActualWeb = document.getElementById("mask01");
volActualWeb.innerHTML = volTanqueWeb.colAgua.toFixed(2);
}
else
{
console.log("Contenido no cargado en Lee_Nivel_Tanque()");
}
};
xhr.open("HTTP_GET", "/data-tanque", true);
xhr.send();
console.log("Solicitada actualización del tanque.");
};
// Funciones para enviar la hora y la fecha a la ventana
function Fecha_Hora() {
let hoyFecha = new Date();
let hoyHora = hoyFecha.toLocaleTimeString();
let dia = hoyFecha.getDate();
let mes = hoyFecha.getMonth() + 1;
let anio = hoyFecha.getFullYear();
let diaSemana = hoyFecha.getDay();
dia = ('0' + dia).slice(-2);
mes = ('0' + mes).slice(-2);
let semana = ['DOMINGO', 'LUNES', 'MARTES', 'MIÉRCOLES', 'JUEVES', 'VIERNES', 'SÁBADO'];
let muestraSemana = semana[diaSemana];
let fechaCompleta = ${muestraSemana}-${dia}-${mes}-${anio};
document.getElementById("la-fecha").innerHTML = fechaCompleta;
document.getElementById("la-hora").innerHTML = hoyHora;
console.log(fechaCompleta + '->' + hoyHora);
};
window.onload = function() {
let intervaloVolumen;
let intervaloFecha;
intervaloFecha = setInterval(Fecha_Hora, 1000);
if((window.location.pathname === "/index") ||
(window.location.pathname === "/apagar") ||
(window.location.pathname === "/encender") ||
(window.location.pathname === "/auto") ||
(window.location.pathname === "/manual"))
{
//Actualiza_Estado();
intervaloVolumen = setInterval(Lee_Nivel_Tanque, 20000);
}
else
{
clearInterval(intervaloVolumen);
intervaloVolumen = null;
}
}
var datoEstado = document.getElementsByClassName("boton-control");
datoEstado.addEventListener("click", function(event) {
event.preventDefault();
Actualiza_Estado();
});
Above the functions that I think matters are Àctualiza_Estado() and the var datoEstado. datoEstado is basically a listener that when I make click at any of the buttons made with <a> elements it calls Àctualiza_Estado() to request the JSON file with the state of the system.
On the window.onload() function, if any of the buttons or the principal page are loaded then it defines an interval to update the parameter to read from the sensor and every 20 seconds, it requests a JSON file with that data (this works excellent).
Is that in the function server.on() related to /encender page? I make the program to send a 200 response to the request to make the ESP32 code to send only the JSON file by calling the Actualiza_Estado() function with requests /data-estado, but like I said the web explorer seems to have an empty response.
I've made a variation in the function server.on() related to /encender page in backend.cpp to force the sending of the JSON file directly from there like follows
server.on("/encender", HTTP_GET,[](AsyncWebServerRequest *request){
digitalWrite(ledPinSistemaApagado,LOW);
digitalWrite(ledPinSistemaEncendido,HIGH);
if(ultimaPaginaCargada == "/encender");
{
Serial.println("Enviando la data de estado.");
sistemaEstado["estado-sistema"] = ledEstado;
sistemaEstado["modo-sistema"] = modoSistema;
String json = "";
serializeJsonPretty(sistemaEstado, json);
Serial.println(json);
ultimaPaginaCargada = "/data-estado";
cuentaAcceso = true;
request->send(200, "application/json", json);
json = String();
}
ultimaPaginaCargada = "/encender";
cuentaAcceso = true;
request->send(SPIFFS,"/index.html", String(), false, Procesador);
});
In the above case the web explorer receives the JSON file and displays de data but in an empty black page and shows the formatted JSON file.
I don't know whats happening because the method of JSON file. It works very well when using it for the sensor reading with Lee_Nivel_Tanque().
What can I do to solve the problem?